From 17a4461d8497f4f0f89871bb80604d449487a4c3 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Sun, 14 Jun 2026 12:33:29 -0700 Subject: payments: guard /replay double-credit race with SET NX idempotency Port of master ca28c19f to the staging stack. The getPayment() pre-check in the lightning listener/replay isn't atomic, so concurrent re-credits of the same settlement each ran the credit path. Claim each lightning/bolt12 settlement with an atomic SET NX on credited: (ref = preimage) and bail if already claimed. Guard sits before tbCredit and the pointer writes so a duplicate bails cleanly. Also disable the /replay route that triggered it. Co-Authored-By: Claude Opus 4.8 --- index.ts | 2 +- lib/payments.ts | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/index.ts b/index.ts index 98a9668e..bb944f41 100644 --- a/index.ts +++ b/index.ts @@ -241,7 +241,7 @@ app.post("/melt", auth, ecash.melt); app.post("/ecash/:id", ecash.receive); app.get("/replay/:index", (c) => { - replay(c.req.param("index")); + // replay(c.req.param("index")); return c.json({}); }); diff --git a/lib/payments.ts b/lib/payments.ts index cf6a344f..0a27143e 100644 --- a/lib/payments.ts +++ b/lib/payments.ts @@ -350,6 +350,21 @@ export const credit = async ({ inv.settled = Date.now(); } + // 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 credit 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 tbCredit. `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; + } + } + let balanceKey = "balance"; if ([PaymentType.bitcoin, PaymentType.liquid].includes(type)) { const [txid, vout] = ref.split(":").slice(-2); -- cgit v1.2.3