diff options
| author | Adam Soltys <[email protected]> | 2026-11-25 09:25:18 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-11-25 09:25:18 -0700 |
| commit | 6d5f69a23b8e52513825465a06911d67702edec3 (patch) | |
| tree | eab409c6d3394c37f9b8b790e7f3e7f8b9ac4301 /lib/payments.ts | |
| parent | 00799bb5ed16d3f2514ba68938e479110a1412a9 (diff) | |
| download | coinos-server-6d5f69a23b8e52513825465a06911d67702edec3.tar.gz coinos-server-6d5f69a23b8e52513825465a06911d67702edec3.zip | |
payments: hold Lightning deposits back from on-chain withdrawal
While hold:enabled is set, Lightning deposits above a daily free allowance
are held: they can still be spent over Lightning or sent internally, but not
withdrawn on-chain or over Lightning into our own on-chain liquidity. The
check and release run inside the atomic debit script, internal transfers
carry the hold to the receiver, and old holds expire via scripts/holds.ts.
The listener notes which peer each deposit arrived from for review.
sendOnchain now refuses frozen accounts before building the transaction or
locking its inputs, so a frozen account retrying withdrawals cannot hold
hot-wallet UTXOs and make other sends fail with locked outputs.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VMan6SEnsbshZrUDtTsxAX
Diffstat (limited to 'lib/payments.ts')
| -rw-r--r-- | lib/payments.ts | 117 |
1 files changed, 98 insertions, 19 deletions
diff --git a/lib/payments.ts b/lib/payments.ts index a745b7b3..59c6d397 100644 --- a/lib/payments.ts +++ b/lib/payments.ts @@ -42,6 +42,7 @@ import { } from "$lib/utils"; import { callWebhook } from "$lib/webhooks"; import { maybeForwardToV3, retryV3Forwards } from "$lib/v3forward"; +import { addHold, heldMessage, holdAllowance, holdKey, isExitNode } from "$lib/hold"; import changeid from "$lib/changeid"; import rpc from "@coinos/rpc"; import { bech32 } from "bech32"; @@ -104,6 +105,13 @@ const { URL } = process.env; const dust = 547; +// Freeze matches on EITHER the current username OR the uid. The uid never +// changes, so renaming the account can't shake the freeze — add the uid to the +// `blacklist` set to freeze a compromised account durably. +export const isBlacklisted = async (user) => + (await db.sIsMember("blacklist", user?.username?.toLowerCase().trim())) || + (!!user?.id && (await db.sIsMember("blacklist", user.id))); + export const debit = async ({ aid = undefined, hash, @@ -116,6 +124,9 @@ export const debit = async ({ // a v3 bridge forward (lib/v3forward.ts) costs routing only exempt = false, maxTotal = undefined, + // a Lightning send that lands in our own on-chain liquidity (see + // isExitNode), which deposit holds treat like an on-chain withdrawal + exitNode = false, }) => { amount = Number.parseInt(amount); @@ -123,13 +134,7 @@ export const debit = async ({ "whitelist", user?.username?.toLowerCase().trim(), ); - - // Blacklist (freeze) matches on EITHER the current username OR the uid. The - // uid never changes, so renaming the account can't shake the freeze — add the - // uid to the `blacklist` set to freeze a compromised account durably. - const blacklisted = - (await db.sIsMember("blacklist", user?.username?.toLowerCase().trim())) || - (!!user?.id && (await db.sIsMember("blacklist", user.id))); + const blacklisted = await isBlacklisted(user); if (hash && await db.sIsMember("blocked_addresses", hash)) { err(`SECURITY: blocked send to ${hash} by ${user.username}`); @@ -266,18 +271,44 @@ export const debit = async ({ const frozenBalance = !blacklisted || whitelisted ? 0 : await g(`balance:${uid}`); - ourfee = await db.debit( - `balance:${aid}`, - `credit:${creditType}:${aid !== uid ? 0 : uid}`, - t(user).insufficientFunds, - amount || 0, - tip || 0, - fee || 0, - ourfee || 0, - frozenBalance || 0, - ); + // Deposit hold: held sats can't leave on-chain (or into our own on-chain + // liquidity over Lightning). v3 bridge forwards and whitelisted accounts are + // not restricted. + const onchain = + !exempt && + !whitelisted && + ([PaymentType.bitcoin, PaymentType.liquid].includes(type) || exitNode) && + !(await db.sIsMember("hold:exempt", aid)); - if (ourfee.err) fail(ourfee.err); + let heldUsed = 0; + let r: any; + try { + r = await db.debit( + `balance:${aid}`, + `credit:${creditType}:${aid !== uid ? 0 : uid}`, + t(user).insufficientFunds, + amount || 0, + tip || 0, + fee || 0, + ourfee || 0, + frozenBalance || 0, + holdKey(aid), + onchain ? 1 : 0, + ); + } catch (e: any) { + r = { err: e?.message }; + } + if (r?.err) { + const m = String(r.err).match(/HELD:(\d+):(\d+)/); + if (m) { + const n = quiet(`block:${aid}:held`, 5 * 60 * 1000); + if (n !== null) warn("Blocking", user.username, amount, hash, aid, type, "held", m[1], suppressed(n)); + fail(heldMessage(Number(m[1]), Number(m[2]))); + } + fail(r.err); + } + if (Array.isArray(r)) [ourfee, heldUsed] = r.map(Number); + else ourfee = r; // Defense-in-depth: the DEBIT lua rejects overdrafts, so a negative balance // here means the invariant was violated by a mismatched input or a non-lua @@ -314,6 +345,7 @@ export const debit = async ({ type, ref, tip, + held: heldUsed || undefined, created: Date.now(), }; @@ -342,8 +374,18 @@ export const credit = async ({ payment_hash = undefined, created = undefined, tip = undefined, + // held sats the sender of an internal transfer spent (debit's p.held) + held = 0, + // where a Lightning deposit came from, for the hold review log + holdNote = undefined, }) => { amount = Number.parseInt(amount) || 0; + // type drives the one-time credit guards below; anything but a known + // string (e.g. ["bitcoin"] from a request body) would skip them. + if (!Object.values(PaymentType).includes(type as any)) { + warn("credit with invalid type", JSON.stringify(type), hash, amount, ref); + return; + } // Kill switch (see routes/payments.ts confirm): no Liquid credits at all // while `liquid:deposits:disabled` is set. @@ -528,6 +570,23 @@ export const credit = async ({ ); } + // Deposit hold: Lightning deposits, and internal transfers of sats that + // were themselves held, can't be withdrawn on-chain until reviewed. + const holdExempt = await db.sIsMember("hold:exempt", aid || uid); + const holdAmt = holdExempt + ? 0 + : [PaymentType.lightning, PaymentType.bolt12].includes(type) + ? ((await g("hold:enabled")) ? amount - (await holdAllowance(aid || uid, amount)) : 0) + : type === PaymentType.internal + ? Math.min(Number(held) || 0, amount) + : 0; + if (holdAmt > 0) + addHold(m, aid || uid, holdAmt, { + type, + pid: p.id, + from: holdNote || (type === PaymentType.internal ? `internal from ${ref}` : undefined), + }); + await m.set(`invoice:${inv.id}`, JSON.stringify(inv)) .set(`payment:${p.id}`, JSON.stringify(p)) .lPush(`${aid || uid}:payments`, p.id) @@ -669,6 +728,22 @@ const inflight = {}; export const sendOnchain = async (params) => { let { aid, hex, rate, user, signed } = params; aid = await requireAccount({ aid, user }); + + // A frozen account's debit is going to fail anyway, but only after we've + // built the tx and locked its inputs. Frozen throwaways retry every few + // seconds, so each attempt holds hot-wallet UTXOs and legit withdrawals fail + // with "output already locked". Refuse before touching the wallet; the + // message matches what debit() would have said. + if ( + (await isBlacklisted(user)) && + !(await db.sIsMember("whitelist", user?.username?.toLowerCase().trim())) + ) { + const n = quiet(`block:${user.id}:frozen-onchain`, 5 * 60 * 1000); + if (n !== null) + warn("Blocking frozen on-chain send", user.username, user.id, suppressed(n)); + fail(`${t(user).insufficientFunds} ⚡️0`); + } + const supplied = !!hex; if (!hex) ({ hex } = await build(params)); @@ -896,6 +971,7 @@ export const sendKeysend = async ({ user, type: PaymentType.lightning, maxTotal, + exitNode: await isExitNode(pubkey), }); let outcome = "unknown"; @@ -1124,6 +1200,7 @@ export const sendLightning = async ({ type: PaymentType.lightning, maxTotal, exempt, + exitNode: await isExitNode(payee), }); await db.sAdd("pending", pr); @@ -1286,7 +1363,7 @@ export const sendInternal = async ({ const { hash } = invoice; const p = await debit({ hash, amount, memo, user: sender, maxTotal }); - await credit({ hash, amount, memo, ref: sender.id, tip: p.tip }); + await credit({ hash, amount, memo, ref: sender.id, tip: p.tip, held: p.held }); if (invoice.memo?.includes("9734")) { const { invoices } = await ln.listinvoices({ invstring: hash }); @@ -1649,6 +1726,8 @@ const reverse = async (p) => { credit, p.hash, ); + // give back any deposit hold the send released + if (p.held > 0) await db.incrBy(holdKey(p.aid || p.uid), p.held); warn("reversed", p.id); }; |
