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 | f95a81db20314b0cc5b31a968908ae86a5bcc22b (patch) | |
| tree | a930540590ce4b33a58988724f2ac6557fed4677 | |
| parent | 9225b8ddea10c15487271a7e4a4c9b26598fc45b (diff) | |
| download | coinos-server-f95a81db20314b0cc5b31a968908ae86a5bcc22b.tar.gz coinos-server-f95a81db20314b0cc5b31a968908ae86a5bcc22b.zip | |
mint: one pay per invoice hash, refuse MPP melts, gate a retired keyset
meltguard refuses repeat and partial pays for a payment hash and can apply
its cap as a rolling window. mintdemux refuses melt quotes with MPP or
amountless options or an unparseable invoice, and only lets ecash from a
gated keyset be spent if its DLEQ blinding factor traces it to an allowed
mint operation.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VMan6SEnsbshZrUDtTsxAX
| -rw-r--r-- | meltguard.ts | 53 | ||||
| -rw-r--r-- | mintdemux.ts | 92 |
2 files changed, 134 insertions, 11 deletions
diff --git a/meltguard.ts b/meltguard.ts index c7195bb0..a50b3d87 100644 --- a/meltguard.ts +++ b/meltguard.ts @@ -18,8 +18,19 @@ // Everything that is not POST /v1/pay|/v1/xpay is proxied through untouched, so mint // startup (getinfo, listinvoices, waitanyinvoice, invoice, listpays…) works normally. // -// Env: CL_URL (http://cl:3010), MELT_MAX_SAT, MELT_CUM_MAX_SAT, GUARD_DIR (/guard), -// PORT (3011). Run: GUARD_DIR=./guard bun meltguard.ts +// 3. ONE PAY PER PAYMENT HASH — refuse any pay for a hash the guard has +// already forwarded, and refuse partial (MPP, `partial_msat`) pays. The +// mint settles a melt by payment hash, so two melt quotes on one invoice +// let a failed (held) first attempt absorb the settlement of a second one +// that cl actually paid: the mint returns the proofs and the same ecash +// can be melted again. +// +// With MELT_WINDOW_SEC set, the cumulative cap is a rolling window and a pay +// over it is REJECTED rather than freezing the guard (for the live mint, where +// normal redemptions would otherwise trip a lifetime cap). +// +// Env: CL_URL (http://cl:3010), MELT_MAX_SAT, MELT_CUM_MAX_SAT, MELT_WINDOW_SEC, +// GUARD_DIR (/guard), PORT (3011). Run: GUARD_DIR=./guard bun meltguard.ts import { readFileSync, writeFileSync, existsSync, appendFileSync, mkdirSync } from "fs"; const CL = process.env.CL_URL || "http://cl:3010"; @@ -31,6 +42,14 @@ mkdirSync(DIR, { recursive: true }); const CUM_FILE = `${DIR}/cumulative_sat`; const FROZEN_FILE = `${DIR}/FROZEN`; const LOG = `${DIR}/meltguard.log`; +const HASH_FILE = `${DIR}/hashes`; +const WINDOW_FILE = `${DIR}/window.json`; +const WINDOW = Number(process.env.MELT_WINDOW_SEC || 0) * 1000; +const seen = new Set(existsSync(HASH_FILE) ? readFileSync(HASH_FILE, "utf8").split("\n").filter(Boolean) : []); +const remember = (h: string) => { seen.add(h); appendFileSync(HASH_FILE, h + "\n"); }; +type Spend = { ts: number; amt: number }; +let spends: Spend[] = existsSync(WINDOW_FILE) ? JSON.parse(readFileSync(WINDOW_FILE, "utf8") || "[]") : []; +const windowSum = () => { const cut = Date.now() - WINDOW; spends = spends.filter((x) => x.ts >= cut); return spends.reduce((a, x) => a + x.amt, 0); }; const readCum = () => (existsSync(CUM_FILE) ? Number(readFileSync(CUM_FILE, "utf8").trim()) || 0 : 0); const writeCum = (n: number) => writeFileSync(CUM_FILE, String(n)); @@ -39,16 +58,17 @@ const log = (m: string) => { try { appendFileSync(LOG, `${new Date().toISOString const freeze = (why: string) => { writeFileSync(FROZEN_FILE, why + "\n"); log(`FROZEN — ${why} — operator must review and clear ${FROZEN_FILE}`); }; const err = (status: number, message: string) => new Response(JSON.stringify({ error: message }), { status, headers: { "content-type": "application/json" } }); -async function decodeSat(bolt11: string, rune: string | null): Promise<number | null> { +async function decode(bolt11: string, rune: string | null): Promise<{ sat: number; hash: string } | null> { try { const r = await fetch(`${CL}/v1/decode`, { method: "POST", headers: { "content-type": "application/json", ...(rune ? { Rune: rune } : {}) }, body: JSON.stringify({ string: bolt11 }) }); const j: any = await r.json(); - if (j.amount_msat != null) return Math.ceil(Number(j.amount_msat) / 1000); - return null; // amountless invoice — no embedded amount to cap on; treat as undecidable + // amountless invoice — no embedded amount to cap on; treat as undecidable + if (j.amount_msat == null || typeof j.payment_hash !== "string") return null; + return { sat: Math.ceil(Number(j.amount_msat) / 1000), hash: j.payment_hash }; } catch { return null; } } -console.log(`meltguard on :${PORT} -> ${CL} | per-melt<=${PER} sat, cumulative freeze at ${CUM} sat | state ${DIR} | frozen=${isFrozen()} cum=${readCum()}`); +console.log(`meltguard on :${PORT} -> ${CL} | per-melt<=${PER} sat, ${WINDOW ? `rolling ${WINDOW / 1000}s cap ${CUM}` : `cumulative freeze at ${CUM}`} sat | state ${DIR} | frozen=${isFrozen()} cum=${readCum()} hashes=${seen.size}`); Bun.serve({ port: PORT, hostname: "0.0.0.0", idleTimeout: 0, @@ -86,11 +106,21 @@ Bun.serve({ for (const k of Object.keys(j)) if (k !== "invoice" && k !== "bolt11" && k !== "invstring") extra[k] = String(j[k]); } catch {} } - const amt = await decodeSat(invoice, rune); - if (amt == null) return err(400, "meltguard: could not determine invoice amount — refusing to forward"); + const inv = await decode(invoice, rune); + if (!inv) return err(400, "meltguard: could not determine invoice amount — refusing to forward"); + const amt = inv.sat; + if (extra.partial_msat != null || extra.amount_msat != null) { log(`REJECT partial pay ${extra.partial_msat ?? extra.amount_msat} msat of ${amt} sat hash=${inv.hash}`); return err(403, "meltguard: partial payments are not allowed"); } + if (seen.has(inv.hash)) { log(`REJECT repeat pay hash=${inv.hash} ${amt} sat`); return err(403, "meltguard: this invoice has already been attempted"); } if (amt > PER) { log(`REJECT per-melt ${amt} > ${PER}`); return err(403, `meltguard: per-melt cap ${PER} sat exceeded (${amt})`); } - const cum = readCum(); - if (cum + amt > CUM) { freeze(`cumulative ${cum}+${amt} > ${CUM}`); return err(403, `meltguard: cumulative cap ${CUM} sat — FROZEN, operator review required`); } + const cum = WINDOW ? windowSum() : readCum(); + if (cum + amt > CUM) { + if (WINDOW) { log(`REJECT window ${cum}+${amt} > ${CUM}`); return err(403, `meltguard: rolling cap ${CUM} sat reached, try later`); } + freeze(`cumulative ${cum}+${amt} > ${CUM}`); return err(403, `meltguard: cumulative cap ${CUM} sat — FROZEN, operator review required`); + } + // Claim the hash and the window budget before forwarding, so concurrent + // or later pays for the same invoice are refused even if this one fails. + remember(inv.hash); + if (WINDOW) { spends.push({ ts: Date.now(), amt }); writeFileSync(WINDOW_FILE, JSON.stringify(spends)); } // forward to cl (official CLNREST) as FORM on the SAME endpoint the mint // called (`invstring` for xpay, `bolt11` for pay), preserving the mint's // other params (maxfee / maxfeepercent / exemptfee). Count cumulative only @@ -98,7 +128,8 @@ Bun.serve({ const fwd = new URLSearchParams(isXpay ? { invstring: invoice, ...extra } : { bolt11: invoice, ...extra }); const resp = await fetch(`${CL}${isXpay ? "/v1/xpay" : "/v1/pay"}`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", ...(rune ? { Rune: rune } : {}) }, body: fwd.toString() }); const text = await resp.text(); - if (resp.ok) { writeCum(cum + amt); log(`PAID ${amt} sat via ${isXpay ? "xpay" : "pay"} (cumulative ${cum + amt}/${CUM})`); } + if (resp.ok) { if (!WINDOW) writeCum(cum + amt); log(`PAID ${amt} sat via ${isXpay ? "xpay" : "pay"} hash=${inv.hash} (${WINDOW ? "window" : "cumulative"} ${cum + amt}/${CUM})`); } + else log(`FAILED ${amt} sat hash=${inv.hash} status=${resp.status} ${text.slice(0, 160)}`); return new Response(text, { status: resp.status, headers: { "content-type": "application/json" } }); } diff --git a/mintdemux.ts b/mintdemux.ts index 68820f94..1b93970b 100644 --- a/mintdemux.ts +++ b/mintdemux.ts @@ -36,6 +36,9 @@ // LOG_DIR (/demux), PORT (3341) import { createHash } from "crypto"; import { appendFileSync, mkdirSync, readFileSync, existsSync, writeFileSync } from "fs"; +import { Database } from "bun:sqlite"; +import { secp256k1 } from "@noble/curves/secp256k1.js"; +import { sha256 } from "@noble/hashes/sha2.js"; const NEW = process.env.NEW_MINT || "http://mint:3338"; const OLD = process.env.OLD_MINT || "http://mint-old:3338"; @@ -53,6 +56,62 @@ const J = { ...CORS, "content-type": "application/json" }; const log = (m: string) => { try { appendFileSync(`${DIR}/demux.log`, `${new Date().toISOString()} ${m}\n`); } catch {} console.log("demux:", m); }; const parse = (s: string) => { try { return JSON.parse(s); } catch { return null; } }; +// --- provenance gate for a compromised keyset --- +// Ecash in a GATED keyset is spendable (swap/melt) only if each input carries +// its NUT-12 DLEQ blinding factor `r`, so we can recompute the blinded message +// B_ = hash_to_curve(secret) + r*G and look up which mint operation signed it. +// Allowed: signed before GATE_CUTOFF, or minted from a mint quote that is not +// blacklisted. Refused (fail-closed): blacklisted quotes, swap/melt-change +// outputs after the cutoff, anything we can't trace. Refusals are logged to +// gate.jsonl for manual review. +const GATED = new Set((process.env.GATED_KEYSETS || "").split(",").map(s => s.trim()).filter(Boolean)); +const GATE_CUTOFF = Number(process.env.GATE_CUTOFF || 0); +const GATE_BL = new Set(existsSync(`${DIR}/gate-blacklist`) ? readFileSync(`${DIR}/gate-blacklist`, "utf8").split("\n").map(s => s.trim()).filter(Boolean) : []); +const RECOVER = process.env.GATE_RECOVER || "email [email protected] with the token"; +let mintdb: Database | null = null; +function promiseOf(b_: string): any { + if (!mintdb) mintdb = new Database(process.env.MINT_DB || "/mintdb/mint.sqlite3", { readonly: true }); + return mintdb.query("select amount, created, mint_quote, swap_id, melt_quote from promises where b_ = ?").get(b_); +} +const G = secp256k1.Point.BASE; +const DST = new TextEncoder().encode("Secp256k1_HashToCurve_Cashu_"); +const cat = (...a: Uint8Array[]) => { const o = new Uint8Array(a.reduce((n, x) => n + x.length, 0)); let i = 0; for (const x of a) { o.set(x, i); i += x.length; } return o; }; +function hashToCurve(msg: Uint8Array) { + const h = sha256(cat(DST, msg)); + for (let c = 0; c < 65536; c++) { + const ctr = new Uint8Array(4); new DataView(ctr.buffer).setUint32(0, c, true); + const x = Buffer.from(sha256(cat(h, ctr))).toString("hex"); + try { return secp256k1.Point.fromHex("02" + x); } catch {} + } + throw new Error("hash_to_curve: no point"); +} +function gateVerdict(p: any): string | null { + const r = String(p?.dleq?.r || ""); + if (!/^[0-9a-f]{64}$/i.test(r)) return "missing DLEQ blinding factor"; + let b_: string; + try { b_ = hashToCurve(new TextEncoder().encode(String(p.secret))).add(G.multiply(BigInt("0x" + r))).toHex(true); } + catch { return "invalid proof"; } + let row: any; + try { row = promiseOf(b_); } catch (e: any) { return `lookup failed: ${e?.message}`; } + if (!row) return "unknown signature"; + if (Number(row.amount) !== Number(p.amount)) return "amount mismatch"; + if (Number(row.created) < GATE_CUTOFF) return null; + if (row.mint_quote && !GATE_BL.has(row.mint_quote)) return null; + if (row.mint_quote) return "issued from a blacklisted quote"; + return row.swap_id ? "swap output after cutoff" : "melt change after cutoff"; +} +function gateInputs(body: any, path: string, ip: string): Response | null { + if (!GATED.size || !Array.isArray(body?.inputs)) return null; + const gated = body.inputs.filter((p: any) => GATED.has(String(p?.id))); + if (!gated.length) return null; + const bad = gated.map((p: any) => ({ p, why: gateVerdict(p) })).filter((x: any) => x.why); + if (!bad.length) { log(`gate pass ${gated.length} input(s) ${gated.reduce((a: number, p: any) => a + (p?.amount || 0), 0)} sat ${path} ip=${ip}`); return null; } + const sat = bad.reduce((a: number, x: any) => a + (x.p?.amount || 0), 0); + try { appendFileSync(`${DIR}/gate.jsonl`, JSON.stringify({ t: new Date().toISOString(), ip, path, refused: bad.map((x: any) => ({ why: x.why, amount: x.p?.amount, id: x.p?.id, secret: x.p?.secret, C: x.p?.C, r: x.p?.dleq?.r })) }) + "\n"); } catch {} + log(`gate REFUSED ${bad.length}/${gated.length} input(s) ${sat} sat (${[...new Set(bad.map((x: any) => x.why))].join("; ")}) ${path} ip=${ip}`); + return new Response(JSON.stringify({ detail: `Some of this ecash is from a retired keyset and could not be verified. To recover it, ${RECOVER}`, code: 12005 }), { status: 400, headers: J }); +} + // --- keyset ownership, refreshed hourly --- let newKeysets = new Set<string>(); let oldKeysets = new Set<string>(); @@ -101,6 +160,31 @@ function rememberQuote(id: string, info: QInfo) { try { writeFileSync(QFILE, JSON.stringify(quoteMem)); } catch {} } +// --- melt quote screening --- +// Refuse MPP/amountless quote options and quotes we can't parse. Repeat quotes +// for one invoice are allowed, as upstream: nutshell >= 0.22.0 handles repeat +// payment attempts on a hash itself. +const B32 = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; +function bolt11Hash(inv: string): string | null { + const s = (inv || "").trim().toLowerCase().replace(/^lightning:/, ""); + const sep = s.lastIndexOf("1"); + if (!s.startsWith("ln") || sep < 0) return null; + const words: number[] = []; + for (const c of s.slice(sep + 1, -6)) { const v = B32.indexOf(c); if (v < 0) return null; words.push(v); } + let i = 7; // skip timestamp; tags stop before the 104-word signature + while (i + 3 <= words.length - 104) { + const tag = words[i], len = words[i + 1] * 32 + words[i + 2]; + const data = words.slice(i + 3, i + 3 + len); + if (tag === 1 && len === 52) { + let acc = 0, bits = 0; const out: number[] = []; + for (const w of data) { acc = (acc << 5) | w; bits += 5; while (bits >= 8) { bits -= 8; out.push((acc >> bits) & 255); } } + return Buffer.from(out.slice(0, 32)).toString("hex"); + } + i += 3 + len; + } + return null; +} + // --- NEW-quote-id -> OLD-quote-id map for melts executed on OLD, so status // polls (GET /v1/melt/quote/bolt11/<id>) can be routed to the mint that ran // the melt. Kept long: a pending lightning payment can be polled much later. @@ -240,6 +324,8 @@ Bun.serve({ // --- POST routes --- const raw = await req.arrayBuffer(); const body = parse(new TextDecoder().decode(raw)); + const gateResp = gateInputs(body, path, req.headers.get("cf-connecting-ip") || ""); + if (gateResp) return gateResp; if (path === "/v1/checkstate") { const [rn, ro] = await Promise.all([ @@ -252,6 +338,12 @@ Bun.serve({ } if (path === "/v1/melt/quote/bolt11") { + if (body?.options && Object.keys(body.options).length) { + log(`melt quote refused: options ${JSON.stringify(body.options).slice(0, 80)} ip=${key}`); + return new Response(JSON.stringify({ detail: "Multi-path and amountless melts are not supported", code: 11000 }), { status: 400, headers: J }); + } + const ph = bolt11Hash(body?.request); + if (!ph) return new Response(JSON.stringify({ detail: "Invalid invoice", code: 11000 }), { status: 400, headers: J }); const r = await fetch(`${NEW}/v1/melt/quote/bolt11`, { method: "POST", headers: fwd(key, true), body: raw }); const txt = await r.text(); const j = parse(txt); if (r.ok && j?.quote && body?.request) rememberQuote(j.quote, { invoice: body.request, unit: body.unit || "sat", ts: Date.now() }); |
