From ca28c19fe26d3f81ae62d2d3f0dc8b175849a9a8 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Sat, 13 Jun 2026 14:21:44 -0700 Subject: payments: guard /replay double-credit race with SET NX idempotency getPayment() pre-check in the lightning listener/replay isn't atomic, so concurrent re-credits of the same settlement each ran incrBy. Claim each lightning/bolt12 settlement with an atomic SET NX on credited: (ref = preimage) and bail if already claimed. Also disable the /replay route that triggered it. Co-Authored-By: Claude Opus 4.8 (1M context) --- index.ts | 2 +- lib/payments.ts | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/index.ts b/index.ts index 793bf2f8..3b90d32b 100644 --- a/index.ts +++ b/index.ts @@ -187,7 +187,7 @@ app.post("/melt", auth, ecash.melt); app.post("/ecash/:id", ecash.receive); app.get("/replay/:index", (req, res) => { - replay(req.params.index); + // replay(req.params.index); res.send({}); }); diff --git a/lib/payments.ts b/lib/payments.ts index aeebcc48..30403b6c 100644 --- a/lib/payments.ts +++ b/lib/payments.ts @@ -342,6 +342,21 @@ export const credit = async ({ await sa(`payment:${hash}`, id); } + // Idempotency guard for external settlements. The getPayment() pre-check in + // the lightning listener/replay is not atomic: N concurrent re-credits of the + // same payment all read it as uncredited before any writes the pointer, so + // each runs the incrBy below — the /replay double-credit race. SET NX is + // atomic, so only the first caller claims the settlement and credits; the rest + // bail here, before the incrBy. `ref` is the lightning preimage, unique per + // settlement; internal/fund/ecash pass ref=uid and are exempt. + if ([PaymentType.lightning, PaymentType.bolt12].includes(type) && ref) { + const claimed = await db.set(`credited:${ref}`, id, { NX: true }); + if (!claimed) { + warn("duplicate credit blocked", hash, ref); + return; + } + } + const m = await db.multi(); let creditType = type; -- cgit v1.2.3