diff options
Diffstat (limited to 'lib')
| -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 |
4 files changed, 255 insertions, 22 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); }; |
