aboutsummaryrefslogtreecommitdiffstats
path: root/names/withdraw.js
blob: b3c9bb8360cdf992fb9a89dded4648cd3ac9d416 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// 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);

// 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));
  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, ...(c.tries > 1 ? { tries: c.tries } : {}) })),
  });

  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 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
    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');
      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' || 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') {
          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]) };
}