@qntx/wallet-chains 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,632 @@
1
+ import { ChainError } from "./index.mjs";
2
+ import { n as secp256k1, t as schnorr } from "./secp256k1-D0CRzacO.mjs";
3
+ import { a as bitcoinNetwork, i as BITCOIN_NETWORKS, t as bip322ToSpendTxid } from "./message-AfNel4WZ.mjs";
4
+ import { Address, OutScript, p2tr, p2wpkh } from "@scure/btc-signer/payment.js";
5
+ import { SigHash, Transaction, getInputType } from "@scure/btc-signer/transaction.js";
6
+ import { HDKey } from "@scure/bip32";
7
+ //#region src/bitcoin/psbt.ts
8
+ /**
9
+ * BIP-32 derivation paths carry a coin type: 0 for mainnet, 1 for every test network. This is what
10
+ * binds PSBT metadata to the requested network — the raw output scripts themselves carry no network
11
+ * marker.
12
+ */
13
+ const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14
+ /**
15
+ * Bip32Derivation values are [pubkey, { fingerprint, path }] tuples; tapBip32Derivation values are
16
+ * { hashes, der: { fingerprint, path } }.
17
+ */
18
+ const derivationPaths = (map) => {
19
+ const entries = map instanceof Map ? [...map.values()] : Array.isArray(map) ? map : isRecord$2(map) ? Object.values(map) : [];
20
+ const paths = [];
21
+ for (const entry of entries) {
22
+ const value = Array.isArray(entry) ? entry[1] : entry;
23
+ if (!isRecord$2(value)) continue;
24
+ const { path } = isRecord$2(value["der"]) ? value["der"] : value;
25
+ if (Array.isArray(path) && path.every((p) => typeof p === "number")) paths.push(path);
26
+ }
27
+ return paths;
28
+ };
29
+ const checkPaths = (paths, where, coinType) => {
30
+ for (const path of paths) if (path.length >= 2 && (path[1] ?? -1) - 2147483648 !== coinType) throw new ChainError("chain-id-mismatch", `${where} derivation coin type is not this network's`);
31
+ };
32
+ const checkDerivations = (tx, coinType) => {
33
+ for (let i = 0; i < tx.inputsLength; i++) {
34
+ const input = tx.getInput(i);
35
+ checkPaths(derivationPaths(input.bip32Derivation), `input ${i}`, coinType);
36
+ checkPaths(derivationPaths(input.tapBip32Derivation), `input ${i}`, coinType);
37
+ }
38
+ for (let i = 0; i < tx.outputsLength; i++) {
39
+ const output = tx.getOutput(i);
40
+ checkPaths(derivationPaths(output.bip32Derivation), `output ${i}`, coinType);
41
+ checkPaths(derivationPaths(output.tapBip32Derivation), `output ${i}`, coinType);
42
+ }
43
+ };
44
+ const DEFAULT_SIGHASH = 0;
45
+ const SIGHASH_ALL = 1;
46
+ const isTaprootInput = (input) => input.tapInternalKey !== void 0 || getInputType(input).type === "taproot";
47
+ /**
48
+ * Validates and canonicalizes a bitcoin.psbt request (network already checked by the caller).
49
+ * `strictPrevoutValidation` makes btc-signer verify every `nonWitnessUtxo`'s txid against its
50
+ * outpoint.
51
+ */
52
+ const normalizeBitcoinPsbt = (psbt, sign, network) => {
53
+ const net = bitcoinNetwork(network);
54
+ let tx;
55
+ try {
56
+ tx = Transaction.fromPSBT(psbt, { strictPrevoutValidation: true });
57
+ } catch {
58
+ throw new ChainError("invalid-request", "PSBT failed to decode");
59
+ }
60
+ if (!Array.isArray(sign) || sign.length === 0 || !sign.every((i) => Number.isSafeInteger(i) && i >= 0)) throw new ChainError("invalid-request", "sign must be a non-empty array of input indices");
61
+ const unique = [...new Set(sign.map(Number))].sort((a, b) => a - b);
62
+ const last = unique.at(-1);
63
+ if (unique.length !== sign.length || last === void 0 || last >= tx.inputsLength) throw new ChainError("invalid-request", "sign must be unique, ascending, and in range");
64
+ checkDerivations(tx, net.coinType);
65
+ for (const idx of unique) {
66
+ const input = tx.getInput(idx);
67
+ if (input.witnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} is missing witnessUtxo`);
68
+ if (input.bip32Derivation === void 0 && input.tapBip32Derivation === void 0) throw new ChainError("invalid-request", `input ${idx} is missing a bip32 derivation`);
69
+ const { type } = getInputType(input);
70
+ if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} is missing nonWitnessUtxo`);
71
+ const sighash = input.sighashType;
72
+ if (!(sighash === void 0 || sighash === SIGHASH_ALL || isTaprootInput(input) && sighash === DEFAULT_SIGHASH)) throw new ChainError("unsupported", `input ${idx} uses a non-default sighash`);
73
+ }
74
+ return {
75
+ psbt: tx.toPSBT(0),
76
+ sign: unique
77
+ };
78
+ };
79
+ //#endregion
80
+ //#region src/bitcoin/account.ts
81
+ /** Public-derivation helpers for account-level extended keys — no secrets involved. */
82
+ /**
83
+ * Derive the address at `change`/`index` under an account-level xpub (`m/84'/c'/i'` or
84
+ * `m/86'/c'/i'`) — P2WPKH for `btc.bip84`, P2TR key-path for `btc.bip86`.
85
+ */
86
+ function bitcoinAddressFromXpub(xpub, template, network, change, index) {
87
+ if (!Number.isInteger(index) || index < 0) throw new ChainError("invalid-request", "index must be a non-negative integer");
88
+ const net = bitcoinNetwork(network);
89
+ let node;
90
+ try {
91
+ node = HDKey.fromExtendedKey(xpub, net.bip32);
92
+ } catch (error) {
93
+ throw new ChainError("invalid-request", `xpub: ${error instanceof Error ? error.message : String(error)}`);
94
+ }
95
+ const pub = node.derive(`m/${change}/${index}`).publicKey;
96
+ if (pub === null) throw new ChainError("invalid-request", "xpub carries no public key");
97
+ const address = template === "btc.bip84" ? p2wpkh(pub, net.params).address : p2tr(pub.subarray(1), void 0, net.params).address;
98
+ if (address === void 0) throw new ChainError("invalid-request", "could not encode the derived address");
99
+ return address;
100
+ }
101
+ //#endregion
102
+ //#region src/bitcoin/decode.ts
103
+ const SATS = "sats";
104
+ const OP_RETURN = 106;
105
+ const bytesToHex = (bytes) => {
106
+ let out = "";
107
+ for (const b of bytes) out += b.toString(16).padStart(2, "0");
108
+ return out;
109
+ };
110
+ /** Decodes an output scriptPubKey; OP_RETURN gets an amount-0 display row. */
111
+ const decodeOutput = (script, amount) => {
112
+ const hex = bytesToHex(script);
113
+ if (script[0] === OP_RETURN) return {
114
+ amount,
115
+ script: hex,
116
+ opReturn: true
117
+ };
118
+ return {
119
+ amount,
120
+ script: hex,
121
+ opReturn: false
122
+ };
123
+ };
124
+ /**
125
+ * Decodes a normalized bitcoin.psbt request for display. `ownScripts` is the set of output script
126
+ * hexes the caller has independently verified as this account's (e.g. the kernel re-deriving
127
+ * change) — not a display hint.
128
+ */
129
+ const decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set()) => {
130
+ const tx = Transaction.fromPSBT(request.psbt);
131
+ const coder = Address(bitcoinNetwork(request.network).params);
132
+ const signed = new Set(request.sign);
133
+ const outflows = [];
134
+ let canFee = true;
135
+ let outSum = 0n;
136
+ for (let i = 0; i < tx.outputsLength; i++) {
137
+ const output = tx.getOutput(i);
138
+ const { script } = output;
139
+ const { amount } = output;
140
+ if (script === void 0 || amount === void 0) continue;
141
+ const decoded = decodeOutput(script, amount);
142
+ outSum += amount;
143
+ if (decoded.opReturn || ownScripts.has(decoded.script)) continue;
144
+ let addr;
145
+ try {
146
+ const out = OutScript.decode(script);
147
+ addr = out === void 0 ? void 0 : coder.encode(out);
148
+ } catch {
149
+ addr = void 0;
150
+ }
151
+ outflows.push({
152
+ to: addr ?? decoded.script,
153
+ amount: {
154
+ asset: SATS,
155
+ amount: amount.toString(10)
156
+ },
157
+ verified: addr !== void 0
158
+ });
159
+ }
160
+ let inSum = 0n;
161
+ for (let i = 0; i < tx.inputsLength; i++) {
162
+ const input = tx.getInput(i);
163
+ if (input.witnessUtxo === void 0) canFee = false;
164
+ else inSum += input.witnessUtxo.amount;
165
+ }
166
+ const external = tx.inputsLength - signed.size > 0;
167
+ const undecodable = outflows.some((o) => !o.verified);
168
+ const verifiability = external ? "opaque" : undecodable ? "partial" : "full";
169
+ return {
170
+ family: "bitcoin",
171
+ network: request.network,
172
+ summary: outflows.length > 0 ? "transfer" : "contract-call",
173
+ outflows,
174
+ approvals: [],
175
+ fee: canFee ? { max: {
176
+ asset: SATS,
177
+ amount: (inSum - outSum).toString(10)
178
+ } } : void 0,
179
+ warnings: [],
180
+ verifiability
181
+ };
182
+ };
183
+ const verifiabilityBitcoin = (request, ownScripts = /* @__PURE__ */ new Set()) => decodeBitcoinPsbt(request, ownScripts).verifiability;
184
+ //#endregion
185
+ //#region ../../node_modules/.bun/@scure+base@2.4.0/node_modules/@scure/base/index.js
186
+ /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
187
+ const freeze = (fn) => Object.freeze(fn());
188
+ function isBytes(a) {
189
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
190
+ }
191
+ /** Asserts something is Uint8Array. */
192
+ function abytes(b) {
193
+ if (!isBytes(b)) throw new TypeError("Uint8Array expected");
194
+ }
195
+ function astr(label, input) {
196
+ if (typeof input !== "string") throw new TypeError(`${label}: string expected`);
197
+ return true;
198
+ }
199
+ function anumber(n, title = "number") {
200
+ if (typeof n !== "number") throw new TypeError(`${title}: expected number, got ${typeof n}`);
201
+ if (!Number.isSafeInteger(n)) throw new RangeError(`${title}: expected safe integer, got ${n}`);
202
+ }
203
+ function chain(...args) {
204
+ const id = (a) => a;
205
+ const wrap = (a, b) => (c) => a(b(c));
206
+ return {
207
+ encode: args.map((x) => x.encode).reduceRight(wrap, id),
208
+ decode: args.map((x) => x.decode).reduce(wrap, id)
209
+ };
210
+ }
211
+ const powers = /* @__PURE__ */ (() => {
212
+ let res = [];
213
+ for (let i = 0; i < 40; i++) res.push(2 ** i);
214
+ return res;
215
+ })();
216
+ const asciiDecoder = /* @__PURE__ */ (() => {
217
+ try {
218
+ const decoder = new TextDecoder();
219
+ return decoder.decode(Uint8Array.of(65, 48, 43, 127)) === "A0+" ? decoder : void 0;
220
+ } catch (e) {
221
+ return;
222
+ }
223
+ })();
224
+ const B2S_CHUNK = 8192;
225
+ function charcodesToString(codes) {
226
+ const len = codes.length;
227
+ if (asciiDecoder !== void 0 && len >= 12) return asciiDecoder.decode(codes);
228
+ if (len <= B2S_CHUNK) return String.fromCharCode.apply(null, codes);
229
+ let res = "";
230
+ for (let i = 0; i < len; i += B2S_CHUNK) res += String.fromCharCode.apply(null, codes.subarray(i, i + B2S_CHUNK));
231
+ return res;
232
+ }
233
+ /**
234
+ * Linear 8 <-> bits regrouping (radix2Slow semantics), with Uint8Array digits and
235
+ * preallocated output.
236
+ */
237
+ function radix2(bits) {
238
+ anumber(bits);
239
+ if (bits <= 0 || bits > 8) throw new RangeError("radix2: bits should be in (0..8]");
240
+ const mask = powers[bits] - 1;
241
+ return {
242
+ encode: (bytes) => {
243
+ abytes(bytes);
244
+ const len = bytes.length;
245
+ const res = new Uint8Array(Math.ceil(len * 8 / bits));
246
+ let carry = 0;
247
+ let pos = 0;
248
+ let j = 0;
249
+ for (let i = 0; i < len;) {
250
+ if (i + 2 < len) {
251
+ carry = carry << 24 | bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
252
+ pos += 24;
253
+ i += 3;
254
+ } else {
255
+ carry = (carry << 8 | bytes[i]) & 65535;
256
+ pos += 8;
257
+ i++;
258
+ }
259
+ for (;;) {
260
+ pos -= bits;
261
+ res[j++] = carry >> pos & mask;
262
+ if (pos < bits) break;
263
+ }
264
+ }
265
+ if (pos > 0) res[j] = carry << bits - pos & mask;
266
+ return res;
267
+ },
268
+ decode: (digits) => {
269
+ const len = digits.length;
270
+ const res = new Uint8Array(Math.floor(len * bits / 8));
271
+ let carry = 0;
272
+ let pos = 0;
273
+ let j = 0;
274
+ for (let i = 0; i < len; i++) {
275
+ carry = (carry << bits | digits[i]) & 65535;
276
+ pos += bits;
277
+ for (; pos >= 8; pos -= 8) res[j++] = carry >> pos - 8 & 255;
278
+ }
279
+ carry = carry << 8 - pos & 255;
280
+ if (pos >= bits) throw new Error("Excess padding");
281
+ if (carry > 0) throw new Error(`Non-zero padding: ${carry}`);
282
+ return res;
283
+ }
284
+ };
285
+ }
286
+ /**
287
+ * Digit <-> letter mapping fused with string join (chain(alphabetSlow(letters), join(''))
288
+ * semantics), via char-code lookup tables.
289
+ */
290
+ function alphabet(letters, aliases) {
291
+ const len = letters.length;
292
+ if (len > 128) throw new Error("alphabet: max 128 letters");
293
+ const encTable = new Uint8Array(len);
294
+ const decTable = (/* @__PURE__ */ new Int8Array(128)).fill(-1);
295
+ for (let i = 0; i < len; i++) {
296
+ const code = letters.charCodeAt(i);
297
+ if (letters.codePointAt(i) !== code || code > 127) throw new Error("alphabet: single-char ASCII letters only");
298
+ encTable[i] = code;
299
+ decTable[code] = i;
300
+ }
301
+ if (aliases !== void 0) for (const alias of Object.keys(aliases)) {
302
+ const code = alias.charCodeAt(0);
303
+ const target = decTable[aliases[alias].charCodeAt(0)];
304
+ if (alias.length !== 1 || code > 127 || target === void 0 || target === -1) throw new Error(`alphabet: invalid alias ${alias}`);
305
+ decTable[code] = target;
306
+ }
307
+ return {
308
+ encode: (digits) => {
309
+ const codes = new Uint8Array(digits.length);
310
+ for (let i = 0; i < digits.length; i++) {
311
+ const d = digits[i];
312
+ const code = encTable[d];
313
+ if (code === void 0) throw new Error(`alphabet.encode: invalid digit ${d}`);
314
+ codes[i] = code;
315
+ }
316
+ return charcodesToString(codes);
317
+ },
318
+ decode: (input) => {
319
+ astr("decode", input);
320
+ const slen = input.length;
321
+ const digits = new Uint8Array(slen);
322
+ for (let i = 0; i < slen; i++) {
323
+ const code = input.charCodeAt(i);
324
+ const digit = code < 128 ? decTable[code] : -1;
325
+ if (digit === -1) throw new Error(`Unknown letter "${input[i]}". Allowed: ${letters}`);
326
+ digits[i] = digit;
327
+ }
328
+ return digits;
329
+ }
330
+ };
331
+ }
332
+ /**
333
+ * Pad / unpad (paddingSlow semantics), on the joined string.
334
+ */
335
+ function padding(bits, chr = "=") {
336
+ anumber(bits);
337
+ astr("padding", chr);
338
+ return {
339
+ encode(data) {
340
+ while (data.length * bits % 8) data += chr;
341
+ return data;
342
+ },
343
+ decode(input) {
344
+ astr("decode", input);
345
+ let end = input.length;
346
+ if (end * bits % 8) throw new Error("padding: invalid length");
347
+ for (; end > 0 && input[end - 1] === chr; end--) if ((end - 1) * bits % 8 === 0) throw new Error("padding: excess padding");
348
+ return input.slice(0, end);
349
+ }
350
+ };
351
+ }
352
+ const hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === "function" && typeof Uint8Array.fromBase64 === "function")();
353
+ const ASCII_WHITESPACE = /[\t\n\f\r ]/;
354
+ const decodeBase64Builtin = (s, isUrl) => {
355
+ astr("base64", s);
356
+ const alphabet = isUrl ? "base64url" : "base64";
357
+ if (s.length > 0 && ASCII_WHITESPACE.test(s)) throw new Error("invalid base64");
358
+ return Uint8Array.fromBase64(s, {
359
+ alphabet,
360
+ lastChunkHandling: "strict"
361
+ });
362
+ };
363
+ /** base64 from RFC 4648. Padded. Pure JS version */
364
+ const base64Fallback = /* @__PURE__ */ freeze(() => chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6)));
365
+ /**
366
+ * base64 from RFC 4648. Padded.
367
+ * Alternative variants: `base64nopad`, `base64url`, `base64urlnopad`.
368
+ * Utilizes native `Uint8Array.fromBase64` builtin, otherwise falls back to `base64fallback` when it's unavailable.
369
+ * @example
370
+ * ```js
371
+ * base64.encode(Uint8Array.from([0x12, 0xab]));
372
+ * // => 'Eqs='
373
+ * base64.decode('Eqs=');
374
+ * // => Uint8Array.from([0x12, 0xab])
375
+ * ```
376
+ */
377
+ const base64 = /* @__PURE__ */ freeze(() => hasBase64Builtin ? {
378
+ encode(b) {
379
+ abytes(b);
380
+ return b.toBase64();
381
+ },
382
+ decode(s) {
383
+ return decodeBase64Builtin(s, false);
384
+ }
385
+ } : base64Fallback);
386
+ //#endregion
387
+ //#region src/bitcoin/verify.ts
388
+ /**
389
+ * Result verification for `chain.sign`: the host re-checks the kernel's Bitcoin work against the
390
+ * account's xpub — a kernel returning someone else's signature fails closed with `integrity`.
391
+ * `/bitcoin` entry only — no private key material.
392
+ */
393
+ const isRecord$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Uint8Array);
394
+ /** Derive the child's public key from the account xpub at `change/index` (non-hardened). */
395
+ const childPub = (xpub, network, change, index) => {
396
+ const child = HDKey.fromExtendedKey(xpub, bitcoinNetwork(network).bip32).deriveChild(change).deriveChild(index);
397
+ if (child.publicKey === null || child.publicKey === void 0) throw new Error("xpub cannot derive this child");
398
+ return child.publicKey;
399
+ };
400
+ /** Extract `[pubkey, {fingerprint, path}]`-shaped entries from either PSBT derivation map. */
401
+ const derivationOf = (map) => {
402
+ const out = [];
403
+ const readEntry = (key, value) => {
404
+ const der = isRecord$1(value) && isRecord$1(value["der"]) ? value["der"] : value;
405
+ const { path } = isRecord$1(der) ? der : {};
406
+ if (key instanceof Uint8Array && Array.isArray(path) && path.every((p) => typeof p === "number")) out.push({
407
+ pubkey: key,
408
+ path
409
+ });
410
+ };
411
+ if (map instanceof Map) for (const [key, value] of map) readEntry(key, value);
412
+ else if (Array.isArray(map)) {
413
+ for (const entry of map) if (Array.isArray(entry) && entry.length === 2) readEntry(entry[0], entry[1]);
414
+ }
415
+ return out;
416
+ };
417
+ /** The non-hardened `{change, index}` tail of a derivation path, if present and valid. */
418
+ const tailOf = (path) => {
419
+ const change = path.at(-2);
420
+ const index = path.at(-1);
421
+ if (change !== 0 && change !== 1 || index === void 0 || index < 0 || index >= 2147483648) return;
422
+ return {
423
+ change,
424
+ index
425
+ };
426
+ };
427
+ const eq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
428
+ /**
429
+ * Verify every signature on the inputs listed in `sign` against the account's xpub: the input's
430
+ * derivation entry must claim the child pubkey re-derived from the xpub, and the signature must
431
+ * verify over the input's sighash (BIP-143 partialSig for P2WPKH, tapKeySig for P2TR key path).
432
+ */
433
+ const verifyBitcoinPsbtSignatures = (signedPsbt, sign, xpub, template, network) => {
434
+ try {
435
+ const tx = Transaction.fromPSBT(signedPsbt);
436
+ const taproot = template === "btc.bip86";
437
+ for (const idx of sign) {
438
+ const input = tx.getInput(idx);
439
+ const claimed = derivationOf(taproot ? input.tapBip32Derivation : input.bip32Derivation).find(({ path }) => tailOf(path) !== void 0);
440
+ const tail = claimed === void 0 ? void 0 : tailOf(claimed.path);
441
+ if (claimed === void 0 || tail === void 0) return false;
442
+ const prevout = input.witnessUtxo;
443
+ if (prevout === void 0) return false;
444
+ const pub = childPub(xpub, network, tail.change, tail.index);
445
+ if (taproot) {
446
+ const xonly = pub.slice(1);
447
+ const rawSig = input.tapKeySig;
448
+ if (!eq(claimed.pubkey, xonly) || !(rawSig instanceof Uint8Array) || rawSig.length !== 64 && rawSig.length !== 65) return false;
449
+ const sighashType = rawSig.length === 65 ? rawSig[64] ?? SigHash.DEFAULT : SigHash.DEFAULT;
450
+ const sig = rawSig.slice(0, 64);
451
+ const scripts = [];
452
+ const amounts = [];
453
+ let complete = true;
454
+ for (let i = 0; i < tx.inputsLength; i++) {
455
+ const w = tx.getInput(i).witnessUtxo;
456
+ if (w === void 0) {
457
+ complete = false;
458
+ break;
459
+ }
460
+ scripts.push(w.script);
461
+ amounts.push(w.amount);
462
+ }
463
+ if (!complete || !schnorr.verify(sig, tx.preimageWitnessV1(idx, scripts, sighashType, amounts), xonly)) return false;
464
+ } else {
465
+ const partial = input.partialSig;
466
+ const found = Array.isArray(partial) ? partial.find(([p]) => p instanceof Uint8Array && eq(p, pub)) : void 0;
467
+ const rawSig = Array.isArray(found) && found[1] instanceof Uint8Array ? found[1] : void 0;
468
+ if (!eq(claimed.pubkey, pub) || rawSig === void 0 || rawSig.length === 0) return false;
469
+ const sighashType = input.sighashType ?? rawSig.at(-1) ?? SigHash.ALL;
470
+ const decoded = OutScript.decode(prevout.script);
471
+ const scriptCode = decoded !== void 0 && decoded.type === "wpkh" ? OutScript.encode({
472
+ type: "pkh",
473
+ hash: decoded.hash
474
+ }) : prevout.script;
475
+ const hash = tx.preimageWitnessV0(idx, scriptCode, sighashType, prevout.amount);
476
+ if (!secp256k1.verify(secp256k1.Signature.fromBytes(rawSig.slice(0, -1), "der").toBytes(), hash, pub, { prehash: false })) return false;
477
+ }
478
+ }
479
+ return true;
480
+ } catch {
481
+ return false;
482
+ }
483
+ };
484
+ /** Deserialize the `smp`-prefixed base64 witness: count + pushData items. */
485
+ const witnessOf = (sig) => {
486
+ if (!sig.startsWith("smp")) return;
487
+ const raw = base64.decode(sig.slice(3));
488
+ if (raw === void 0 || raw.length === 0) return;
489
+ const items = [];
490
+ let off = 1;
491
+ for (let i = 0; i < (raw[0] ?? 0); i++) {
492
+ const len = raw[off];
493
+ if (len === void 0 || off + 1 + len > raw.length) return;
494
+ items.push(raw.slice(off + 1, off + 1 + len));
495
+ off += 1 + len;
496
+ }
497
+ return off === raw.length ? items : void 0;
498
+ };
499
+ /**
500
+ * BIP-322 simple verification against an address: rebuild to_spend/to_sign exactly as the signer
501
+ * does, then verify the witness signature (P2WPKH ECDSA / P2TR schnorr) over the input preimage.
502
+ */
503
+ const verifyBitcoinMessage = (address, message, signatureBase64, network) => {
504
+ try {
505
+ const net = bitcoinNetwork(network);
506
+ const scriptPubKey = OutScript.encode(Address(net.params).decode(address));
507
+ const witness = witnessOf(signatureBase64);
508
+ if (witness === void 0 || witness.length === 0) return false;
509
+ const tx = new Transaction({
510
+ version: 0,
511
+ lockTime: 0,
512
+ allowUnknownOutputs: true
513
+ });
514
+ tx.addInput({
515
+ txid: Uint8Array.from([...bip322ToSpendTxid(scriptPubKey, message)].reverse()),
516
+ index: 0,
517
+ sequence: 0,
518
+ witnessUtxo: {
519
+ script: scriptPubKey,
520
+ amount: 0n
521
+ }
522
+ });
523
+ tx.addOutput({
524
+ script: Uint8Array.of(106),
525
+ amount: 0n
526
+ });
527
+ if (scriptPubKey.at(0) === 81) {
528
+ const [rawSig] = witness;
529
+ const xonly = scriptPubKey.slice(2);
530
+ if (rawSig === void 0 || xonly.length !== 32 || rawSig.length !== 64 && rawSig.length !== 65) return false;
531
+ const sighashType = rawSig.length === 65 ? rawSig.at(64) ?? SigHash.DEFAULT : SigHash.DEFAULT;
532
+ return schnorr.verify(rawSig.slice(0, 64), tx.preimageWitnessV1(0, [scriptPubKey], sighashType, [0n]), xonly);
533
+ }
534
+ const [rawSig, pub] = witness;
535
+ if (rawSig === void 0 || pub === void 0 || pub.length !== 33 || rawSig.length === 0) return false;
536
+ const sighashType = rawSig.at(-1) ?? SigHash.ALL;
537
+ const decoded = OutScript.decode(scriptPubKey);
538
+ const scriptCode = decoded !== void 0 && decoded.type === "wpkh" ? OutScript.encode({
539
+ type: "pkh",
540
+ hash: decoded.hash
541
+ }) : scriptPubKey;
542
+ return secp256k1.verify(secp256k1.Signature.fromBytes(rawSig.slice(0, -1), "der").toBytes(), tx.preimageWitnessV0(0, scriptCode, sighashType, 0n), pub, { prehash: false });
543
+ } catch {
544
+ return false;
545
+ }
546
+ };
547
+ //#endregion
548
+ //#region src/bitcoin/index.ts
549
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
550
+ const isAccountRef = (value) => {
551
+ if (!isRecord(value) || typeof value["kind"] !== "string") return false;
552
+ if (value["kind"] === "hd") return typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["template"] === "string";
553
+ return value["kind"] === "imported" && typeof value["keyId"] === "string" && typeof value["family"] === "string";
554
+ };
555
+ const common = (request) => {
556
+ const { network } = request;
557
+ const { account } = request;
558
+ if (typeof network !== "string") throw new ChainError("invalid-request", "request.network must be a string");
559
+ if (!isAccountRef(account)) throw new ChainError("invalid-request", "request.account must be an AccountRef");
560
+ bitcoinNetwork(network);
561
+ return {
562
+ network,
563
+ account
564
+ };
565
+ };
566
+ const messageTarget = (address, network, format) => {
567
+ if (typeof address !== "string") throw new ChainError("invalid-request", "address must be a string");
568
+ const net = bitcoinNetwork(network);
569
+ let decoded;
570
+ try {
571
+ decoded = Address(net.params).decode(address);
572
+ } catch {
573
+ throw new ChainError("invalid-address", "address does not belong to this network");
574
+ }
575
+ if (format === "bip322-simple") {
576
+ if (decoded.type !== "wpkh" && decoded.type !== "tr") throw new ChainError("unsupported", "bip322-simple is only for P2WPKH/P2TR addresses");
577
+ } else if (format === "legacy") {
578
+ if (decoded.type !== "pkh") throw new ChainError("unsupported", "legacy signing is only for P2PKH addresses");
579
+ } else throw new ChainError("unsupported", `unsupported message format: ${String(format)}`);
580
+ const scriptPubKey = OutScript.encode(decoded);
581
+ return {
582
+ type: decoded.type,
583
+ address,
584
+ format,
585
+ scriptPubKey
586
+ };
587
+ };
588
+ /**
589
+ * Normalizes a bitcoin sign request. Idempotent: the returned PSBT is the canonical
590
+ * re-serialization.
591
+ */
592
+ const normalizeBitcoin = (request) => {
593
+ if (!isRecord(request) || typeof request["kind"] !== "string") throw new ChainError("invalid-request", "request must be an object with a kind");
594
+ const { network, account } = common(request);
595
+ if (request["kind"] === "bitcoin.psbt") {
596
+ const { psbt } = request;
597
+ if (!(psbt instanceof Uint8Array)) throw new ChainError("invalid-request", "psbt must be bytes");
598
+ const normalized = normalizeBitcoinPsbt(psbt, request["sign"], network);
599
+ return {
600
+ kind: "bitcoin.psbt",
601
+ network,
602
+ account,
603
+ psbt: normalized.psbt,
604
+ sign: normalized.sign
605
+ };
606
+ }
607
+ if (request["kind"] === "bitcoin.message") {
608
+ const { format } = request;
609
+ const target = messageTarget(request["address"], network, format);
610
+ const { message, change, index } = request;
611
+ if (typeof message !== "string") throw new ChainError("invalid-request", "message must be a string");
612
+ if (change !== 0 && change !== 1) throw new ChainError("invalid-request", "change must be 0 or 1");
613
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0 || index >= 2147483648) throw new ChainError("invalid-request", "index must be a non-hardened path index");
614
+ return {
615
+ kind: "bitcoin.message",
616
+ network,
617
+ account,
618
+ address: target.address,
619
+ message,
620
+ format: target.format,
621
+ change,
622
+ index
623
+ };
624
+ }
625
+ throw new ChainError("unsupported", `unsupported sign request kind: ${request["kind"]}`);
626
+ };
627
+ /** Decodes the message `address` into the scriptPubKey the signer needs. */
628
+ const decodeMessageTarget = (request) => messageTarget(request.address, request.network, request.format);
629
+ //#endregion
630
+ export { BITCOIN_NETWORKS, bitcoinAddressFromXpub, bitcoinNetwork, decodeBitcoinPsbt, decodeMessageTarget, normalizeBitcoin, verifiabilityBitcoin, verifyBitcoinMessage, verifyBitcoinPsbtSignatures };
631
+
632
+ //# sourceMappingURL=bitcoin.mjs.map