From a29af6f290d68a362a89140efb2f181064a2ebe1 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Sat, 14 Nov 2026 21:38:12 -0700 Subject: names: a withdraw-link claim with no route right now is tried again for up to ten minutes. "I made a transaction for 1,000,000 sats using the Withdraw link method, but they never arrived" (a user via Adam, 2026-11-14). The claim's invoice sat behind a private channel; at that moment this node's own channels couldn't carry 1M ("could not find a usable set of paths", answered in a tenth of a second), so the payout failed at once and the sats went back on the link, while the claimer's wallet, told OK as LUD-03 has it, waited for nothing. Minutes later a route was there. Now a payout to another node that definitely failed (no part pending or complete) is paid again after 30 s, 90 s, 3 min and 5 min, as long as the invoice has a minute to spare; the claim stays 'paying' meanwhile and settlePending leaves it alone. Reclaims are not retried (the creator is waiting on them). The claim's view carries tries, so the app can say it's still trying Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VMan6UKGJyuGyZFxddYRxS --- names/withdraw.js | 38 +++++++++++++++++++++++++++++++------- names/withdraw.test.js | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 8 deletions(-) (limited to 'names') diff --git a/names/withdraw.js b/names/withdraw.js index 255c66a..b3c9bb8 100644 --- a/names/withdraw.js +++ b/names/withdraw.js @@ -29,11 +29,18 @@ const MAX_TOTAL_SAT = 2_000_000; export const feeCapSat = (sat) => Math.max(10, Math.ceil(sat * 0.01)); const msatOf = (v) => Number(v?.msat ?? v ?? 0); -export function withdrawService({ state, persist, log = () => {}, lnFor, ourNodeId, payCircular, circularPick, canCircular = () => true, publicBase, now = () => Date.now() }) { +// A claim the network can't route right now is tried again before it's +// given back: on 2026-11-14 a 1M-sat claim found this node's own channels +// empty for a moment ("could not find a usable set of paths") and failed in +// a tenth of a second, though a route was there minutes later. +export const RETRY_DELAYS = [30_000, 90_000, 180_000, 300_000]; + +export function withdrawService({ state, persist, log = () => {}, lnFor, ourNodeId, payCircular, circularPick, canCircular = () => true, publicBase, now = () => Date.now(), retryDelays = RETRY_DELAYS, wait = (ms) => new Promise((r) => setTimeout(r, ms)) }) { const links = () => (state.withdraws ||= {}); const funding = () => (state.withdrawFunding ||= {}); // fund payment hash -> id const paidHashes = () => (state.withdrawPaid ||= {}); // claim payment hash -> id (never pay one twice) const busy = new Set(); // ids with a claim being validated/started right now + const active = new Set(); // claim hashes this process is still paying (settlePending leaves them alone) const remaining = (w) => w.totalSat - w.spentSat; const perClaimMax = (w) => Math.min(w.sat, remaining(w)); @@ -41,7 +48,7 @@ export function withdrawService({ state, persist, log = () => {}, lnFor, ourNode id: w.id, url: `${publicBase}/w/${w.id}`, net: w.net, sat: w.sat, uses: w.uses, used: w.used, totalSat: w.totalSat, spentSat: w.spentSat, remainingSat: remaining(w), note: w.note || '', status: w.status, created: w.created, - claims: (w.claims || []).map((c) => ({ sat: c.sat, status: c.status, at: c.at, reclaim: !!c.reclaim })), + claims: (w.claims || []).map((c) => ({ sat: c.sat, status: c.status, at: c.at, reclaim: !!c.reclaim, ...(c.tries > 1 ? { tries: c.tries } : {}) })), }); function sweep() { @@ -164,14 +171,31 @@ export function withdrawService({ state, persist, log = () => {}, lnFor, ourNode if (r.status !== 'complete') throw new Error('payment ' + r.status); return Math.ceil(feeMsat / 1000); })() : (async () => { - const r = await ln.call('pay', { bolt11: pr, maxfee: `${feeCapSat(sat)}sat`, retry_for: 60 }); - if (r.status && r.status !== 'complete') throw new Error(`payment ${r.status}`); - return Math.ceil((msatOf(r.amount_sent_msat) - msatOf(r.amount_msat)) / 1000); + const expiresAt = dec.created_at && dec.expiry ? (dec.created_at + dec.expiry) * 1000 : Infinity; + for (let i = 0; ; i++) { + claim.tries = i + 1; + try { + const r = await ln.call('pay', { bolt11: pr, maxfee: `${feeCapSat(sat)}sat`, retry_for: 60 }); + if (r.status && r.status !== 'complete') throw new Error(`payment ${r.status}`); + return Math.ceil((msatOf(r.amount_sent_msat) - msatOf(r.amount_msat)) / 1000); + } catch (e) { + // a part may still be out there: never start another attempt over it + const st = await outcome(ln, hash).catch(() => 'unknown'); + if (st !== 'failed' && st !== 'none') throw e; + const delay = reclaim ? undefined : retryDelays[i]; + if (delay == null || now() + delay + 60_000 > expiresAt) throw e; + claim.error = String(e.message || e).slice(0, 200); + persist(); + log(`withdraw link ${w.id}: ${sat} sat payout attempt ${i + 1} failed (${claim.error.slice(0, 120)}), trying again in ${Math.round(delay / 1000)} s`); + await wait(delay); + } + } })(); // the answer to the claimer does not wait for the route (LUD-03: OK, then // pay); `settled` is true once paid, false once definitely not, null if unknown - const settled = run.then((fee) => { done(fee); return true; }, async (e) => { + active.add(hash); + const settled = run.finally(() => active.delete(hash)).then((fee) => { done(fee); return true; }, async (e) => { if (e.definite) { fail(e.message); return false; } // did it really fail, or is it still out there? const st = await outcome(ln, hash).catch(() => 'unknown'); @@ -244,7 +268,7 @@ export function withdrawService({ state, persist, log = () => {}, lnFor, ourNode async function settlePending() { for (const w of Object.values(links())) { for (const c of w.claims || []) { - if (c.status !== 'paying' || now() - c.at < 120_000) continue; + if (c.status !== 'paying' || active.has(c.hash) || now() - c.at < 120_000) continue; const st = await outcome(lnFor(w.net), c.hash).catch(() => 'unknown'); if (st === 'complete') { c.status = 'paid'; persist(); log(`withdraw link ${w.id}: ${c.sat} sat payout settled late`); } else if (st === 'failed' || st === 'none') { diff --git a/names/withdraw.test.js b/names/withdraw.test.js index 80da774..ee856f1 100644 --- a/names/withdraw.test.js +++ b/names/withdraw.test.js @@ -1,6 +1,7 @@ // bun test names/withdraw.test.js import { test, expect } from 'bun:test'; -import { withdrawService } from './withdraw.js'; +import { withdrawService, RETRY_DELAYS } from './withdraw.js'; +const RETRIES = RETRY_DELAYS.length; const OUR = '02' + 'aa'.repeat(32), THEIRS = '03' + 'bb'.repeat(32); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); @@ -32,6 +33,7 @@ function rig({ payBehaviour = 'ok', circularCap = 1e9 } = {}) { const svc = withdrawService({ state, persist: () => {}, lnFor: () => ln, ourNodeId: async () => OUR, circularPick: async () => ({ cap: circularCap }), payCircular: async () => { circular++; return { feeMsat: 1500 }; }, + wait: async () => {}, publicBase: 'https://names.test', }); const invoice = (sat, payee = THEIRS, extra = {}) => { @@ -100,6 +102,7 @@ test('a failed payout goes back on the link', async () => { const v = r.svc.mine('me')[0]; expect(v.remainingSat).toBe(1000); expect(v.used).toBe(0); + expect(v.claims[0]).toMatchObject({ status: 'failed', tries: RETRIES + 1 }); expect(r.svc.params(c.id).tag).toBe('withdrawRequest'); }); @@ -139,3 +142,47 @@ test('confirmFunded checks the invoice', async () => { expect((await r.svc.confirmFunded(c.id, 'me')).status).toBe('open'); expect(r.svc.onSettled(c.paymentHash)).toBe(false); // the settle loop arriving later is a no-op }); + +test('a claim with no route right now is tried again, and pays when one turns up', async () => { + const waits = []; + const state = {}; const pays = {}; const fakes = {}; let tries = 0; + const ln = { + async call(m, p) { + if (m === 'invoice') return { bolt11: 'lnfundx', payment_hash: 'fx' }; + if (m === 'decode') return fakes[p.string]; + if (m === 'pay') { tries++; const d = fakes[p.bolt11]; if (tries < 3) { pays[d.payment_hash] = 'failed'; throw new Error('could not find a usable set of paths'); } pays[d.payment_hash] = 'complete'; return { status: 'complete', amount_msat: d.amount_msat, amount_sent_msat: d.amount_msat }; } + if (m === 'listsendpays') return { payments: pays[p.payment_hash] ? [{ status: pays[p.payment_hash] }] : [] }; + throw new Error('unexpected ' + m); + }, + }; + const svc = withdrawService({ state, persist: () => {}, lnFor: () => ln, ourNodeId: async () => OUR, publicBase: 'https://names.test', wait: async (ms) => { waits.push(ms); } }); + const made = await svc.create({ pubkey: 'me', sat: 1000 }); + svc.onSettled('fx'); + fakes.lnbcz = { valid: true, payment_hash: 'cz', amount_msat: 1_000_000, payee: THEIRS, created_at: Math.floor(Date.now() / 1000), expiry: 3600 }; + expect((await svc.callback(made.id, svc.params(made.id).k1, 'lnbcz')).status).toBe('OK'); + await sleep(10); + expect(tries).toBe(3); + expect(waits.length).toBe(2); + expect(svc.mine('me')[0]).toMatchObject({ remainingSat: 0, used: 1 }); + expect(svc.mine('me')[0].claims[0]).toMatchObject({ status: 'paid', tries: 3 }); +}); + +test('retries stop short of the invoice expiring, then the sats go back', async () => { + const state = {}; const pays = {}; let tries = 0; + const ln = { + async call(m, p) { + if (m === 'invoice') return { bolt11: 'lnfundy', payment_hash: 'fy' }; + if (m === 'decode') return { valid: true, payment_hash: 'cy', amount_msat: 500_000, payee: THEIRS, created_at: Math.floor(Date.now() / 1000), expiry: 120 }; + if (m === 'pay') { tries++; pays.cy = 'failed'; throw new Error('no route'); } + if (m === 'listsendpays') return { payments: pays[p.payment_hash] ? [{ status: pays[p.payment_hash] }] : [] }; + throw new Error('unexpected ' + m); + }, + }; + const svc = withdrawService({ state, persist: () => {}, lnFor: () => ln, ourNodeId: async () => OUR, publicBase: 'https://names.test', wait: async () => {} }); + const made = await svc.create({ pubkey: 'me', sat: 500 }); + svc.onSettled('fy'); + await svc.callback(made.id, svc.params(made.id).k1, 'lnbcy'); + await sleep(10); + expect(tries).toBe(2); // 30 s + a minute's margin fits in 120 s, 90 s more doesn't + expect(svc.mine('me')[0]).toMatchObject({ remainingSat: 500, used: 0 }); +}); -- cgit v1.2.3