aboutsummaryrefslogtreecommitdiffstats
path: root/meltguard.ts
diff options
context:
space:
mode:
Diffstat (limited to 'meltguard.ts')
-rw-r--r--meltguard.ts86
1 files changed, 74 insertions, 12 deletions
diff --git a/meltguard.ts b/meltguard.ts
index c7195bb0..33b579bf 100644
--- a/meltguard.ts
+++ b/meltguard.ts
@@ -18,8 +18,28 @@
// 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).
+//
+// A pay the guard refuses for an amount cap (per-melt or rolling window) never
+// reaches cl, so cl's listpays has nothing for that hash. nutshell >= 0.22 reads
+// an empty listpays as NOT_FOUND and keeps the melt quote PENDING forever, which
+// locks the user's proofs. Such hashes are recorded in GUARD_DIR/rejected, and a
+// listpays for one of them that cl answers with no pays is reported as a failed
+// pay, so the mint marks the quote UNPAID and releases the proofs. When cl has a
+// pay for the hash, cl's answer is passed through unchanged. Repeat-hash and
+// partial-pay refusals are not recorded: another quote on that hash may be real.
+//
+// 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 +51,18 @@ 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"); };
+const REJECTED_FILE = `${DIR}/rejected`;
+const loadRejected = () => new Set(existsSync(REJECTED_FILE) ? readFileSync(REJECTED_FILE, "utf8").split("\n").map((x) => x.trim()).filter(Boolean) : []);
+let rejected = loadRejected();
+const markRejected = (h: string) => { if (rejected.has(h)) return; rejected.add(h); appendFileSync(REJECTED_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 +71,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 +119,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");
- 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 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) { markRejected(inv.hash); log(`REJECT per-melt ${amt} > ${PER}`); return err(403, `meltguard: per-melt cap ${PER} sat exceeded (${amt})`); }
+ const cum = WINDOW ? windowSum() : readCum();
+ if (cum + amt > CUM) {
+ if (WINDOW) { markRejected(inv.hash); 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,13 +141,32 @@ 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" } });
}
// transparent proxy for all other CLNRest calls
const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.arrayBuffer();
const resp = await fetch(`${CL}${url.pathname}${url.search}`, { method: req.method, headers: { ...(req.headers.get("content-type") ? { "content-type": req.headers.get("content-type")! } : {}), ...(rune ? { Rune: rune } : {}) }, body });
+ if (req.method === "POST" && url.pathname === "/v1/listpays" && body && resp.ok) {
+ const raw = new TextDecoder().decode(body);
+ let hash = "";
+ try { hash = new URLSearchParams(raw).get("payment_hash") || ""; } catch {}
+ if (!hash) { try { hash = JSON.parse(raw).payment_hash || ""; } catch {} }
+ // re-read so an operator can add a hash without a restart
+ if (hash) rejected = loadRejected();
+ if (hash && rejected.has(hash)) {
+ const text = await resp.text();
+ let j: any = null;
+ try { j = JSON.parse(text); } catch {}
+ if (j && Array.isArray(j.pays) && j.pays.length === 0) {
+ log(`listpays ${hash}: refused by guard, cl has no pay -> reporting failed`);
+ return new Response(JSON.stringify({ pays: [{ payment_hash: hash, status: "failed" }] }), { status: 200, headers: { "content-type": "application/json" } });
+ }
+ return new Response(text, { status: resp.status, headers: { "content-type": resp.headers.get("content-type") || "application/json" } });
+ }
+ }
return new Response(await resp.arrayBuffer(), { status: resp.status, headers: { "content-type": resp.headers.get("content-type") || "application/json" } });
},
});