@qntx/wallet-chains 0.4.0 → 0.6.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.
@@ -1,5 +1,5 @@
1
1
  import { ChainError } from "./index.mjs";
2
- import { a as bitcoinNetwork, n as signBip322Simple, r as signLegacyMessage } from "./message-AfNel4WZ.mjs";
2
+ import { a as bitcoinNetwork, n as signBip322Simple, r as signLegacyMessage } from "./message-DtIS0ZWB.mjs";
3
3
  import { Address, OutScript } from "@scure/btc-signer/payment.js";
4
4
  import { Transaction } from "@scure/btc-signer/transaction.js";
5
5
  //#region src/bitcoin/sign.ts
@@ -16,12 +16,18 @@ export declare const BITCOIN_NETWORKS: Readonly<Record<string, BitcoinNetwork>>;
16
16
  export declare const bitcoinNetwork: (caip2: string) => BitcoinNetwork;
17
17
  //#endregion
18
18
  //#region src/bitcoin/account.d.ts
19
- type BitcoinAccountTemplate = "btc.bip84" | "btc.bip86";
19
+ type BitcoinAccountTemplate = "btc.bip44" | "btc.bip49" | "btc.bip84" | "btc.bip86";
20
20
  /**
21
21
  * Derive the address at `change`/`index` under an account-level xpub (`m/84'/c'/i'` or
22
22
  * `m/86'/c'/i'`) — P2WPKH for `btc.bip84`, P2TR key-path for `btc.bip86`.
23
23
  */
24
24
  export declare function bitcoinAddressFromXpub(xpub: string, template: BitcoinAccountTemplate, network: string, change: 0 | 1, index: number): string;
25
+ /**
26
+ * The compressed (P2WPKH) or x-only (P2TR) public key at `change`/`index` under an account-level
27
+ * xpub — the key placed in a PSBT's bip32Derivation/tapBip32Derivation entry so the signing kernel
28
+ * can re-derive it.
29
+ */
30
+ export declare function bitcoinPubkeyFromXpub(xpub: string, template: BitcoinAccountTemplate, network: string, change: 0 | 1, index: number): Uint8Array;
25
31
  //#endregion
26
32
  //#region src/bitcoin/decode.d.ts
27
33
  /**
@@ -37,11 +43,6 @@ export declare const verifiabilityBitcoin: (request: Extract<SignRequest, {
37
43
  }>, ownScripts?: ReadonlySet<string>) => Verifiability;
38
44
  //#endregion
39
45
  //#region src/bitcoin/verify.d.ts
40
- /**
41
- * Verify every signature on the inputs listed in `sign` against the account's xpub: the input's
42
- * derivation entry must claim the child pubkey re-derived from the xpub, and the signature must
43
- * verify over the input's sighash (BIP-143 partialSig for P2WPKH, tapKeySig for P2TR key path).
44
- */
45
46
  export declare const verifyBitcoinPsbtSignatures: (signedPsbt: Uint8Array, sign: ReadonlyArray<number>, xpub: string, template: BitcoinAccountTemplate, network: string) => boolean;
46
47
  /**
47
48
  * BIP-322 simple verification against an address: rebuild to_spend/to_sign exactly as the signer
package/dist/bitcoin.mjs CHANGED
@@ -1,9 +1,10 @@
1
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";
2
+ import { a as bitcoinNetwork, i as BITCOIN_NETWORKS, t as bip322ToSpendTxid } from "./message-DtIS0ZWB.mjs";
3
+ import { schnorr, secp256k1 } from "@noble/curves/secp256k1.js";
4
+ import { Address, OutScript, p2pkh, p2sh, p2tr, p2wpkh } from "@scure/btc-signer/payment.js";
5
5
  import { SigHash, Transaction, getInputType } from "@scure/btc-signer/transaction.js";
6
6
  import { HDKey } from "@scure/bip32";
7
+ import { base64 } from "@scure/base";
7
8
  //#region src/bitcoin/psbt.ts
8
9
  /**
9
10
  * BIP-32 derivation paths carry a coin type: 0 for mainnet, 1 for every test network. This is what
@@ -64,7 +65,7 @@ const normalizeBitcoinPsbt = (psbt, sign, network) => {
64
65
  checkDerivations(tx, net.coinType);
65
66
  for (const idx of unique) {
66
67
  const input = tx.getInput(idx);
67
- if (input.witnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} is missing witnessUtxo`);
68
+ if (input.witnessUtxo === void 0 && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`);
68
69
  if (input.bip32Derivation === void 0 && input.tapBip32Derivation === void 0) throw new ChainError("invalid-request", `input ${idx} is missing a bip32 derivation`);
69
70
  const { type } = getInputType(input);
70
71
  if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} is missing nonWitnessUtxo`);
@@ -94,10 +95,28 @@ function bitcoinAddressFromXpub(xpub, template, network, change, index) {
94
95
  }
95
96
  const pub = node.derive(`m/${change}/${index}`).publicKey;
96
97
  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
+ const address = template === "btc.bip84" ? p2wpkh(pub, net.params).address : template === "btc.bip49" ? p2sh(p2wpkh(pub, net.params), net.params).address : template === "btc.bip44" ? p2pkh(pub, net.params).address : p2tr(pub.subarray(1), void 0, net.params).address;
98
99
  if (address === void 0) throw new ChainError("invalid-request", "could not encode the derived address");
99
100
  return address;
100
101
  }
102
+ /**
103
+ * The compressed (P2WPKH) or x-only (P2TR) public key at `change`/`index` under an account-level
104
+ * xpub — the key placed in a PSBT's bip32Derivation/tapBip32Derivation entry so the signing kernel
105
+ * can re-derive it.
106
+ */
107
+ function bitcoinPubkeyFromXpub(xpub, template, network, change, index) {
108
+ if (!Number.isInteger(index) || index < 0) throw new ChainError("invalid-request", "index must be a non-negative integer");
109
+ const net = bitcoinNetwork(network);
110
+ let node;
111
+ try {
112
+ node = HDKey.fromExtendedKey(xpub, net.bip32);
113
+ } catch (error) {
114
+ throw new ChainError("invalid-request", `xpub: ${error instanceof Error ? error.message : String(error)}`);
115
+ }
116
+ const pub = node.derive(`m/${change}/${index}`).publicKey;
117
+ if (pub === null) throw new ChainError("invalid-request", "xpub carries no public key");
118
+ return template === "btc.bip86" ? pub.subarray(1) : pub;
119
+ }
101
120
  //#endregion
102
121
  //#region src/bitcoin/decode.ts
103
122
  const SATS = "sats";
@@ -182,208 +201,6 @@ const decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set()) => {
182
201
  };
183
202
  const verifiabilityBitcoin = (request, ownScripts = /* @__PURE__ */ new Set()) => decodeBitcoinPsbt(request, ownScripts).verifiability;
184
203
  //#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
204
  //#region src/bitcoin/verify.ts
388
205
  /**
389
206
  * Result verification for `chain.sign`: the host re-checks the kernel's Bitcoin work against the
@@ -430,6 +247,16 @@ const eq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
430
247
  * derivation entry must claim the child pubkey re-derived from the xpub, and the signature must
431
248
  * verify over the input's sighash (BIP-143 partialSig for P2WPKH, tapKeySig for P2TR key path).
432
249
  */
250
+ const preimageLegacy = (tx, idx, scriptCode, sighashType) => {
251
+ const f = Reflect.get(tx, "preimageLegacy");
252
+ if (typeof f !== "function") return /* @__PURE__ */ new Uint8Array(0);
253
+ const out = Reflect.apply(f, tx, [
254
+ idx,
255
+ scriptCode,
256
+ sighashType
257
+ ]);
258
+ return out instanceof Uint8Array ? out : /* @__PURE__ */ new Uint8Array(0);
259
+ };
433
260
  const verifyBitcoinPsbtSignatures = (signedPsbt, sign, xpub, template, network) => {
434
261
  try {
435
262
  const tx = Transaction.fromPSBT(signedPsbt);
@@ -439,8 +266,13 @@ const verifyBitcoinPsbtSignatures = (signedPsbt, sign, xpub, template, network)
439
266
  const claimed = derivationOf(taproot ? input.tapBip32Derivation : input.bip32Derivation).find(({ path }) => tailOf(path) !== void 0);
440
267
  const tail = claimed === void 0 ? void 0 : tailOf(claimed.path);
441
268
  if (claimed === void 0 || tail === void 0) return false;
442
- const prevout = input.witnessUtxo;
269
+ const vout = input.index;
270
+ const nw = input.nonWitnessUtxo;
271
+ const legacyOut = nw === void 0 || vout === void 0 ? void 0 : nw.outputs[vout];
272
+ const prevout = input.witnessUtxo ?? legacyOut;
443
273
  if (prevout === void 0) return false;
274
+ const prevScript = prevout.script;
275
+ const prevAmount = prevout.amount;
444
276
  const pub = childPub(xpub, network, tail.change, tail.index);
445
277
  if (taproot) {
446
278
  const xonly = pub.slice(1);
@@ -467,12 +299,13 @@ const verifyBitcoinPsbtSignatures = (signedPsbt, sign, xpub, template, network)
467
299
  const rawSig = Array.isArray(found) && found[1] instanceof Uint8Array ? found[1] : void 0;
468
300
  if (!eq(claimed.pubkey, pub) || rawSig === void 0 || rawSig.length === 0) return false;
469
301
  const sighashType = input.sighashType ?? rawSig.at(-1) ?? SigHash.ALL;
470
- const decoded = OutScript.decode(prevout.script);
302
+ const effective = input.redeemScript ?? prevScript;
303
+ const decoded = OutScript.decode(effective);
471
304
  const scriptCode = decoded !== void 0 && decoded.type === "wpkh" ? OutScript.encode({
472
305
  type: "pkh",
473
306
  hash: decoded.hash
474
- }) : prevout.script;
475
- const hash = tx.preimageWitnessV0(idx, scriptCode, sighashType, prevout.amount);
307
+ }) : effective;
308
+ const hash = input.nonWitnessUtxo === void 0 ? tx.preimageWitnessV0(idx, scriptCode, sighashType, prevAmount) : preimageLegacy(tx, idx, scriptCode, sighashType);
476
309
  if (!secp256k1.verify(secp256k1.Signature.fromBytes(rawSig.slice(0, -1), "der").toBytes(), hash, pub, { prehash: false })) return false;
477
310
  }
478
311
  }
@@ -627,6 +460,6 @@ const normalizeBitcoin = (request) => {
627
460
  /** Decodes the message `address` into the scriptPubKey the signer needs. */
628
461
  const decodeMessageTarget = (request) => messageTarget(request.address, request.network, request.format);
629
462
  //#endregion
630
- export { BITCOIN_NETWORKS, bitcoinAddressFromXpub, bitcoinNetwork, decodeBitcoinPsbt, decodeMessageTarget, normalizeBitcoin, verifiabilityBitcoin, verifyBitcoinMessage, verifyBitcoinPsbtSignatures };
463
+ export { BITCOIN_NETWORKS, bitcoinAddressFromXpub, bitcoinNetwork, bitcoinPubkeyFromXpub, decodeBitcoinPsbt, decodeMessageTarget, normalizeBitcoin, verifiabilityBitcoin, verifyBitcoinMessage, verifyBitcoinPsbtSignatures };
631
464
 
632
465
  //# sourceMappingURL=bitcoin.mjs.map