@cashu/cashu-ts
Version:
cashu library for communicating with a cashu mint
1,744 lines • 192 kB
JavaScript
import { bytesToHex as e, bytesToNumberBE as t, hexToBytes as n, numberToBytesBE as r, randomBytes as i } from "@noble/curves/utils.js";
import { sha256 as a } from "@noble/hashes/sha2.js";
import { bech32 as o, bech32m as s } from "@scure/base";
import { schnorr as c, secp256k1 as l } from "@noble/curves/secp256k1.js";
import { bytesToHex as u, concatBytes as d, hexToBytes as f, randomBytes as p, utf8ToBytes as m } from "@noble/hashes/utils.js";
import { HDKey as h } from "@scure/bip32";
import { hmac as g } from "@noble/hashes/hmac.js";
//#region src/model/Errors.ts
var _ = class e extends Error {
constructor(t, n) {
super(t), this.name = "CTSError", n?.cause !== void 0 && Object.defineProperty(this, "cause", {
configurable: !0,
enumerable: !1,
value: n.cause,
writable: !0
}), Object.setPrototypeOf(this, e.prototype);
}
}, v = class e extends _ {
constructor(t, n, r) {
super(t, r), this.status = n, this.name = "HttpResponseError", Object.setPrototypeOf(this, e.prototype);
}
}, y = class e extends _ {
constructor(t, n) {
super(t, n), this.name = "NetworkError", Object.setPrototypeOf(this, e.prototype);
}
}, b = class e extends v {
constructor(t, n) {
super(t, 429), this.retryAfterMs = n, this.name = "RateLimitError", Object.setPrototypeOf(this, e.prototype);
}
}, x = class e extends v {
constructor(t, n) {
super(n || "Unknown mint operation error", 400), this.code = t, this.name = "MintOperationError", Object.setPrototypeOf(this, e.prototype);
}
}, S = {
error() {},
warn() {},
info() {},
debug() {},
trace() {},
log() {}
};
//#endregion
//#region src/logger/helpers.ts
function C(e, t = S, n) {
throw t.error(e, n), new _(e);
}
function w(e, t, n = S, r) {
e && C(t, n, r);
}
function ee(e, t, n = S, r) {
e ?? C(t, n, r);
}
function T(e, t, n = S, r) {
if (e) try {
let i = e(t);
i && typeof i.then == "function" && i.catch((t) => {
try {
n.warn("callback failed", {
...r ?? {},
error: t,
cb: e.name ?? ""
});
} catch {}
});
} catch (t) {
try {
n.warn("callback failed", {
...r ?? {},
error: t,
cb: e.name ?? ""
});
} catch {}
}
}
//#endregion
//#region src/logger/ConsoleLogger.ts
var te = {
error: 0,
warn: 1,
info: 2,
debug: 3,
trace: 4
}, E = class {
constructor(e = "info") {
this.minLevel = e;
}
should(e) {
return te[e] <= te[this.minLevel];
}
method(e) {
switch (e) {
case "error": return console.error;
case "warn": return console.warn;
case "info": return console.info;
case "debug": return console.debug;
case "trace": return console.trace;
default: return console.log;
}
}
header(e, t) {
return `[${e.toUpperCase()}] ${t}`;
}
flattenContext(e) {
if (!e) return;
let t = {};
for (let [n, r] of Object.entries(e)) t[n] = r instanceof Error ? {
message: r.message,
stack: r.stack
} : r;
return t;
}
emit(e, t, n) {
if (!this.should(e)) return;
let r = this.header(e, t), i = this.flattenContext(n), a = this.method(e);
i && Object.keys(i).length ? a(r, i) : a(r);
}
error(e, t) {
this.emit("error", e, t);
}
warn(e, t) {
this.emit("warn", e, t);
}
info(e, t) {
this.emit("info", e, t);
}
debug(e, t) {
this.emit("debug", e, t);
}
trace(e, t) {
this.emit("trace", e, t);
}
log(e, t, n) {
this.emit(e, t, n);
}
};
function ne() {
let e = Date.now();
return { elapsed: () => Date.now() - e };
}
//#endregion
//#region src/utils/Bytes.ts
function re() {
return globalThis.Buffer;
}
var D = class {
static fromHex(e) {
if (e = e.trim(), e.length === 0) return new Uint8Array();
if (e.length < 2 || e.length & 1) throw new _("Invalid hex string: odd length.");
if ((e.startsWith("0x") || e.startsWith("0X")) && (e = e.slice(2)), !e.match(/^[0-9a-fA-F]*$/)) throw new _("Invalid hex string: contains non-hex characters");
let t = e.match(/.{1,2}/g);
if (!t) throw new _("Invalid hex string");
return new Uint8Array(t.map((e) => parseInt(e, 16)));
}
static toHex(e) {
return Array.from(e, (e) => e.toString(16).padStart(2, "0")).join("");
}
static fromString(e) {
return e = e.trim(), new TextEncoder().encode(e);
}
static toString(e) {
return new TextDecoder("utf-8").decode(e);
}
static concat(...e) {
let t = e.reduce((e, t) => e + t.length, 0), n = new Uint8Array(t), r = 0;
for (let t of e) n.set(t, r), r += t.length;
return n;
}
static alloc(e) {
return new Uint8Array(e);
}
static writeBigUint64BE(e) {
let t = /* @__PURE__ */ new ArrayBuffer(8);
return new DataView(t).setBigUint64(0, e, !1), new Uint8Array(t);
}
static toBase64(e) {
let t = re();
if (t) return t.from(e).toString("base64");
if (e.length > 32768) {
let t = "";
for (let n = 0; n < e.length; n += 32768) {
let r = e.slice(n, n + 32768);
t += btoa(String.fromCharCode(...r));
}
return t;
}
return btoa(String.fromCharCode(...e));
}
static fromBase64(e) {
e = e.trim();
let t = e.replace(/-/g, "+").replace(/_/g, "/");
for (; t.length % 4;) t += "=";
let n = re();
return n ? new Uint8Array(n.from(t, "base64")) : new Uint8Array([...atob(t)].map((e) => e.charCodeAt(0)));
}
static equals(e, t) {
if (e.length !== t.length) return !1;
let n = 0;
for (let r = 0; r < e.length; r++) n |= e[r] ^ t[r];
return n === 0;
}
static compare(e, t) {
let n = Math.min(e.length, t.length);
for (let r = 0; r < n; r++) {
if (e[r] < t[r]) return -1;
if (e[r] > t[r]) return 1;
}
return e.length - t.length;
}
static toBigInt(e) {
let t = 0n;
for (let n of e) t = t << 8n | BigInt(n);
return t;
}
static fromBigInt(e) {
if (e < 0n) throw RangeError("value must be non-negative");
if (e === 0n) return new Uint8Array([0]);
let t = e, n = 0;
for (; t > 0n;) n++, t >>= 8n;
let r = new Uint8Array(n);
t = e;
for (let e = n - 1; e >= 0; e--) r[e] = Number(t & 255n), t >>= 8n;
return r;
}
}, O = class e extends _ {
constructor(t) {
super(t), this.name = "AmountError", Object.setPrototypeOf(this, e.prototype);
}
}, k = class e {
constructor(e) {
this.value = e, Object.freeze(this);
}
static from(t) {
if (t instanceof e) return t;
if (typeof t == "bigint") {
if (t < 0n) throw new O(`Amount must be >= 0, got ${t}`);
return new e(t);
}
if (typeof t == "number") {
if (!Number.isFinite(t) || !Number.isInteger(t)) throw new O(`Invalid number amount: ${t}`);
if (t < 0) throw new O(`Amount must be >= 0, got ${t}`);
if (!Number.isSafeInteger(t)) throw new O(`Unsafe integer amount: ${t}. Use bigint or decimal string.`);
return new e(BigInt(t));
}
if (typeof t == "string") {
if (!/^(0|[1-9]\d*)$/.test(t)) throw new O(`Invalid amount string "${t}". Expected non-negative decimal integer.`);
return new e(BigInt(t));
}
throw new O("Unsupported amount input type");
}
static zero() {
return new e(0n);
}
static one() {
return new e(1n);
}
toBigInt() {
return this.value;
}
toNumber() {
if (!this.isSafeNumber()) throw new O(`Amount ${this.value} exceeds Number.MAX_SAFE_INTEGER; use toBigInt/toString/toJSON.`);
return Number(this.value);
}
toNumberUnsafe() {
return Number(this.value);
}
toString() {
return this.value.toString(10);
}
toJSON() {
return this.toString();
}
add(t) {
let n = e.from(t);
return new e(this.value + n.value);
}
subtract(t) {
let n = e.from(t), r = this.value - n.value;
if (r < 0n) throw new O(`Amount underflow: ${this.value} - ${n.value} would be negative`);
return new e(r);
}
multiplyBy(t) {
let n = e.from(t).value;
return new e(this.value * n);
}
divideBy(t) {
let n = e.from(t).value;
if (n <= 0n) throw new O(`Divisor must be > 0, got ${n}`);
return new e(this.value / n);
}
modulo(t) {
let n = e.from(t).value;
if (n <= 0n) throw new O(`Divisor must be > 0, got ${n}`);
return new e(this.value % n);
}
ceilPercent(e, t = 100) {
if (!Number.isInteger(e) || e <= 0) throw new O(`ceilPercent: numerator must be a positive integer, got ${e}`);
if (!Number.isInteger(t) || t <= 0) throw new O(`ceilPercent: denominator must be a positive integer, got ${t}`);
return this.multiplyBy(e).add(t - 1).divideBy(t);
}
floorPercent(e, t = 100) {
if (!Number.isInteger(e) || e <= 0) throw new O(`floorPercent: numerator must be a positive integer, got ${e}`);
if (!Number.isInteger(t) || t <= 0) throw new O(`floorPercent: denominator must be a positive integer, got ${t}`);
return this.multiplyBy(e).divideBy(t);
}
inRange(t, n) {
let r = e.from(t), i = e.from(n);
if (r.greaterThan(i)) throw new O(`inRange: min (${r.toString()}) must be <= max (${i.toString()})`);
return this.greaterThanOrEqual(r) && this.lessThanOrEqual(i);
}
clamp(t, n) {
let r = e.from(t), i = e.from(n);
if (r.greaterThan(i)) throw new O(`clamp: min (${r.toString()}) must be <= max (${i.toString()})`);
return e.max(r, e.min(i, this));
}
scaledBy(t, n) {
let r = e.from(t), i = e.from(n);
if (r.isZero()) return e.zero();
if (i.isZero()) throw new O("scaledBy: denominator must be > 0");
return this.multiplyBy(r).multiplyBy(2).add(i).divideBy(i.multiplyBy(2));
}
isSafeNumber() {
let e = BigInt(2 ** 53 - 1);
return this.value <= e;
}
isZero() {
return this.value === 0n;
}
equals(t) {
return this.value === e.from(t).value;
}
compareTo(t) {
let n = e.from(t).value;
return this.value < n ? -1 : +(this.value > n);
}
lessThan(e) {
return this.compareTo(e) < 0;
}
lessThanOrEqual(e) {
return this.compareTo(e) <= 0;
}
greaterThan(e) {
return this.compareTo(e) > 0;
}
greaterThanOrEqual(e) {
return this.compareTo(e) >= 0;
}
static min(t, n) {
let r = e.from(t), i = e.from(n);
return r.compareTo(i) <= 0 ? r : i;
}
static max(t, n) {
let r = e.from(t), i = e.from(n);
return r.compareTo(i) >= 0 ? r : i;
}
static sum(t) {
let n = 0n;
for (let r of t) n += e.from(r).value;
return new e(n);
}
withUnit(e) {
return new ae(this, e);
}
}, ie = class e extends _ {
constructor(t) {
super(t), this.name = "AmountWithUnitError", Object.setPrototypeOf(this, e.prototype);
}
}, ae = class e {
constructor(e, t) {
if (typeof t != "string" || t.length === 0) throw new ie("unit required");
this._amount = e, this.unit = t, Object.freeze(this);
}
static from(t, n) {
return new e(k.from(t), n);
}
static zero(t) {
return new e(k.zero(), t);
}
static one(t) {
return new e(k.one(), t);
}
toAmount() {
return this._amount;
}
toBigInt() {
return this._amount.toBigInt();
}
toNumber() {
return this._amount.toNumber();
}
toString() {
return `[${this.unit}]: ${this._amount.toString()}`;
}
toJSON() {
return {
amount: this._amount.toString(),
unit: this.unit
};
}
[Symbol.toPrimitive](e) {
if (e === "string") return this.toString();
throw new ie(`Implicit ${e === "number" ? "numeric" : "default"} coercion of AmountWithUnit is unsafe; use .toAmount() then explicit arithmetic, or .toString() for display.`);
}
isZero() {
return this._amount.isZero();
}
isSafeNumber() {
return this._amount.isSafeNumber();
}
requireSameUnit(e) {
if (this.unit !== e.unit) throw new ie(`unit mismatch: ${this.unit} vs ${e.unit}`);
}
add(t) {
return this.requireSameUnit(t), new e(this._amount.add(t._amount), this.unit);
}
subtract(t) {
return this.requireSameUnit(t), new e(this._amount.subtract(t._amount), this.unit);
}
equals(e) {
return this.requireSameUnit(e), this._amount.equals(e._amount);
}
compareTo(e) {
return this.requireSameUnit(e), this._amount.compareTo(e._amount);
}
lessThan(e) {
return this.compareTo(e) < 0;
}
lessThanOrEqual(e) {
return this.compareTo(e) <= 0;
}
greaterThan(e) {
return this.compareTo(e) > 0;
}
greaterThanOrEqual(e) {
return this.compareTo(e) >= 0;
}
inRange(e, t) {
return this.requireSameUnit(e), this.requireSameUnit(t), this._amount.inRange(e._amount, t._amount);
}
clamp(t, n) {
return this.requireSameUnit(t), this.requireSameUnit(n), new e(this._amount.clamp(t._amount, n._amount), this.unit);
}
multiplyBy(t) {
return new e(this._amount.multiplyBy(t), this.unit);
}
divideBy(t) {
return new e(this._amount.divideBy(t), this.unit);
}
modulo(t) {
return new e(this._amount.modulo(t), this.unit);
}
ceilPercent(t, n) {
return new e(this._amount.ceilPercent(t, n), this.unit);
}
floorPercent(t, n) {
return new e(this._amount.floorPercent(t, n), this.unit);
}
scaledBy(t, n) {
return new e(this._amount.scaledBy(t, n), this.unit);
}
static min(e, t) {
return e.requireSameUnit(t), e.compareTo(t) <= 0 ? e : t;
}
static max(e, t) {
return e.requireSameUnit(t), e.compareTo(t) >= 0 ? e : t;
}
static sum(t, n) {
let r = n, i = 0n, a = !1;
for (let e of t) {
if (r === void 0) r = e.unit;
else if (e.unit !== r) throw new ie(`unit mismatch: ${r} vs ${e.unit}`);
i += e._amount.toBigInt(), a = !0;
}
if (r === void 0) throw new ie("cannot infer unit from empty sum");
return new e(a ? k.from(i) : k.zero(), r);
}
}, A = Object.freeze({
parse: fe,
stringify: ge
}), oe;
function se(e) {
return typeof e == "object" && !!e && !Array.isArray(e);
}
function ce() {
let e = globalThis.BigInt;
return typeof e == "function" ? e : void 0;
}
function le(e) {
if (!oe) {
let t = e(String(2 ** 53 - 1));
oe = {
max: t,
min: -t
};
}
return oe;
}
var ue = class {
constructor(e, t, n, r) {
this.src = e, this.strict = t, this.fallbackTo = n, this.bigIntCtor = r, this.i = 0;
}
parse() {
let e = this.parseValue();
if (this.skipWhitespace(), !this.isEnd()) throw this.syntaxError("Unexpected trailing input");
return e;
}
parseValue() {
this.skipWhitespace();
let e = this.peek();
if (e === "{") return this.parseObject();
if (e === "[") return this.parseArray();
if (e === "\"") return this.parseString();
if (e === "-" || this.isDigit(e)) return this.parseNumber();
if (e === "t") return this.parseLiteral("true", !0);
if (e === "f") return this.parseLiteral("false", !1);
if (e === "n") return this.parseLiteral("null", null);
throw this.syntaxError(`Unexpected token '${e || "EOF"}'`);
}
parseObject() {
this.expect("{"), this.skipWhitespace();
let e = {}, t = /* @__PURE__ */ new Set();
if (this.peek() === "}") return this.expect("}"), e;
for (; !this.isEnd();) {
let n = this.parseString();
if (this.strict && t.has(n)) throw this.syntaxError(`Duplicate key "${n}"`);
if (t.add(n), this.skipWhitespace(), this.expect(":"), Object.defineProperty(e, n, {
value: this.parseValue(),
writable: !0,
enumerable: !0,
configurable: !0
}), this.skipWhitespace(), this.peek() === "}") return this.expect("}"), e;
this.expect(","), this.skipWhitespace();
}
throw this.syntaxError("Unterminated object");
}
parseArray() {
this.expect("["), this.skipWhitespace();
let e = [];
if (this.peek() === "]") return this.expect("]"), e;
for (; !this.isEnd();) {
if (e.push(this.parseValue()), this.skipWhitespace(), this.peek() === "]") return this.expect("]"), e;
this.expect(","), this.skipWhitespace();
}
throw this.syntaxError("Unterminated array");
}
parseString() {
this.expect("\"");
let e = "";
for (; !this.isEnd();) {
let t = this.next();
if (t === "\"") return e;
if (t === "\\") {
let t = this.next();
switch (t) {
case "\"":
case "\\":
case "/":
e += t;
break;
case "b":
e += "\b";
break;
case "f":
e += "\f";
break;
case "n":
e += "\n";
break;
case "r":
e += "\r";
break;
case "t":
e += " ";
break;
case "u": {
let t = this.src.slice(this.i, this.i + 4);
if (!/^[0-9a-fA-F]{4}$/.test(t)) throw this.syntaxError("Invalid unicode escape");
this.i += 4, e += String.fromCharCode(parseInt(t, 16));
break;
}
default: throw this.syntaxError(`Invalid escape '\\${t}'`);
}
continue;
}
if (t < " ") throw this.syntaxError("Invalid control character in string");
e += t;
}
throw this.syntaxError("Unterminated string");
}
parseNumber() {
let e = this.i;
this.peek() === "-" && (this.i += 1), this.peek() === "0" ? this.i += 1 : this.readDigits(), this.peek() === "." && (this.i += 1, this.readDigits());
let t = this.peek();
if (t === "e" || t === "E") {
this.i += 1;
let e = this.peek();
(e === "+" || e === "-") && (this.i += 1), this.readDigits();
}
let n = this.src.slice(e, this.i);
if (!(n.indexOf(".") === -1 && n.indexOf("e") === -1 && n.indexOf("E") === -1)) {
let e = Number(n);
if (!Number.isFinite(e)) throw this.syntaxError("Bad number");
return e;
}
if (!this.bigIntCtor) switch (this.fallbackTo) {
case "number": {
let e = Number(n);
if (!Number.isFinite(e)) throw this.syntaxError("Bad number");
return e;
}
case "string": return n;
case "error": throw new _("BigInt is not available in this runtime");
}
let r = this.bigIntCtor(n), { max: i, min: a } = le(this.bigIntCtor);
return r > i || r < a ? r : Number(n);
}
parseLiteral(e, t) {
if (this.src.slice(this.i, this.i + e.length) !== e) throw this.syntaxError(`Unexpected token near '${this.src.slice(this.i, this.i + 8)}'`);
return this.i += e.length, t;
}
readDigits() {
let e = this.i;
for (; this.isDigit(this.peek());) this.i += 1;
if (this.i === e) throw this.syntaxError("Bad number");
}
skipWhitespace() {
for (; !this.isEnd();) {
let e = this.peek();
if (e === " " || e === "\n" || e === "\r" || e === " ") {
this.i += 1;
continue;
}
break;
}
}
expect(e) {
if (this.next() !== e) throw this.syntaxError(`Expected '${e}'`);
}
peek() {
return this.src.charAt(this.i);
}
next() {
let e = this.src.charAt(this.i);
return this.i += 1, e;
}
isDigit(e) {
return e >= "0" && e <= "9";
}
isEnd() {
return this.i >= this.src.length;
}
syntaxError(e) {
return /* @__PURE__ */ SyntaxError(`${e} at position ${this.i}`);
}
};
function de(e, t, n) {
let r = e[t];
if (Array.isArray(r)) for (let e = 0; e < r.length; e += 1) {
let t = de(r, String(e), n);
t === void 0 ? Reflect.deleteProperty(r, e) : r[e] = t;
}
else if (se(r)) for (let e of Object.keys(r)) {
let t = de(r, e, n);
t === void 0 ? delete r[e] : r[e] = t;
}
return n.call(e, t, r);
}
function fe(e, t, n) {
let r = n?.strict === !0, i = n?.fallbackTo ?? "number";
if (i !== "number" && i !== "string" && i !== "error") throw new _(`Incorrect value for fallbackTo option, must be "number", "string", "error" or undefined but passed ${String(n?.fallbackTo)}`);
let a = new ue(String(e), r, i, ce()).parse();
return typeof t == "function" ? de({ "": a }, "", t) : a;
}
function pe(e) {
let t = JSON.stringify(e);
if (typeof t != "string") throw new _("Failed to stringify string value");
return t;
}
function me(e) {
return typeof e == "object" && !!e && "toJSON" in e && typeof e.toJSON == "function";
}
function he(e) {
return e instanceof Number || e instanceof String || e instanceof Boolean ? e.valueOf() : e;
}
function ge(e, t, n) {
let r = "", i = "", a = /* @__PURE__ */ new WeakSet();
if (typeof n == "number" ? i = " ".repeat(Math.min(10, Math.max(0, Math.floor(n)))) : typeof n == "string" && (i = n), t && typeof t != "function" && !Array.isArray(t)) throw new _("stringify: replacer must be a function or array");
let o = Array.isArray(t) ? t.map((e) => String(e)) : void 0, s = (e, n) => {
let c = e[n];
switch (c instanceof k ? c = c.toBigInt() : me(c) && (c = c.toJSON(n)), typeof t == "function" && (c = t.call(e, n, c)), c = he(c), typeof c) {
case "string": return pe(c);
case "number": return Number.isFinite(c) ? String(c) : "null";
case "boolean": return c ? "true" : "false";
case "bigint": return String(c);
case "undefined": return;
case "object": {
if (c === null) return "null";
if (a.has(c)) throw TypeError("Converting circular structure to JSON");
a.add(c);
let e = r;
r += i;
try {
if (Array.isArray(c)) {
let t = [], n = c;
for (let e = 0; e < c.length; e += 1) {
let r = s(n, String(e));
t.push(r ?? "null");
}
let i = t.length === 0 ? "[]" : r ? `[\n${r}${t.join(`,\n${r}`)}\n${e}]` : `[${t.join(",")}]`;
return r = e, i;
}
let t = c, n = o ?? Object.keys(t), i = [];
for (let e of n) {
let n = s(t, e);
n !== void 0 && i.push(`${pe(e)}${r ? ": " : ":"}${n}`);
}
let a = i.length === 0 ? "{}" : r ? `{\n${r}${i.join(`,\n${r}`)}\n${e}}` : `{${i.join(",")}}`;
return r = e, a;
} finally {
a.delete(c);
}
}
default: return;
}
};
return s({ "": e }, "");
}
//#endregion
//#region src/utils/base64.ts
function _e(e) {
return D.toBase64(e).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function ve(e) {
return D.toBase64(e).replace(/\+/g, "-").replace(/\//g, "_");
}
function ye(e) {
return D.fromBase64(e);
}
function be(e) {
let t = D.toString(D.fromBase64(xe(e)));
return A.parse(t);
}
function xe(e) {
return e.replace(/-/g, "+").replace(/_/g, "/").split("=")[0];
}
function Se(e) {
if (typeof e != "string" || e.length === 0 || !/^[A-Za-z0-9\-_]+={0,2}$/.test(e) && !/^[A-Za-z0-9+/]+={0,2}$/.test(e)) return !1;
let t = e.replace(/-/g, "+").replace(/_/g, "/"), n = (4 - t.length % 4) % 4;
if (n > 2) return !1;
let r = t + "=".repeat(n);
try {
let e = D.fromBase64(r), n = D.toBase64(e), i = n.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""), a = t.replace(/=+$/, "");
return n.replace(/=+$/, "") === a || i === a;
} catch {
return !1;
}
}
//#endregion
//#region src/utils/bech32m.ts
var Ce = 1023;
function we(e) {
let t = e.lastIndexOf("1");
if (t < 1 || t === e.length - 1) throw new _("Invalid bech32m string: missing or misplaced separator");
}
function Te(e, t, n = Ce) {
let r = s.toWords(t);
return s.encode(e, r, n);
}
function Ee(e, t = Ce) {
we(e);
let { prefix: n, words: r } = s.decode(e, t);
return {
hrp: n,
data: s.fromWords(r)
};
}
function De(e, t = Ce) {
return Ee(e, t).data;
}
//#endregion
//#region src/utils/cbor.ts
function Oe(e) {
return typeof e == "number" || typeof e == "bigint" || typeof e == "string";
}
function ke(e) {
let t = [];
return Ae(e, t), new Uint8Array(t);
}
function Ae(e, t) {
if (e === null) t.push(246);
else if (e === void 0) t.push(247);
else if (typeof e == "boolean") t.push(e ? 245 : 244);
else if (typeof e == "number") Ie(e, t);
else if (typeof e == "bigint") Me(e, t);
else if (typeof e == "string") Re(e, t);
else if (Array.isArray(e)) ze(e, t);
else if (e instanceof Uint8Array) Le(e, t);
else if (typeof e == "object" && e && !Array.isArray(e)) Be(e, t);
else throw new _("Unsupported type");
}
function je(e, t) {
e < 24 ? t.push(e) : e < 256 ? t.push(24, e) : e < 65536 ? t.push(25, e >>> 8 & 255, e & 255) : e < 4294967296 ? t.push(26, e >>> 24 & 255, e >>> 16 & 255, e >>> 8 & 255, e & 255) : Me(BigInt(e), t);
}
function Me(e, t) {
e >= 0n ? Ne(0, e, t) : Ne(1, -1n - e, t);
}
function Ne(e, t, n) {
let r = e << 5;
if (t < 24n) n.push(r | Number(t));
else if (t < 256n) n.push(r | 24, Number(t));
else if (t < 65536n) {
let e = Number(t);
n.push(r | 25, e >>> 8 & 255, e & 255);
} else if (t < 4294967296n) {
let e = Number(t);
n.push(r | 26, e >>> 24 & 255, e >>> 16 & 255, e >>> 8 & 255, e & 255);
} else if (t < 18446744073709551616n) {
let e = Number(t >> 32n), i = Number(t & 4294967295n);
n.push(r | 27, e >>> 24 & 255, e >>> 16 & 255, e >>> 8 & 255, e & 255, i >>> 24 & 255, i >>> 16 & 255, i >>> 8 & 255, i & 255);
} else throw new _("BigInt value out of uint64 range");
}
function Pe(e, t) {
let n = -1 - e;
n < 24 ? t.push(32 | n) : n < 256 ? t.push(56, n & 255) : n < 65536 ? t.push(57, n >>> 8 & 255, n & 255) : n < 4294967296 ? t.push(58, n >>> 24 & 255, n >>> 16 & 255, n >>> 8 & 255, n & 255) : Me(BigInt(e), t);
}
function Fe(e, t) {
let n = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
n.setFloat64(0, e, !1), t.push(251);
for (let e = 0; e < 8; e++) t.push(n.getUint8(e));
}
function Ie(e, t) {
Number.isInteger(e) ? e >= 0 ? je(e, t) : Pe(e, t) : Fe(e, t);
}
function Le(e, t) {
let n = e.length;
if (n < 24) t.push(64 + n);
else if (n < 256) t.push(88, n);
else if (n < 65536) t.push(89, n >> 8 & 255, n & 255);
else if (n < 4294967296) t.push(90, n >>> 24 & 255, n >>> 16 & 255, n >>> 8 & 255, n & 255);
else throw new _("Byte string too long to encode");
for (let n = 0; n < e.length; n++) t.push(e[n]);
}
function Re(e, t) {
let n = new TextEncoder().encode(e), r = n.length;
if (r < 24) t.push(96 + r);
else if (r < 256) t.push(120, r);
else if (r < 65536) t.push(121, r >>> 8 & 255, r & 255);
else if (r < 4294967296) t.push(122, r >>> 24 & 255, r >>> 16 & 255, r >>> 8 & 255, r & 255);
else throw new _("String too long to encode");
for (let e = 0; e < n.length; e++) t.push(n[e]);
}
function ze(e, t) {
let n = e.length;
if (n < 24) t.push(128 | n);
else if (n < 256) t.push(152, n);
else if (n < 65536) t.push(153, n >>> 8 & 255, n & 255);
else throw new _("Unsupported array length");
for (let n of e) Ae(n, t);
}
function Be(e, t) {
let n = Object.keys(e), r = n.length;
if (r >= 4294967296) throw new _("Object has too many keys to encode");
r < 24 ? t.push(160 | r) : r < 256 ? t.push(184, r) : r < 65536 ? t.push(185, r >> 8 & 255, r & 255) : t.push(186, r >> 24 & 255, r >> 16 & 255, r >> 8 & 255, r & 255);
for (let r of n) Re(r, t), Ae(e[r], t);
}
function Ve(e) {
return He(new DataView(e.buffer, e.byteOffset, e.byteLength), 0).value;
}
function He(e, t) {
if (t >= e.byteLength) throw new _("Unexpected end of data");
let n = e.getUint8(t++), r = n >> 5, i = n & 31;
switch (r) {
case 0: return Ue(e, t, i);
case 1: return We(e, t, i);
case 2: return Ge(e, t, i);
case 3: return Ke(e, t, i);
case 4: return qe(e, t, i);
case 5: return Je(e, t, i);
case 7: return Xe(e, t, i);
default: throw new _(`Unsupported major type: ${r}`);
}
}
function j(e, t, n) {
if (t + n > e.byteLength) throw new _("Unexpected end of data");
}
function M(e, t, n) {
if (n < 24) return {
value: n,
offset: t
};
if (n === 24) return j(e, t, 1), {
value: e.getUint8(t++),
offset: t
};
if (n === 25) {
j(e, t, 2);
let n = e.getUint16(t, !1);
return t += 2, {
value: n,
offset: t
};
}
if (n === 26) {
j(e, t, 4);
let n = e.getUint32(t, !1);
return t += 4, {
value: n,
offset: t
};
}
if (n === 27) {
j(e, t, 8);
let n = e.getUint32(t, !1), r = e.getUint32(t + 4, !1);
t += 8;
let i = n * 2 ** 32 + r;
return i > 2 ** 53 - 1 ? {
value: BigInt(n) << 32n | BigInt(r),
offset: t
} : {
value: i,
offset: t
};
}
throw new _(`Unsupported length: ${n}`);
}
function Ue(e, t, n) {
let { value: r, offset: i } = M(e, t, n);
return {
value: r,
offset: i
};
}
function We(e, t, n) {
let { value: r, offset: i } = M(e, t, n);
if (typeof r == "bigint") return {
value: -1n - r,
offset: i
};
let a = -1 - r;
return Number.isSafeInteger(a) ? {
value: a,
offset: i
} : {
value: -1n - BigInt(r),
offset: i
};
}
function Ge(e, t, n) {
let { value: r, offset: i } = M(e, t, n), a = Number(r);
if (i + a > e.byteLength) throw new _("Byte string length exceeds data length");
return {
value: new Uint8Array(e.buffer, e.byteOffset + i, a),
offset: i + a
};
}
function Ke(e, t, n) {
let { value: r, offset: i } = M(e, t, n), a = Number(r);
if (i + a > e.byteLength) throw new _("String length exceeds data length");
let o = new Uint8Array(e.buffer, e.byteOffset + i, a);
return {
value: new TextDecoder().decode(o),
offset: i + a
};
}
function qe(e, t, n) {
let { value: r, offset: i } = M(e, t, n), a = Number(r), o = [], s = i;
for (let t = 0; t < a; t++) {
let t = He(e, s);
o.push(t.value), s = t.offset;
}
return {
value: o,
offset: s
};
}
function Je(e, t, n) {
let { value: r, offset: i } = M(e, t, n), a = Number(r), o = {}, s = i;
for (let t = 0; t < a; t++) {
let t = He(e, s);
if (!Oe(t.value)) throw new _("Invalid key type");
let n = He(e, t.offset);
o[String(t.value)] = n.value, s = n.offset;
}
return {
value: o,
offset: s
};
}
function Ye(e) {
let t = (e & 31744) >> 10, n = e & 1023, r = e & 32768 ? -1 : 1;
return t === 0 ? r * 2 ** -14 * (n / 1024) : t === 31 ? n ? NaN : r * Infinity : r * 2 ** (t - 15) * (1 + n / 1024);
}
function Xe(e, t, n) {
if (n < 24) switch (n) {
case 20: return {
value: !1,
offset: t
};
case 21: return {
value: !0,
offset: t
};
case 22: return {
value: null,
offset: t
};
case 23: return {
value: void 0,
offset: t
};
default: throw new _(`Unknown simple value: ${n}`);
}
if (n === 24) return j(e, t, 1), {
value: e.getUint8(t++),
offset: t
};
if (n === 25) {
j(e, t, 2);
let n = Ye(e.getUint16(t, !1));
return t += 2, {
value: n,
offset: t
};
}
if (n === 26) {
j(e, t, 4);
let n = e.getFloat32(t, !1);
return t += 4, {
value: n,
offset: t
};
}
if (n === 27) {
j(e, t, 8);
let n = e.getFloat64(t, !1);
return t += 8, {
value: n,
offset: t
};
}
throw new _(`Unknown simple or float value: ${n}`);
}
//#endregion
//#region src/crypto/core.ts
var Ze = m("Secp256k1_HashToCurve_Cashu_");
function Qe(t) {
let n = a(D.concat(Ze, t)), r = new Uint32Array(1), i = 2 ** 16;
for (let t = 0; t < i; t++) {
let t = new Uint8Array(r.buffer), i = a(D.concat(n, t));
try {
return N(e(D.concat(new Uint8Array([2]), i)));
} catch {
r[0]++;
}
}
throw new _("No valid point found");
}
function $e(e) {
let t = e.map((e) => e.toHex(!1)).join("");
return a(new TextEncoder().encode(t));
}
function et(t) {
return l.Point.fromHex(e(t));
}
function N(e) {
return l.Point.fromHex(e);
}
var tt = (e) => {
let t;
return t = /^[a-fA-F0-9]+$/.test(e) ? Ar(e) % BigInt(2 ** 31 - 1) : D.toBigInt(ye(e)) % BigInt(2 ** 31 - 1), t;
};
function nt() {
return l.utils.randomSecretKey();
}
function rt(e, t, n) {
let r = l.Point.Fn.fromBytes(t);
return {
C_: e.multiply(r),
id: n
};
}
function it() {
let t = e(i(32));
return at(new TextEncoder().encode(t));
}
function at(e, t) {
let n = Qe(e);
if (t === void 0) t = l.Point.Fn.fromBytes(nt());
else if (t === 0n) throw new _("Blinding factor r must be non-zero");
let r = l.Point.BASE.multiply(t);
return {
B_: n.add(r),
r: t,
secret: e
};
}
function ot(e, t, n) {
return e.subtract(n.multiply(t));
}
function st(e, t, n, r) {
let i = ot(e.C_, t, r);
return {
id: e.id,
secret: n,
C: i
};
}
function P(t, n = !1) {
let r = a(new TextEncoder().encode(t));
return n ? e(r) : r;
}
var ct = (t, r) => {
let i = typeof t == "string" ? n(t) : t, a = typeof r == "string" ? n(r) : r;
return e(c.sign(i, a));
}, lt = (e, t) => ct(P(e), t), ut = (e, t, r, i = !1) => {
try {
let i = P(t), a = r.length === 66 ? r.slice(2) : r;
return c.verify(n(e), i, n(a));
} catch (e) {
if (i) throw e;
}
return !1;
};
function dt(t, r) {
let i = Array.isArray(r) ? r : [r];
for (let r of i) if (e(l.getPublicKey(n(r), !0)).toLowerCase() === t.toLowerCase()) return r;
throw new _(`No private key matches quote pubkey ${t}`);
}
function ft(e, t, n) {
return Array.from(new Set(n)).filter((n) => e.some((e) => ut(e, t, n)));
}
var pt = (e, t, n, r = 1) => ft(e, t, n).length >= r, mt = "m/0'/0'/0'";
function ht(t) {
let n = {};
return Object.keys(t).forEach((r) => {
n[r] = e(t[r]);
}), n;
}
function gt(e) {
let t = {};
return Object.keys(e).forEach((r) => {
t[r] = n(e[r]);
}), t;
}
function _t(e) {
return l.getPublicKey(e, !0);
}
function vt(e, t, n) {
let { expiry: r, input_fee_ppk: i, unit: a = "sat", versionByte: o = 1 } = n || {}, s = 0n, c = {}, l = {}, u;
for (t && (u = h.fromMasterSeed(t)); s < e;) {
let e = (2n ** s).toString();
if (u) {
let t = u.derive(`${mt}/${s}`).privateKey;
if (t) l[e] = t;
else throw new _(`Could not derive Private key from: ${mt}/${s}`);
} else l[e] = nt();
c[e] = _t(l[e]), s++;
}
return {
pubKeys: c,
privKeys: l,
keysetId: Hr(ht(c), {
expiry: r,
input_fee_ppk: i,
unit: a,
versionByte: o
})
};
}
function yt(e, t) {
let n = Qe(e.secret), r = l.Point.Fn.fromBytes(t);
return n.multiply(r).equals(e.C);
}
//#endregion
//#region src/crypto/NUT10.ts
function bt(t, n, r) {
let a = [t, {
nonce: e(i(32)),
data: n,
tags: r
}];
return JSON.stringify(a);
}
function F(e) {
let t;
try {
t = typeof e == "string" ? JSON.parse(e) : e;
} catch (e) {
throw new _("Can't parse secret", { cause: e });
}
if (!Array.isArray(t) || t.length !== 2 || typeof t[0] != "string" || typeof t[1] != "object" || t[0].trim().length === 0 || t[1] === null) throw new _("Invalid NUT-10 secret");
let [n, r] = t;
if (typeof r.nonce != "string" || typeof r.data != "string") throw new _("Invalid NUT-10 secret nonce / data");
if (r.tags) {
if (!Array.isArray(r.tags)) throw new _("Invalid NUT-10 secret tags");
if (r.tags.some((e) => !Array.isArray(e) || e.length === 0 || e.some((e) => typeof e != "string" || !e.length))) throw new _("Invalid NUT-10 tag(s)");
}
return [n, {
nonce: r.nonce,
data: r.data,
tags: r.tags
}];
}
function xt(e, t) {
let n = Array.isArray(e) ? e : [e], r = F(t), i = r[0];
if (!n.includes(i)) throw new _(`Invalid secret kind: ${i} Allowed: ${n.join(", ")}`);
return r;
}
function St(e) {
return F(e)[0];
}
function Ct(e) {
return F(e)[1];
}
function wt(e) {
let { data: t } = Ct(e);
return t;
}
function Tt(e) {
let { tags: t } = Ct(e);
return t ?? [];
}
function Et(e, t) {
return Tt(e).some((e) => e[0] === t);
}
function Dt(e, t) {
let n = Tt(e).find((e) => e[0] === t);
if (!(!n || n.length <= 1)) return n.slice(1);
}
function Ot(e, t) {
let n = Dt(e, t);
return n && n.length > 0 ? n[0] : void 0;
}
function kt(e, t) {
let n = Ot(e, t);
if (n === void 0) return;
let r = Number.parseInt(n, 10);
return Number.isFinite(r) ? r : void 0;
}
//#endregion
//#region src/crypto/NUT28.ts
var At = m("Cashu_P2BK_v1");
function jt(e, t) {
if (!e.length) return {
blinded: [],
Ehex: ""
};
t = t ?? l.utils.randomSecretKey();
let n = l.Point.Fn.fromBytes(t), r = l.getPublicKey(t, !0);
return {
blinded: e.map((e, t) => {
let r = N(e), i = Pt(r, n, t), a = r.add(l.Point.BASE.multiply(i));
if (a.equals(l.Point.ZERO)) throw new _("Blinded key at infinity");
return a.toHex(!0);
}),
Ehex: u(r)
};
}
function Mt(e, t, n) {
let r = Array.isArray(t) ? t : [t], i = Array.isArray(n) ? n : [n], a = /* @__PURE__ */ new Set(), o = l.Point.fromHex(e);
for (let e of r) {
let t = l.Point.Fn.fromBytes(f(e)), n = l.getPublicKey(f(e), !0);
i.forEach((r, i) => {
let s = Nt(e, Pt(o, t, i), f(r), n);
s && a.add(s);
});
}
return Array.from(a);
}
function Nt(e, t, n, r) {
let i = l.Point.CURVE().n, a = typeof e == "string" ? Ar(e) : e, o = typeof t == "string" ? Ar(t) : t;
if (a <= 0n || a >= i) throw new _("Invalid private key");
if (o <= 0n || o >= i) throw new _("Invalid scalar r");
if (r = r ?? l.Point.BASE.multiply(a).toBytes(!0), r.length !== 33) throw new _("naturalPub must be 33 bytes");
let s = (a + o) % i, c = (i - a + o) % i;
if (!n) {
if (s === 0n) throw new _("Derived secret key is zero");
return jr(s);
}
if (n.length !== 33) throw new _("blindPubkey must be 33 bytes");
let d = l.Point.fromHex(u(n)), f = l.Point.BASE.multiply(o), p = d.subtract(f);
if (p.equals(l.Point.ZERO)) return null;
let m = p.toBytes(!0).slice(1), h = r.slice(1);
if (!D.equals(m, h)) return null;
let g = (p.toBytes(!0)[0] & 1) == (r[0] & 1) ? s : c;
if (g === 0n) throw new _("Derived secret key is zero");
return jr(g);
}
function Pt(e, t, n) {
let r = e.multiply(t).toBytes(!0).slice(1), i = new Uint8Array([n & 255]), o = D.toBigInt(a(D.concat(At, r, i)));
if ((o === 0n || o >= l.Point.CURVE().n) && (o = D.toBigInt(a(D.concat(At, r, i, new Uint8Array([255])))), o === 0n || o >= l.Point.CURVE().n)) throw new _("P2BK: tweak derivation failed");
return o;
}
//#endregion
//#region src/crypto/NUT11.ts
var Ft = {
SIG_INPUTS: "SIG_INPUTS",
SIG_ALL: "SIG_ALL"
}, It = new Set(Object.values(Ft)), Lt = new Set([
"locktime",
"pubkeys",
"n_sigs",
"refund",
"n_sigs_refund",
"sigflag"
]);
function Rt(e, t) {
let n = bt("P2PK", e, t);
return I(n), n;
}
function I(e) {
let t = xt(["P2PK", "HTLC"], e);
en(Tt(t));
let n = Ot(t, "sigflag");
return n !== void 0 && tn(n), t;
}
function zt(e) {
let t = e.toLowerCase();
if (t.length === 66 && (t.startsWith("02") || t.startsWith("03"))) return t;
if (t.length === 64) return `02${t}`;
throw new _(`Invalid pubkey, expected 33 byte compressed or 32 byte x only, got length ${t.length}`);
}
function L(e) {
let t = /* @__PURE__ */ new Set(), n = [];
for (let r of e) {
let e = zt(r), i = e.slice(-64);
t.has(i) || (t.add(i), n.push(e));
}
return n;
}
function Bt(e) {
let t = L(Array.isArray(e.pubkey) ? e.pubkey : [e.pubkey]), n = L(e.refundKeys ?? []);
if (t.length === 0) throw new _("P2PK requires at least one pubkey");
let r = t.length + n.length;
if (r > 10) throw new _(`Too many pubkeys, ${r} provided, maximum allowed is 10 in total`);
e.sigFlag !== void 0 && tn(e.sigFlag);
let i = e.requiredSignatures ?? 1, a = e.requiredRefundSignatures;
return rn({
mainKeyCount: t.length,
refundKeyCount: n.length,
nSigs: i,
nSigsRefund: a,
hasLocktime: e.locktime !== void 0
}), {
pubkey: t.length === 1 ? t[0] : t,
...e.locktime === void 0 ? {} : { locktime: e.locktime },
...n.length > 0 ? { refundKeys: n } : {},
...i > 1 ? { requiredSignatures: i } : {},
...a !== void 0 && a > 1 ? { requiredRefundSignatures: a } : {},
...e.additionalTags?.length ? { additionalTags: e.additionalTags } : {},
...e.blindKeys ? { blindKeys: !0 } : {},
...e.sigFlag === void 0 ? {} : { sigFlag: e.sigFlag },
...e.hashlock ? { hashlock: e.hashlock } : {}
};
}
function Vt(e) {
let t = I(e), n = cn(sn(t)), r = an(t), i = on(t);
return n === "ACTIVE" || n === "PERMANENT" ? r : n === "EXPIRED" && i.length ? Array.from(new Set([...r, ...i])) : [];
}
function Ht(e) {
return Ot(I(e), "sigflag") ?? "SIG_INPUTS";
}
function Ut(e) {
return Wt(e)?.signatures ?? [];
}
function Wt(e) {
if (!e) return;
let t;
try {
t = typeof e == "string" ? JSON.parse(e) : e;
} catch (e) {
console.error("Failed to parse witness string:", e);
return;
}
let n = { signatures: t.signatures ?? [] };
return typeof t.preimage == "string" && t.preimage.length > 0 && (n.preimage = t.preimage), n;
}
function Gt(t, n, r = S, i) {
let a = (t) => typeof t == "string" ? t : e(t), o = Array.isArray(n) ? n.map(a) : a(n);
return t.map((e, t) => {
let n = Xt(o, e), a = e;
for (let e of n) try {
a = Kt(a, e, i);
} catch (e) {
let n = e instanceof Error ? e.message : "Unknown error";
r.warn(`Proof #${t + 1}: ${n}`);
}
return a;
});
}
function Kt(t, r, i) {
let a = I(t.secret);
i = i ?? t.secret;
let o = typeof r == "string" ? n(r) : r, s = e(c.getPublicKey(o)), l = Vt(a);
if (!l.length || !l.some((e) => e.includes(s))) throw new _(`Signature not required from [02|03]${s}`);
if (Ut(t.witness).some((e) => ut(e, i, s))) throw new _(`Proof already signed by [02|03]${s}`);
let u = lt(i, r), d = Wt(t.witness), f = {
...d && d.preimage !== void 0 ? { preimage: d.preimage } : {},
signatures: [...d?.signatures ?? [], u]
};
return {
...t,
witness: f
};
}
function qt(e, t, n) {
if (!t.witness) return !1;
if ($t([t]) && !n) throw new _("Cannot verify a SIG_ALL proof without the message to sign");
return n = n ?? t.secret, Ut(t.witness).some((t) => ut(t, n, e));
}
function Jt(e, t = S, n) {
if ($t([e]) && !n) throw t.error("Cannot verify a SIG_ALL proof without the message to sign"), new _("Cannot verify a SIG_ALL proof without the message to sign");
n = n ?? e.secret;
let r = I(e.secret), i = an(r), a = on(r);
rn({
mainKeyCount: i.length,
refundKeyCount: a.length,
nSigs: kt(r, "n_sigs"),
nSigsRefund: kt(r, "n_sigs_refund"),
hasLocktime: Number.isFinite(sn(r))
});
let o = Ut(e.witness), s = sn(r), c = cn(s), l = ln(r, c, a), u = un(r, c, a), d = ft(o, n, i), f = a.length ? ft(o, n, a) : [], p = {
locktime: s,
lockState: c,
main: {
pubkeys: i,
requiredSigners: l,
receivedSigners: d
},
refund: {
pubkeys: a,
requiredSigners: u,
receivedSigners: f
}
};
if (i.length && l > 0 && d.length >= l) {
let e = {
...p,
success: !0,
path: "MAIN"
};
return t.debug("Spending condition satisfied via main pubkeys", { result: e }), e;
}
if (c !== "EXPIRED") {
let e = {
...p,
success: !1,
path: "FAILED"
};
return t.debug("P2PK lock enabled, but threshold not met by main pubkeys", { result: e }), e;
}
if (t.debug("P2PK lock expired. Checking refund path.", { lockState: c }), a.length) {
if (u > 0 && f.length >= u) {
let e = {
...p,
success: !0,
path: "REFUND"
};
return t.debug("Spending condition satisfied via refund pubkeys", { result: e }), e;
}
let e = {
...p,
success: !1,
path: "FAILED"
};
return t.debug("Spending threshold not met by either pathway", { result: e }), e;
}
let m = {
...p,
success: !0,
path: "UNLOCKED"
};
return t.debug("No refund pubkeys, anyone can spend.", { result: m }), m;
}
function Yt(e, t = S, n) {
return Jt(e, t, n).success;
}
function Xt(e, t) {
let n = Array.isArray(e) ? e : [e], r = t?.p2pk_e;
if (!r) return Array.from(new Set(n));
let i = I(t.secret);
return Mt(r, n, [...an(i), ...on(i)]);
}
function Zt(e) {
if (e.length === 0) throw new _("No proofs");
let t = I(e[0].secret);
if (Ht(t) !== "SIG_ALL") throw new _("First proof is not SIG_ALL");
let n = t[1].data, r = JSON.stringify(t[1].tags ?? []);
for (let i = 1; i < e.length; i++) {
let a = I(e[i].secret);
if (a[0] !== t[0]) throw new _(`Proof #${i + 1} is not ${t[0]}`);
if (Ht(a) !== "SIG_ALL") throw new _(`Proof #${i + 1} is not SIG_ALL`);
if (a[1].data !== n) throw new _("SIG_ALL inputs must share identical Secret.data");
if (JSON.stringify(a[1].tags ?? []) !== r) throw new _("SIG_ALL inputs must share identical Secret.tags");
}
}
function Qt(e, t, n) {
let r = [];
for (let t of e) r.push(t.secret, t.C);
for (let e of t) r.push(String(e.blindedMessage.amount), e.blindedMessage.B_);
return n && r.push(n), r.join("");
}
function $t(e) {
return e.some((e) => {
try {
return Ht(e.secret) === "SIG_ALL";
} catch {
return !1;
}
});
}
function en(e) {
let t = /* @__PURE__ */ new Set();
for (let n of e) {
let e = n[0];
if (Lt.has(e)) {
if (t.has(e)) throw new _(`Duplicate P2PK tag "${e}"`);
t.add(e);
}
}
}
function tn(e) {
if (!It.has(e)) throw new _(`Invalid sigflag "${e}": must be "SIG_INPUTS" or "SIG_ALL"`);
}
function nn(e, t) {
if (!Number.isInteger(e) || e < 1) throw new _(`${t} must be a positive integer, got ${e}`);
return e;
}
function rn(e) {
let { mainKeyCount: t, refundKeyCount: n, nSigs: r, nSigsRefund: i, hasLocktime: a } = e;
if (r !== void 0 && (nn(r, "requiredSignatures (n_sigs)"), r > t)) throw new _(`requiredSignatures (n_sigs) (${r}) exceeds available pubkeys (${t})`);
if (i !== void 0) {
if (nn(i, "requiredRefundSignatures (n_sigs_refund)"), n === 0) throw new _("requiredRefundSignatures (n_sigs_refund) requires refund keys");
if (i > n) throw new _(`requiredRefundSignatures (n_sigs_refund) (${i}) exceeds available refund keys (${n})`);
}
if (n > 0 && !a) throw new _("refund keys require a locktime");
}
function an(e) {
let t = St(e) === "P2PK" ? wt(e) : "", n = Dt(e, "pubkeys") ?? [], r = (t ? [t, ...n] : n).map((e) => zt(e));
if (L(r).length !== r.length) throw new _("Duplicate main pubkeys are not allowed");
return r;
}
function on(e) {
let t = (Dt(e, "refund") ?? []).map((e) => zt(e));
if (L(t).length !== t.length) throw new _("Duplicate refund pubkeys are not allowed");
return t;
}
function sn(e) {
let t = kt(e, "locktime");
return t === void 0 || !Number.isFinite(t) || t <= 0 ? Infinity : t;
}
function cn(e, t = Math.floor(Date.now() / 1e3)) {
return Number.isFinite(e) ? t < e ? "ACTIVE" : "EXPIRED" : "PERMANENT";
}
function ln(e, t, n) {
return !n.length && t === "EXPIRED" ? 0 : Math.max(kt(e, "n_sigs") ?? 1, 1);
}
function un(e, t, n) {
return n.length && t === "EXPIRED" ? Math.max(kt(e, "n_sigs_refund") ?? 1, 1) : 0;
}
function dn(e, t, n) {
let r = [];
for (let t of e) r.push(t.secret);
for (let e of t) r.push(e.blindedMessage.B_);
return n && r.push(n), r.join("");
}
//#endregion
//#region src/crypto/NUT12.ts
var fn = m("Cashu_DLEQ_R_v1"), pn = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
function mn(e, n, r, i) {
let o = d(fn, n.toBytes(!1), r.toBytes(!1), i.toBytes(!1));
for (let n = 0; n < 256; n++) {
let r = t(g(a, e, d(o, new Uint8Array([n])))), i = r >= pn ? r - pn : r;
/* c8 ignore next */
if (i !== 0n) return i;
}
/* c8 ignore next */
throw new _("DLEQ nonce derivation failed");
}
var hn = (e, t, n, r) => {
let i = l.Point.Fn.fromBytes(e.s), a = l.Point.Fn.fromBytes(e.e), o = l.Point.BASE.multiply(i), s = r.multiply(a), c = t.multiply(i), u = n.multiply(a), d = $e([
o.subtract(s),
c.subtract(u),
r,
n
]);
return D.equals(d, e.e);
}, gn = (e, t, n, r) => {
if (t.r === void 0) throw new _("verifyDLEQProof_reblind: Undefined blinding factor");
let i = Qe(e), a = n.add(r.multiply(t.r)), o = l.Point.BASE.multiply(t.r);
return hn(t, i.add(o), a, r);
}, _n = (e, t) => {
let n = l.Point.Fn.fromBytes(t), i = l.Point.BASE.multiply(n), a = e.multiply(n), o = mn(t, i, e, a), s = $e([
l.Point.BASE.multiply(o),
e.multiply(o),
i,
a
]), c = l.Point.Fn.fromBytes(s);
return {
s: r(l.Point.Fn.add(o, l.Point.Fn.mul(c, n)), 32),
e: s
};
}, vn = "m/129372'/0'", yn = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"), R = /* @__PURE__ */ function(e) {
return e[e.SECRET = 0] = "SECRET", e[e.BLINDING_FACTOR = 1] = "BLINDING_FACTOR", e;
}(R || {}), bn = /* @__PURE__ */ function(e) {
return e[e.DEPRECATED_BIP32 = 0] = "DEPRECATED_BIP32", e[e.HMAC_SHA256 = 1] = "HMAC_SHA256", e;
}(bn || {}), xn = (e, t, n) => Cn(e, t, n).secret, Sn = (e, t, n) => Cn(e, t, n).blindingFactor;
function Cn(e, t, n) {
return wn(e, t)(n);
}
function wn(e, t) {
switch (Tn(t)) {
case bn.DEPRECATED_BIP32: {
let n = h.fromMasterSeed(e);
return (e) => En(n, t, e);
}
case bn.HMAC_SHA256: return (n) => Dn(e, t, n);
}
}
function Tn(e) {
let t = /^[a-fA-F0-9]+$/.test(e);
if (!t && Se(e) || t && e.startsWith("00")) return bn.DEPRECATED_BIP32;
if (t && e.startsWith("01")) return bn.HMAC_SHA256;
throw new _(`Unrecognized keyset ID version ${e.slice(0, 2)}`);
}
function En(e, t, n) {
let r = `${vn}/${tt(t)}'/${n}'`, i = e.derive(r), a = i.deriveChild(0).privateKey, o = i.deriveChild(1).privateKey;
/* c8 ignore next */
if (a === null || o === null) throw new _("Could not derive private key");
return {
secret: a,
blindingFactor: o
};
}
function Dn(e, t, n) {
return {
secret: On(e, t, n, R.SECRET),
blindingFactor: On(e, t, n, R.BLINDING_FACTOR)
};
}
function On(e, t, n, i) {
let o = D.concat(D.fromString("Cashu_KDF_HMAC_SHA256"), D.fromHex(t), D.writeBigUint64BE(BigInt(n)));
switch (i) {
case R.SECRET:
o = D.concat(o, D.fromHex("00"));
break;
case R.BLINDING_FACTOR: o = D.concat(o, D.fromHex("01"));
}
let s = g(a, e, o);
if (i === R.BLINDING_FACTOR) {
let e = D.toBigInt(s), t = e >= yn ? e - yn : e;
/* c8 ignore next */
if (t === 0n) throw new _("Derived invalid blinding scalar r == 0");
return r(t, 32);
}
return s;
}
//#endregion
//#region src/crypto/NUT14.ts
function kn(e, t) {
return bt("HTLC", e, t);
}
function An(e) {
return xt("HTLC", e);
}
function jn(t) {
let r = t !== void 0;
if (r && !/^[0-9a-f]{64}$/i.test(t)) throw new _("Preimage must be a 64 character hexadecimal string (32 bytes).");
let o = r ? n(t) : i(32);
return {
hash: e(a(o)),
preimage: e(o)
};
}
function Mn(e, t) {
let { hash: n } = jn(e);
return t === n;
}
function Nn(e, t = S, n) {
let r;
n = n ?? e.secret;
let i = F(e.secret), a = Jt(e, t, n);
if (a.path != "MAIN" || St(i) !== "HTLC") return a;
let o = Fn(e.witness);
return o ? Mn(o, wt(i)) ? (r = a, t.debug("Spending condition satisfied via hashlock (receiver) pathway", { result: r }), r) : (r = {
...a,
success: !1,
path: "FAILED"
}, t.debug("Hashlock spend failed, wrong preimage for hash", { result: r }), r) : (r = {
...a,
success: !1,
path: "FAILED"
}, t.debug("Hashlock spend failed, no preimage found", { result: r }), r);
}
function Pn(e, t = S, n) {
return Nn(e, t, n).success;
}
function Fn(e) {
if (!e) return;
let t;
try {
t = typeof e == "string" ? JSON.parse(e) : e;
} catch (e) {
console.error("Failed to parse HTLC witness string:", e);
return;
}
let n = t.preimage;
return typeof n == "string" && n.length > 0 ? n : void 0;
}
//#endregion
//#region src/crypto/NUT20.ts
function In(e, t) {
let n = e;
for (let e of t) n += e.B_;
return a(new TextEncoder().encode(n));
}
function Ln(e, t, n) {
let r = In(t, n), i = f(e);
return u(c.sign(r, i));
}
function Rn(e, t, n, r) {
let i = f(r), a = f(e);
if (a.length !== 33) return !1;
a = a.slice(1);
let o = In(t, n);
return c.verify(i, o, a);
}
//#endregion
//#region src/wallet/types/payment-requests.ts
var zn = /* @__PURE__ */ function(e) {
return e.POST = "post", e.NOSTR = "nostr", e;
}({}), Bn = 1, Vn = 2, Hn = 3, Un = 4, Wn = 5, Gn = 6, Kn = 7, qn = 8, Jn = 1, Yn = 2, Xn = 3, Zn = 0, Qn = 1, $n = 1, er = 2, tr = 3, nr = 0, rr = 1;
function ir(e) {
let t = ar(e), n = {};
for (let e of t) switch (e.tag) {
case Bn:
n.id = z(e.value);
break;
case Vn:
n.amount = sr(e.value);
break;
case Hn:
e.value.length === 1 && e.value[0] === 0 ? n.unit = "sat" : n.unit = z(e.value);
break;
c