aboutsummaryrefslogtreecommitdiffstats
path: root/lib/lightning.ts
blob: 609fad41f38cd05648240cf63dc3c8f440a5faa4 (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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import { db, g, s } from "$lib/db";
import ln, { lnListen, LightningUnavailableError } from "$lib/ln";
import { err, l, warn } from "$lib/logging";
import { handleZap } from "$lib/nostr";
import { credit } from "$lib/payments";
import { PaymentType } from "$lib/types";
import { getInvoice, getPayment, getUser } from "$lib/utils";

const LISTENER_RETRY_DELAY = 5000; // 5 seconds
const MAX_LISTENER_RETRIES = 10;
// If the listener has been blocked in waitanyinvoice this long without the call
// returning, AND cl is actually reachable, treat the socket as a zombie and
// force-recycle it. Sized well above normal quiet periods (receives are sparse
// but cl still responds to getinfo) so it only fires on a genuine stall.
const LISTENER_STALL_MS = 5 * 60 * 1000; // 5 minutes
let listenerRetries = 0;
let listenerActive = false;
let lastPayTime = Date.now();
// When the current waitanyinvoice call started — used by the watchdog to tell a
// legitimately-quiet listener (recently armed) from a zombie (armed long ago,
// never returned). Reset every time we (re)enter the wait.
let waitStartedAt = Date.now();
// Incremented whenever the watchdog force-recycles a stalled listener. The
// blocked invocation captures the epoch at entry; if it later unblocks (the
// reset makes its waitanyinvoice reject) it sees the epoch has moved and bows
// out instead of re-arming, so we never run two listeners concurrently.
let listenerEpoch = 0;

// Recover the invoice listener the instant its long-poll socket dies (e.g. a cl
// restart) instead of waiting up to LISTENER_STALL_MS for the stall watchdog.
// waitanyinvoice is a NO_TIMEOUT long-poll, so a dead socket leaves it blocked
// forever with no error — this onDrop signal is the only prompt trigger. Bump the
// epoch so the (possibly forever-blocked) old invocation bows out, mark inactive,
// and re-arm. If cl is still down, ensure()'s backoff + the retry loop below wait
// it out. Debounced so a burst of socket errors recycles once.
let recycleArmed = false;
(lnListen as any).onDrop?.(() => {
  if (!listenerActive || recycleArmed) return;
  recycleArmed = true;
  listenerEpoch++;
  listenerActive = false;
  warn("lightning listener: listen socket dropped — recycling immediately");
  setTimeout(() => {
    recycleArmed = false;
    listenForLightning();
  }, 100);
});

export async function listenForLightning() {
  if (listenerActive) {
    warn("lightning listener: already active, skipping duplicate call");
    return;
  }

  listenerActive = true;
  waitStartedAt = Date.now();
  const myEpoch = listenerEpoch;

  try {
    const payIndex = (await g("pay_index")) || 0;
    // l(`lightning listener: waiting for invoice (pay_index=${payIndex})`);

    const inv = await lnListen.waitanyinvoice(payIndex);
    const {
      label,
      local_offer_id,
      bolt11,
      bolt12,
      description,
      invreq_payer_note,
      pay_index,
      payment_hash,
      amount_received_msat,
      payment_preimage: preimage,
    } = inv;

    // If the watchdog recycled the listener while this call was blocked, a new
    // listener now owns the stream. Bail without advancing pay_index or
    // processing — the new listener's waitanyinvoice(payIndex) will return this
    // same invoice and handle it, so nothing is lost or double-credited.
    if (myEpoch !== listenerEpoch) return;

    await s("pay_index", pay_index);
    lastPayTime = Date.now();

    // Reset retry counter on successful receive
    if (listenerRetries > 0) {
      l(`lightning listener: recovered after ${listenerRetries} retries`);
    }
    listenerRetries = 0;
    listenerActive = false;

    // Schedule next listen
    setTimeout(listenForLightning);

    const received = Math.round(amount_received_msat / 1000);

    try {
      if (!preimage) return;

      // The mint (nutshell) shares this cl node, so waitanyinvoice also fires for
      // mint-quote invoices. Those are owned by the mint (it issues ecash for
      // them) and must NOT credit a coinos balance — otherwise a single payment
      // is credited twice (coinos balance + ecash = double-mint exploit). The
      // mint labels its invoices "lbl<random>"; coinos labels are
      // "<uuid> <username> <ts>". Never credit a mint-owned invoice.
      if (typeof label === "string" && label.startsWith("lbl"))
        return warn("skipping mint-owned invoice (not a coinos deposit)", label, bolt11);

      const invoice = await getInvoice(bolt11 ?? local_offer_id ?? bolt12);
      if (!invoice) return warn("received lightning with no invoice", bolt11);

      const p = await getPayment(bolt11 || bolt12);
      if (p) return warn("already processed", bolt11 || bolt12);

      if (invoice?.memo) {
        // A non-JSON description just means this isn't a zap (the common case) —
        // skip silently. Only a real kind-9734 zap request that fails to process
        // is worth a warning. (The old `!includes("Unexpected")` guard was V8's
        // parse-error wording; Bun's is "Unable to parse JSON string", so every
        // non-zap memo'd invoice slipped through and spammed this warning.)
        let zapreq;
        try { zapreq = JSON.parse(description); } catch { zapreq = null; }
        if (zapreq?.kind === 9734) {
          try {
            const { pubkey } = await getUser(invoice.uid);
            handleZap(inv, pubkey);
          } catch (e) {
            warn("failed to handle zap", e.message);
          }
        }
      }

      await credit({
        hash: bolt11 || bolt12,
        amount: received,
        // A bolt12 payer note (e.g. nostr:nip177:<zap-intent-id>) identifies
        // this specific payment; the offer's own memo is just its static label
        memo: invreq_payer_note || invoice.memo,
        ref: preimage,
        type: bolt12 ? PaymentType.bolt12 : PaymentType.lightning,
        payment_hash,
      });
    } catch (e) {
      err("problem receiving lightning payment", e.message);
    }
  } catch (e: any) {
    listenerActive = false;

    // If the watchdog already recycled us (its reset is what made this
    // waitanyinvoice reject), a fresh listener is running — don't retry or
    // re-arm here, or we'd run two listeners.
    if (myEpoch !== listenerEpoch) return;

    const errorCode = e?.code ?? e?.errno ?? "unknown";
    const errorMsg = e?.message ?? String(e);

    err(
      `lightning listener: error waiting for invoice`,
      `code=${errorCode}`,
      `error=${errorMsg}`
    );

    // A cl restart makes ensure() throw LightningUnavailableError until the socket
    // returns — expected, self-heals, and restarting the app can't fix a down cl.
    // So don't count it toward the process-exit escalation; just keep retrying and
    // resume within LISTENER_RETRY_DELAY of cl coming back. Only genuine listener
    // errors climb toward a container restart.
    if (e instanceof LightningUnavailableError) {
      err("lightning listener: RPC socket unavailable");
      warn(`lightning listener: cl unavailable, retrying in ${LISTENER_RETRY_DELAY / 1000}s`);
      setTimeout(listenForLightning, LISTENER_RETRY_DELAY);
      return;
    }

    listenerRetries++;

    if (listenerRetries >= MAX_LISTENER_RETRIES) {
      err(
        `lightning listener: ${MAX_LISTENER_RETRIES} consecutive failures, ` +
          `last error: ${errorMsg}`
      );
      err("lightning listener: exiting process to trigger container restart");

      setTimeout(() => {
        process.exit(1);
      }, 1000);
      return;
    }

    warn(
      `lightning listener: retry ${listenerRetries}/${MAX_LISTENER_RETRIES} ` +
        `in ${LISTENER_RETRY_DELAY / 1000}s`
    );
    setTimeout(listenForLightning, LISTENER_RETRY_DELAY);
  }
}

export async function ensureListenerAlive() {
  // Case 1: listener fell over (threw, or never armed) — just restart it.
  if (!listenerActive) {
    warn("lightning listener: not active, restarting");
    listenForLightning();
    return;
  }

  // Case 2: listener claims active. A long-blocked waitanyinvoice is NORMAL
  // during quiet periods — the only way to tell a zombie socket from a healthy
  // idle wait is whether cl actually has a paid invoice the listener is failing
  // to pick up. (The original "blocked > 5min while cl alive" check false-fired
  // every few minutes during normal quiet stretches and needlessly recycled the
  // socket — see 2026-06-07.) So: only act if there's a real backlog.
  if (Date.now() - waitStartedAt < LISTENER_STALL_MS) return;

  // Probe for a backlog: ask cl (on the MAIN socket, not the wedged listen one)
  // whether a paid invoice exists at or after the app's stored pay_index, using
  // waitanyinvoice with a short server-side timeout so it returns fast either
  // way. If it returns an invoice, the listener's socket is stuck while real
  // payments are waiting -> genuine zombie, recycle. If it times out (no waiting
  // invoice), the listener is simply idle and healthy -> leave it alone.
  let backlog = false;
  try {
    const payIndex = (await g("pay_index")) || 0;
    const probe = await ln.waitanyinvoice(payIndex, 2); // 2s server-side timeout
    if (probe?.pay_index) backlog = true;
  } catch (e: any) {
    // CLN returns an error (code 904) on timeout with no waiting invoice — that
    // means NO backlog (healthy). Any other error: stay conservative, don't
    // recycle on ambiguous signals.
    backlog = false;
  }
  if (!backlog) return; // healthy idle wait, not a zombie.

  err(
    `lightning listener: backlog detected while listener blocked ${Math.round(
      (Date.now() - waitStartedAt) / 1000,
    )}s — recycling listen socket`,
  );
  // Bump the epoch first so the wedged invocation bows out when its
  // waitanyinvoice rejects, then drop the socket and re-arm a fresh listener.
  listenerEpoch++;
  try {
    (lnListen as any).reset?.();
  } catch (_) {}
  listenerActive = false;
  setTimeout(listenForLightning);
}

export async function replay(index) {
  const inv = await lnListen.waitanyinvoice(index - 1);
  const {
    local_offer_id,
    bolt11,
    bolt12,
    description,
    invreq_payer_note,
    amount_received_msat,
    payment_preimage: preimage,
    paid_at,
  } = inv;

  const received = Math.round(amount_received_msat / 1000);

  try {
    if (!preimage) return;

    const invoice = await getInvoice(bolt11 ?? local_offer_id ?? bolt12);
    if (!invoice) return warn("received lightning with no invoice", bolt11);

    let p = await getPayment(bolt11 || bolt12);
    if (p) return warn("already processed", bolt11 || bolt12);

    if (invoice?.memo) {
      // Non-JSON description = not a zap (common case); skip silently. Only a
      // real kind-9734 zap request that fails processing warrants a warning.
      // (The old `!includes("Unexpected")` guard was V8 wording; Bun's parse
      // error is "Unable to parse JSON string", so non-zaps spammed the warning.)
      let zapreq;
      try { zapreq = JSON.parse(description); } catch { zapreq = null; }
      if (zapreq?.kind === 9734) {
        try {
          const { pubkey } = await getUser(invoice.uid);
          handleZap(inv, pubkey);
        } catch (e) {
          warn("failed to handle zap", e.message);
        }
      }
    }

    p = await credit({
      hash: bolt11 || bolt12,
      amount: received,
      memo: invreq_payer_note || invoice.memo,
      ref: preimage,
      type: bolt12 ? PaymentType.bolt12 : PaymentType.lightning,
      created: paid_at ? paid_at * 1000 : undefined,
    });

    return p;
  } catch (e) {
    err("problem receiving lightning payment", e.message);
  }
}

export const fixBolt12 = async (_, res) => {
  for await (const k of db.scanIterator({ MATCH: "payment:*" })) {
    const p = await g(k);
    if (p.type === "bolt12") {
      console.log(k);
      const { invoices } = await ln.listinvoices({ invstring: p.hash });
      const { local_offer_id } = invoices[0];
      const oid = await g(`payment:${local_offer_id}`);
      const op = await g(`payment:${oid}`);
      if (op) {
        db.del(`payment:${oid}`);
        db.del(`payment:${local_offer_id}`);
        db.decrBy(`balance:${op.uid}`, op.amount);
      }
    }
  }

  res.send({});
};