aboutsummaryrefslogtreecommitdiffstats
path: root/mintdemux.ts
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2026-11-25 09:25:18 -0700
committerAdam Soltys <[email protected]>2026-11-25 09:25:18 -0700
commitf95a81db20314b0cc5b31a968908ae86a5bcc22b (patch)
treea930540590ce4b33a58988724f2ac6557fed4677 /mintdemux.ts
parent9225b8ddea10c15487271a7e4a4c9b26598fc45b (diff)
downloadcoinos-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
Diffstat (limited to 'mintdemux.ts')
-rw-r--r--mintdemux.ts92
1 files changed, 92 insertions, 0 deletions
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() });