From 6d5f69a23b8e52513825465a06911d67702edec3 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Wed, 25 Nov 2026 09:25:18 -0700 Subject: 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 Claude-Session: https://claude.ai/code/session_01VMan6SEnsbshZrUDtTsxAX --- scripts/holds.ts | 246 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 246 insertions(+) create mode 100644 scripts/holds.ts (limited to 'scripts/holds.ts') diff --git a/scripts/holds.ts b/scripts/holds.ts new file mode 100644 index 00000000..3de04a09 --- /dev/null +++ b/scripts/holds.ts @@ -0,0 +1,246 @@ +// Review and lift deposit holds (lib/hold.ts). +// +// bun scripts/holds.ts list accounts with held sats +// bun scripts/holds.ts show hold log for one account +// bun scripts/holds.ts lift [sats] lift all (or part) of a hold +// bun scripts/holds.ts set set a hold by hand +// bun scripts/holds.ts backfill hold Lightning deposits since then +// bun scripts/holds.ts expire [--dry] release holds older than hold:expire_hours +// bun scripts/holds.ts on|off start/stop holding new deposits +// +// Run inside the app container: docker exec -w /home/bun/app app bun scripts/holds.ts +import { db } from "$lib/db"; +import { HOLD_EXPIRE_HOURS, holdKey, logHold } from "$lib/hold"; +import ln from "$lib/ln"; + +const [cmd = "list", arg, arg2] = process.argv.slice(2); +const get = async (k: string) => { + const v = await db.get(k); + try { return v ? JSON.parse(v) : null; } catch { return v; } +}; +const uidOf = async (name: string) => { + if (/^[0-9a-f-]{36}$/.test(name)) return name; + const id = await get(`user:${name.toLowerCase()}`); + if (!id) throw new Error(`no user ${name}`); + return id; +}; +const userOf = async (id: string) => (await get(`user:${id}`)) || {}; +const frozen = async (id: string, u: any) => + (await db.sIsMember("blacklist", id)) || (!!u.username && (await db.sIsMember("blacklist", u.username.toLowerCase()))); +const sats = (n: number) => n.toLocaleString("en-US"); +const ago = (t: number) => { + const m = Math.round((Date.now() - t) / 60000); + return m < 60 ? `${m}m` : m < 2880 ? `${Math.round(m / 60)}h` : `${Math.round(m / 1440)}d`; +}; + +async function list() { + const ids = await db.sMembers("held"); + const rows: any[] = []; + for (const id of ids) { + const held = Number(await db.get(holdKey(id))) || 0; + if (held <= 0) continue; + const u = await userOf(id); + const log = (await db.lRange(`held:log:${id}`, 0, 49)).map((l) => JSON.parse(l)); + const sources = [...new Set(log.filter((e) => e.amount > 0 && e.from).map((e) => e.from))]; + rows.push({ + held, + user: u.username || id, + balance: Number(await db.get(`balance:${id}`)) || 0, + frozen: await frozen(id, u), + last: log[0]?.at, + watched: sources.some((s) => String(s).includes("(watched)")), + sources: sources.slice(0, 3).join("; "), + }); + } + rows.sort((a, b) => b.held - a.held); + const total = rows.reduce((a, r) => a + r.held, 0); + console.log(`holds ${(await db.get("hold:enabled")) ? "ON" : "OFF"} · ${rows.length} accounts · ${sats(total)} sats held · ! = came via a watched peer\n`); + console.log("held".padStart(12), "balance".padStart(12), " ", "user".padEnd(24), "last".padStart(5), " sources"); + for (const r of rows) + console.log( + sats(r.held).padStart(12), + sats(r.balance).padStart(12), + `${r.watched ? "!" : " "}${r.frozen ? "F" : " "}`, + String(r.user).slice(0, 24).padEnd(24), + (r.last ? ago(r.last) : "").padStart(5), + "", + r.sources, + ); +} + +async function show(name: string) { + const id = await uidOf(name); + const u = await userOf(id); + console.log(`${u.username} ${id}`); + console.log(`held ${sats(Number(await db.get(holdKey(id))) || 0)} · balance ${sats(Number(await db.get(`balance:${id}`)) || 0)}${(await frozen(id, u)) ? " · FROZEN" : ""}\n`); + for (const l of await db.lRange(`held:log:${id}`, 0, -1)) { + const e = JSON.parse(l); + console.log(new Date(e.at).toISOString().slice(0, 19), String(e.amount ?? "").padStart(10), e.type || e.action || "", e.from || e.note || ""); + } +} + +async function lift(name: string, amount?: string) { + const id = await uidOf(name); + const held = Number(await db.get(holdKey(id))) || 0; + const n = amount ? Math.min(held, Number.parseInt(amount)) : held; + if (!(n > 0)) return console.log("nothing held"); + const left = await db.decrBy(holdKey(id), n); + if (left <= 0) await db.multi().del(holdKey(id)).sRem("held", id).exec(); + await logHold(id, { amount: -n, action: "lift", note: "lifted by operator" }); + console.log(`lifted ${sats(n)}, ${sats(Math.max(0, left))} still held`); +} + +async function set(name: string, amount: string) { + const id = await uidOf(name); + const n = Math.max(0, Number.parseInt(amount) || 0); + await db.multi().set(holdKey(id), n).sAdd("held", id).exec(); + await logHold(id, { amount: n, action: "set", note: "set by operator" }); + console.log(`held set to ${sats(n)}`); +} + +// Hold Lightning deposits received since `since`, less what each account has +// since sent over Lightning or internally (held sats are spent first), capped +// at the current balance. Internal receipts count as held when the sender +// itself received Lightning in the window. Receipts come from cl's paid +// invoices (credit() doesn't index receipts globally); spends from the +// global `payments` list, which holds debits. +async function backfill(since: string) { + const cutoff = Date.parse(since); + if (!cutoff) throw new Error("backfill needs an ISO time"); + const recv = new Map(); + const spent = new Map(); + const internalIn: [string, string, number][] = []; + const add = (m: Map, k: string, v: number) => m.set(k, (m.get(k) || 0) + v); + + // which peer each payment hash came in from, for the review log + const { channels } = await ln.listpeerchannels(); + const scidPeer = new Map(); + for (const c of channels || []) if (c.short_channel_id) scidPeer.set(c.short_channel_id, c.peer_id); + const watched = new Set(await db.sMembers("freeze:inbound_peers")); + const alias = new Map(); + const name = async (id: string) => { + if (!alias.has(id)) { + const { nodes } = await ln.listnodes(id).catch(() => ({ nodes: [] })); + alias.set(id, `${nodes?.[0]?.alias || id.slice(0, 16)}${watched.has(id) ? " (watched)" : ""}`); + } + return alias.get(id)!; + }; + const hashPeers = new Map>(); + const { created } = await ln.call("wait", { subsystem: "htlcs", indexname: "created", nextvalue: 0 }); + for (let start = Math.max(1, Number(created) - 200_000); ; start += 5000) { + const { htlcs } = await ln.call("listhtlcs", { index: "created", start, limit: 5000 }); + for (const h of htlcs || []) { + if (h.direction !== "in" || !scidPeer.has(h.short_channel_id)) continue; + if (!hashPeers.has(h.payment_hash)) hashPeers.set(h.payment_hash, new Set()); + hashPeers.get(h.payment_hash)!.add(scidPeer.get(h.short_channel_id)!); + } + if (!htlcs || htlcs.length < 5000) break; + } + const via = new Map>(); + + const { updated } = await ln.call("wait", { subsystem: "invoices", indexname: "updated", nextvalue: 0 }); + for (let start = Math.max(1, Number(updated) - 300_000); ; start += 5000) { + const { invoices } = await ln.call("listinvoices", { index: "updated", start, limit: 5000 }); + for (const i of invoices || []) { + if (i.status !== "paid" || i.paid_at * 1000 < cutoff) continue; + const pid = await get(`payment:${i.bolt11 || i.bolt12}`); + const p = pid && (await get(`payment:${pid}`)); + if (p?.amount > 0) { + const acct = p.aid || p.uid; + add(recv, acct, p.amount + (p.tip || 0)); + if (!via.has(acct)) via.set(acct, new Map()); + for (const peer of hashPeers.get(i.payment_hash) || []) { + const n = await name(peer); + via.get(acct)!.set(n, (via.get(acct)!.get(n) || 0) + p.amount + (p.tip || 0)); + } + } + } + if (!invoices || invoices.length < 5000) break; + } + + let done = false; + for (let i = 0; !done; i += 1000) { + const ids = await db.lRange("payments", i, i + 999); + if (!ids.length) break; + for (const pid of ids) { + const p = await get(`payment:${pid}`); + if (!p?.created) continue; + if (p.created < cutoff) { done = true; break; } + if (p.amount >= 0 || !["lightning", "bolt12", "internal"].includes(p.type)) continue; + const from = p.aid || p.uid; + add(spent, from, -p.amount + (p.fee || 0) + (p.ourfee || 0) + (p.tip || 0)); + if (p.type === "internal" && p.iid) { + const inv = await get(`invoice:${p.iid}`); + const to = inv?.aid || inv?.uid; + if (to) internalIn.push([to, from, -p.amount + (p.tip || 0)]); + } + } + } + for (const [to, from, amt] of internalIn) if (recv.has(from)) add(recv, to, amt); + + let total = 0; + let count = 0; + for (const [id, r] of recv) { + const bal = Number(await db.get(`balance:${id}`)) || 0; + const n = Math.min(bal, Math.max(0, r - (spent.get(id) || 0))); + if (n <= 0) continue; + const cur = Number(await db.get(holdKey(id))) || 0; + if (n <= cur) continue; + await db.multi().set(holdKey(id), n).sAdd("held", id).exec(); + const from = [...(via.get(id) || new Map()).entries()].sort((a, b) => b[1] - a[1]).map(([k, v]) => `via ${k} ${v}`).join(", "); + await logHold(id, { amount: n - cur, action: "backfill", from: from || "internal", note: `Lightning deposits since ${since}` }); + total += n - cur; + count++; + } + console.log(`backfilled ${count} accounts, ${sats(total)} sats held`); +} + +// Release the part of each hold that's older than the expiry window: an +// account keeps held only what was added to its hold inside the window +// (from its hold log). Frozen accounts keep their holds. If the log was +// trimmed inside the window we can't tell how much is recent, so we skip. +async function expire(dry: boolean) { + const hours = Number((await db.get("hold:expire_hours")) ?? HOLD_EXPIRE_HOURS); + if (!(hours > 0)) return console.log("expiry off"); + const since = Date.now() - hours * 3600_000; + let total = 0; + let count = 0; + for (const id of await db.sMembers("held")) { + const held = Number(await db.get(holdKey(id))) || 0; + if (held <= 0) { + if (!dry) await db.multi().del(holdKey(id)).sRem("held", id).exec(); + continue; + } + const u = await userOf(id); + if (await frozen(id, u)) continue; + const log = (await db.lRange(`held:log:${id}`, 0, -1)).map((l) => JSON.parse(l)); + if (log.length >= 100 && log[log.length - 1].at >= since) continue; + const recent = log.filter((e) => e.at >= since && e.amount > 0).reduce((a, e) => a + e.amount, 0); + const n = held - recent; + if (n <= 0) continue; + total += n; + count++; + if (dry) { console.log(`${String(u.username || id).padEnd(24)} release ${sats(n)} of ${sats(held)}`); continue; } + const left = await db.decrBy(holdKey(id), n); + if (left <= 0) await db.multi().del(holdKey(id)).sRem("held", id).exec(); + await logHold(id, { amount: -n, action: "expire", note: `older than ${hours}h` }); + } + console.log(`${dry ? "would release" : "released"} ${sats(total)} sats on ${count} accounts`); +} + +try { + if (cmd === "list") await list(); + else if (cmd === "show") await show(arg); + else if (cmd === "lift") await lift(arg, arg2); + else if (cmd === "expire") await expire(arg === "--dry"); + else if (cmd === "set") await set(arg, arg2); + else if (cmd === "backfill") await backfill(arg); + else if (cmd === "exempt") { const id = await uidOf(arg); await db.sAdd("hold:exempt", id); await lift(arg); console.log(`${arg} exempt from holds`); } + else if (cmd === "unexempt") { const id = await uidOf(arg); await db.sRem("hold:exempt", id); console.log(`${arg} no longer exempt`); } + else if (cmd === "on") { await db.set("hold:enabled", "1"); console.log("holding new Lightning deposits"); } + else if (cmd === "off") { await db.del("hold:enabled"); console.log("no longer holding new deposits (existing holds stay)"); } + else console.log("usage: holds.ts [list|show |lift [sats]|set |backfill |on|off]"); +} catch (e: any) { + console.error(e.message); +} +process.exit(0); -- cgit v1.2.3