@dynamic-labs-wallet/btc-utils 0.0.354 → 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.
- package/index.cjs +681 -136
- package/index.esm.js +672 -138
- package/internal/core/ed_bls12_377.cjs +1 -1
- package/internal/core/ed_bls12_377.d.ts +1 -0
- package/internal/core/ed_bls12_377.js +1 -1
- package/internal/core/native.d.ts +1 -0
- package/package.json +5 -4
- package/src/assertSighashAllowed/assertSighashAllowed.d.ts +21 -0
- package/src/assertSighashAllowed/assertSighashAllowed.d.ts.map +1 -0
- package/src/assertSighashAllowed/index.d.ts +2 -0
- package/src/assertSighashAllowed/index.d.ts.map +1 -0
- package/src/buildToSpendTx/buildToSpendTx.d.ts +12 -0
- package/src/buildToSpendTx/buildToSpendTx.d.ts.map +1 -0
- package/src/buildToSpendTx/index.d.ts +2 -0
- package/src/buildToSpendTx/index.d.ts.map +1 -0
- package/src/bytesEqual/bytesEqual.d.ts +10 -0
- package/src/bytesEqual/bytesEqual.d.ts.map +1 -0
- package/src/bytesEqual/index.d.ts +2 -0
- package/src/bytesEqual/index.d.ts.map +1 -0
- package/src/calculateBip322Hash/calculateBip322Hash.d.ts.map +1 -1
- package/src/computeBip322HashHex/computeBip322HashHex.d.ts +2 -4
- package/src/computeBip322HashHex/computeBip322HashHex.d.ts.map +1 -1
- package/src/convertSignatureToDER/convertSignatureToDER.d.ts +4 -1
- package/src/convertSignatureToDER/convertSignatureToDER.d.ts.map +1 -1
- package/src/convertSignatureToTaprootBuffer/convertSignatureToTaprootBuffer.d.ts +5 -2
- package/src/convertSignatureToTaprootBuffer/convertSignatureToTaprootBuffer.d.ts.map +1 -1
- package/src/doesInputBelongToAddress/doesInputBelongToAddress.d.ts +15 -4
- package/src/doesInputBelongToAddress/doesInputBelongToAddress.d.ts.map +1 -1
- package/src/extractPsbtIntentOperation/extractPsbtIntentOperation.d.ts +36 -0
- package/src/extractPsbtIntentOperation/extractPsbtIntentOperation.d.ts.map +1 -0
- package/src/extractPsbtIntentOperation/index.d.ts +3 -0
- package/src/extractPsbtIntentOperation/index.d.ts.map +1 -0
- package/src/extractPsbtSighashes/extractPsbtSighashes.d.ts +6 -2
- package/src/extractPsbtSighashes/extractPsbtSighashes.d.ts.map +1 -1
- package/src/filterInputsBySigningIndexes/filterInputsBySigningIndexes.d.ts +12 -0
- package/src/filterInputsBySigningIndexes/filterInputsBySigningIndexes.d.ts.map +1 -0
- package/src/filterInputsBySigningIndexes/index.d.ts +2 -0
- package/src/filterInputsBySigningIndexes/index.d.ts.map +1 -0
- package/src/getBtcChainId/getBtcChainId.d.ts +13 -0
- package/src/getBtcChainId/getBtcChainId.d.ts.map +1 -0
- package/src/getBtcChainId/index.d.ts +2 -0
- package/src/getBtcChainId/index.d.ts.map +1 -0
- package/src/getFeeRates/getFeeRates.d.ts +12 -8
- package/src/getFeeRates/getFeeRates.d.ts.map +1 -1
- package/src/getSegwitV0ScriptCode/getSegwitV0ScriptCode.d.ts +20 -0
- package/src/getSegwitV0ScriptCode/getSegwitV0ScriptCode.d.ts.map +1 -0
- package/src/getSegwitV0ScriptCode/index.d.ts +2 -0
- package/src/getSegwitV0ScriptCode/index.d.ts.map +1 -0
- package/src/getSigHashType/getSigHashType.d.ts +21 -0
- package/src/getSigHashType/getSigHashType.d.ts.map +1 -0
- package/src/getSigHashType/index.d.ts +2 -0
- package/src/getSigHashType/index.d.ts.map +1 -0
- package/src/getUTXOs/getUTXOs.d.ts +2 -2
- package/src/getUTXOs/getUTXOs.d.ts.map +1 -1
- package/src/index.d.ts +11 -0
- package/src/index.d.ts.map +1 -1
- package/src/isP2wshOutputScript/index.d.ts +2 -0
- package/src/isP2wshOutputScript/index.d.ts.map +1 -0
- package/src/isP2wshOutputScript/isP2wshOutputScript.d.ts +10 -0
- package/src/isP2wshOutputScript/isP2wshOutputScript.d.ts.map +1 -0
- package/src/resolveBitcoinAddressType/index.d.ts +2 -0
- package/src/resolveBitcoinAddressType/index.d.ts.map +1 -0
- package/src/resolveBitcoinAddressType/resolveBitcoinAddressType.d.ts +34 -0
- package/src/resolveBitcoinAddressType/resolveBitcoinAddressType.d.ts.map +1 -0
- package/src/resolveRpcUrl/index.d.ts +2 -0
- package/src/resolveRpcUrl/index.d.ts.map +1 -0
- package/src/resolveRpcUrl/resolveRpcUrl.d.ts +14 -0
- package/src/resolveRpcUrl/resolveRpcUrl.d.ts.map +1 -0
- package/src/rpcFetch/index.d.ts +2 -0
- package/src/rpcFetch/index.d.ts.map +1 -0
- package/src/rpcFetch/rpcFetch.d.ts +9 -0
- package/src/rpcFetch/rpcFetch.d.ts.map +1 -0
package/index.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { BitcoinNetwork, BitcoinAddressType } from '@dynamic-labs-wallet/core';
|
|
2
2
|
import * as bitcoin from 'bitcoinjs-lib';
|
|
3
3
|
import { initEccLib as initEccLib$1, payments } from 'bitcoinjs-lib';
|
|
4
|
-
import {
|
|
4
|
+
import { BIP322, Address } from 'bip322-js';
|
|
5
5
|
import bs58 from 'bs58';
|
|
6
6
|
import { sha256 } from '@noble/hashes/sha256';
|
|
7
7
|
|
|
@@ -162,7 +162,7 @@ function _instanceof$8(left, right) {
|
|
|
162
162
|
return left instanceof right;
|
|
163
163
|
}
|
|
164
164
|
}
|
|
165
|
-
function _type_of$
|
|
165
|
+
function _type_of$2(obj) {
|
|
166
166
|
"@swc/helpers - typeof";
|
|
167
167
|
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
|
|
168
168
|
}
|
|
@@ -187,7 +187,7 @@ function _type_of$1(obj) {
|
|
|
187
187
|
}
|
|
188
188
|
return result;
|
|
189
189
|
}
|
|
190
|
-
if ((typeof actualPubkey === "undefined" ? "undefined" : _type_of$
|
|
190
|
+
if ((typeof actualPubkey === "undefined" ? "undefined" : _type_of$2(actualPubkey)) === 'object' && actualPubkey !== null) {
|
|
191
191
|
return convertObjectToBuffer(actualPubkey);
|
|
192
192
|
}
|
|
193
193
|
throw new Error('Invalid public key format');
|
|
@@ -270,6 +270,114 @@ var convertObjectToBuffer = function(actualPubkey) {
|
|
|
270
270
|
return addressType;
|
|
271
271
|
};
|
|
272
272
|
|
|
273
|
+
/**
|
|
274
|
+
* Infers the Bitcoin address type from a bech32/bech32m account address.
|
|
275
|
+
*
|
|
276
|
+
* The character immediately after the '1' separator encodes the witness
|
|
277
|
+
* version: 'q' => v0 (P2WPKH, native segwit), 'p' => v1 (P2TR, taproot). The
|
|
278
|
+
* type is intrinsic to the address, so this works regardless of wallet
|
|
279
|
+
* metadata and for every network prefix (`bc1…`, `tb1…`, `bcrt1…`). Legacy
|
|
280
|
+
* (`1…`/`3…`) addresses are not supported and return undefined.
|
|
281
|
+
*
|
|
282
|
+
* @param address - The Bitcoin account address
|
|
283
|
+
* @returns The inferred BitcoinAddressType, or undefined if it cannot be determined
|
|
284
|
+
*/ var getAddressTypeFromAddress = function(address) {
|
|
285
|
+
var normalizedAddress = address.toLowerCase();
|
|
286
|
+
// The bech32 data charset excludes '1', so the separator is always the last '1'.
|
|
287
|
+
var separatorIndex = normalizedAddress.lastIndexOf('1');
|
|
288
|
+
var witnessVersionIndex = separatorIndex + 1;
|
|
289
|
+
if (separatorIndex === -1 || witnessVersionIndex >= normalizedAddress.length) {
|
|
290
|
+
return undefined;
|
|
291
|
+
}
|
|
292
|
+
switch(normalizedAddress[witnessVersionIndex]){
|
|
293
|
+
case 'q':
|
|
294
|
+
return BitcoinAddressType.NATIVE_SEGWIT;
|
|
295
|
+
case 'p':
|
|
296
|
+
return BitcoinAddressType.TAPROOT;
|
|
297
|
+
default:
|
|
298
|
+
return undefined;
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
/**
|
|
302
|
+
* Resolves the address type a BTC signing operation must use.
|
|
303
|
+
*
|
|
304
|
+
* Imported wallets are non-HD: the MPC server derives them with an empty path
|
|
305
|
+
* and persists `"[]"`, so a derivation path cannot be relied on to carry the
|
|
306
|
+
* address type. The account address always can — the witness version is part
|
|
307
|
+
* of the address — so it backs the path up rather than the other way around.
|
|
308
|
+
*
|
|
309
|
+
* @param addressType - Address type already recorded against the wallet, if any
|
|
310
|
+
* @param derivationPath - Serialized derivation path, `"[]"` for imported wallets
|
|
311
|
+
* @param accountAddress - The wallet's account address
|
|
312
|
+
* @returns The resolved BitcoinAddressType
|
|
313
|
+
* @throws If none of the three inputs can determine the address type
|
|
314
|
+
*/ var resolveBitcoinAddressType = function(param) {
|
|
315
|
+
var addressType = param.addressType, derivationPath = param.derivationPath, accountAddress = param.accountAddress;
|
|
316
|
+
if (addressType) {
|
|
317
|
+
return addressType;
|
|
318
|
+
}
|
|
319
|
+
if (derivationPath) {
|
|
320
|
+
try {
|
|
321
|
+
return getAddressTypeFromDerivationPath(derivationPath);
|
|
322
|
+
} catch (e) {
|
|
323
|
+
// Empty or unrecognised path — fall through to the address.
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
var fromAddress = accountAddress ? getAddressTypeFromAddress(accountAddress) : undefined;
|
|
327
|
+
if (fromAddress) {
|
|
328
|
+
return fromAddress;
|
|
329
|
+
}
|
|
330
|
+
throw new Error('Unable to determine Bitcoin address type');
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
function _array_like_to_array$3(arr, len) {
|
|
334
|
+
if (len == null || len > arr.length) len = arr.length;
|
|
335
|
+
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
|
|
336
|
+
return arr2;
|
|
337
|
+
}
|
|
338
|
+
function _array_without_holes$3(arr) {
|
|
339
|
+
if (Array.isArray(arr)) return _array_like_to_array$3(arr);
|
|
340
|
+
}
|
|
341
|
+
function _iterable_to_array$3(iter) {
|
|
342
|
+
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
|
|
343
|
+
}
|
|
344
|
+
function _non_iterable_spread$3() {
|
|
345
|
+
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
346
|
+
}
|
|
347
|
+
function _to_consumable_array$3(arr) {
|
|
348
|
+
return _array_without_holes$3(arr) || _iterable_to_array$3(arr) || _unsupported_iterable_to_array$3(arr) || _non_iterable_spread$3();
|
|
349
|
+
}
|
|
350
|
+
function _unsupported_iterable_to_array$3(o, minLen) {
|
|
351
|
+
if (!o) return;
|
|
352
|
+
if (typeof o === "string") return _array_like_to_array$3(o, minLen);
|
|
353
|
+
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
354
|
+
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
355
|
+
if (n === "Map" || n === "Set") return Array.from(n);
|
|
356
|
+
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$3(o, minLen);
|
|
357
|
+
}
|
|
358
|
+
var NULL_PREVOUT_HASH = new Uint8Array(32);
|
|
359
|
+
var NULL_PREVOUT_INDEX = 0xffffffff;
|
|
360
|
+
var OP_0_PUSH32 = [
|
|
361
|
+
0x00,
|
|
362
|
+
0x20
|
|
363
|
+
];
|
|
364
|
+
/**
|
|
365
|
+
* Builds the BIP-322 `to_spend` transaction as a plain Transaction.
|
|
366
|
+
*
|
|
367
|
+
* `BIP322.buildToSpendTx` goes through `Psbt.extractTransaction()`, which bitcoinjs-lib >= 7.0.4 rejects
|
|
368
|
+
* because the virtual input has no UTXO ("Need a Utxo input item for input #0"). A Transaction has no such check.
|
|
369
|
+
*
|
|
370
|
+
* @param message - The message to sign
|
|
371
|
+
* @param scriptPubKey - The message challenge (the signer's script public key)
|
|
372
|
+
*/ var buildToSpendTx = function(message, scriptPubKey) {
|
|
373
|
+
var tx = new bitcoin.Transaction();
|
|
374
|
+
tx.version = 0;
|
|
375
|
+
tx.locktime = 0;
|
|
376
|
+
tx.addInput(NULL_PREVOUT_HASH, NULL_PREVOUT_INDEX, 0, new Uint8Array(_to_consumable_array$3(OP_0_PUSH32).concat(_to_consumable_array$3(BIP322.hashMessage(message)))));
|
|
377
|
+
tx.addOutput(scriptPubKey, BigInt(0));
|
|
378
|
+
return tx;
|
|
379
|
+
};
|
|
380
|
+
|
|
273
381
|
/**
|
|
274
382
|
* Calculates the hash to be signed for a BIP-322 message verification
|
|
275
383
|
*
|
|
@@ -286,7 +394,7 @@ var convertObjectToBuffer = function(actualPubkey) {
|
|
|
286
394
|
throw new Error('Failed to generate address for BIP-322');
|
|
287
395
|
}
|
|
288
396
|
var scriptPubKey = Address.convertAdressToScriptPubkey(address);
|
|
289
|
-
var toSpendTx =
|
|
397
|
+
var toSpendTx = buildToSpendTx(message, scriptPubKey);
|
|
290
398
|
var toSignPsbt = BIP322.buildToSignTx(toSpendTx.getId(), scriptPubKey);
|
|
291
399
|
var txToSign = toSignPsbt.__CACHE.__TX;
|
|
292
400
|
var hashToSign;
|
|
@@ -295,7 +403,7 @@ var convertObjectToBuffer = function(actualPubkey) {
|
|
|
295
403
|
scriptPubKey
|
|
296
404
|
];
|
|
297
405
|
var values = [
|
|
298
|
-
0
|
|
406
|
+
BigInt(0)
|
|
299
407
|
];
|
|
300
408
|
hashToSign = Buffer.from(txToSign.hashForWitnessV1(0, prevOutScripts, values, bitcoin.Transaction.SIGHASH_DEFAULT));
|
|
301
409
|
} else {
|
|
@@ -706,8 +814,12 @@ function _instanceof$3(left, right) {
|
|
|
706
814
|
* Converts an ECDSA signature to DER format
|
|
707
815
|
*
|
|
708
816
|
* @param signature - The ECDSA signature
|
|
817
|
+
* @param sighashType - The sighash type to append as the DER trailing byte.
|
|
818
|
+
* Must match the type the signing hash was built with, or the signature will
|
|
819
|
+
* fail verification at finalize/broadcast. Defaults to SIGHASH_ALL.
|
|
709
820
|
* @returns The DER encoded signature
|
|
710
821
|
*/ var convertSignatureToDER = function(signature) {
|
|
822
|
+
var sighashType = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : bitcoin.Transaction.SIGHASH_ALL;
|
|
711
823
|
var r = _instanceof$3(signature.r, Uint8Array) ? signature.r : new Uint8Array(signature.r);
|
|
712
824
|
var s = _instanceof$3(signature.s, Uint8Array) ? signature.s : new Uint8Array(signature.s);
|
|
713
825
|
var r32 = new Uint8Array(32);
|
|
@@ -719,7 +831,7 @@ function _instanceof$3(left, right) {
|
|
|
719
831
|
var rawSignature = new Uint8Array(64);
|
|
720
832
|
rawSignature.set(r32, 0);
|
|
721
833
|
rawSignature.set(s32, 32);
|
|
722
|
-
var derSignature = bitcoin.script.signature.encode(rawSignature,
|
|
834
|
+
var derSignature = bitcoin.script.signature.encode(rawSignature, sighashType);
|
|
723
835
|
return derSignature;
|
|
724
836
|
};
|
|
725
837
|
|
|
@@ -732,6 +844,54 @@ function _instanceof$3(left, right) {
|
|
|
732
844
|
return network === BitcoinNetwork.MAINNET ? 'https://mempool.space/api' : 'https://mempool.space/testnet/api';
|
|
733
845
|
};
|
|
734
846
|
|
|
847
|
+
var LOOPBACK_HOSTNAMES = new Set([
|
|
848
|
+
'localhost',
|
|
849
|
+
'127.0.0.1',
|
|
850
|
+
'[::1]'
|
|
851
|
+
]);
|
|
852
|
+
/**
|
|
853
|
+
* Resolves the Esplora-compatible base URL to use for a network.
|
|
854
|
+
* Falls back to the default (mempool.space) when no custom URL is given.
|
|
855
|
+
*
|
|
856
|
+
* @param network - The Bitcoin network
|
|
857
|
+
* @param rpcUrl - Optional custom Esplora-compatible base URL
|
|
858
|
+
* @returns The base URL without a trailing slash
|
|
859
|
+
*/ var resolveRpcUrl = function(param) {
|
|
860
|
+
var network = param.network, rpcUrl = param.rpcUrl;
|
|
861
|
+
if (!rpcUrl) {
|
|
862
|
+
return getDefaultRpcUrl(network);
|
|
863
|
+
}
|
|
864
|
+
var parsed;
|
|
865
|
+
try {
|
|
866
|
+
parsed = new URL(rpcUrl);
|
|
867
|
+
} catch (e) {
|
|
868
|
+
throw new Error('Invalid Bitcoin RPC URL');
|
|
869
|
+
}
|
|
870
|
+
var isSecure = parsed.protocol === 'https:';
|
|
871
|
+
var isLocalHttp = parsed.protocol === 'http:' && LOOPBACK_HOSTNAMES.has(parsed.hostname);
|
|
872
|
+
if (!isSecure && !isLocalHttp) {
|
|
873
|
+
throw new Error('Bitcoin RPC URL must use https (http is only allowed for localhost)');
|
|
874
|
+
}
|
|
875
|
+
// Manual trim: a /\/+$/ regex backtracks quadratically on long runs of slashes.
|
|
876
|
+
var end = rpcUrl.length;
|
|
877
|
+
while(end > 0 && rpcUrl[end - 1] === '/'){
|
|
878
|
+
end -= 1;
|
|
879
|
+
}
|
|
880
|
+
return rpcUrl.slice(0, end);
|
|
881
|
+
};
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* fetch wrapper for Esplora requests. Requests to a custom `rpcUrl` do not follow
|
|
885
|
+
* redirects, so they cannot be bounced to a host other than the configured backend.
|
|
886
|
+
*
|
|
887
|
+
* @param url - The full request URL
|
|
888
|
+
* @param rpcUrl - The custom RPC URL the request was built from, if any
|
|
889
|
+
*/ var rpcFetch = function(url, rpcUrl) {
|
|
890
|
+
return rpcUrl ? fetch(url, {
|
|
891
|
+
redirect: 'error'
|
|
892
|
+
}) : fetch(url);
|
|
893
|
+
};
|
|
894
|
+
|
|
735
895
|
function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
|
|
736
896
|
try {
|
|
737
897
|
var info = gen[key](arg);
|
|
@@ -857,11 +1017,11 @@ function _ts_generator$1(thisArg, body) {
|
|
|
857
1017
|
}
|
|
858
1018
|
}
|
|
859
1019
|
/**
|
|
860
|
-
* Fetches UTXOs for a given address using mempool.space
|
|
1020
|
+
* Fetches UTXOs for a given address using an Esplora-compatible API (mempool.space by default)
|
|
861
1021
|
*
|
|
862
1022
|
* @param address - The address to fetch UTXOs for
|
|
863
1023
|
* @param network - The Bitcoin network (default: MAINNET)
|
|
864
|
-
* @param rpcUrl - Optional custom RPC URL
|
|
1024
|
+
* @param rpcUrl - Optional custom Esplora-compatible RPC URL
|
|
865
1025
|
* @returns The list of UTXOs
|
|
866
1026
|
*/ var getUTXOs = /*#__PURE__*/ function() {
|
|
867
1027
|
var _ref = _async_to_generator$1(function(param) {
|
|
@@ -870,7 +1030,10 @@ function _ts_generator$1(thisArg, body) {
|
|
|
870
1030
|
switch(_state.label){
|
|
871
1031
|
case 0:
|
|
872
1032
|
address = param.address, _param_network = param.network, network = _param_network === void 0 ? BitcoinNetwork.MAINNET : _param_network, rpcUrl = param.rpcUrl;
|
|
873
|
-
baseUrl =
|
|
1033
|
+
baseUrl = resolveRpcUrl({
|
|
1034
|
+
network: network,
|
|
1035
|
+
rpcUrl: rpcUrl
|
|
1036
|
+
});
|
|
874
1037
|
_state.label = 1;
|
|
875
1038
|
case 1:
|
|
876
1039
|
_state.trys.push([
|
|
@@ -881,7 +1044,7 @@ function _ts_generator$1(thisArg, body) {
|
|
|
881
1044
|
]);
|
|
882
1045
|
return [
|
|
883
1046
|
4,
|
|
884
|
-
|
|
1047
|
+
rpcFetch("".concat(baseUrl, "/address/").concat(address, "/utxo"), rpcUrl)
|
|
885
1048
|
];
|
|
886
1049
|
case 2:
|
|
887
1050
|
response = _state.sent();
|
|
@@ -919,30 +1082,30 @@ function _ts_generator$1(thisArg, body) {
|
|
|
919
1082
|
};
|
|
920
1083
|
}();
|
|
921
1084
|
|
|
922
|
-
function _array_like_to_array(arr, len) {
|
|
1085
|
+
function _array_like_to_array$2(arr, len) {
|
|
923
1086
|
if (len == null || len > arr.length) len = arr.length;
|
|
924
1087
|
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
|
|
925
1088
|
return arr2;
|
|
926
1089
|
}
|
|
927
|
-
function _array_without_holes(arr) {
|
|
928
|
-
if (Array.isArray(arr)) return _array_like_to_array(arr);
|
|
1090
|
+
function _array_without_holes$2(arr) {
|
|
1091
|
+
if (Array.isArray(arr)) return _array_like_to_array$2(arr);
|
|
929
1092
|
}
|
|
930
|
-
function _iterable_to_array(iter) {
|
|
1093
|
+
function _iterable_to_array$2(iter) {
|
|
931
1094
|
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
|
|
932
1095
|
}
|
|
933
|
-
function _non_iterable_spread() {
|
|
1096
|
+
function _non_iterable_spread$2() {
|
|
934
1097
|
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
935
1098
|
}
|
|
936
|
-
function _to_consumable_array(arr) {
|
|
937
|
-
return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
|
|
1099
|
+
function _to_consumable_array$2(arr) {
|
|
1100
|
+
return _array_without_holes$2(arr) || _iterable_to_array$2(arr) || _unsupported_iterable_to_array$2(arr) || _non_iterable_spread$2();
|
|
938
1101
|
}
|
|
939
|
-
function _unsupported_iterable_to_array(o, minLen) {
|
|
1102
|
+
function _unsupported_iterable_to_array$2(o, minLen) {
|
|
940
1103
|
if (!o) return;
|
|
941
|
-
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
1104
|
+
if (typeof o === "string") return _array_like_to_array$2(o, minLen);
|
|
942
1105
|
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
943
1106
|
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
944
1107
|
if (n === "Map" || n === "Set") return Array.from(n);
|
|
945
|
-
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
1108
|
+
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$2(o, minLen);
|
|
946
1109
|
}
|
|
947
1110
|
/**
|
|
948
1111
|
* Simple greedy coin selection
|
|
@@ -954,7 +1117,7 @@ function _unsupported_iterable_to_array(o, minLen) {
|
|
|
954
1117
|
*/ var selectUTXOs = function(param) {
|
|
955
1118
|
var utxos = param.utxos, amount = param.amount, feeRate = param.feeRate;
|
|
956
1119
|
// Sort by value descending
|
|
957
|
-
var sorted = _to_consumable_array(utxos).sort(function(a, b) {
|
|
1120
|
+
var sorted = _to_consumable_array$2(utxos).sort(function(a, b) {
|
|
958
1121
|
return Number(b.value - a.value);
|
|
959
1122
|
});
|
|
960
1123
|
var inputs = [];
|
|
@@ -1000,6 +1163,14 @@ function _unsupported_iterable_to_array(o, minLen) {
|
|
|
1000
1163
|
throw new Error('Insufficient funds');
|
|
1001
1164
|
};
|
|
1002
1165
|
|
|
1166
|
+
function _array_like_to_array$1(arr, len) {
|
|
1167
|
+
if (len == null || len > arr.length) len = arr.length;
|
|
1168
|
+
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
|
|
1169
|
+
return arr2;
|
|
1170
|
+
}
|
|
1171
|
+
function _array_without_holes$1(arr) {
|
|
1172
|
+
if (Array.isArray(arr)) return _array_like_to_array$1(arr);
|
|
1173
|
+
}
|
|
1003
1174
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
1004
1175
|
try {
|
|
1005
1176
|
var info = gen[key](arg);
|
|
@@ -1029,6 +1200,27 @@ function _async_to_generator(fn) {
|
|
|
1029
1200
|
});
|
|
1030
1201
|
};
|
|
1031
1202
|
}
|
|
1203
|
+
function _iterable_to_array$1(iter) {
|
|
1204
|
+
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
|
|
1205
|
+
}
|
|
1206
|
+
function _non_iterable_spread$1() {
|
|
1207
|
+
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
1208
|
+
}
|
|
1209
|
+
function _to_consumable_array$1(arr) {
|
|
1210
|
+
return _array_without_holes$1(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread$1();
|
|
1211
|
+
}
|
|
1212
|
+
function _type_of$1(obj) {
|
|
1213
|
+
"@swc/helpers - typeof";
|
|
1214
|
+
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
|
|
1215
|
+
}
|
|
1216
|
+
function _unsupported_iterable_to_array$1(o, minLen) {
|
|
1217
|
+
if (!o) return;
|
|
1218
|
+
if (typeof o === "string") return _array_like_to_array$1(o, minLen);
|
|
1219
|
+
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
1220
|
+
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
1221
|
+
if (n === "Map" || n === "Set") return Array.from(n);
|
|
1222
|
+
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
|
|
1223
|
+
}
|
|
1032
1224
|
function _ts_generator(thisArg, body) {
|
|
1033
1225
|
var f, y, t, g, _ = {
|
|
1034
1226
|
label: 0,
|
|
@@ -1124,30 +1316,65 @@ function _ts_generator(thisArg, body) {
|
|
|
1124
1316
|
};
|
|
1125
1317
|
}
|
|
1126
1318
|
}
|
|
1319
|
+
// Block targets approximating mempool's fastest / half-hour / hour fees.
|
|
1320
|
+
var ESPLORA_TARGETS = {
|
|
1321
|
+
fast: 1,
|
|
1322
|
+
medium: 3,
|
|
1323
|
+
slow: 6
|
|
1324
|
+
};
|
|
1325
|
+
// Backends are untrusted input: reject anything that is not a positive finite number.
|
|
1326
|
+
var assertFeeRate = function(value) {
|
|
1327
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
|
|
1328
|
+
throw new Error('invalid fee estimate');
|
|
1329
|
+
}
|
|
1330
|
+
return value;
|
|
1331
|
+
};
|
|
1332
|
+
var pickEstimate = function(estimates, target) {
|
|
1333
|
+
var targets = Object.keys(estimates).map(Number).filter(function(key) {
|
|
1334
|
+
return Number.isFinite(key);
|
|
1335
|
+
}).sort(function(a, b) {
|
|
1336
|
+
return a - b;
|
|
1337
|
+
});
|
|
1338
|
+
if (targets.length === 0) {
|
|
1339
|
+
throw new Error('empty fee estimates');
|
|
1340
|
+
}
|
|
1341
|
+
var _reverse_find;
|
|
1342
|
+
// Closest target not exceeding the wanted one, else the fastest available.
|
|
1343
|
+
var key = (_reverse_find = _to_consumable_array$1(targets).reverse().find(function(candidate) {
|
|
1344
|
+
return candidate <= target;
|
|
1345
|
+
})) !== null && _reverse_find !== void 0 ? _reverse_find : targets[0];
|
|
1346
|
+
return Math.ceil(assertFeeRate(estimates[String(key)]));
|
|
1347
|
+
};
|
|
1127
1348
|
/**
|
|
1128
|
-
* Fetches current fee rates
|
|
1129
|
-
*
|
|
1349
|
+
* Fetches current fee rates in sat/vByte.
|
|
1350
|
+
* Uses the mempool.space `/v1/fees/recommended` endpoint. For a custom Esplora-compatible
|
|
1351
|
+
* `rpcUrl` that does not serve it, falls back to the standard `/fee-estimates` endpoint
|
|
1352
|
+
* on the same backend. Never falls back to a different host.
|
|
1130
1353
|
*
|
|
1131
1354
|
* @param network - The Bitcoin network (default: MAINNET)
|
|
1132
|
-
* @param rpcUrl - Optional custom RPC URL
|
|
1355
|
+
* @param rpcUrl - Optional custom Esplora-compatible RPC URL
|
|
1133
1356
|
* @returns The fee rates for fast, medium, and slow transactions
|
|
1134
1357
|
*/ var getFeeRates = /*#__PURE__*/ function() {
|
|
1135
1358
|
var _ref = _async_to_generator(function(param) {
|
|
1136
|
-
var _param_network, network, rpcUrl, baseUrl, response, fees;
|
|
1359
|
+
var _param_network, network, rpcUrl, baseUrl, response, fees, fallback, estimates, rates;
|
|
1137
1360
|
return _ts_generator(this, function(_state) {
|
|
1138
1361
|
switch(_state.label){
|
|
1139
1362
|
case 0:
|
|
1140
1363
|
_param_network = param.network, network = _param_network === void 0 ? BitcoinNetwork.MAINNET : _param_network, rpcUrl = param.rpcUrl;
|
|
1141
|
-
baseUrl =
|
|
1364
|
+
baseUrl = resolveRpcUrl({
|
|
1365
|
+
network: network,
|
|
1366
|
+
rpcUrl: rpcUrl
|
|
1367
|
+
});
|
|
1142
1368
|
return [
|
|
1143
1369
|
4,
|
|
1144
|
-
|
|
1370
|
+
rpcFetch("".concat(baseUrl, "/v1/fees/recommended"), rpcUrl)
|
|
1145
1371
|
];
|
|
1146
1372
|
case 1:
|
|
1147
1373
|
response = _state.sent();
|
|
1148
|
-
if (!response.ok)
|
|
1149
|
-
|
|
1150
|
-
|
|
1374
|
+
if (!response.ok) return [
|
|
1375
|
+
3,
|
|
1376
|
+
3
|
|
1377
|
+
];
|
|
1151
1378
|
return [
|
|
1152
1379
|
4,
|
|
1153
1380
|
response.json()
|
|
@@ -1157,9 +1384,41 @@ function _ts_generator(thisArg, body) {
|
|
|
1157
1384
|
return [
|
|
1158
1385
|
2,
|
|
1159
1386
|
{
|
|
1160
|
-
fast: fees.fastestFee,
|
|
1161
|
-
medium: fees.halfHourFee,
|
|
1162
|
-
slow: fees.hourFee
|
|
1387
|
+
fast: assertFeeRate(fees.fastestFee),
|
|
1388
|
+
medium: assertFeeRate(fees.halfHourFee),
|
|
1389
|
+
slow: assertFeeRate(fees.hourFee)
|
|
1390
|
+
}
|
|
1391
|
+
];
|
|
1392
|
+
case 3:
|
|
1393
|
+
if (!rpcUrl) {
|
|
1394
|
+
throw new Error("Failed to fetch fee rates: ".concat(response.statusText));
|
|
1395
|
+
}
|
|
1396
|
+
return [
|
|
1397
|
+
4,
|
|
1398
|
+
rpcFetch("".concat(baseUrl, "/fee-estimates"), rpcUrl)
|
|
1399
|
+
];
|
|
1400
|
+
case 4:
|
|
1401
|
+
fallback = _state.sent();
|
|
1402
|
+
if (!fallback.ok) {
|
|
1403
|
+
// Report the origin only; custom URLs may embed credentials or API keys in the path.
|
|
1404
|
+
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.');
|
|
1405
|
+
}
|
|
1406
|
+
return [
|
|
1407
|
+
4,
|
|
1408
|
+
fallback.json()
|
|
1409
|
+
];
|
|
1410
|
+
case 5:
|
|
1411
|
+
estimates = _state.sent();
|
|
1412
|
+
if ((typeof estimates === "undefined" ? "undefined" : _type_of$1(estimates)) !== 'object' || estimates === null || Array.isArray(estimates)) {
|
|
1413
|
+
throw new Error('invalid fee estimates response');
|
|
1414
|
+
}
|
|
1415
|
+
rates = estimates;
|
|
1416
|
+
return [
|
|
1417
|
+
2,
|
|
1418
|
+
{
|
|
1419
|
+
fast: pickEstimate(rates, ESPLORA_TARGETS.fast),
|
|
1420
|
+
medium: pickEstimate(rates, ESPLORA_TARGETS.medium),
|
|
1421
|
+
slow: pickEstimate(rates, ESPLORA_TARGETS.slow)
|
|
1163
1422
|
}
|
|
1164
1423
|
];
|
|
1165
1424
|
}
|
|
@@ -1190,19 +1449,34 @@ function _instanceof$2(left, right) {
|
|
|
1190
1449
|
* Converts a signature to a Buffer format suitable for Taproot (BIP340/Schnorr)
|
|
1191
1450
|
*
|
|
1192
1451
|
* @param signature - The signature from MPC (can be Uint8Array, Buffer, or EcdsaSignature object)
|
|
1193
|
-
* @
|
|
1452
|
+
* @param sighashType - The sighash type the signing hash was built with. Per
|
|
1453
|
+
* BIP-341 the signature stays 64 bytes for SIGHASH_DEFAULT and gains the
|
|
1454
|
+
* sighash type as a 65th byte for any other type. Defaults to SIGHASH_DEFAULT.
|
|
1455
|
+
* @returns A Buffer containing the 64-byte (or 65-byte) Schnorr signature
|
|
1194
1456
|
*/ var convertSignatureToTaprootBuffer = function(signature) {
|
|
1457
|
+
var sighashType = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : bitcoin.Transaction.SIGHASH_DEFAULT;
|
|
1458
|
+
var schnorrSignature;
|
|
1195
1459
|
if (_instanceof$2(signature, Uint8Array) || Buffer.isBuffer(signature)) {
|
|
1196
|
-
|
|
1460
|
+
schnorrSignature = Buffer.from(signature);
|
|
1461
|
+
} else {
|
|
1462
|
+
var r = signature.r;
|
|
1463
|
+
var s = signature.s;
|
|
1464
|
+
var rBuf = Buffer.isBuffer(r) ? r : Buffer.from(r);
|
|
1465
|
+
var sBuf = Buffer.isBuffer(s) ? s : Buffer.from(s);
|
|
1466
|
+
// Safe: creates Uint8Array views over Buffer's underlying memory without copying
|
|
1467
|
+
schnorrSignature = Buffer.concat([
|
|
1468
|
+
new Uint8Array(rBuf),
|
|
1469
|
+
new Uint8Array(sBuf)
|
|
1470
|
+
]);
|
|
1471
|
+
}
|
|
1472
|
+
if (sighashType === bitcoin.Transaction.SIGHASH_DEFAULT) {
|
|
1473
|
+
return schnorrSignature;
|
|
1197
1474
|
}
|
|
1198
|
-
var r = signature.r;
|
|
1199
|
-
var s = signature.s;
|
|
1200
|
-
var rBuf = Buffer.isBuffer(r) ? r : Buffer.from(r);
|
|
1201
|
-
var sBuf = Buffer.isBuffer(s) ? s : Buffer.from(s);
|
|
1202
|
-
// Safe: creates Uint8Array views over Buffer's underlying memory without copying
|
|
1203
1475
|
return Buffer.concat([
|
|
1204
|
-
new Uint8Array(
|
|
1205
|
-
new Uint8Array(
|
|
1476
|
+
new Uint8Array(schnorrSignature),
|
|
1477
|
+
new Uint8Array([
|
|
1478
|
+
sighashType
|
|
1479
|
+
])
|
|
1206
1480
|
]);
|
|
1207
1481
|
};
|
|
1208
1482
|
|
|
@@ -1228,6 +1502,30 @@ function _instanceof$2(left, right) {
|
|
|
1228
1502
|
};
|
|
1229
1503
|
};
|
|
1230
1504
|
|
|
1505
|
+
/**
|
|
1506
|
+
* Checks if an output script (scriptPubKey) is P2WSH: OP_0 <32-byte sha256(witnessScript)>
|
|
1507
|
+
*
|
|
1508
|
+
* ArrayLike keeps this callable with Buffer or Uint8Array — the iframe build
|
|
1509
|
+
* compiles with browser typings where Buffer is not assignable to Uint8Array.
|
|
1510
|
+
* @param script - The output script to check
|
|
1511
|
+
* @returns True if the script has the P2WSH shape
|
|
1512
|
+
*/ var isP2wshOutputScript = function(script) {
|
|
1513
|
+
return script.length === 34 && script[0] === 0x00 && script[1] === 0x20;
|
|
1514
|
+
};
|
|
1515
|
+
|
|
1516
|
+
/**
|
|
1517
|
+
* Constant-shape byte equality without Buffer — the iframe build compiles
|
|
1518
|
+
* this package with browser typings where Buffer is not assignable to
|
|
1519
|
+
* Uint8Array.
|
|
1520
|
+
* @param a - First byte array
|
|
1521
|
+
* @param b - Second byte array
|
|
1522
|
+
* @returns True if both arrays have identical length and contents
|
|
1523
|
+
*/ var bytesEqual = function(a, b) {
|
|
1524
|
+
return a.length === b.length && a.every(function(byte, index) {
|
|
1525
|
+
return byte === b[index];
|
|
1526
|
+
});
|
|
1527
|
+
};
|
|
1528
|
+
|
|
1231
1529
|
function _instanceof$1(left, right) {
|
|
1232
1530
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
1233
1531
|
return !!right[Symbol.hasInstance](left);
|
|
@@ -1236,33 +1534,98 @@ function _instanceof$1(left, right) {
|
|
|
1236
1534
|
}
|
|
1237
1535
|
}
|
|
1238
1536
|
/**
|
|
1239
|
-
*
|
|
1537
|
+
* P2WSH ownership: the caller allowlisted the witnessScript, it hashes to the
|
|
1538
|
+
* scriptPubKey commitment, and it is a canonical m-of-n CHECKMULTISIG with
|
|
1539
|
+
* `publicKey` in a signing position.
|
|
1540
|
+
*/ var matchesAllowedP2wshMultisig = function(input, script, publicKey, allowedWitnessScripts) {
|
|
1541
|
+
if (!publicKey || !input.witnessScript || !(allowedWitnessScripts === null || allowedWitnessScripts === void 0 ? void 0 : allowedWitnessScripts.length)) {
|
|
1542
|
+
return false;
|
|
1543
|
+
}
|
|
1544
|
+
var witnessScript = Uint8Array.from(input.witnessScript);
|
|
1545
|
+
// P2WSH co-signing is opt-in: the wallet only signs arrangements the
|
|
1546
|
+
// caller explicitly named in this request.
|
|
1547
|
+
var witnessScriptHex = Buffer.from(witnessScript).toString('hex');
|
|
1548
|
+
if (!allowedWitnessScripts.some(function(hex) {
|
|
1549
|
+
return hex.toLowerCase() === witnessScriptHex;
|
|
1550
|
+
})) {
|
|
1551
|
+
return false;
|
|
1552
|
+
}
|
|
1553
|
+
// The scriptPubKey commits to the witnessScript; a mismatch means the
|
|
1554
|
+
// PSBT is lying about the script this signature would authorize.
|
|
1555
|
+
if (!bytesEqual(sha256(witnessScript), Uint8Array.from(script).subarray(2))) {
|
|
1556
|
+
return false;
|
|
1557
|
+
}
|
|
1558
|
+
// p2ms throws unless the script is exactly OP_m <keys...> OP_n
|
|
1559
|
+
// OP_CHECKMULTISIG, so the key must occupy a signing position.
|
|
1560
|
+
var multisigPubkeys;
|
|
1561
|
+
try {
|
|
1562
|
+
multisigPubkeys = bitcoin.payments.p2ms({
|
|
1563
|
+
output: witnessScript
|
|
1564
|
+
}).pubkeys;
|
|
1565
|
+
} catch (e) {
|
|
1566
|
+
return false;
|
|
1567
|
+
}
|
|
1568
|
+
if (!multisigPubkeys) {
|
|
1569
|
+
return false;
|
|
1570
|
+
}
|
|
1571
|
+
var publicKeyBytes = Uint8Array.from(publicKey);
|
|
1572
|
+
return multisigPubkeys.some(function(key) {
|
|
1573
|
+
return bytesEqual(Uint8Array.from(key), publicKeyBytes);
|
|
1574
|
+
});
|
|
1575
|
+
};
|
|
1576
|
+
/**
|
|
1577
|
+
* Checks if a PSBT input belongs to a specific address.
|
|
1578
|
+
*
|
|
1579
|
+
* For P2WSH inputs address equality cannot work (the address commits to the
|
|
1580
|
+
* script, not our key), so ownership is opt-in and means ALL of: the caller
|
|
1581
|
+
* explicitly allowlisted the witnessScript, it hashes to the scriptPubKey
|
|
1582
|
+
* commitment, and it is a canonical m-of-n CHECKMULTISIG script with
|
|
1583
|
+
* `publicKey` in a signing position. Any other script shape is rejected even
|
|
1584
|
+
* if the key appears in it, so a hostile PSBT cannot obtain a signature over
|
|
1585
|
+
* an arbitrary script that merely name-drops the wallet key, and the wallet
|
|
1586
|
+
* never co-signs a multisig arrangement the caller did not name.
|
|
1240
1587
|
* @param input - The PSBT input (from psbt.data.inputs)
|
|
1241
1588
|
* @param address - The address to check against
|
|
1242
1589
|
* @param network - The Bitcoin network
|
|
1243
|
-
* @
|
|
1244
|
-
|
|
1590
|
+
* @param publicKey - The wallet's compressed ECDSA public key; required to match P2WSH inputs
|
|
1591
|
+
* @param allowedWitnessScripts - Hex-encoded witnessScripts the caller consents to co-sign; required to match P2WSH inputs
|
|
1592
|
+
* @returns True if the input belongs to the address (or public key, for P2WSH), false otherwise
|
|
1593
|
+
*/ var doesInputBelongToAddress = function(input, address, network, publicKey, allowedWitnessScripts) {
|
|
1245
1594
|
if (!input.witnessUtxo) {
|
|
1246
1595
|
return false;
|
|
1247
1596
|
}
|
|
1248
1597
|
var script = Buffer.isBuffer(input.witnessUtxo.script) ? input.witnessUtxo.script : Buffer.from(input.witnessUtxo.script);
|
|
1249
|
-
|
|
1598
|
+
// Callers key wallets by the identity (mainnet) address regardless of the
|
|
1599
|
+
// signing network, so accept the input under either encoding — the script
|
|
1600
|
+
// itself is network-independent.
|
|
1601
|
+
var networksToTry = network === BitcoinNetwork.MAINNET ? [
|
|
1602
|
+
getBitcoinNetwork(network)
|
|
1603
|
+
] : [
|
|
1604
|
+
getBitcoinNetwork(network),
|
|
1605
|
+
getBitcoinNetwork(BitcoinNetwork.MAINNET)
|
|
1606
|
+
];
|
|
1250
1607
|
try {
|
|
1251
1608
|
// Try P2WPKH (Native SegWit) - script is OP_0 <20-byte hash>
|
|
1252
1609
|
if (script.length === 22 && script[0] === 0x00 && script[1] === 0x14) {
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1610
|
+
return networksToTry.some(function(bitcoinNetwork) {
|
|
1611
|
+
return bitcoin.payments.p2wpkh({
|
|
1612
|
+
output: script,
|
|
1613
|
+
network: bitcoinNetwork
|
|
1614
|
+
}).address === address;
|
|
1256
1615
|
});
|
|
1257
|
-
|
|
1616
|
+
}
|
|
1617
|
+
// Try P2WSH - script is OP_0 <32-byte sha256(witnessScript)>
|
|
1618
|
+
if (isP2wshOutputScript(script)) {
|
|
1619
|
+
return matchesAllowedP2wshMultisig(input, script, publicKey, allowedWitnessScripts);
|
|
1258
1620
|
}
|
|
1259
1621
|
// Try P2TR (Taproot) - script is OP_1 <32-byte x-only pubkey>
|
|
1260
1622
|
if (script.length === 34 && script[0] === 0x51 && script[1] === 0x20) {
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1623
|
+
return networksToTry.some(function(bitcoinNetwork) {
|
|
1624
|
+
return bitcoin.payments.p2tr({
|
|
1625
|
+
output: script,
|
|
1626
|
+
network: bitcoinNetwork
|
|
1627
|
+
}).address === address;
|
|
1264
1628
|
});
|
|
1265
|
-
return p2tr.address === address;
|
|
1266
1629
|
}
|
|
1267
1630
|
return false;
|
|
1268
1631
|
} catch (error) {
|
|
@@ -1276,6 +1639,139 @@ function _instanceof$1(left, right) {
|
|
|
1276
1639
|
}
|
|
1277
1640
|
};
|
|
1278
1641
|
|
|
1642
|
+
/**
|
|
1643
|
+
* Resolves the BIP-143 scriptCode for a segwit v0 input. Shared by the signer
|
|
1644
|
+
* and the sighash-verification helper so both derive the identical digest.
|
|
1645
|
+
*
|
|
1646
|
+
* P2WSH inputs sign over the full witnessScript, verified against the
|
|
1647
|
+
* scriptPubKey commitment so a PSBT cannot substitute a script the UTXO does
|
|
1648
|
+
* not commit to. P2WPKH inputs sign over the implied P2PKH script.
|
|
1649
|
+
*
|
|
1650
|
+
* @param input - The PSBT input (from psbt.data.inputs)
|
|
1651
|
+
* @param script - The input's witnessUtxo scriptPubKey
|
|
1652
|
+
* @param index - The input index (for error messages)
|
|
1653
|
+
* @param bitcoinNetwork - The bitcoinjs-lib network for P2PKH reconstruction
|
|
1654
|
+
* @returns The scriptCode to feed hashForWitnessV0
|
|
1655
|
+
* @throws Error if a P2WSH input is missing its witnessScript, the witnessScript
|
|
1656
|
+
* does not hash to the scriptPubKey commitment, or scriptCode generation fails
|
|
1657
|
+
*/ var getSegwitV0ScriptCode = function(input, script, index, bitcoinNetwork) {
|
|
1658
|
+
if (isP2wshOutputScript(script)) {
|
|
1659
|
+
if (!input.witnessScript) {
|
|
1660
|
+
throw new Error("Input ".concat(index, " is P2WSH but missing witnessScript"));
|
|
1661
|
+
}
|
|
1662
|
+
var witnessScript = Uint8Array.from(input.witnessScript);
|
|
1663
|
+
// The scriptPubKey commits to the witnessScript; refuse to compute a
|
|
1664
|
+
// sighash over a script the UTXO does not commit to.
|
|
1665
|
+
if (!bytesEqual(sha256(witnessScript), Uint8Array.from(script).subarray(2))) {
|
|
1666
|
+
throw new Error("Input ".concat(index, " witnessScript does not match the P2WSH scriptPubKey commitment"));
|
|
1667
|
+
}
|
|
1668
|
+
return witnessScript;
|
|
1669
|
+
}
|
|
1670
|
+
// Build P2PKH script code from the pubkey hash in the witness program
|
|
1671
|
+
var p2pkh = bitcoin.payments.p2pkh({
|
|
1672
|
+
hash: Uint8Array.from(script).subarray(2),
|
|
1673
|
+
network: bitcoinNetwork
|
|
1674
|
+
});
|
|
1675
|
+
if (!p2pkh.output) {
|
|
1676
|
+
throw new Error("Failed to generate scriptCode for input ".concat(index));
|
|
1677
|
+
}
|
|
1678
|
+
return p2pkh.output;
|
|
1679
|
+
};
|
|
1680
|
+
|
|
1681
|
+
/**
|
|
1682
|
+
* Restricts wallet-owned PSBT inputs to an explicitly requested subset.
|
|
1683
|
+
*
|
|
1684
|
+
* @param inputsToSign - Wallet-owned inputs, each carrying its PSBT index
|
|
1685
|
+
* @param signingIndexes - Optional subset of input indexes the caller wants signed
|
|
1686
|
+
* @returns The requested subset, or all inputs when signingIndexes is omitted/empty
|
|
1687
|
+
* @throws Error if signingIndexes references an input the wallet does not own
|
|
1688
|
+
*/ var filterInputsBySigningIndexes = function(inputsToSign, signingIndexes) {
|
|
1689
|
+
if (!(signingIndexes === null || signingIndexes === void 0 ? void 0 : signingIndexes.length)) {
|
|
1690
|
+
return inputsToSign;
|
|
1691
|
+
}
|
|
1692
|
+
var walletOwnedIndexSet = new Set(inputsToSign.map(function(param) {
|
|
1693
|
+
var index = param.index;
|
|
1694
|
+
return index;
|
|
1695
|
+
}));
|
|
1696
|
+
var invalidIndexes = signingIndexes.filter(function(i) {
|
|
1697
|
+
return !walletOwnedIndexSet.has(i);
|
|
1698
|
+
});
|
|
1699
|
+
if (invalidIndexes.length > 0) {
|
|
1700
|
+
throw new Error("signingIndexes contains indexes that do not belong to the signing address: ".concat(invalidIndexes.join(', ')));
|
|
1701
|
+
}
|
|
1702
|
+
var requestedIndexSet = new Set(signingIndexes);
|
|
1703
|
+
return inputsToSign.filter(function(param) {
|
|
1704
|
+
var index = param.index;
|
|
1705
|
+
return requestedIndexSet.has(index);
|
|
1706
|
+
});
|
|
1707
|
+
};
|
|
1708
|
+
|
|
1709
|
+
/**
|
|
1710
|
+
* Resolves the sighash type for a PSBT input.
|
|
1711
|
+
*
|
|
1712
|
+
* The type is read from the PSBT itself (BIP-174 `PSBT_IN_SIGHASH_TYPE`), never
|
|
1713
|
+
* supplied by the caller — the signing hash and the policy layer's verification
|
|
1714
|
+
* hash must be derived from the same bytes, or every non-default signature
|
|
1715
|
+
* would be rejected as tampered.
|
|
1716
|
+
*
|
|
1717
|
+
* When the input declares nothing, falls back to the historical default:
|
|
1718
|
+
* SIGHASH_DEFAULT (0x00) for Taproot, SIGHASH_ALL (0x01) otherwise.
|
|
1719
|
+
*
|
|
1720
|
+
* @param input - The PSBT input to resolve the sighash type for
|
|
1721
|
+
* @param isTaproot - Whether the input is spent as Taproot. Defaults to
|
|
1722
|
+
* detecting `tapInternalKey`; pass explicitly when the caller already knows
|
|
1723
|
+
* which signing branch it is on, so the fallback matches the hash function
|
|
1724
|
+
* actually used.
|
|
1725
|
+
* @returns The sighash type to build and encode the signature with
|
|
1726
|
+
*/ var getSigHashType = function(input) {
|
|
1727
|
+
var isTaproot = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : Boolean(input.tapInternalKey);
|
|
1728
|
+
var _input_sighashType;
|
|
1729
|
+
return (_input_sighashType = input.sighashType) !== null && _input_sighashType !== void 0 ? _input_sighashType : isTaproot ? bitcoin.Transaction.SIGHASH_DEFAULT : bitcoin.Transaction.SIGHASH_ALL;
|
|
1730
|
+
};
|
|
1731
|
+
|
|
1732
|
+
/**
|
|
1733
|
+
* Throws unless every input's PSBT-declared sighash type is in the allow-list.
|
|
1734
|
+
*
|
|
1735
|
+
* Call this before any signing begins — inputs are signed in parallel, so
|
|
1736
|
+
* throwing partway through would leave a partially signed PSBT behind.
|
|
1737
|
+
*
|
|
1738
|
+
* An empty array permits nothing rather than everything: a caller whose
|
|
1739
|
+
* allow-list computes to empty must not silently get the guard disabled. Omit
|
|
1740
|
+
* the parameter entirely to permit any declared type.
|
|
1741
|
+
*
|
|
1742
|
+
* @param inputsToSign - The wallet-owned inputs about to be signed, with their PSBT indexes
|
|
1743
|
+
* @param isTaproot - Whether signing takes the Taproot branch, so the fallback
|
|
1744
|
+
* sighash type matches the hash function actually used
|
|
1745
|
+
* @param allowedSighash - Optional allow-list of permitted sighash types
|
|
1746
|
+
*/ var assertSighashAllowed = function(inputsToSign, isTaproot, allowedSighash) {
|
|
1747
|
+
if (!allowedSighash) {
|
|
1748
|
+
return;
|
|
1749
|
+
}
|
|
1750
|
+
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
|
|
1751
|
+
try {
|
|
1752
|
+
for(var _iterator = inputsToSign[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
|
|
1753
|
+
var _step_value = _step.value, input = _step_value.input, index = _step_value.index;
|
|
1754
|
+
var sigHashType = getSigHashType(input, isTaproot);
|
|
1755
|
+
if (!allowedSighash.includes(sigHashType)) {
|
|
1756
|
+
throw new Error("Input ".concat(index, " declares sighash type ").concat(sigHashType, ", which is not in allowedSighash: ").concat(allowedSighash.join(', ') || '(empty)'));
|
|
1757
|
+
}
|
|
1758
|
+
}
|
|
1759
|
+
} catch (err) {
|
|
1760
|
+
_didIteratorError = true;
|
|
1761
|
+
_iteratorError = err;
|
|
1762
|
+
} finally{
|
|
1763
|
+
try {
|
|
1764
|
+
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
|
1765
|
+
_iterator.return();
|
|
1766
|
+
}
|
|
1767
|
+
} finally{
|
|
1768
|
+
if (_didIteratorError) {
|
|
1769
|
+
throw _iteratorError;
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
};
|
|
1774
|
+
|
|
1279
1775
|
function _instanceof(left, right) {
|
|
1280
1776
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
1281
1777
|
return !!right[Symbol.hasInstance](left);
|
|
@@ -1362,9 +1858,13 @@ function _type_of(obj) {
|
|
|
1362
1858
|
* Extracts sighashes from a PSBT for validation.
|
|
1363
1859
|
* This is used to verify that the message being signed matches the PSBT context.
|
|
1364
1860
|
*
|
|
1861
|
+
* P2WSH inputs whose witnessScript is absent yield `null` instead of a hash:
|
|
1862
|
+
* finalization strips witnessScript from completed inputs, so a co-signer's
|
|
1863
|
+
* already-finalized input must not block validation of the remaining inputs.
|
|
1864
|
+
*
|
|
1365
1865
|
* @param psbtBase64 - PSBT in base64 format
|
|
1366
1866
|
* @param network - 'mainnet' or 'testnet' or BitcoinNetwork enum (defaults to 'mainnet')
|
|
1367
|
-
* @returns Array of sighash hex strings for
|
|
1867
|
+
* @returns Array of sighash hex strings, aligned by input index; `null` for inputs whose sighash cannot be derived
|
|
1368
1868
|
*/ var extractPsbtSighashes = function(psbtBase64) {
|
|
1369
1869
|
var network = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 'mainnet';
|
|
1370
1870
|
// Convert string network to BitcoinNetwork enum
|
|
@@ -1382,29 +1882,125 @@ function _type_of(obj) {
|
|
|
1382
1882
|
for(var i = 0; i < psbt.inputCount; i++){
|
|
1383
1883
|
var input = psbt.data.inputs[i];
|
|
1384
1884
|
if (input.tapInternalKey) {
|
|
1385
|
-
// Taproot (BIP-341) - uses hashForWitnessV1 with
|
|
1386
|
-
|
|
1885
|
+
// Taproot (BIP-341) - uses hashForWitnessV1 with the input's declared
|
|
1886
|
+
// sighash type, defaulting to SIGHASH_DEFAULT
|
|
1887
|
+
var hash = tx.hashForWitnessV1(i, prevOutScripts, values, getSigHashType(input, true));
|
|
1387
1888
|
sighashes.push(Buffer.from(hash).toString('hex'));
|
|
1388
|
-
|
|
1389
|
-
// Native SegWit (BIP-143) - uses hashForWitnessV0 with SIGHASH_ALL
|
|
1390
|
-
// witnessUtxo is guaranteed to exist from collectPSBTInputData validation
|
|
1391
|
-
var _input_witnessUtxo = input.witnessUtxo, script = _input_witnessUtxo.script, value = _input_witnessUtxo.value;
|
|
1392
|
-
// Build P2PKH script code from the pubkey hash in the witness program
|
|
1393
|
-
var p2pkh = bitcoin.payments.p2pkh({
|
|
1394
|
-
hash: new Uint8Array(toBuffer(script).subarray(2)),
|
|
1395
|
-
network: bitcoinNetwork
|
|
1396
|
-
});
|
|
1397
|
-
var scriptCode = p2pkh.output;
|
|
1398
|
-
if (!scriptCode) {
|
|
1399
|
-
throw new Error("Failed to generate scriptCode for input ".concat(i));
|
|
1400
|
-
}
|
|
1401
|
-
var hash1 = tx.hashForWitnessV0(i, scriptCode, value, bitcoin.Transaction.SIGHASH_ALL);
|
|
1402
|
-
sighashes.push(Buffer.from(hash1).toString('hex'));
|
|
1889
|
+
continue;
|
|
1403
1890
|
}
|
|
1891
|
+
// Native SegWit (BIP-143) - uses hashForWitnessV0 with the input's
|
|
1892
|
+
// declared sighash type, defaulting to SIGHASH_ALL
|
|
1893
|
+
// witnessUtxo is guaranteed to exist from collectPSBTInputData validation
|
|
1894
|
+
var _input_witnessUtxo = input.witnessUtxo, script = _input_witnessUtxo.script, value = _input_witnessUtxo.value;
|
|
1895
|
+
if (isP2wshOutputScript(script) && !input.witnessScript) {
|
|
1896
|
+
sighashes.push(null);
|
|
1897
|
+
continue;
|
|
1898
|
+
}
|
|
1899
|
+
var scriptCode = getSegwitV0ScriptCode(input, script, i, bitcoinNetwork);
|
|
1900
|
+
var hash1 = tx.hashForWitnessV0(i, scriptCode, value, getSigHashType(input, false));
|
|
1901
|
+
sighashes.push(Buffer.from(hash1).toString('hex'));
|
|
1404
1902
|
}
|
|
1405
1903
|
return sighashes;
|
|
1406
1904
|
};
|
|
1407
1905
|
|
|
1906
|
+
function _array_like_to_array(arr, len) {
|
|
1907
|
+
if (len == null || len > arr.length) len = arr.length;
|
|
1908
|
+
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
|
|
1909
|
+
return arr2;
|
|
1910
|
+
}
|
|
1911
|
+
function _array_without_holes(arr) {
|
|
1912
|
+
if (Array.isArray(arr)) return _array_like_to_array(arr);
|
|
1913
|
+
}
|
|
1914
|
+
function _iterable_to_array(iter) {
|
|
1915
|
+
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
|
|
1916
|
+
}
|
|
1917
|
+
function _non_iterable_spread() {
|
|
1918
|
+
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
1919
|
+
}
|
|
1920
|
+
function _to_consumable_array(arr) {
|
|
1921
|
+
return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
|
|
1922
|
+
}
|
|
1923
|
+
function _unsupported_iterable_to_array(o, minLen) {
|
|
1924
|
+
if (!o) return;
|
|
1925
|
+
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
1926
|
+
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
1927
|
+
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
1928
|
+
if (n === "Map" || n === "Set") return Array.from(n);
|
|
1929
|
+
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
1930
|
+
}
|
|
1931
|
+
/**
|
|
1932
|
+
* Describes a PSBT the way a BTC signing intent does: its txid, fee, outputs
|
|
1933
|
+
* and the sighashes of the inputs a wallet is about to sign.
|
|
1934
|
+
*
|
|
1935
|
+
* Every input must carry a `witnessUtxo`: the fee needs the value of every
|
|
1936
|
+
* input, and the txid of a segwit transaction does not change once its inputs
|
|
1937
|
+
* are signed. An input with only a `nonWitnessUtxo` is rejected.
|
|
1938
|
+
*
|
|
1939
|
+
* @param psbtBase64 - The PSBT in base64 format
|
|
1940
|
+
* @param network - The Bitcoin network the PSBT is for
|
|
1941
|
+
* @param inputIndexes - The PSBT input indexes the wallet signs
|
|
1942
|
+
* @returns The txid, fee, outputs and the sighashes of `inputIndexes`
|
|
1943
|
+
* @throws Error if an input lacks a `witnessUtxo`, the outputs exceed the inputs,
|
|
1944
|
+
* `inputIndexes` is empty or out of range, or a requested input has no derivable sighash
|
|
1945
|
+
*/ var extractPsbtIntentOperation = function(param) {
|
|
1946
|
+
var inputIndexes = param.inputIndexes, network = param.network, psbtBase64 = param.psbtBase64;
|
|
1947
|
+
var psbt = bitcoin.Psbt.fromBase64(psbtBase64, {
|
|
1948
|
+
network: getBitcoinNetwork(toBitcoinNetwork(network))
|
|
1949
|
+
});
|
|
1950
|
+
var values = collectPSBTInputData(psbt).values;
|
|
1951
|
+
var tx = psbt.__CACHE.__TX;
|
|
1952
|
+
var inputTotal = values.reduce(function(sum, value) {
|
|
1953
|
+
return sum + value;
|
|
1954
|
+
}, 0n);
|
|
1955
|
+
var outputTotal = tx.outs.reduce(function(sum, output) {
|
|
1956
|
+
return sum + output.value;
|
|
1957
|
+
}, 0n);
|
|
1958
|
+
if (outputTotal > inputTotal) {
|
|
1959
|
+
throw new Error('Transaction outputs exceed its inputs');
|
|
1960
|
+
}
|
|
1961
|
+
var requested = _to_consumable_array(new Set(inputIndexes)).sort(function(a, b) {
|
|
1962
|
+
return a - b;
|
|
1963
|
+
});
|
|
1964
|
+
if (requested.length === 0) {
|
|
1965
|
+
throw new Error('At least one input to sign is required');
|
|
1966
|
+
}
|
|
1967
|
+
var allSighashes = extractPsbtSighashes(psbtBase64, network);
|
|
1968
|
+
var sighashes = requested.map(function(index) {
|
|
1969
|
+
if (!Number.isInteger(index) || index < 0 || index >= allSighashes.length) {
|
|
1970
|
+
throw new Error("Input ".concat(index, " is not in the PSBT"));
|
|
1971
|
+
}
|
|
1972
|
+
var sighash = allSighashes[index];
|
|
1973
|
+
if (sighash === null) {
|
|
1974
|
+
throw new Error("Input ".concat(index, " has no derivable sighash"));
|
|
1975
|
+
}
|
|
1976
|
+
return sighash;
|
|
1977
|
+
});
|
|
1978
|
+
return {
|
|
1979
|
+
feeSats: (inputTotal - outputTotal).toString(),
|
|
1980
|
+
outputs: tx.outs.map(function(output) {
|
|
1981
|
+
return {
|
|
1982
|
+
script: Buffer.from(output.script).toString('hex'),
|
|
1983
|
+
valueSats: output.value.toString()
|
|
1984
|
+
};
|
|
1985
|
+
}),
|
|
1986
|
+
sighashes: sighashes,
|
|
1987
|
+
txid: tx.getId()
|
|
1988
|
+
};
|
|
1989
|
+
};
|
|
1990
|
+
|
|
1991
|
+
/**
|
|
1992
|
+
* The `chainId` label that identifies a Bitcoin network to the policy layer
|
|
1993
|
+
* and in a signing intent: `'2'` for an explicit testnet, `'1'` otherwise.
|
|
1994
|
+
*
|
|
1995
|
+
* An omitted network is labelled mainnet, which matches the mainnet default
|
|
1996
|
+
* the signing clients already use for the PSBT itself.
|
|
1997
|
+
*
|
|
1998
|
+
* @param network - The Bitcoin network, if known
|
|
1999
|
+
* @returns `'2'` for testnet, `'1'` for mainnet or when no network is given
|
|
2000
|
+
*/ var getBtcChainId = function(network) {
|
|
2001
|
+
return network === 'testnet' ? '2' : '1';
|
|
2002
|
+
};
|
|
2003
|
+
|
|
1408
2004
|
/**
|
|
1409
2005
|
* Converts a string address type identifier to a BitcoinAddressType enum value.
|
|
1410
2006
|
* If the input is already a BitcoinAddressType enum, it is returned as-is.
|
|
@@ -1425,9 +2021,6 @@ function _type_of(obj) {
|
|
|
1425
2021
|
* Computes the BIP-322 message hash for a given message and public key,
|
|
1426
2022
|
* returning the result as a hex string.
|
|
1427
2023
|
*
|
|
1428
|
-
* This function implements the BIP-322 hash computation for
|
|
1429
|
-
* native_segwit and taproot address types.
|
|
1430
|
-
*
|
|
1431
2024
|
* @param message - The raw message to be signed
|
|
1432
2025
|
* @param publicKey - The public key (hex string, Buffer, or Uint8Array)
|
|
1433
2026
|
* @param addressType - The address type (BitcoinAddressType enum or 'native_segwit', 'taproot')
|
|
@@ -1436,70 +2029,11 @@ function _type_of(obj) {
|
|
|
1436
2029
|
* @returns The BIP-322 message hash as a hex string
|
|
1437
2030
|
*/ var computeBip322HashHex = function(message, publicKey, addressType) {
|
|
1438
2031
|
var network = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : BitcoinNetwork.MAINNET, ecc = arguments.length > 4 ? arguments[4] : void 0;
|
|
1439
|
-
// Convert string network to BitcoinNetwork enum
|
|
1440
2032
|
var btcNetwork = toBitcoinNetwork(network);
|
|
1441
|
-
// Convert string addressType to enum
|
|
1442
2033
|
var addressTypeEnum = toBitcoinAddressType(addressType);
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
}
|
|
1447
|
-
// Convert publicKey to Buffer
|
|
1448
|
-
var pubKeyBuffer;
|
|
1449
|
-
if (typeof publicKey === 'string') {
|
|
1450
|
-
pubKeyBuffer = Buffer.from(publicKey.replace(/^0x/, ''), 'hex');
|
|
1451
|
-
} else {
|
|
1452
|
-
pubKeyBuffer = toBuffer(publicKey);
|
|
1453
|
-
}
|
|
1454
|
-
// Compress public key if uncompressed
|
|
1455
|
-
pubKeyBuffer = normalizeForCompressed(pubKeyBuffer);
|
|
1456
|
-
// Generate address from public key
|
|
1457
|
-
var address = publicKeyToBitcoinAddress(pubKeyBuffer, addressTypeEnum, btcNetwork, ecc);
|
|
1458
|
-
// Convert address to scriptPubKey using bip322-js
|
|
1459
|
-
var scriptPubKey = Address.convertAdressToScriptPubkey(address);
|
|
1460
|
-
// Create the BIP-322 to_spend transaction
|
|
1461
|
-
var toSpendTx = BIP322.buildToSpendTx(message, scriptPubKey);
|
|
1462
|
-
// Create the to_sign PSBT
|
|
1463
|
-
var toSignPsbt = BIP322.buildToSignTx(toSpendTx.getId(), scriptPubKey);
|
|
1464
|
-
// Get the transaction from the PSBT
|
|
1465
|
-
var txToSign = toSignPsbt.__CACHE.__TX;
|
|
1466
|
-
// Get bitcoinjs-lib network
|
|
1467
|
-
var bitcoinNetwork = getBitcoinNetwork(btcNetwork);
|
|
1468
|
-
// Compute sighash based on address type
|
|
1469
|
-
if (addressTypeEnum === BitcoinAddressType.TAPROOT) {
|
|
1470
|
-
// Taproot (BIP-341) uses hashForWitnessV1 with SIGHASH_DEFAULT
|
|
1471
|
-
var prevOutScripts = [
|
|
1472
|
-
scriptPubKey
|
|
1473
|
-
];
|
|
1474
|
-
var values = [
|
|
1475
|
-
0
|
|
1476
|
-
]; // Use number, not BigInt - BIP-322 uses 0 value
|
|
1477
|
-
var hash = txToSign.hashForWitnessV1(0, prevOutScripts, values, bitcoin.Transaction.SIGHASH_DEFAULT);
|
|
1478
|
-
return Buffer.from(hash).toString('hex');
|
|
1479
|
-
} else {
|
|
1480
|
-
// SegWit (BIP-143) uses hashForWitnessV0 with SIGHASH_ALL
|
|
1481
|
-
// Create a new transaction for signing
|
|
1482
|
-
var txToSignSegwit = new bitcoin.Transaction();
|
|
1483
|
-
txToSignSegwit.version = 0;
|
|
1484
|
-
txToSignSegwit.locktime = 0;
|
|
1485
|
-
var prevTxId = toSpendTx.getId();
|
|
1486
|
-
var prevHash = Buffer.from(prevTxId, 'hex').reverse();
|
|
1487
|
-
txToSignSegwit.addInput(new Uint8Array(prevHash), 0, 0);
|
|
1488
|
-
txToSignSegwit.addOutput(new Uint8Array(Buffer.from([
|
|
1489
|
-
0x6a
|
|
1490
|
-
])), BigInt(0));
|
|
1491
|
-
// Build P2PKH script code from pubkey
|
|
1492
|
-
var p2pkh = bitcoin.payments.p2pkh({
|
|
1493
|
-
pubkey: new Uint8Array(pubKeyBuffer),
|
|
1494
|
-
network: bitcoinNetwork
|
|
1495
|
-
});
|
|
1496
|
-
var scriptCode = p2pkh.output;
|
|
1497
|
-
if (!scriptCode) {
|
|
1498
|
-
throw new Error('Failed to generate scriptCode for BIP-322 hash');
|
|
1499
|
-
}
|
|
1500
|
-
var hash1 = txToSignSegwit.hashForWitnessV0(0, scriptCode, BigInt(0), bitcoin.Transaction.SIGHASH_ALL);
|
|
1501
|
-
return Buffer.from(hash1).toString('hex');
|
|
1502
|
-
}
|
|
2034
|
+
var normalizedPublicKey = typeof publicKey === 'string' ? publicKey.replace(/^0x/, '') : publicKey;
|
|
2035
|
+
var formattedMessage = calculateBip322Hash(message, normalizedPublicKey, addressTypeEnum, btcNetwork, ecc).formattedMessage;
|
|
2036
|
+
return Buffer.from(formattedMessage).toString('hex');
|
|
1503
2037
|
};
|
|
1504
2038
|
|
|
1505
|
-
export { calculateBip322Hash, calculateTaprootTweak, collectPSBTInputData, computeBip322HashHex, convertSignatureToDER, convertSignatureToTaprootBuffer, createLegacyAddress, createNativeSegWitAddress, createSegWitAddress, createTaprootAddress, doesInputBelongToAddress, encodeBip322Signature, extractPsbtSighashes, extractPublicKeyHex, getAddressTypeFromDerivationPath, getBitcoinNetwork, getDefaultRpcUrl, getFeeRates, getPublicKeyFromPrivateKey, getUTXOs, initEccLib, normalizeForCompressed, normalizeForTaproot, normalizePublicKey, privateKeyToWIF, publicKeyToBitcoinAddress, selectUTXOs, toBitcoinNetwork, toBuffer, wifToPrivateKey };
|
|
2039
|
+
export { assertSighashAllowed, calculateBip322Hash, calculateTaprootTweak, collectPSBTInputData, computeBip322HashHex, convertSignatureToDER, convertSignatureToTaprootBuffer, createLegacyAddress, createNativeSegWitAddress, createSegWitAddress, createTaprootAddress, doesInputBelongToAddress, encodeBip322Signature, extractPsbtIntentOperation, extractPsbtSighashes, extractPublicKeyHex, filterInputsBySigningIndexes, getAddressTypeFromAddress, getAddressTypeFromDerivationPath, getBitcoinNetwork, getBtcChainId, getDefaultRpcUrl, getFeeRates, getPublicKeyFromPrivateKey, getSegwitV0ScriptCode, getSigHashType, getUTXOs, initEccLib, isP2wshOutputScript, normalizeForCompressed, normalizeForTaproot, normalizePublicKey, privateKeyToWIF, publicKeyToBitcoinAddress, resolveBitcoinAddressType, resolveRpcUrl, rpcFetch, selectUTXOs, toBitcoinNetwork, toBuffer, wifToPrivateKey };
|