diff options
Diffstat (limited to 'names/withdraw.js')
| -rw-r--r-- | names/withdraw.js | 264 |
1 files changed, 264 insertions, 0 deletions
diff --git a/names/withdraw.js b/names/withdraw.js new file mode 100644 index 0000000..255c66a --- /dev/null +++ b/names/withdraw.js @@ -0,0 +1,264 @@ +// Prepaid Lightning withdraw links (LNURL-withdraw, LUD-03). +// +// "Do we have lnurl withdraw links somewhere? can we add them?" (a community +// member via Adam, 2026-11-07). A withdraw link is a URL whoever holds it can +// pull sats from — a voucher, a faucet, a printed QR — and the one who scans +// it expects to be paid on the spot, maybe days later. A self-custodial +// wallet asleep in someone's pocket can't answer that, so the link is +// PREPAID: its creator pays the whole amount to this node up front, and this +// service pays each claim out of that reserve. Until a claim takes it, the +// reserve is held here (like a POS sale before it forwards); the creator can +// take back whatever is left at any time (reclaim), which closes the link. +// +// A link: { id, k1, pubkey, net, sat (most per claim), uses (claims allowed), +// used, totalSat (funded), spentSat, note, status: unfunded|open|closed, +// created, fundHash, claims: [{ hash, sat, feeSat?, status: paying|paid|failed, at }] } +// Its id is the bearer secret in the URL (names.coinos.io/w/<id>); k1 is a +// second one only the GET hands out, which the callback must echo. +// +// Payouts: an invoice on another node is a plain `pay`, routing fee capped +// and borne here. An invoice on THIS node (any coinos wallet's Lightning +// receive — the ASP's node is this one) can't be paid directly, it's a +// self-payment the hold plugin never sees, so it goes round a circular route +// (deps.payCircular), and its settlement is read back with waitsendpay. +import { randomBytes } from 'node:crypto'; + +const UNFUNDED_TTL = 24 * 3600_000; +const MAX_USES = 1000; +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() }) { + 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 remaining = (w) => w.totalSat - w.spentSat; + const perClaimMax = (w) => Math.min(w.sat, remaining(w)); + const view = (w) => ({ + 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 })), + }); + + function sweep() { + for (const [id, w] of Object.entries(links())) { + if (w.status === 'unfunded' && now() - w.created > UNFUNDED_TTL) { + delete links()[id]; + if (w.fundHash) delete funding()[w.fundHash]; + } + } + } + + async function create({ pubkey, sat, uses = 1, note = '', net = 'mainnet' }) { + sat = Math.floor(Number(sat)); + uses = Math.floor(Number(uses) || 1); + if (!(sat >= 1)) throw Object.assign(new Error('amount must be at least 1 sat'), { status: 400 }); + if (!(uses >= 1 && uses <= MAX_USES)) throw Object.assign(new Error(`claims must be 1–${MAX_USES}`), { status: 400 }); + const totalSat = sat * uses; + if (totalSat > MAX_TOTAL_SAT) throw Object.assign(new Error(`at most ${MAX_TOTAL_SAT} sats per link`), { status: 400 }); + const ln = lnFor(net); + if (!ln) throw Object.assign(new Error('withdraw links are not available right now'), { status: 503 }); + sweep(); + const id = randomBytes(16).toString('base64url'); + note = String(note || '').slice(0, 120); + const inv = await ln.call('invoice', { + amount_msat: totalSat * 1000, + label: `withdraw-${id}`, + description: `coinos withdraw link: ${totalSat} sats${uses > 1 ? ` (${uses} × ${sat})` : ''}`, + expiry: 900, + }); + links()[id] = { + id, k1: randomBytes(32).toString('hex'), pubkey, net, sat, uses, used: 0, totalSat, spentSat: 0, + note, status: 'unfunded', created: now(), fundHash: inv.payment_hash, claims: [], + }; + funding()[inv.payment_hash] = id; + persist(); + log(`withdraw link ${id}: invoiced ${totalSat} sat (${uses} × ${sat}) for ${pubkey.slice(0, 12)}`); + return { id, invoice: inv.bolt11, paymentHash: inv.payment_hash, totalSat }; + } + + // The settle loop saw a payment; true when it was a link's funding. + function onSettled(hash) { + const id = funding()[hash]; + if (!id) return false; + const w = links()[id]; + delete funding()[hash]; + if (w && w.status === 'unfunded') { w.status = 'open'; w.funded = now(); log(`withdraw link ${id}: funded ${w.totalSat} sat`); } + persist(); + return true; + } + + // The creator pings right after paying (the mutinynet node has no settle + // loop, and the mainnet one may not have caught up yet). + async function confirmFunded(id, pubkey) { + const w = links()[id]; + if (!w) throw Object.assign(new Error('no such link'), { status: 404 }); + if (w.pubkey !== pubkey) throw Object.assign(new Error('not your link'), { status: 403 }); + if (w.status !== 'unfunded') return view(w); + const r = await lnFor(w.net).call('listinvoices', { payment_hash: w.fundHash }); + if ((r.invoices || [])[0]?.status !== 'paid') throw Object.assign(new Error('not paid yet'), { status: 402 }); + onSettled(w.fundHash); + return view(w); + } + + // LUD-03 first step: the terms. + function params(id) { + const w = links()[id]; + if (!w || w.status === 'unfunded') return { status: 'ERROR', reason: 'No such withdraw link' }; + if (w.status === 'closed' || w.used >= w.uses || remaining(w) < 1) return { status: 'ERROR', reason: 'This withdraw link has been used up' }; + return { + tag: 'withdrawRequest', + callback: `${publicBase}/w/${id}/cb`, + k1: w.k1, + minWithdrawable: 1000, + maxWithdrawable: perClaimMax(w) * 1000, + defaultDescription: w.note || 'coinos withdraw link', + }; + } + + // Pay one invoice out of a link's reserve. The reserve is taken BEFORE the + // payment starts and handed back only on a definite failure; an outcome we + // can't read yet stays 'paying' for settlePending() to finish. + async function payout(w, pr, { maxSat, reclaim = false } = {}) { + const ln = lnFor(w.net); + const dec = await ln.call('decode', { string: pr }).catch(() => null); + if (!dec || dec.valid === false || !dec.payment_hash) throw new Error('That is not a valid Lightning invoice'); + const sat = Math.floor(msatOf(dec.amount_msat) / 1000); + if (!sat || msatOf(dec.amount_msat) % 1000) throw new Error('The invoice needs a whole-sat amount'); + if (sat > maxSat) throw new Error(`At most ${maxSat} sats`); + if (dec.created_at && dec.expiry && (dec.created_at + dec.expiry) * 1000 < now() + 30_000) throw new Error('The invoice has expired'); + const hash = dec.payment_hash; + if (paidHashes()[hash]) throw new Error('That invoice was already paid'); + const claim = { hash, sat, status: 'paying', at: now(), ...(reclaim ? { reclaim: true } : {}) }; + w.spentSat += sat; + if (!reclaim) w.used += 1; + (w.claims ||= []).push(claim); + paidHashes()[hash] = w.id; + persist(); + + const fail = (why) => { + claim.status = 'failed'; claim.error = String(why).slice(0, 200); + w.spentSat -= sat; + if (!reclaim) w.used -= 1; + delete paidHashes()[hash]; + persist(); + log(`withdraw link ${w.id}: ${sat} sat payout failed: ${claim.error}`); + }; + const done = (feeSat) => { + claim.status = 'paid'; claim.feeSat = feeSat || 0; + persist(); + log(`withdraw link ${w.id}: paid ${sat} sat${reclaim ? ' back to its creator' : ''} (fee ${claim.feeSat}), ${remaining(w)} left`); + }; + + const own = circularPick && canCircular(ln) && dec.payee && dec.payee === (await ourNodeId(ln).catch(() => null)); + const run = own ? (async () => { + const pick = await circularPick(); + if (!pick || pick.cap < sat) throw Object.assign(new Error('no circular route capacity'), { definite: true }); + claim.circular = true; + const { feeMsat } = await payCircular(pr, pick); + const r = await ln.call('waitsendpay', { payment_hash: hash, timeout: 90 }); + 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); + })(); + + // 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) => { + 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'); + if (st === 'complete') { done(0); return true; } + if (st === 'failed' || st === 'none') { fail(e.message); return false; } + log(`withdraw link ${w.id}: ${sat} sat payout unresolved (${e.message}) — will check again`); + return null; + }); + return { claim, settled }; + } + + async function outcome(ln, hash) { + const r = await ln.call('listsendpays', { payment_hash: hash }); + const parts = r.payments || []; + if (!parts.length) return 'none'; + if (parts.some((p) => p.status === 'complete')) return 'complete'; + if (parts.some((p) => p.status === 'pending')) return 'pending'; + return 'failed'; + } + + // LUD-03 second step: the claimer's invoice. + async function callback(id, k1, pr) { + const w = links()[id]; + if (!w || w.status === 'unfunded') return { status: 'ERROR', reason: 'No such withdraw link' }; + if (k1 !== w.k1) return { status: 'ERROR', reason: 'Wrong k1' }; + if (w.status === 'closed' || w.used >= w.uses || remaining(w) < 1) return { status: 'ERROR', reason: 'This withdraw link has been used up' }; + if (busy.has(id)) return { status: 'ERROR', reason: 'Another claim is in progress, try again in a moment' }; + busy.add(id); + try { + await payout(w, String(pr || ''), { maxSat: perClaimMax(w) }); + return { status: 'OK' }; + } catch (e) { + return { status: 'ERROR', reason: e.message }; + } finally { busy.delete(id); } + } + + // The creator takes back what's left: they hand an invoice for exactly the + // remainder, the link closes first so no claim races it, and reopens if the + // payment definitely fails. + async function reclaim(id, pubkey, pr) { + const w = links()[id]; + if (!w) throw Object.assign(new Error('no such link'), { status: 404 }); + if (w.pubkey !== pubkey) throw Object.assign(new Error('not your link'), { status: 403 }); + if (w.status === 'unfunded') { delete links()[id]; delete funding()[w.fundHash]; persist(); return { closed: true, remainingSat: 0 }; } + if (busy.has(id) || (w.claims || []).some((c) => c.status === 'paying')) throw Object.assign(new Error('a claim is still being paid, try again in a moment'), { status: 409 }); + const left = remaining(w); + if (left < 1) { w.status = 'closed'; persist(); return view(w); } + busy.add(id); + const was = w.status; + w.status = 'closed'; + persist(); + try { + const { settled } = await payout(w, String(pr || ''), { maxSat: left, reclaim: true }); + const ok = await Promise.race([settled, new Promise((r) => setTimeout(() => r(null), 100_000))]); + if (ok === false) { w.status = was; persist(); } + return { ...view(w), paid: ok === true }; + } catch (e) { + w.status = was; persist(); + throw Object.assign(new Error(e.message), { status: 400 }); + } finally { busy.delete(id); } + } + + function mine(pubkey) { + sweep(); + return Object.values(links()).filter((w) => w.pubkey === pubkey && w.status !== 'unfunded') + .sort((a, b) => b.created - a.created).slice(0, 100).map(view); + } + + // Payouts whose outcome wasn't known when they ran (a restart, a timeout). + 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; + 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') { + c.status = 'failed'; + w.spentSat -= c.sat; + if (!c.reclaim) w.used -= 1; + else if (w.status === 'closed' && remaining(w) > 0) w.status = 'open'; + delete paidHashes()[c.hash]; + persist(); + log(`withdraw link ${w.id}: ${c.sat} sat payout failed, returned to the link`); + } + } + } + } + + return { create, onSettled, confirmFunded, params, callback, reclaim, mine, settlePending, view: (id) => links()[id] && view(links()[id]) }; +} |
