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 | |
| 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
| -rw-r--r-- | lib/db.ts | 25 | ||||
| -rw-r--r-- | lib/hold.ts | 70 | ||||
| -rw-r--r-- | lib/lightning.ts | 65 | ||||
| -rw-r--r-- | lib/payments.ts | 117 | ||||
| -rw-r--r-- | routes/shopify.ts | 49 | ||||
| -rw-r--r-- | scripts/holds.ts | 246 |
6 files changed, 501 insertions, 71 deletions
@@ -12,20 +12,39 @@ local tip = tonumber(ARGV[2]) local fee = tonumber(ARGV[3]) local ourfee = tonumber(ARGV[4]) local frozen = tonumber(ARGV[5]) +-- Optional deposit hold (see lib/hold.ts). Held sats can leave over Lightning +-- or internally but not on-chain; spending them releases the hold, and the +-- amount released is returned so the receiver of an internal send inherits it. +local heldKey = ARGV[6] +local onchain = ARGV[7] == '1' +local held = 0 +if heldKey and heldKey ~= '' then held = tonumber(redis.call('get', heldKey) or '0') end local balance = tonumber(redis.call('get', balanceKey) or '0') local credit = tonumber(redis.call('get', creditKey) or '0') local covered = math.min(credit, ourfee) ourfee = ourfee - covered +local total = amount + tip + fee + ourfee -if balance - frozen < amount + tip + fee + ourfee then - return {err = insufficientString .. ' ⚡️' .. balance - frozen .. ' / ' .. amount + tip + fee + ourfee} +if balance - frozen < total then + return {err = insufficientString .. ' ⚡️' .. balance - frozen .. ' / ' .. total} +end +if onchain and held > 0 and balance - math.max(frozen, held) < total then + return {err = 'HELD:' .. held .. ':' .. math.max(0, balance - math.max(frozen, held))} end redis.call('decrby', creditKey, tostring(math.floor(covered))) -redis.call('decrby', balanceKey, tostring(math.floor(amount + tip + fee + ourfee))) +redis.call('decrby', balanceKey, tostring(math.floor(total))) +if heldKey and heldKey ~= '' then + local used = 0 + if not onchain and held > 0 then + used = math.min(held, math.floor(total)) + redis.call('decrby', heldKey, tostring(used)) + end + return {ourfee, used} +end return ourfee `; diff --git a/lib/hold.ts b/lib/hold.ts new file mode 100644 index 00000000..9404d0c8 --- /dev/null +++ b/lib/hold.ts @@ -0,0 +1,70 @@ +// Deposit holds. +// +// While `hold:enabled` is set, every Lightning (and bolt12) deposit adds to +// the receiving account's `held:<id>`. Held sats can still be spent over +// Lightning or sent to another coinos account, but not withdrawn on-chain +// (bitcoin, liquid) or over Lightning into our own on-chain liquidity (the +// nodes in `hold:exit_nodes`). Spending held sats over Lightning releases +// that much of the hold. An internal transfer of held sats moves the hold to +// the receiver, so passing funds through a second account doesn't clear it. +// The check and the release happen inside the atomic debit script in +// lib/db.ts. A failed send that's reversed gets its hold back. +// +// The first `hold:free_sat` (default 50k) of Lightning deposits per account +// in any 24h aren't held at all, and holds older than `hold:expire_hours` +// (default 72h) are released by `holds.ts expire` (hourly cron) unless the +// account is frozen. Big recent deposits are what we want to look at; small +// ones were mostly false positives. +// +// Accounts with a hold are listed in the `held` set, and each account keeps a +// short log of what added to or lifted its hold (`held:log:<id>`). Review and +// lift holds with scripts/holds.ts. +import { db } from "$lib/db"; + +export const holdKey = (id: string) => `held:${id}`; +const LOG_MAX = 100; + +// Add to a hold inside the caller's MULTI so the balance and the hold change +// together. +export const addHold = (m: any, id: string, amount: number, entry: Record<string, any>) => { + m.incrBy(holdKey(id), amount) + .sAdd("held", id) + .lPush(`held:log:${id}`, JSON.stringify({ at: Date.now(), amount, ...entry })) + .lTrim(`held:log:${id}`, 0, LOG_MAX - 1); +}; + +export const HOLD_FREE_SAT = 50_000; +export const HOLD_EXPIRE_HOURS = 72; + +// How much of a Lightning deposit falls inside the account's daily free +// allowance. Counts the deposit against the allowance as a side effect. +export const holdAllowance = async (id: string, amount: number) => { + const cap = Number(await db.get("hold:free_sat") ?? HOLD_FREE_SAT); + if (!(cap > 0) || !(amount > 0)) return 0; + const k = `holdfree:${id}`; + const used = await db.incrBy(k, amount); + if (used === amount) await db.expire(k, 86400); + return Math.max(0, Math.min(amount, cap - (used - amount))); +}; + +export const logHold = async (id: string, entry: Record<string, any>) => { + await db + .multi() + .lPush(`held:log:${id}`, JSON.stringify({ at: Date.now(), ...entry })) + .lTrim(`held:log:${id}`, 0, LOG_MAX - 1) + .exec(); +}; + +// Lightning destinations that are really our own on-chain liquidity (the +// swap/Ark node). Cached briefly: it's checked on every Lightning send. +let exitNodes = { at: 0, set: new Set<string>() }; +export const isExitNode = async (pubkey?: string) => { + if (!pubkey) return false; + if (Date.now() - exitNodes.at > 60_000) + exitNodes = { at: Date.now(), set: new Set(await db.sMembers("hold:exit_nodes")) }; + return exitNodes.set.has(pubkey); +}; + +export const heldMessage = (held: number, available: number) => + `⚡️${held} of your balance came from recent Lightning deposits and can't be withdrawn on-chain right now. ` + + `You can still send it over Lightning. Available for on-chain withdrawal: ⚡️${available}.`; diff --git a/lib/lightning.ts b/lib/lightning.ts index 6c37ddf1..34c698cb 100644 --- a/lib/lightning.ts +++ b/lib/lightning.ts @@ -142,6 +142,15 @@ export async function listenForLightning() { } } + // Note which peer the deposit came in from, for reviewing deposit holds + // (lib/hold.ts). Peers in `freeze:inbound_peers` are flagged. + let holdNote; + try { + holdNote = await inboundNote(payment_hash); + } catch (e) { + warn("inbound peer lookup failed", payment_hash, e.message); + } + const paymentRequest = bolt11 || bolt12; await credit({ hash: paymentRequest, @@ -152,6 +161,7 @@ export async function listenForLightning() { ref: preimage, type: bolt12 ? PaymentType.bolt12 : PaymentType.lightning, payment_hash, + holdNote, }); // credit() may decline a duplicate idempotency claim. Only advance the @@ -402,3 +412,58 @@ export const fixBolt12 = async (_, res) => { res.send({}); }; + +// --- inbound peer lookup (see the listener) --- +// HTLCs are read incrementally by created index, so each lookup only fetches +// what arrived since the last one. +let htlcCursor = 0; +const inboundByHash = new Map<string, Set<string>>(); +let peers: { at: number; scid: Map<string, string>; watched: Set<string> } = { at: 0, scid: new Map(), watched: new Set() }; +const aliases = new Map<string, string>(); + +async function refreshPeers() { + if (Date.now() - peers.at < 60_000) return peers; + const { channels } = await ln.listpeerchannels(); + const scid = new Map<string, string>(); + for (const c of channels || []) if (c.short_channel_id) scid.set(c.short_channel_id, c.peer_id); + const watched = new Set<string>(await db.sMembers("freeze:inbound_peers")); + peers = { at: Date.now(), scid, watched }; + return peers; +} + +async function alias(id: string) { + if (!aliases.has(id)) { + try { + const { nodes } = await ln.listnodes(id); + aliases.set(id, nodes?.[0]?.alias || id.slice(0, 16)); + } catch { + return id.slice(0, 16); + } + } + return aliases.get(id)!; +} + +async function inboundNote(hash: string): Promise<string | undefined> { + if (!hash) return; + const { scid, watched } = await refreshPeers(); + if (!htlcCursor) { + const { created } = await ln.call("wait", { subsystem: "htlcs", indexname: "created", nextvalue: 0 }); + htlcCursor = Math.max(1, Number(created) - 5000); + } + for (;;) { + const { htlcs } = await ln.call("listhtlcs", { index: "created", start: htlcCursor, limit: 1000 }); + for (const h of htlcs || []) { + htlcCursor = Math.max(htlcCursor, Number(h.created_index) + 1); + if (h.direction !== "in") continue; + if (!inboundByHash.has(h.payment_hash)) inboundByHash.set(h.payment_hash, new Set()); + inboundByHash.get(h.payment_hash)!.add(h.short_channel_id); + } + if (!htlcs || htlcs.length < 1000) break; + } + if (inboundByHash.size > 50_000) + for (const k of [...inboundByHash.keys()].slice(0, 25_000)) inboundByHash.delete(k); + const ids = [...new Set([...(inboundByHash.get(hash) || [])].map((c) => scid.get(c)).filter(Boolean))] as string[]; + if (!ids.length) return; + const names = await Promise.all(ids.map(async (id) => `${await alias(id)}${watched.has(id) ? " (watched)" : ""}`)); + return `via ${names.join(", ")}`; +} 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); }; diff --git a/routes/shopify.ts b/routes/shopify.ts deleted file mode 100644 index ff601963..00000000 --- a/routes/shopify.ts +++ /dev/null @@ -1,49 +0,0 @@ -import got from "got"; -import { g } from "$lib/db"; -import { l, err } from "$lib/logging"; -import { getPayment } from "$lib/utils"; - -const query = `mutation orderMarkAsPaid($input: OrderMarkAsPaidInput!) { - orderMarkAsPaid(input: $input) { - order { id } - userErrors { - field - message - } - } -}`; - -export default async (req, res) => { - const { - body: { hash }, - params: { id }, - } = req; - const p = await getPayment(hash); - const user = await g(`user:${p.uid}`); - - l("marking shopify order paid", id, user.username, p.id, user.shopifyStore); - - try { - const r = await got - .post( - `https://${user.shopifyStore}.myshopify.com/admin/api/2023-07/graphql.json`, - { - headers: { - "Content-Type": "application/json", - "X-Shopify-Access-Token": user.shopifyToken, - }, - json: { - query, - variables: { input: { id: `gid://shopify/Order/${id}` } }, - }, - }, - ) - .json(); - - l("shopify success", r); - - res.send(r); - } catch (e) { - err("problem marking shopify order as paid", e.message); - } -}; 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 <user> hold log for one account +// bun scripts/holds.ts lift <user> [sats] lift all (or part) of a hold +// bun scripts/holds.ts set <user> <sats> set a hold by hand +// bun scripts/holds.ts backfill <iso time> 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<string, number>(); + const spent = new Map<string, number>(); + const internalIn: [string, string, number][] = []; + const add = (m: Map<string, number>, 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<string, string>(); + for (const c of channels || []) if (c.short_channel_id) scidPeer.set(c.short_channel_id, c.peer_id); + const watched = new Set<string>(await db.sMembers("freeze:inbound_peers")); + const alias = new Map<string, string>(); + 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<string, Set<string>>(); + 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<string, Map<string, number>>(); + + 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 <user>|lift <user> [sats]|set <user> <sats>|backfill <iso>|on|off]"); +} catch (e: any) { + console.error(e.message); +} +process.exit(0); |
