@dynamic-labs-wallet/btc-utils 0.0.353 → 0.1.0-request-signing

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.
Files changed (72) hide show
  1. package/index.cjs +681 -136
  2. package/index.esm.js +672 -138
  3. package/internal/core/ed_bls12_377.cjs +1 -1
  4. package/internal/core/ed_bls12_377.d.ts +1 -0
  5. package/internal/core/ed_bls12_377.js +1 -1
  6. package/internal/core/native.d.ts +1 -0
  7. package/package.json +5 -4
  8. package/src/assertSighashAllowed/assertSighashAllowed.d.ts +21 -0
  9. package/src/assertSighashAllowed/assertSighashAllowed.d.ts.map +1 -0
  10. package/src/assertSighashAllowed/index.d.ts +2 -0
  11. package/src/assertSighashAllowed/index.d.ts.map +1 -0
  12. package/src/buildToSpendTx/buildToSpendTx.d.ts +12 -0
  13. package/src/buildToSpendTx/buildToSpendTx.d.ts.map +1 -0
  14. package/src/buildToSpendTx/index.d.ts +2 -0
  15. package/src/buildToSpendTx/index.d.ts.map +1 -0
  16. package/src/bytesEqual/bytesEqual.d.ts +10 -0
  17. package/src/bytesEqual/bytesEqual.d.ts.map +1 -0
  18. package/src/bytesEqual/index.d.ts +2 -0
  19. package/src/bytesEqual/index.d.ts.map +1 -0
  20. package/src/calculateBip322Hash/calculateBip322Hash.d.ts.map +1 -1
  21. package/src/computeBip322HashHex/computeBip322HashHex.d.ts +2 -4
  22. package/src/computeBip322HashHex/computeBip322HashHex.d.ts.map +1 -1
  23. package/src/convertSignatureToDER/convertSignatureToDER.d.ts +4 -1
  24. package/src/convertSignatureToDER/convertSignatureToDER.d.ts.map +1 -1
  25. package/src/convertSignatureToTaprootBuffer/convertSignatureToTaprootBuffer.d.ts +5 -2
  26. package/src/convertSignatureToTaprootBuffer/convertSignatureToTaprootBuffer.d.ts.map +1 -1
  27. package/src/doesInputBelongToAddress/doesInputBelongToAddress.d.ts +15 -4
  28. package/src/doesInputBelongToAddress/doesInputBelongToAddress.d.ts.map +1 -1
  29. package/src/extractPsbtIntentOperation/extractPsbtIntentOperation.d.ts +36 -0
  30. package/src/extractPsbtIntentOperation/extractPsbtIntentOperation.d.ts.map +1 -0
  31. package/src/extractPsbtIntentOperation/index.d.ts +3 -0
  32. package/src/extractPsbtIntentOperation/index.d.ts.map +1 -0
  33. package/src/extractPsbtSighashes/extractPsbtSighashes.d.ts +6 -2
  34. package/src/extractPsbtSighashes/extractPsbtSighashes.d.ts.map +1 -1
  35. package/src/filterInputsBySigningIndexes/filterInputsBySigningIndexes.d.ts +12 -0
  36. package/src/filterInputsBySigningIndexes/filterInputsBySigningIndexes.d.ts.map +1 -0
  37. package/src/filterInputsBySigningIndexes/index.d.ts +2 -0
  38. package/src/filterInputsBySigningIndexes/index.d.ts.map +1 -0
  39. package/src/getBtcChainId/getBtcChainId.d.ts +13 -0
  40. package/src/getBtcChainId/getBtcChainId.d.ts.map +1 -0
  41. package/src/getBtcChainId/index.d.ts +2 -0
  42. package/src/getBtcChainId/index.d.ts.map +1 -0
  43. package/src/getFeeRates/getFeeRates.d.ts +12 -8
  44. package/src/getFeeRates/getFeeRates.d.ts.map +1 -1
  45. package/src/getSegwitV0ScriptCode/getSegwitV0ScriptCode.d.ts +20 -0
  46. package/src/getSegwitV0ScriptCode/getSegwitV0ScriptCode.d.ts.map +1 -0
  47. package/src/getSegwitV0ScriptCode/index.d.ts +2 -0
  48. package/src/getSegwitV0ScriptCode/index.d.ts.map +1 -0
  49. package/src/getSigHashType/getSigHashType.d.ts +21 -0
  50. package/src/getSigHashType/getSigHashType.d.ts.map +1 -0
  51. package/src/getSigHashType/index.d.ts +2 -0
  52. package/src/getSigHashType/index.d.ts.map +1 -0
  53. package/src/getUTXOs/getUTXOs.d.ts +2 -2
  54. package/src/getUTXOs/getUTXOs.d.ts.map +1 -1
  55. package/src/index.d.ts +11 -0
  56. package/src/index.d.ts.map +1 -1
  57. package/src/isP2wshOutputScript/index.d.ts +2 -0
  58. package/src/isP2wshOutputScript/index.d.ts.map +1 -0
  59. package/src/isP2wshOutputScript/isP2wshOutputScript.d.ts +10 -0
  60. package/src/isP2wshOutputScript/isP2wshOutputScript.d.ts.map +1 -0
  61. package/src/resolveBitcoinAddressType/index.d.ts +2 -0
  62. package/src/resolveBitcoinAddressType/index.d.ts.map +1 -0
  63. package/src/resolveBitcoinAddressType/resolveBitcoinAddressType.d.ts +34 -0
  64. package/src/resolveBitcoinAddressType/resolveBitcoinAddressType.d.ts.map +1 -0
  65. package/src/resolveRpcUrl/index.d.ts +2 -0
  66. package/src/resolveRpcUrl/index.d.ts.map +1 -0
  67. package/src/resolveRpcUrl/resolveRpcUrl.d.ts +14 -0
  68. package/src/resolveRpcUrl/resolveRpcUrl.d.ts.map +1 -0
  69. package/src/rpcFetch/index.d.ts +2 -0
  70. package/src/rpcFetch/index.d.ts.map +1 -0
  71. package/src/rpcFetch/rpcFetch.d.ts +9 -0
  72. package/src/rpcFetch/rpcFetch.d.ts.map +1 -0
package/index.cjs CHANGED
@@ -182,7 +182,7 @@ function _instanceof$8(left, right) {
182
182
  return left instanceof right;
183
183
  }
184
184
  }
185
- function _type_of$1(obj) {
185
+ function _type_of$2(obj) {
186
186
  "@swc/helpers - typeof";
187
187
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
188
188
  }
@@ -207,7 +207,7 @@ function _type_of$1(obj) {
207
207
  }
208
208
  return result;
209
209
  }
210
- if ((typeof actualPubkey === "undefined" ? "undefined" : _type_of$1(actualPubkey)) === 'object' && actualPubkey !== null) {
210
+ if ((typeof actualPubkey === "undefined" ? "undefined" : _type_of$2(actualPubkey)) === 'object' && actualPubkey !== null) {
211
211
  return convertObjectToBuffer(actualPubkey);
212
212
  }
213
213
  throw new Error('Invalid public key format');
@@ -290,6 +290,114 @@ var convertObjectToBuffer = function(actualPubkey) {
290
290
  return addressType;
291
291
  };
292
292
 
293
+ /**
294
+ * Infers the Bitcoin address type from a bech32/bech32m account address.
295
+ *
296
+ * The character immediately after the '1' separator encodes the witness
297
+ * version: 'q' => v0 (P2WPKH, native segwit), 'p' => v1 (P2TR, taproot). The
298
+ * type is intrinsic to the address, so this works regardless of wallet
299
+ * metadata and for every network prefix (`bc1…`, `tb1…`, `bcrt1…`). Legacy
300
+ * (`1…`/`3…`) addresses are not supported and return undefined.
301
+ *
302
+ * @param address - The Bitcoin account address
303
+ * @returns The inferred BitcoinAddressType, or undefined if it cannot be determined
304
+ */ var getAddressTypeFromAddress = function(address) {
305
+ var normalizedAddress = address.toLowerCase();
306
+ // The bech32 data charset excludes '1', so the separator is always the last '1'.
307
+ var separatorIndex = normalizedAddress.lastIndexOf('1');
308
+ var witnessVersionIndex = separatorIndex + 1;
309
+ if (separatorIndex === -1 || witnessVersionIndex >= normalizedAddress.length) {
310
+ return undefined;
311
+ }
312
+ switch(normalizedAddress[witnessVersionIndex]){
313
+ case 'q':
314
+ return core.BitcoinAddressType.NATIVE_SEGWIT;
315
+ case 'p':
316
+ return core.BitcoinAddressType.TAPROOT;
317
+ default:
318
+ return undefined;
319
+ }
320
+ };
321
+ /**
322
+ * Resolves the address type a BTC signing operation must use.
323
+ *
324
+ * Imported wallets are non-HD: the MPC server derives them with an empty path
325
+ * and persists `"[]"`, so a derivation path cannot be relied on to carry the
326
+ * address type. The account address always can — the witness version is part
327
+ * of the address — so it backs the path up rather than the other way around.
328
+ *
329
+ * @param addressType - Address type already recorded against the wallet, if any
330
+ * @param derivationPath - Serialized derivation path, `"[]"` for imported wallets
331
+ * @param accountAddress - The wallet's account address
332
+ * @returns The resolved BitcoinAddressType
333
+ * @throws If none of the three inputs can determine the address type
334
+ */ var resolveBitcoinAddressType = function(param) {
335
+ var addressType = param.addressType, derivationPath = param.derivationPath, accountAddress = param.accountAddress;
336
+ if (addressType) {
337
+ return addressType;
338
+ }
339
+ if (derivationPath) {
340
+ try {
341
+ return getAddressTypeFromDerivationPath(derivationPath);
342
+ } catch (e) {
343
+ // Empty or unrecognised path — fall through to the address.
344
+ }
345
+ }
346
+ var fromAddress = accountAddress ? getAddressTypeFromAddress(accountAddress) : undefined;
347
+ if (fromAddress) {
348
+ return fromAddress;
349
+ }
350
+ throw new Error('Unable to determine Bitcoin address type');
351
+ };
352
+
353
+ function _array_like_to_array$3(arr, len) {
354
+ if (len == null || len > arr.length) len = arr.length;
355
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
356
+ return arr2;
357
+ }
358
+ function _array_without_holes$3(arr) {
359
+ if (Array.isArray(arr)) return _array_like_to_array$3(arr);
360
+ }
361
+ function _iterable_to_array$3(iter) {
362
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
363
+ }
364
+ function _non_iterable_spread$3() {
365
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
366
+ }
367
+ function _to_consumable_array$3(arr) {
368
+ return _array_without_holes$3(arr) || _iterable_to_array$3(arr) || _unsupported_iterable_to_array$3(arr) || _non_iterable_spread$3();
369
+ }
370
+ function _unsupported_iterable_to_array$3(o, minLen) {
371
+ if (!o) return;
372
+ if (typeof o === "string") return _array_like_to_array$3(o, minLen);
373
+ var n = Object.prototype.toString.call(o).slice(8, -1);
374
+ if (n === "Object" && o.constructor) n = o.constructor.name;
375
+ if (n === "Map" || n === "Set") return Array.from(n);
376
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$3(o, minLen);
377
+ }
378
+ var NULL_PREVOUT_HASH = new Uint8Array(32);
379
+ var NULL_PREVOUT_INDEX = 0xffffffff;
380
+ var OP_0_PUSH32 = [
381
+ 0x00,
382
+ 0x20
383
+ ];
384
+ /**
385
+ * Builds the BIP-322 `to_spend` transaction as a plain Transaction.
386
+ *
387
+ * `BIP322.buildToSpendTx` goes through `Psbt.extractTransaction()`, which bitcoinjs-lib >= 7.0.4 rejects
388
+ * because the virtual input has no UTXO ("Need a Utxo input item for input #0"). A Transaction has no such check.
389
+ *
390
+ * @param message - The message to sign
391
+ * @param scriptPubKey - The message challenge (the signer's script public key)
392
+ */ var buildToSpendTx = function(message, scriptPubKey) {
393
+ var tx = new bitcoin__namespace.Transaction();
394
+ tx.version = 0;
395
+ tx.locktime = 0;
396
+ tx.addInput(NULL_PREVOUT_HASH, NULL_PREVOUT_INDEX, 0, new Uint8Array(_to_consumable_array$3(OP_0_PUSH32).concat(_to_consumable_array$3(bip322Js.BIP322.hashMessage(message)))));
397
+ tx.addOutput(scriptPubKey, BigInt(0));
398
+ return tx;
399
+ };
400
+
293
401
  /**
294
402
  * Calculates the hash to be signed for a BIP-322 message verification
295
403
  *
@@ -306,7 +414,7 @@ var convertObjectToBuffer = function(actualPubkey) {
306
414
  throw new Error('Failed to generate address for BIP-322');
307
415
  }
308
416
  var scriptPubKey = bip322Js.Address.convertAdressToScriptPubkey(address);
309
- var toSpendTx = bip322Js.BIP322.buildToSpendTx(message, scriptPubKey);
417
+ var toSpendTx = buildToSpendTx(message, scriptPubKey);
310
418
  var toSignPsbt = bip322Js.BIP322.buildToSignTx(toSpendTx.getId(), scriptPubKey);
311
419
  var txToSign = toSignPsbt.__CACHE.__TX;
312
420
  var hashToSign;
@@ -315,7 +423,7 @@ var convertObjectToBuffer = function(actualPubkey) {
315
423
  scriptPubKey
316
424
  ];
317
425
  var values = [
318
- 0
426
+ BigInt(0)
319
427
  ];
320
428
  hashToSign = Buffer.from(txToSign.hashForWitnessV1(0, prevOutScripts, values, bitcoin__namespace.Transaction.SIGHASH_DEFAULT));
321
429
  } else {
@@ -726,8 +834,12 @@ function _instanceof$3(left, right) {
726
834
  * Converts an ECDSA signature to DER format
727
835
  *
728
836
  * @param signature - The ECDSA signature
837
+ * @param sighashType - The sighash type to append as the DER trailing byte.
838
+ * Must match the type the signing hash was built with, or the signature will
839
+ * fail verification at finalize/broadcast. Defaults to SIGHASH_ALL.
729
840
  * @returns The DER encoded signature
730
841
  */ var convertSignatureToDER = function(signature) {
842
+ var sighashType = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : bitcoin__namespace.Transaction.SIGHASH_ALL;
731
843
  var r = _instanceof$3(signature.r, Uint8Array) ? signature.r : new Uint8Array(signature.r);
732
844
  var s = _instanceof$3(signature.s, Uint8Array) ? signature.s : new Uint8Array(signature.s);
733
845
  var r32 = new Uint8Array(32);
@@ -739,7 +851,7 @@ function _instanceof$3(left, right) {
739
851
  var rawSignature = new Uint8Array(64);
740
852
  rawSignature.set(r32, 0);
741
853
  rawSignature.set(s32, 32);
742
- var derSignature = bitcoin__namespace.script.signature.encode(rawSignature, bitcoin__namespace.Transaction.SIGHASH_ALL);
854
+ var derSignature = bitcoin__namespace.script.signature.encode(rawSignature, sighashType);
743
855
  return derSignature;
744
856
  };
745
857
 
@@ -752,6 +864,54 @@ function _instanceof$3(left, right) {
752
864
  return network === core.BitcoinNetwork.MAINNET ? 'https://mempool.space/api' : 'https://mempool.space/testnet/api';
753
865
  };
754
866
 
867
+ var LOOPBACK_HOSTNAMES = new Set([
868
+ 'localhost',
869
+ '127.0.0.1',
870
+ '[::1]'
871
+ ]);
872
+ /**
873
+ * Resolves the Esplora-compatible base URL to use for a network.
874
+ * Falls back to the default (mempool.space) when no custom URL is given.
875
+ *
876
+ * @param network - The Bitcoin network
877
+ * @param rpcUrl - Optional custom Esplora-compatible base URL
878
+ * @returns The base URL without a trailing slash
879
+ */ var resolveRpcUrl = function(param) {
880
+ var network = param.network, rpcUrl = param.rpcUrl;
881
+ if (!rpcUrl) {
882
+ return getDefaultRpcUrl(network);
883
+ }
884
+ var parsed;
885
+ try {
886
+ parsed = new URL(rpcUrl);
887
+ } catch (e) {
888
+ throw new Error('Invalid Bitcoin RPC URL');
889
+ }
890
+ var isSecure = parsed.protocol === 'https:';
891
+ var isLocalHttp = parsed.protocol === 'http:' && LOOPBACK_HOSTNAMES.has(parsed.hostname);
892
+ if (!isSecure && !isLocalHttp) {
893
+ throw new Error('Bitcoin RPC URL must use https (http is only allowed for localhost)');
894
+ }
895
+ // Manual trim: a /\/+$/ regex backtracks quadratically on long runs of slashes.
896
+ var end = rpcUrl.length;
897
+ while(end > 0 && rpcUrl[end - 1] === '/'){
898
+ end -= 1;
899
+ }
900
+ return rpcUrl.slice(0, end);
901
+ };
902
+
903
+ /**
904
+ * fetch wrapper for Esplora requests. Requests to a custom `rpcUrl` do not follow
905
+ * redirects, so they cannot be bounced to a host other than the configured backend.
906
+ *
907
+ * @param url - The full request URL
908
+ * @param rpcUrl - The custom RPC URL the request was built from, if any
909
+ */ var rpcFetch = function(url, rpcUrl) {
910
+ return rpcUrl ? fetch(url, {
911
+ redirect: 'error'
912
+ }) : fetch(url);
913
+ };
914
+
755
915
  function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
756
916
  try {
757
917
  var info = gen[key](arg);
@@ -877,11 +1037,11 @@ function _ts_generator$1(thisArg, body) {
877
1037
  }
878
1038
  }
879
1039
  /**
880
- * Fetches UTXOs for a given address using mempool.space API
1040
+ * Fetches UTXOs for a given address using an Esplora-compatible API (mempool.space by default)
881
1041
  *
882
1042
  * @param address - The address to fetch UTXOs for
883
1043
  * @param network - The Bitcoin network (default: MAINNET)
884
- * @param rpcUrl - Optional custom RPC URL
1044
+ * @param rpcUrl - Optional custom Esplora-compatible RPC URL
885
1045
  * @returns The list of UTXOs
886
1046
  */ var getUTXOs = /*#__PURE__*/ function() {
887
1047
  var _ref = _async_to_generator$1(function(param) {
@@ -890,7 +1050,10 @@ function _ts_generator$1(thisArg, body) {
890
1050
  switch(_state.label){
891
1051
  case 0:
892
1052
  address = param.address, _param_network = param.network, network = _param_network === void 0 ? core.BitcoinNetwork.MAINNET : _param_network, rpcUrl = param.rpcUrl;
893
- baseUrl = rpcUrl || getDefaultRpcUrl(network);
1053
+ baseUrl = resolveRpcUrl({
1054
+ network: network,
1055
+ rpcUrl: rpcUrl
1056
+ });
894
1057
  _state.label = 1;
895
1058
  case 1:
896
1059
  _state.trys.push([
@@ -901,7 +1064,7 @@ function _ts_generator$1(thisArg, body) {
901
1064
  ]);
902
1065
  return [
903
1066
  4,
904
- fetch("".concat(baseUrl, "/address/").concat(address, "/utxo"))
1067
+ rpcFetch("".concat(baseUrl, "/address/").concat(address, "/utxo"), rpcUrl)
905
1068
  ];
906
1069
  case 2:
907
1070
  response = _state.sent();
@@ -939,30 +1102,30 @@ function _ts_generator$1(thisArg, body) {
939
1102
  };
940
1103
  }();
941
1104
 
942
- function _array_like_to_array(arr, len) {
1105
+ function _array_like_to_array$2(arr, len) {
943
1106
  if (len == null || len > arr.length) len = arr.length;
944
1107
  for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
945
1108
  return arr2;
946
1109
  }
947
- function _array_without_holes(arr) {
948
- if (Array.isArray(arr)) return _array_like_to_array(arr);
1110
+ function _array_without_holes$2(arr) {
1111
+ if (Array.isArray(arr)) return _array_like_to_array$2(arr);
949
1112
  }
950
- function _iterable_to_array(iter) {
1113
+ function _iterable_to_array$2(iter) {
951
1114
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
952
1115
  }
953
- function _non_iterable_spread() {
1116
+ function _non_iterable_spread$2() {
954
1117
  throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
955
1118
  }
956
- function _to_consumable_array(arr) {
957
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
1119
+ function _to_consumable_array$2(arr) {
1120
+ return _array_without_holes$2(arr) || _iterable_to_array$2(arr) || _unsupported_iterable_to_array$2(arr) || _non_iterable_spread$2();
958
1121
  }
959
- function _unsupported_iterable_to_array(o, minLen) {
1122
+ function _unsupported_iterable_to_array$2(o, minLen) {
960
1123
  if (!o) return;
961
- if (typeof o === "string") return _array_like_to_array(o, minLen);
1124
+ if (typeof o === "string") return _array_like_to_array$2(o, minLen);
962
1125
  var n = Object.prototype.toString.call(o).slice(8, -1);
963
1126
  if (n === "Object" && o.constructor) n = o.constructor.name;
964
1127
  if (n === "Map" || n === "Set") return Array.from(n);
965
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
1128
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$2(o, minLen);
966
1129
  }
967
1130
  /**
968
1131
  * Simple greedy coin selection
@@ -974,7 +1137,7 @@ function _unsupported_iterable_to_array(o, minLen) {
974
1137
  */ var selectUTXOs = function(param) {
975
1138
  var utxos = param.utxos, amount = param.amount, feeRate = param.feeRate;
976
1139
  // Sort by value descending
977
- var sorted = _to_consumable_array(utxos).sort(function(a, b) {
1140
+ var sorted = _to_consumable_array$2(utxos).sort(function(a, b) {
978
1141
  return Number(b.value - a.value);
979
1142
  });
980
1143
  var inputs = [];
@@ -1020,6 +1183,14 @@ function _unsupported_iterable_to_array(o, minLen) {
1020
1183
  throw new Error('Insufficient funds');
1021
1184
  };
1022
1185
 
1186
+ function _array_like_to_array$1(arr, len) {
1187
+ if (len == null || len > arr.length) len = arr.length;
1188
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1189
+ return arr2;
1190
+ }
1191
+ function _array_without_holes$1(arr) {
1192
+ if (Array.isArray(arr)) return _array_like_to_array$1(arr);
1193
+ }
1023
1194
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
1024
1195
  try {
1025
1196
  var info = gen[key](arg);
@@ -1049,6 +1220,27 @@ function _async_to_generator(fn) {
1049
1220
  });
1050
1221
  };
1051
1222
  }
1223
+ function _iterable_to_array$1(iter) {
1224
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1225
+ }
1226
+ function _non_iterable_spread$1() {
1227
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1228
+ }
1229
+ function _to_consumable_array$1(arr) {
1230
+ return _array_without_holes$1(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread$1();
1231
+ }
1232
+ function _type_of$1(obj) {
1233
+ "@swc/helpers - typeof";
1234
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
1235
+ }
1236
+ function _unsupported_iterable_to_array$1(o, minLen) {
1237
+ if (!o) return;
1238
+ if (typeof o === "string") return _array_like_to_array$1(o, minLen);
1239
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1240
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1241
+ if (n === "Map" || n === "Set") return Array.from(n);
1242
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
1243
+ }
1052
1244
  function _ts_generator(thisArg, body) {
1053
1245
  var f, y, t, g, _ = {
1054
1246
  label: 0,
@@ -1144,30 +1336,65 @@ function _ts_generator(thisArg, body) {
1144
1336
  };
1145
1337
  }
1146
1338
  }
1339
+ // Block targets approximating mempool's fastest / half-hour / hour fees.
1340
+ var ESPLORA_TARGETS = {
1341
+ fast: 1,
1342
+ medium: 3,
1343
+ slow: 6
1344
+ };
1345
+ // Backends are untrusted input: reject anything that is not a positive finite number.
1346
+ var assertFeeRate = function(value) {
1347
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
1348
+ throw new Error('invalid fee estimate');
1349
+ }
1350
+ return value;
1351
+ };
1352
+ var pickEstimate = function(estimates, target) {
1353
+ var targets = Object.keys(estimates).map(Number).filter(function(key) {
1354
+ return Number.isFinite(key);
1355
+ }).sort(function(a, b) {
1356
+ return a - b;
1357
+ });
1358
+ if (targets.length === 0) {
1359
+ throw new Error('empty fee estimates');
1360
+ }
1361
+ var _reverse_find;
1362
+ // Closest target not exceeding the wanted one, else the fastest available.
1363
+ var key = (_reverse_find = _to_consumable_array$1(targets).reverse().find(function(candidate) {
1364
+ return candidate <= target;
1365
+ })) !== null && _reverse_find !== void 0 ? _reverse_find : targets[0];
1366
+ return Math.ceil(assertFeeRate(estimates[String(key)]));
1367
+ };
1147
1368
  /**
1148
- * Fetches current fee rates from mempool.space
1149
- * Returns fees in sat/vByte
1369
+ * Fetches current fee rates in sat/vByte.
1370
+ * Uses the mempool.space `/v1/fees/recommended` endpoint. For a custom Esplora-compatible
1371
+ * `rpcUrl` that does not serve it, falls back to the standard `/fee-estimates` endpoint
1372
+ * on the same backend. Never falls back to a different host.
1150
1373
  *
1151
1374
  * @param network - The Bitcoin network (default: MAINNET)
1152
- * @param rpcUrl - Optional custom RPC URL
1375
+ * @param rpcUrl - Optional custom Esplora-compatible RPC URL
1153
1376
  * @returns The fee rates for fast, medium, and slow transactions
1154
1377
  */ var getFeeRates = /*#__PURE__*/ function() {
1155
1378
  var _ref = _async_to_generator(function(param) {
1156
- var _param_network, network, rpcUrl, baseUrl, response, fees;
1379
+ var _param_network, network, rpcUrl, baseUrl, response, fees, fallback, estimates, rates;
1157
1380
  return _ts_generator(this, function(_state) {
1158
1381
  switch(_state.label){
1159
1382
  case 0:
1160
1383
  _param_network = param.network, network = _param_network === void 0 ? core.BitcoinNetwork.MAINNET : _param_network, rpcUrl = param.rpcUrl;
1161
- baseUrl = rpcUrl || getDefaultRpcUrl(network);
1384
+ baseUrl = resolveRpcUrl({
1385
+ network: network,
1386
+ rpcUrl: rpcUrl
1387
+ });
1162
1388
  return [
1163
1389
  4,
1164
- fetch("".concat(baseUrl, "/v1/fees/recommended"))
1390
+ rpcFetch("".concat(baseUrl, "/v1/fees/recommended"), rpcUrl)
1165
1391
  ];
1166
1392
  case 1:
1167
1393
  response = _state.sent();
1168
- if (!response.ok) {
1169
- throw new Error("Failed to fetch fee rates: ".concat(response.statusText));
1170
- }
1394
+ if (!response.ok) return [
1395
+ 3,
1396
+ 3
1397
+ ];
1171
1398
  return [
1172
1399
  4,
1173
1400
  response.json()
@@ -1177,9 +1404,41 @@ function _ts_generator(thisArg, body) {
1177
1404
  return [
1178
1405
  2,
1179
1406
  {
1180
- fast: fees.fastestFee,
1181
- medium: fees.halfHourFee,
1182
- slow: fees.hourFee
1407
+ fast: assertFeeRate(fees.fastestFee),
1408
+ medium: assertFeeRate(fees.halfHourFee),
1409
+ slow: assertFeeRate(fees.hourFee)
1410
+ }
1411
+ ];
1412
+ case 3:
1413
+ if (!rpcUrl) {
1414
+ throw new Error("Failed to fetch fee rates: ".concat(response.statusText));
1415
+ }
1416
+ return [
1417
+ 4,
1418
+ rpcFetch("".concat(baseUrl, "/fee-estimates"), rpcUrl)
1419
+ ];
1420
+ case 4:
1421
+ fallback = _state.sent();
1422
+ if (!fallback.ok) {
1423
+ // Report the origin only; custom URLs may embed credentials or API keys in the path.
1424
+ throw new Error("Failed to fetch fee rates from ".concat(new URL(baseUrl).origin, ": ").concat(fallback.statusText, ". ") + 'Provide an explicit feeRate to skip the fee lookup.');
1425
+ }
1426
+ return [
1427
+ 4,
1428
+ fallback.json()
1429
+ ];
1430
+ case 5:
1431
+ estimates = _state.sent();
1432
+ if ((typeof estimates === "undefined" ? "undefined" : _type_of$1(estimates)) !== 'object' || estimates === null || Array.isArray(estimates)) {
1433
+ throw new Error('invalid fee estimates response');
1434
+ }
1435
+ rates = estimates;
1436
+ return [
1437
+ 2,
1438
+ {
1439
+ fast: pickEstimate(rates, ESPLORA_TARGETS.fast),
1440
+ medium: pickEstimate(rates, ESPLORA_TARGETS.medium),
1441
+ slow: pickEstimate(rates, ESPLORA_TARGETS.slow)
1183
1442
  }
1184
1443
  ];
1185
1444
  }
@@ -1210,19 +1469,34 @@ function _instanceof$2(left, right) {
1210
1469
  * Converts a signature to a Buffer format suitable for Taproot (BIP340/Schnorr)
1211
1470
  *
1212
1471
  * @param signature - The signature from MPC (can be Uint8Array, Buffer, or EcdsaSignature object)
1213
- * @returns A Buffer containing the 64-byte Schnorr signature
1472
+ * @param sighashType - The sighash type the signing hash was built with. Per
1473
+ * BIP-341 the signature stays 64 bytes for SIGHASH_DEFAULT and gains the
1474
+ * sighash type as a 65th byte for any other type. Defaults to SIGHASH_DEFAULT.
1475
+ * @returns A Buffer containing the 64-byte (or 65-byte) Schnorr signature
1214
1476
  */ var convertSignatureToTaprootBuffer = function(signature) {
1477
+ var sighashType = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : bitcoin__namespace.Transaction.SIGHASH_DEFAULT;
1478
+ var schnorrSignature;
1215
1479
  if (_instanceof$2(signature, Uint8Array) || Buffer.isBuffer(signature)) {
1216
- return Buffer.from(signature);
1480
+ schnorrSignature = Buffer.from(signature);
1481
+ } else {
1482
+ var r = signature.r;
1483
+ var s = signature.s;
1484
+ var rBuf = Buffer.isBuffer(r) ? r : Buffer.from(r);
1485
+ var sBuf = Buffer.isBuffer(s) ? s : Buffer.from(s);
1486
+ // Safe: creates Uint8Array views over Buffer's underlying memory without copying
1487
+ schnorrSignature = Buffer.concat([
1488
+ new Uint8Array(rBuf),
1489
+ new Uint8Array(sBuf)
1490
+ ]);
1491
+ }
1492
+ if (sighashType === bitcoin__namespace.Transaction.SIGHASH_DEFAULT) {
1493
+ return schnorrSignature;
1217
1494
  }
1218
- var r = signature.r;
1219
- var s = signature.s;
1220
- var rBuf = Buffer.isBuffer(r) ? r : Buffer.from(r);
1221
- var sBuf = Buffer.isBuffer(s) ? s : Buffer.from(s);
1222
- // Safe: creates Uint8Array views over Buffer's underlying memory without copying
1223
1495
  return Buffer.concat([
1224
- new Uint8Array(rBuf),
1225
- new Uint8Array(sBuf)
1496
+ new Uint8Array(schnorrSignature),
1497
+ new Uint8Array([
1498
+ sighashType
1499
+ ])
1226
1500
  ]);
1227
1501
  };
1228
1502
 
@@ -1248,6 +1522,30 @@ function _instanceof$2(left, right) {
1248
1522
  };
1249
1523
  };
1250
1524
 
1525
+ /**
1526
+ * Checks if an output script (scriptPubKey) is P2WSH: OP_0 <32-byte sha256(witnessScript)>
1527
+ *
1528
+ * ArrayLike keeps this callable with Buffer or Uint8Array — the iframe build
1529
+ * compiles with browser typings where Buffer is not assignable to Uint8Array.
1530
+ * @param script - The output script to check
1531
+ * @returns True if the script has the P2WSH shape
1532
+ */ var isP2wshOutputScript = function(script) {
1533
+ return script.length === 34 && script[0] === 0x00 && script[1] === 0x20;
1534
+ };
1535
+
1536
+ /**
1537
+ * Constant-shape byte equality without Buffer — the iframe build compiles
1538
+ * this package with browser typings where Buffer is not assignable to
1539
+ * Uint8Array.
1540
+ * @param a - First byte array
1541
+ * @param b - Second byte array
1542
+ * @returns True if both arrays have identical length and contents
1543
+ */ var bytesEqual = function(a, b) {
1544
+ return a.length === b.length && a.every(function(byte, index) {
1545
+ return byte === b[index];
1546
+ });
1547
+ };
1548
+
1251
1549
  function _instanceof$1(left, right) {
1252
1550
  if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
1253
1551
  return !!right[Symbol.hasInstance](left);
@@ -1256,33 +1554,98 @@ function _instanceof$1(left, right) {
1256
1554
  }
1257
1555
  }
1258
1556
  /**
1259
- * Checks if a PSBT input belongs to a specific address
1557
+ * P2WSH ownership: the caller allowlisted the witnessScript, it hashes to the
1558
+ * scriptPubKey commitment, and it is a canonical m-of-n CHECKMULTISIG with
1559
+ * `publicKey` in a signing position.
1560
+ */ var matchesAllowedP2wshMultisig = function(input, script, publicKey, allowedWitnessScripts) {
1561
+ if (!publicKey || !input.witnessScript || !(allowedWitnessScripts === null || allowedWitnessScripts === void 0 ? void 0 : allowedWitnessScripts.length)) {
1562
+ return false;
1563
+ }
1564
+ var witnessScript = Uint8Array.from(input.witnessScript);
1565
+ // P2WSH co-signing is opt-in: the wallet only signs arrangements the
1566
+ // caller explicitly named in this request.
1567
+ var witnessScriptHex = Buffer.from(witnessScript).toString('hex');
1568
+ if (!allowedWitnessScripts.some(function(hex) {
1569
+ return hex.toLowerCase() === witnessScriptHex;
1570
+ })) {
1571
+ return false;
1572
+ }
1573
+ // The scriptPubKey commits to the witnessScript; a mismatch means the
1574
+ // PSBT is lying about the script this signature would authorize.
1575
+ if (!bytesEqual(sha256.sha256(witnessScript), Uint8Array.from(script).subarray(2))) {
1576
+ return false;
1577
+ }
1578
+ // p2ms throws unless the script is exactly OP_m <keys...> OP_n
1579
+ // OP_CHECKMULTISIG, so the key must occupy a signing position.
1580
+ var multisigPubkeys;
1581
+ try {
1582
+ multisigPubkeys = bitcoin__namespace.payments.p2ms({
1583
+ output: witnessScript
1584
+ }).pubkeys;
1585
+ } catch (e) {
1586
+ return false;
1587
+ }
1588
+ if (!multisigPubkeys) {
1589
+ return false;
1590
+ }
1591
+ var publicKeyBytes = Uint8Array.from(publicKey);
1592
+ return multisigPubkeys.some(function(key) {
1593
+ return bytesEqual(Uint8Array.from(key), publicKeyBytes);
1594
+ });
1595
+ };
1596
+ /**
1597
+ * Checks if a PSBT input belongs to a specific address.
1598
+ *
1599
+ * For P2WSH inputs address equality cannot work (the address commits to the
1600
+ * script, not our key), so ownership is opt-in and means ALL of: the caller
1601
+ * explicitly allowlisted the witnessScript, it hashes to the scriptPubKey
1602
+ * commitment, and it is a canonical m-of-n CHECKMULTISIG script with
1603
+ * `publicKey` in a signing position. Any other script shape is rejected even
1604
+ * if the key appears in it, so a hostile PSBT cannot obtain a signature over
1605
+ * an arbitrary script that merely name-drops the wallet key, and the wallet
1606
+ * never co-signs a multisig arrangement the caller did not name.
1260
1607
  * @param input - The PSBT input (from psbt.data.inputs)
1261
1608
  * @param address - The address to check against
1262
1609
  * @param network - The Bitcoin network
1263
- * @returns True if the input belongs to the address, false otherwise
1264
- */ var doesInputBelongToAddress = function(input, address, network) {
1610
+ * @param publicKey - The wallet's compressed ECDSA public key; required to match P2WSH inputs
1611
+ * @param allowedWitnessScripts - Hex-encoded witnessScripts the caller consents to co-sign; required to match P2WSH inputs
1612
+ * @returns True if the input belongs to the address (or public key, for P2WSH), false otherwise
1613
+ */ var doesInputBelongToAddress = function(input, address, network, publicKey, allowedWitnessScripts) {
1265
1614
  if (!input.witnessUtxo) {
1266
1615
  return false;
1267
1616
  }
1268
1617
  var script = Buffer.isBuffer(input.witnessUtxo.script) ? input.witnessUtxo.script : Buffer.from(input.witnessUtxo.script);
1269
- var bitcoinNetwork = getBitcoinNetwork(network);
1618
+ // Callers key wallets by the identity (mainnet) address regardless of the
1619
+ // signing network, so accept the input under either encoding — the script
1620
+ // itself is network-independent.
1621
+ var networksToTry = network === core.BitcoinNetwork.MAINNET ? [
1622
+ getBitcoinNetwork(network)
1623
+ ] : [
1624
+ getBitcoinNetwork(network),
1625
+ getBitcoinNetwork(core.BitcoinNetwork.MAINNET)
1626
+ ];
1270
1627
  try {
1271
1628
  // Try P2WPKH (Native SegWit) - script is OP_0 <20-byte hash>
1272
1629
  if (script.length === 22 && script[0] === 0x00 && script[1] === 0x14) {
1273
- var p2wpkh = bitcoin__namespace.payments.p2wpkh({
1274
- output: script,
1275
- network: bitcoinNetwork
1630
+ return networksToTry.some(function(bitcoinNetwork) {
1631
+ return bitcoin__namespace.payments.p2wpkh({
1632
+ output: script,
1633
+ network: bitcoinNetwork
1634
+ }).address === address;
1276
1635
  });
1277
- return p2wpkh.address === address;
1636
+ }
1637
+ // Try P2WSH - script is OP_0 <32-byte sha256(witnessScript)>
1638
+ if (isP2wshOutputScript(script)) {
1639
+ return matchesAllowedP2wshMultisig(input, script, publicKey, allowedWitnessScripts);
1278
1640
  }
1279
1641
  // Try P2TR (Taproot) - script is OP_1 <32-byte x-only pubkey>
1280
1642
  if (script.length === 34 && script[0] === 0x51 && script[1] === 0x20) {
1281
- var p2tr = bitcoin__namespace.payments.p2tr({
1282
- output: script,
1283
- network: bitcoinNetwork
1643
+ return networksToTry.some(function(bitcoinNetwork) {
1644
+ return bitcoin__namespace.payments.p2tr({
1645
+ output: script,
1646
+ network: bitcoinNetwork
1647
+ }).address === address;
1284
1648
  });
1285
- return p2tr.address === address;
1286
1649
  }
1287
1650
  return false;
1288
1651
  } catch (error) {
@@ -1296,6 +1659,139 @@ function _instanceof$1(left, right) {
1296
1659
  }
1297
1660
  };
1298
1661
 
1662
+ /**
1663
+ * Resolves the BIP-143 scriptCode for a segwit v0 input. Shared by the signer
1664
+ * and the sighash-verification helper so both derive the identical digest.
1665
+ *
1666
+ * P2WSH inputs sign over the full witnessScript, verified against the
1667
+ * scriptPubKey commitment so a PSBT cannot substitute a script the UTXO does
1668
+ * not commit to. P2WPKH inputs sign over the implied P2PKH script.
1669
+ *
1670
+ * @param input - The PSBT input (from psbt.data.inputs)
1671
+ * @param script - The input's witnessUtxo scriptPubKey
1672
+ * @param index - The input index (for error messages)
1673
+ * @param bitcoinNetwork - The bitcoinjs-lib network for P2PKH reconstruction
1674
+ * @returns The scriptCode to feed hashForWitnessV0
1675
+ * @throws Error if a P2WSH input is missing its witnessScript, the witnessScript
1676
+ * does not hash to the scriptPubKey commitment, or scriptCode generation fails
1677
+ */ var getSegwitV0ScriptCode = function(input, script, index, bitcoinNetwork) {
1678
+ if (isP2wshOutputScript(script)) {
1679
+ if (!input.witnessScript) {
1680
+ throw new Error("Input ".concat(index, " is P2WSH but missing witnessScript"));
1681
+ }
1682
+ var witnessScript = Uint8Array.from(input.witnessScript);
1683
+ // The scriptPubKey commits to the witnessScript; refuse to compute a
1684
+ // sighash over a script the UTXO does not commit to.
1685
+ if (!bytesEqual(sha256.sha256(witnessScript), Uint8Array.from(script).subarray(2))) {
1686
+ throw new Error("Input ".concat(index, " witnessScript does not match the P2WSH scriptPubKey commitment"));
1687
+ }
1688
+ return witnessScript;
1689
+ }
1690
+ // Build P2PKH script code from the pubkey hash in the witness program
1691
+ var p2pkh = bitcoin__namespace.payments.p2pkh({
1692
+ hash: Uint8Array.from(script).subarray(2),
1693
+ network: bitcoinNetwork
1694
+ });
1695
+ if (!p2pkh.output) {
1696
+ throw new Error("Failed to generate scriptCode for input ".concat(index));
1697
+ }
1698
+ return p2pkh.output;
1699
+ };
1700
+
1701
+ /**
1702
+ * Restricts wallet-owned PSBT inputs to an explicitly requested subset.
1703
+ *
1704
+ * @param inputsToSign - Wallet-owned inputs, each carrying its PSBT index
1705
+ * @param signingIndexes - Optional subset of input indexes the caller wants signed
1706
+ * @returns The requested subset, or all inputs when signingIndexes is omitted/empty
1707
+ * @throws Error if signingIndexes references an input the wallet does not own
1708
+ */ var filterInputsBySigningIndexes = function(inputsToSign, signingIndexes) {
1709
+ if (!(signingIndexes === null || signingIndexes === void 0 ? void 0 : signingIndexes.length)) {
1710
+ return inputsToSign;
1711
+ }
1712
+ var walletOwnedIndexSet = new Set(inputsToSign.map(function(param) {
1713
+ var index = param.index;
1714
+ return index;
1715
+ }));
1716
+ var invalidIndexes = signingIndexes.filter(function(i) {
1717
+ return !walletOwnedIndexSet.has(i);
1718
+ });
1719
+ if (invalidIndexes.length > 0) {
1720
+ throw new Error("signingIndexes contains indexes that do not belong to the signing address: ".concat(invalidIndexes.join(', ')));
1721
+ }
1722
+ var requestedIndexSet = new Set(signingIndexes);
1723
+ return inputsToSign.filter(function(param) {
1724
+ var index = param.index;
1725
+ return requestedIndexSet.has(index);
1726
+ });
1727
+ };
1728
+
1729
+ /**
1730
+ * Resolves the sighash type for a PSBT input.
1731
+ *
1732
+ * The type is read from the PSBT itself (BIP-174 `PSBT_IN_SIGHASH_TYPE`), never
1733
+ * supplied by the caller — the signing hash and the policy layer's verification
1734
+ * hash must be derived from the same bytes, or every non-default signature
1735
+ * would be rejected as tampered.
1736
+ *
1737
+ * When the input declares nothing, falls back to the historical default:
1738
+ * SIGHASH_DEFAULT (0x00) for Taproot, SIGHASH_ALL (0x01) otherwise.
1739
+ *
1740
+ * @param input - The PSBT input to resolve the sighash type for
1741
+ * @param isTaproot - Whether the input is spent as Taproot. Defaults to
1742
+ * detecting `tapInternalKey`; pass explicitly when the caller already knows
1743
+ * which signing branch it is on, so the fallback matches the hash function
1744
+ * actually used.
1745
+ * @returns The sighash type to build and encode the signature with
1746
+ */ var getSigHashType = function(input) {
1747
+ var isTaproot = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : Boolean(input.tapInternalKey);
1748
+ var _input_sighashType;
1749
+ return (_input_sighashType = input.sighashType) !== null && _input_sighashType !== void 0 ? _input_sighashType : isTaproot ? bitcoin__namespace.Transaction.SIGHASH_DEFAULT : bitcoin__namespace.Transaction.SIGHASH_ALL;
1750
+ };
1751
+
1752
+ /**
1753
+ * Throws unless every input's PSBT-declared sighash type is in the allow-list.
1754
+ *
1755
+ * Call this before any signing begins — inputs are signed in parallel, so
1756
+ * throwing partway through would leave a partially signed PSBT behind.
1757
+ *
1758
+ * An empty array permits nothing rather than everything: a caller whose
1759
+ * allow-list computes to empty must not silently get the guard disabled. Omit
1760
+ * the parameter entirely to permit any declared type.
1761
+ *
1762
+ * @param inputsToSign - The wallet-owned inputs about to be signed, with their PSBT indexes
1763
+ * @param isTaproot - Whether signing takes the Taproot branch, so the fallback
1764
+ * sighash type matches the hash function actually used
1765
+ * @param allowedSighash - Optional allow-list of permitted sighash types
1766
+ */ var assertSighashAllowed = function(inputsToSign, isTaproot, allowedSighash) {
1767
+ if (!allowedSighash) {
1768
+ return;
1769
+ }
1770
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1771
+ try {
1772
+ for(var _iterator = inputsToSign[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1773
+ var _step_value = _step.value, input = _step_value.input, index = _step_value.index;
1774
+ var sigHashType = getSigHashType(input, isTaproot);
1775
+ if (!allowedSighash.includes(sigHashType)) {
1776
+ throw new Error("Input ".concat(index, " declares sighash type ").concat(sigHashType, ", which is not in allowedSighash: ").concat(allowedSighash.join(', ') || '(empty)'));
1777
+ }
1778
+ }
1779
+ } catch (err) {
1780
+ _didIteratorError = true;
1781
+ _iteratorError = err;
1782
+ } finally{
1783
+ try {
1784
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1785
+ _iterator.return();
1786
+ }
1787
+ } finally{
1788
+ if (_didIteratorError) {
1789
+ throw _iteratorError;
1790
+ }
1791
+ }
1792
+ }
1793
+ };
1794
+
1299
1795
  function _instanceof(left, right) {
1300
1796
  if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
1301
1797
  return !!right[Symbol.hasInstance](left);
@@ -1382,9 +1878,13 @@ function _type_of(obj) {
1382
1878
  * Extracts sighashes from a PSBT for validation.
1383
1879
  * This is used to verify that the message being signed matches the PSBT context.
1384
1880
  *
1881
+ * P2WSH inputs whose witnessScript is absent yield `null` instead of a hash:
1882
+ * finalization strips witnessScript from completed inputs, so a co-signer's
1883
+ * already-finalized input must not block validation of the remaining inputs.
1884
+ *
1385
1885
  * @param psbtBase64 - PSBT in base64 format
1386
1886
  * @param network - 'mainnet' or 'testnet' or BitcoinNetwork enum (defaults to 'mainnet')
1387
- * @returns Array of sighash hex strings for each input
1887
+ * @returns Array of sighash hex strings, aligned by input index; `null` for inputs whose sighash cannot be derived
1388
1888
  */ var extractPsbtSighashes = function(psbtBase64) {
1389
1889
  var network = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 'mainnet';
1390
1890
  // Convert string network to BitcoinNetwork enum
@@ -1402,29 +1902,125 @@ function _type_of(obj) {
1402
1902
  for(var i = 0; i < psbt.inputCount; i++){
1403
1903
  var input = psbt.data.inputs[i];
1404
1904
  if (input.tapInternalKey) {
1405
- // Taproot (BIP-341) - uses hashForWitnessV1 with SIGHASH_DEFAULT
1406
- var hash = tx.hashForWitnessV1(i, prevOutScripts, values, bitcoin__namespace.Transaction.SIGHASH_DEFAULT);
1905
+ // Taproot (BIP-341) - uses hashForWitnessV1 with the input's declared
1906
+ // sighash type, defaulting to SIGHASH_DEFAULT
1907
+ var hash = tx.hashForWitnessV1(i, prevOutScripts, values, getSigHashType(input, true));
1407
1908
  sighashes.push(Buffer.from(hash).toString('hex'));
1408
- } else {
1409
- // Native SegWit (BIP-143) - uses hashForWitnessV0 with SIGHASH_ALL
1410
- // witnessUtxo is guaranteed to exist from collectPSBTInputData validation
1411
- var _input_witnessUtxo = input.witnessUtxo, script = _input_witnessUtxo.script, value = _input_witnessUtxo.value;
1412
- // Build P2PKH script code from the pubkey hash in the witness program
1413
- var p2pkh = bitcoin__namespace.payments.p2pkh({
1414
- hash: new Uint8Array(toBuffer(script).subarray(2)),
1415
- network: bitcoinNetwork
1416
- });
1417
- var scriptCode = p2pkh.output;
1418
- if (!scriptCode) {
1419
- throw new Error("Failed to generate scriptCode for input ".concat(i));
1420
- }
1421
- var hash1 = tx.hashForWitnessV0(i, scriptCode, value, bitcoin__namespace.Transaction.SIGHASH_ALL);
1422
- sighashes.push(Buffer.from(hash1).toString('hex'));
1909
+ continue;
1423
1910
  }
1911
+ // Native SegWit (BIP-143) - uses hashForWitnessV0 with the input's
1912
+ // declared sighash type, defaulting to SIGHASH_ALL
1913
+ // witnessUtxo is guaranteed to exist from collectPSBTInputData validation
1914
+ var _input_witnessUtxo = input.witnessUtxo, script = _input_witnessUtxo.script, value = _input_witnessUtxo.value;
1915
+ if (isP2wshOutputScript(script) && !input.witnessScript) {
1916
+ sighashes.push(null);
1917
+ continue;
1918
+ }
1919
+ var scriptCode = getSegwitV0ScriptCode(input, script, i, bitcoinNetwork);
1920
+ var hash1 = tx.hashForWitnessV0(i, scriptCode, value, getSigHashType(input, false));
1921
+ sighashes.push(Buffer.from(hash1).toString('hex'));
1424
1922
  }
1425
1923
  return sighashes;
1426
1924
  };
1427
1925
 
1926
+ function _array_like_to_array(arr, len) {
1927
+ if (len == null || len > arr.length) len = arr.length;
1928
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1929
+ return arr2;
1930
+ }
1931
+ function _array_without_holes(arr) {
1932
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
1933
+ }
1934
+ function _iterable_to_array(iter) {
1935
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1936
+ }
1937
+ function _non_iterable_spread() {
1938
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1939
+ }
1940
+ function _to_consumable_array(arr) {
1941
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
1942
+ }
1943
+ function _unsupported_iterable_to_array(o, minLen) {
1944
+ if (!o) return;
1945
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
1946
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1947
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1948
+ if (n === "Map" || n === "Set") return Array.from(n);
1949
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
1950
+ }
1951
+ /**
1952
+ * Describes a PSBT the way a BTC signing intent does: its txid, fee, outputs
1953
+ * and the sighashes of the inputs a wallet is about to sign.
1954
+ *
1955
+ * Every input must carry a `witnessUtxo`: the fee needs the value of every
1956
+ * input, and the txid of a segwit transaction does not change once its inputs
1957
+ * are signed. An input with only a `nonWitnessUtxo` is rejected.
1958
+ *
1959
+ * @param psbtBase64 - The PSBT in base64 format
1960
+ * @param network - The Bitcoin network the PSBT is for
1961
+ * @param inputIndexes - The PSBT input indexes the wallet signs
1962
+ * @returns The txid, fee, outputs and the sighashes of `inputIndexes`
1963
+ * @throws Error if an input lacks a `witnessUtxo`, the outputs exceed the inputs,
1964
+ * `inputIndexes` is empty or out of range, or a requested input has no derivable sighash
1965
+ */ var extractPsbtIntentOperation = function(param) {
1966
+ var inputIndexes = param.inputIndexes, network = param.network, psbtBase64 = param.psbtBase64;
1967
+ var psbt = bitcoin__namespace.Psbt.fromBase64(psbtBase64, {
1968
+ network: getBitcoinNetwork(toBitcoinNetwork(network))
1969
+ });
1970
+ var values = collectPSBTInputData(psbt).values;
1971
+ var tx = psbt.__CACHE.__TX;
1972
+ var inputTotal = values.reduce(function(sum, value) {
1973
+ return sum + value;
1974
+ }, 0n);
1975
+ var outputTotal = tx.outs.reduce(function(sum, output) {
1976
+ return sum + output.value;
1977
+ }, 0n);
1978
+ if (outputTotal > inputTotal) {
1979
+ throw new Error('Transaction outputs exceed its inputs');
1980
+ }
1981
+ var requested = _to_consumable_array(new Set(inputIndexes)).sort(function(a, b) {
1982
+ return a - b;
1983
+ });
1984
+ if (requested.length === 0) {
1985
+ throw new Error('At least one input to sign is required');
1986
+ }
1987
+ var allSighashes = extractPsbtSighashes(psbtBase64, network);
1988
+ var sighashes = requested.map(function(index) {
1989
+ if (!Number.isInteger(index) || index < 0 || index >= allSighashes.length) {
1990
+ throw new Error("Input ".concat(index, " is not in the PSBT"));
1991
+ }
1992
+ var sighash = allSighashes[index];
1993
+ if (sighash === null) {
1994
+ throw new Error("Input ".concat(index, " has no derivable sighash"));
1995
+ }
1996
+ return sighash;
1997
+ });
1998
+ return {
1999
+ feeSats: (inputTotal - outputTotal).toString(),
2000
+ outputs: tx.outs.map(function(output) {
2001
+ return {
2002
+ script: Buffer.from(output.script).toString('hex'),
2003
+ valueSats: output.value.toString()
2004
+ };
2005
+ }),
2006
+ sighashes: sighashes,
2007
+ txid: tx.getId()
2008
+ };
2009
+ };
2010
+
2011
+ /**
2012
+ * The `chainId` label that identifies a Bitcoin network to the policy layer
2013
+ * and in a signing intent: `'2'` for an explicit testnet, `'1'` otherwise.
2014
+ *
2015
+ * An omitted network is labelled mainnet, which matches the mainnet default
2016
+ * the signing clients already use for the PSBT itself.
2017
+ *
2018
+ * @param network - The Bitcoin network, if known
2019
+ * @returns `'2'` for testnet, `'1'` for mainnet or when no network is given
2020
+ */ var getBtcChainId = function(network) {
2021
+ return network === 'testnet' ? '2' : '1';
2022
+ };
2023
+
1428
2024
  /**
1429
2025
  * Converts a string address type identifier to a BitcoinAddressType enum value.
1430
2026
  * If the input is already a BitcoinAddressType enum, it is returned as-is.
@@ -1445,9 +2041,6 @@ function _type_of(obj) {
1445
2041
  * Computes the BIP-322 message hash for a given message and public key,
1446
2042
  * returning the result as a hex string.
1447
2043
  *
1448
- * This function implements the BIP-322 hash computation for
1449
- * native_segwit and taproot address types.
1450
- *
1451
2044
  * @param message - The raw message to be signed
1452
2045
  * @param publicKey - The public key (hex string, Buffer, or Uint8Array)
1453
2046
  * @param addressType - The address type (BitcoinAddressType enum or 'native_segwit', 'taproot')
@@ -1456,72 +2049,14 @@ function _type_of(obj) {
1456
2049
  * @returns The BIP-322 message hash as a hex string
1457
2050
  */ var computeBip322HashHex = function(message, publicKey, addressType) {
1458
2051
  var network = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : core.BitcoinNetwork.MAINNET, ecc = arguments.length > 4 ? arguments[4] : void 0;
1459
- // Convert string network to BitcoinNetwork enum
1460
2052
  var btcNetwork = toBitcoinNetwork(network);
1461
- // Convert string addressType to enum
1462
2053
  var addressTypeEnum = toBitcoinAddressType(addressType);
1463
- // Validate address type
1464
- if (addressTypeEnum !== core.BitcoinAddressType.NATIVE_SEGWIT && addressTypeEnum !== core.BitcoinAddressType.TAPROOT) {
1465
- throw new Error("Unsupported address type: ".concat(addressType));
1466
- }
1467
- // Convert publicKey to Buffer
1468
- var pubKeyBuffer;
1469
- if (typeof publicKey === 'string') {
1470
- pubKeyBuffer = Buffer.from(publicKey.replace(/^0x/, ''), 'hex');
1471
- } else {
1472
- pubKeyBuffer = toBuffer(publicKey);
1473
- }
1474
- // Compress public key if uncompressed
1475
- pubKeyBuffer = normalizeForCompressed(pubKeyBuffer);
1476
- // Generate address from public key
1477
- var address = publicKeyToBitcoinAddress(pubKeyBuffer, addressTypeEnum, btcNetwork, ecc);
1478
- // Convert address to scriptPubKey using bip322-js
1479
- var scriptPubKey = bip322Js.Address.convertAdressToScriptPubkey(address);
1480
- // Create the BIP-322 to_spend transaction
1481
- var toSpendTx = bip322Js.BIP322.buildToSpendTx(message, scriptPubKey);
1482
- // Create the to_sign PSBT
1483
- var toSignPsbt = bip322Js.BIP322.buildToSignTx(toSpendTx.getId(), scriptPubKey);
1484
- // Get the transaction from the PSBT
1485
- var txToSign = toSignPsbt.__CACHE.__TX;
1486
- // Get bitcoinjs-lib network
1487
- var bitcoinNetwork = getBitcoinNetwork(btcNetwork);
1488
- // Compute sighash based on address type
1489
- if (addressTypeEnum === core.BitcoinAddressType.TAPROOT) {
1490
- // Taproot (BIP-341) uses hashForWitnessV1 with SIGHASH_DEFAULT
1491
- var prevOutScripts = [
1492
- scriptPubKey
1493
- ];
1494
- var values = [
1495
- 0
1496
- ]; // Use number, not BigInt - BIP-322 uses 0 value
1497
- var hash = txToSign.hashForWitnessV1(0, prevOutScripts, values, bitcoin__namespace.Transaction.SIGHASH_DEFAULT);
1498
- return Buffer.from(hash).toString('hex');
1499
- } else {
1500
- // SegWit (BIP-143) uses hashForWitnessV0 with SIGHASH_ALL
1501
- // Create a new transaction for signing
1502
- var txToSignSegwit = new bitcoin__namespace.Transaction();
1503
- txToSignSegwit.version = 0;
1504
- txToSignSegwit.locktime = 0;
1505
- var prevTxId = toSpendTx.getId();
1506
- var prevHash = Buffer.from(prevTxId, 'hex').reverse();
1507
- txToSignSegwit.addInput(new Uint8Array(prevHash), 0, 0);
1508
- txToSignSegwit.addOutput(new Uint8Array(Buffer.from([
1509
- 0x6a
1510
- ])), BigInt(0));
1511
- // Build P2PKH script code from pubkey
1512
- var p2pkh = bitcoin__namespace.payments.p2pkh({
1513
- pubkey: new Uint8Array(pubKeyBuffer),
1514
- network: bitcoinNetwork
1515
- });
1516
- var scriptCode = p2pkh.output;
1517
- if (!scriptCode) {
1518
- throw new Error('Failed to generate scriptCode for BIP-322 hash');
1519
- }
1520
- var hash1 = txToSignSegwit.hashForWitnessV0(0, scriptCode, BigInt(0), bitcoin__namespace.Transaction.SIGHASH_ALL);
1521
- return Buffer.from(hash1).toString('hex');
1522
- }
2054
+ var normalizedPublicKey = typeof publicKey === 'string' ? publicKey.replace(/^0x/, '') : publicKey;
2055
+ var formattedMessage = calculateBip322Hash(message, normalizedPublicKey, addressTypeEnum, btcNetwork, ecc).formattedMessage;
2056
+ return Buffer.from(formattedMessage).toString('hex');
1523
2057
  };
1524
2058
 
2059
+ exports.assertSighashAllowed = assertSighashAllowed;
1525
2060
  exports.calculateBip322Hash = calculateBip322Hash;
1526
2061
  exports.calculateTaprootTweak = calculateTaprootTweak;
1527
2062
  exports.collectPSBTInputData = collectPSBTInputData;
@@ -1534,20 +2069,30 @@ exports.createSegWitAddress = createSegWitAddress;
1534
2069
  exports.createTaprootAddress = createTaprootAddress;
1535
2070
  exports.doesInputBelongToAddress = doesInputBelongToAddress;
1536
2071
  exports.encodeBip322Signature = encodeBip322Signature;
2072
+ exports.extractPsbtIntentOperation = extractPsbtIntentOperation;
1537
2073
  exports.extractPsbtSighashes = extractPsbtSighashes;
1538
2074
  exports.extractPublicKeyHex = extractPublicKeyHex;
2075
+ exports.filterInputsBySigningIndexes = filterInputsBySigningIndexes;
2076
+ exports.getAddressTypeFromAddress = getAddressTypeFromAddress;
1539
2077
  exports.getAddressTypeFromDerivationPath = getAddressTypeFromDerivationPath;
1540
2078
  exports.getBitcoinNetwork = getBitcoinNetwork;
2079
+ exports.getBtcChainId = getBtcChainId;
1541
2080
  exports.getDefaultRpcUrl = getDefaultRpcUrl;
1542
2081
  exports.getFeeRates = getFeeRates;
1543
2082
  exports.getPublicKeyFromPrivateKey = getPublicKeyFromPrivateKey;
2083
+ exports.getSegwitV0ScriptCode = getSegwitV0ScriptCode;
2084
+ exports.getSigHashType = getSigHashType;
1544
2085
  exports.getUTXOs = getUTXOs;
1545
2086
  exports.initEccLib = initEccLib;
2087
+ exports.isP2wshOutputScript = isP2wshOutputScript;
1546
2088
  exports.normalizeForCompressed = normalizeForCompressed;
1547
2089
  exports.normalizeForTaproot = normalizeForTaproot;
1548
2090
  exports.normalizePublicKey = normalizePublicKey;
1549
2091
  exports.privateKeyToWIF = privateKeyToWIF;
1550
2092
  exports.publicKeyToBitcoinAddress = publicKeyToBitcoinAddress;
2093
+ exports.resolveBitcoinAddressType = resolveBitcoinAddressType;
2094
+ exports.resolveRpcUrl = resolveRpcUrl;
2095
+ exports.rpcFetch = rpcFetch;
1551
2096
  exports.selectUTXOs = selectUTXOs;
1552
2097
  exports.toBitcoinNetwork = toBitcoinNetwork;
1553
2098
  exports.toBuffer = toBuffer;