From 912944d6931065dc4e06d57dd28883a96f149057 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Sat, 7 Nov 2026 13:46:30 -0700 Subject: names: prepaid Lightning withdraw links (LNURL-withdraw, LUD-03). "Do we have lnurl withdraw links somewhere? can we add them?" → "Prepaid" (Adam, 2026-11-07). A self-custodial wallet asleep in a pocket can't answer a withdraw link days later, so the creator pays the whole amount up front (POST /withdraw/new → a CLN invoice for sat × uses; the settle loop, or the creator's POST /withdraw/funded checking listinvoices, opens the link) and this service pays each claim out of that reserve: GET /w/ serves the withdrawRequest (up to the per-claim amount, never past what's left), GET /w//cb?k1&pr pays it — a plain pay with the routing fee capped at max(10 sat, 1%) and borne here, or, for an invoice on this very node (any coinos wallet's Lightning receive), round the float top-up's circular route, read back with waitsendpay. The reserve is taken before a payment starts and handed back only on a definite failure; an unknown outcome stays reserved for a minute-ly listsendpays check. No invoice is ever paid twice, one claim per link at a time. The creator lists theirs (GET /withdraw/mine) and takes back the remainder with an invoice of their own (POST /withdraw/reclaim), which closes the link first and reopens it if that payment fails. All NIP-98 by the wallet key. Mainnet and (play money) mutinynet, on the hat stand's nodes. names/withdraw.test.js covers it against a fake node MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VMan6Ts5Tktega8VbLg31q --- names/server.js | 41 ++++++++ names/withdraw.js | 264 +++++++++++++++++++++++++++++++++++++++++++++++++ names/withdraw.test.js | 141 ++++++++++++++++++++++++++ 3 files changed, 446 insertions(+) create mode 100644 names/withdraw.js create mode 100644 names/withdraw.test.js (limited to 'names') diff --git a/names/server.js b/names/server.js index e12e71b..6336e2b 100644 --- a/names/server.js +++ b/names/server.js @@ -35,6 +35,7 @@ import { decodeBolt11 } from '../coinosv3/src/ark/lightning.js'; import { decodeOffer } from '../coinosv3/src/bolt12.js'; import { registrationIdentity } from './ownership.js'; import { openStore } from './store.js'; +import { withdrawService } from './withdraw.js'; const CFG = JSON.parse(readFileSync(process.env.NAMES_CONFIG || join(import.meta.dir, 'config.json'), 'utf8')); @@ -696,6 +697,16 @@ function grantHat(pk, hat, net = 'mainnet', { equip = true } = {}) { if (equip || !r.equipped) r.equipped = hat; } +// Prepaid LNURL-withdraw links (withdraw.js): funded on the same node as the +// hats, mainnet or mutinynet; a mainnet claim to a coinos wallet's own +// Lightning receive goes round the float top-up's circular route. +const withdraws = withdrawService({ + state, persist, log, lnFor: hatLn, ourNodeId, + payCircular, circularPick, canCircular: (node) => node === ln, + publicBase: PUBLIC_BASE, +}); +setInterval(() => { withdraws.settlePending().catch((e) => log('withdraw settle check failed: ' + e.message)); }, 60_000); + async function settleLoop() { if (!ln || !fwd) return; state.lastPayIndex = state.lastPayIndex || 0; @@ -709,6 +720,7 @@ async function settleLoop() { } state.lastPayIndex = inv.pay_index || state.lastPayIndex; persist(); + if (withdraws.onSettled(inv.payment_hash)) continue; // a withdraw link's funding: it stays here // hat purchases settle here too — grant and keep the sats (that's the point) const hatPending = state.hatInvoices && state.hatInvoices[inv.payment_hash]; if (hatPending) { @@ -1664,6 +1676,35 @@ Bun.serve({ return json(hatRec(pk, net)); } + // ---- prepaid withdraw links (withdraw.js) ---- + { + const m = url.pathname.match(/^\/w\/([A-Za-z0-9_-]{16,32})(\/cb)?$/); + if (m && req.method === 'GET') { + const nocache = (body) => { const r = json(body); r.headers.set('cache-control', 'no-store'); return r; }; + if (!m[2]) return nocache(withdraws.params(m[1])); + if (!rateOk(ip, 20)) return nocache({ status: 'ERROR', reason: 'Too many attempts, try again in a minute' }); + return nocache(await withdraws.callback(m[1], url.searchParams.get('k1') || '', url.searchParams.get('pr') || '')); + } + } + if (url.pathname.startsWith('/withdraw/')) { + const bodyText = req.method === 'POST' ? await req.text() : ''; + const a = await checkNip98(req, url, bodyText); + if (a.error) return json({ error: a.error }, 401); + let body = {}; + if (bodyText) { try { body = JSON.parse(bodyText); } catch { return json({ error: 'bad body' }, 400); } } + const fail = (e) => { log(`withdraw ${url.pathname}: ${e.message}`); return json({ error: e.message }, e.status || 500); }; + try { + if (url.pathname === '/withdraw/mine' && req.method === 'GET') return json({ links: withdraws.mine(a.pubkey) }); + if (url.pathname === '/withdraw/new' && req.method === 'POST') { + if (!rateOk(ip)) return json({ error: 'rate limited' }, 429); + return json(await withdraws.create({ pubkey: a.pubkey, sat: body.sat, uses: body.uses, note: body.note, net: hatNetOf(body.net) })); + } + if (url.pathname === '/withdraw/funded' && req.method === 'POST') return json(await withdraws.confirmFunded(String(body.id || ''), a.pubkey)); + if (url.pathname === '/withdraw/reclaim' && req.method === 'POST') return json(await withdraws.reclaim(String(body.id || ''), a.pubkey, body.invoice)); + } catch (e) { return fail(e); } + return json({ error: 'not found' }, 404); + } + if (url.pathname === '/hats/invoice' && req.method === 'POST') { if (!rateOk(ip)) return json({ error: 'rate limited' }, 429); const bodyText = await req.text(); 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/); 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]) }; +} diff --git a/names/withdraw.test.js b/names/withdraw.test.js new file mode 100644 index 0000000..80da774 --- /dev/null +++ b/names/withdraw.test.js @@ -0,0 +1,141 @@ +// bun test names/withdraw.test.js +import { test, expect } from 'bun:test'; +import { withdrawService } from './withdraw.js'; + +const OUR = '02' + 'aa'.repeat(32), THEIRS = '03' + 'bb'.repeat(32); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +function rig({ payBehaviour = 'ok', circularCap = 1e9 } = {}) { + const state = {}; + const invoices = {}; // our invoices: hash -> { status } + const pays = {}; // outbound: hash -> status + const fakes = {}; // bolt11 string -> decoded + let n = 0; + const ln = { + async call(m, p) { + if (m === 'invoice') { const hash = 'f' + (++n); invoices[hash] = { status: 'unpaid' }; return { bolt11: 'lnfund' + hash, payment_hash: hash }; } + if (m === 'listinvoices') return { invoices: invoices[p.payment_hash] ? [invoices[p.payment_hash]] : [] }; + if (m === 'decode') { const d = fakes[p.string]; if (!d) throw new Error('bad'); return d; } + if (m === 'pay') { + const d = fakes[p.bolt11]; + if (payBehaviour === 'fail') { pays[d.payment_hash] = 'failed'; throw new Error('no route'); } + if (payBehaviour === 'hang') { pays[d.payment_hash] = 'pending'; throw new Error('timed out'); } + pays[d.payment_hash] = 'complete'; + return { status: 'complete', amount_msat: d.amount_msat, amount_sent_msat: d.amount_msat + 3000 }; + } + if (m === 'waitsendpay') { pays[p.payment_hash] = 'complete'; return { status: 'complete' }; } + if (m === 'listsendpays') return { payments: pays[p.payment_hash] ? [{ status: pays[p.payment_hash] }] : [] }; + throw new Error('unexpected ' + m); + }, + }; + let circular = 0; + const svc = withdrawService({ + state, persist: () => {}, lnFor: () => ln, ourNodeId: async () => OUR, + circularPick: async () => ({ cap: circularCap }), payCircular: async () => { circular++; return { feeMsat: 1500 }; }, + publicBase: 'https://names.test', + }); + const invoice = (sat, payee = THEIRS, extra = {}) => { + const hash = 'c' + (++n); const s = 'lnbc' + hash; + fakes[s] = { valid: true, payment_hash: hash, amount_msat: sat * 1000, payee, created_at: Math.floor(Date.now() / 1000), expiry: 3600, ...extra }; + return s; + }; + return { svc, state, invoices, pays, invoice, circular: () => circular }; +} + +async function funded(r, opts) { + const c = await r.svc.create({ pubkey: 'me', ...opts }); + expect(r.svc.params(c.id).status).toBe('ERROR'); // unfunded is invisible + r.invoices[c.paymentHash].status = 'paid'; + expect(r.svc.onSettled(c.paymentHash)).toBe(true); + return c; +} + +test('a funded link pays a claim, then is used up', async () => { + const r = rig(); + const c = await funded(r, { sat: 1000 }); + const p = r.svc.params(c.id); + expect(p.tag).toBe('withdrawRequest'); + expect(p.maxWithdrawable).toBe(1_000_000); + expect(p.callback).toBe(`https://names.test/w/${c.id}/cb`); + expect(await r.svc.callback(c.id, 'nope', r.invoice(1000))).toMatchObject({ status: 'ERROR' }); + expect(await r.svc.callback(c.id, p.k1, r.invoice(1001))).toMatchObject({ status: 'ERROR' }); + expect(await r.svc.callback(c.id, p.k1, r.invoice(1000))).toEqual({ status: 'OK' }); + await sleep(5); + const v = r.svc.mine('me')[0]; + expect(v.remainingSat).toBe(0); + expect(v.claims[0].status).toBe('paid'); + expect(r.svc.params(c.id).status).toBe('ERROR'); + expect(await r.svc.callback(c.id, p.k1, r.invoice(1))).toMatchObject({ status: 'ERROR' }); +}); + +test('multi-use: each claim up to the per-claim amount, no invoice paid twice', async () => { + const r = rig(); + const c = await funded(r, { sat: 500, uses: 3 }); + const k1 = r.svc.params(c.id).k1; + const inv = r.invoice(500); + expect((await r.svc.callback(c.id, k1, inv)).status).toBe('OK'); + expect((await r.svc.callback(c.id, k1, inv)).status).toBe('ERROR'); + expect((await r.svc.callback(c.id, k1, r.invoice(200))).status).toBe('OK'); + await sleep(5); + const v = r.svc.mine('me')[0]; + expect(v.used).toBe(2); + expect(v.remainingSat).toBe(800); + expect(r.svc.params(c.id).maxWithdrawable).toBe(500_000); +}); + +test('an invoice on our own node goes round the circular route', async () => { + const r = rig(); + const c = await funded(r, { sat: 1000 }); + expect((await r.svc.callback(c.id, r.svc.params(c.id).k1, r.invoice(1000, OUR))).status).toBe('OK'); + await sleep(5); + expect(r.circular()).toBe(1); + expect(r.svc.mine('me')[0].claims[0]).toMatchObject({ status: 'paid' }); +}); + +test('a failed payout goes back on the link', async () => { + const r = rig({ payBehaviour: 'fail' }); + const c = await funded(r, { sat: 1000 }); + expect((await r.svc.callback(c.id, r.svc.params(c.id).k1, r.invoice(1000))).status).toBe('OK'); + await sleep(5); + const v = r.svc.mine('me')[0]; + expect(v.remainingSat).toBe(1000); + expect(v.used).toBe(0); + expect(r.svc.params(c.id).tag).toBe('withdrawRequest'); +}); + +test('an unresolved payout stays reserved', async () => { + const r = rig({ payBehaviour: 'hang' }); + const c = await funded(r, { sat: 1000 }); + await r.svc.callback(c.id, r.svc.params(c.id).k1, r.invoice(1000)); + await sleep(5); + expect(r.svc.mine('me')[0]).toMatchObject({ remainingSat: 0 }); +}); + +test('expired and amountless invoices are refused', async () => { + const r = rig(); + const c = await funded(r, { sat: 1000 }); + const k1 = r.svc.params(c.id).k1; + expect((await r.svc.callback(c.id, k1, r.invoice(100, THEIRS, { created_at: 1000, expiry: 60 }))).status).toBe('ERROR'); + expect((await r.svc.callback(c.id, k1, r.invoice(0))).status).toBe('ERROR'); +}); + +test('reclaim pays the rest to the creator and closes the link', async () => { + const r = rig(); + const c = await funded(r, { sat: 400, uses: 2 }); + const k1 = r.svc.params(c.id).k1; + await r.svc.callback(c.id, k1, r.invoice(400)); + await sleep(5); + await expect(r.svc.reclaim(c.id, 'someone-else', r.invoice(400, OUR))).rejects.toThrow('not your link'); + const out = await r.svc.reclaim(c.id, 'me', r.invoice(400, OUR)); + expect(out).toMatchObject({ status: 'closed', remainingSat: 0, paid: true }); + expect(r.svc.params(c.id).status).toBe('ERROR'); +}); + +test('confirmFunded checks the invoice', async () => { + const r = rig(); + const c = await r.svc.create({ pubkey: 'me', sat: 10 }); + await expect(r.svc.confirmFunded(c.id, 'me')).rejects.toThrow('not paid'); + r.invoices[c.paymentHash].status = 'paid'; + 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 +}); -- cgit v1.2.3