diff options
| author | Adam Soltys <[email protected]> | 2026-06-14 12:33:29 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-06-17 07:47:45 -0700 |
| commit | 17a4461d8497f4f0f89871bb80604d449487a4c3 (patch) | |
| tree | 1a66a54249afad5f5ec774b3912f1e0657df7bf1 | |
| parent | 9595de876df5264846227f6f80a7306df9154278 (diff) | |
| download | coinos-server-17a4461d8497f4f0f89871bb80604d449487a4c3.tar.gz coinos-server-17a4461d8497f4f0f89871bb80604d449487a4c3.zip | |
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> (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 <[email protected]>
| -rw-r--r-- | index.ts | 2 | ||||
| -rw-r--r-- | lib/payments.ts | 15 |
2 files changed, 16 insertions, 1 deletions
@@ -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); |
