1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
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);
|