@bitcoinerlab/descriptors-core 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +710 -0
  2. package/dist/adapters/applyPR2137.d.ts +2 -0
  3. package/dist/adapters/applyPR2137.js +150 -0
  4. package/dist/adapters/bitcoinjs.d.ts +8 -0
  5. package/dist/adapters/bitcoinjs.js +36 -0
  6. package/dist/adapters/scure/address.d.ts +2 -0
  7. package/dist/adapters/scure/address.js +50 -0
  8. package/dist/adapters/scure/bip32.d.ts +2 -0
  9. package/dist/adapters/scure/bip32.js +16 -0
  10. package/dist/adapters/scure/common.d.ts +14 -0
  11. package/dist/adapters/scure/common.js +36 -0
  12. package/dist/adapters/scure/ecpair.d.ts +2 -0
  13. package/dist/adapters/scure/ecpair.js +58 -0
  14. package/dist/adapters/scure/payments.d.ts +2 -0
  15. package/dist/adapters/scure/payments.js +216 -0
  16. package/dist/adapters/scure/psbt.d.ts +43 -0
  17. package/dist/adapters/scure/psbt.js +382 -0
  18. package/dist/adapters/scure/script.d.ts +20 -0
  19. package/dist/adapters/scure/script.js +163 -0
  20. package/dist/adapters/scure/transaction.d.ts +2 -0
  21. package/dist/adapters/scure/transaction.js +32 -0
  22. package/dist/adapters/scure.d.ts +6 -0
  23. package/dist/adapters/scure.js +37 -0
  24. package/dist/adapters/scureKeys.d.ts +4 -0
  25. package/dist/adapters/scureKeys.js +135 -0
  26. package/dist/bip174.d.ts +87 -0
  27. package/dist/bip174.js +12 -0
  28. package/dist/bitcoinLib.d.ts +385 -0
  29. package/dist/bitcoinLib.js +19 -0
  30. package/dist/bitcoinjs-lib-internals.d.ts +6 -0
  31. package/dist/bitcoinjs-lib-internals.js +60 -0
  32. package/dist/bitcoinjs.d.ts +12 -0
  33. package/dist/bitcoinjs.js +18 -0
  34. package/dist/checksum.d.ts +6 -0
  35. package/dist/checksum.js +58 -0
  36. package/dist/crypto.d.ts +3 -0
  37. package/dist/crypto.js +79 -0
  38. package/dist/descriptors.d.ts +481 -0
  39. package/dist/descriptors.js +1888 -0
  40. package/dist/index.d.ts +23 -0
  41. package/dist/index.js +87 -0
  42. package/dist/keyExpressions.d.ts +124 -0
  43. package/dist/keyExpressions.js +310 -0
  44. package/dist/keyInterfaces.d.ts +5 -0
  45. package/dist/keyInterfaces.js +50 -0
  46. package/dist/ledger.d.ts +183 -0
  47. package/dist/ledger.js +618 -0
  48. package/dist/miniscript.d.ts +125 -0
  49. package/dist/miniscript.js +310 -0
  50. package/dist/multipath.d.ts +13 -0
  51. package/dist/multipath.js +76 -0
  52. package/dist/networkUtils.d.ts +3 -0
  53. package/dist/networkUtils.js +16 -0
  54. package/dist/networks.d.ts +16 -0
  55. package/dist/networks.js +31 -0
  56. package/dist/parseUtils.d.ts +7 -0
  57. package/dist/parseUtils.js +46 -0
  58. package/dist/psbt.d.ts +40 -0
  59. package/dist/psbt.js +228 -0
  60. package/dist/re.d.ts +31 -0
  61. package/dist/re.js +79 -0
  62. package/dist/resourceLimits.d.ts +28 -0
  63. package/dist/resourceLimits.js +84 -0
  64. package/dist/scriptExpressions.d.ts +95 -0
  65. package/dist/scriptExpressions.js +98 -0
  66. package/dist/scure.d.ts +4 -0
  67. package/dist/scure.js +10 -0
  68. package/dist/signers.d.ts +161 -0
  69. package/dist/signers.js +324 -0
  70. package/dist/tapMiniscript.d.ts +231 -0
  71. package/dist/tapMiniscript.js +524 -0
  72. package/dist/tapTree.d.ts +91 -0
  73. package/dist/tapTree.js +166 -0
  74. package/dist/types.d.ts +296 -0
  75. package/dist/types.js +4 -0
  76. package/package.json +148 -0
@@ -0,0 +1,2 @@
1
+ import type { Psbt } from 'bitcoinjs-lib';
2
+ export declare const applyPR2137: (psbt: Psbt) => void;
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.applyPR2137 = void 0;
4
+ const bip174_1 = require("../bip174");
5
+ const bitcoinjs_lib_internals_1 = require("../bitcoinjs-lib-internals");
6
+ const crypto_1 = require("../crypto");
7
+ const uint8array_tools_1 = require("uint8array-tools");
8
+ const toXOnly = (pubKey) => pubKey.length === 32 ? pubKey : pubKey.slice(1, 33);
9
+ function range(n) {
10
+ return [...Array(n).keys()];
11
+ }
12
+ function tapBranchHash(a, b) {
13
+ return (0, crypto_1.taggedHash)('TapBranch', (0, uint8array_tools_1.concat)([a, b]));
14
+ }
15
+ function calculateScriptTreeMerkleRoot(leafHashes) {
16
+ if (!leafHashes || leafHashes.length === 0) {
17
+ return undefined;
18
+ }
19
+ const leafHashCopies = leafHashes.map(leafHash => Uint8Array.from(leafHash));
20
+ // sort the leaf nodes
21
+ leafHashCopies.sort(uint8array_tools_1.compare);
22
+ // create the initial hash node
23
+ let currentLevel = leafHashCopies;
24
+ // build Merkle Tree
25
+ while (currentLevel.length > 1) {
26
+ const nextLevel = [];
27
+ for (let i = 0; i < currentLevel.length; i += 2) {
28
+ const left = currentLevel[i];
29
+ if (!left)
30
+ throw new Error('Invalid tapleaf hash tree level');
31
+ const right = i + 1 < currentLevel.length ? (currentLevel[i + 1] ?? left) : left;
32
+ nextLevel.push(i + 1 < currentLevel.length ? tapBranchHash(left, right) : left);
33
+ }
34
+ currentLevel = nextLevel;
35
+ }
36
+ return currentLevel[0];
37
+ }
38
+ function getTweakSignersFromHD(inputIndex, inputs, hdKeyPair) {
39
+ const input = (0, bip174_1.checkForInput)(inputs, inputIndex);
40
+ if (!input.tapBip32Derivation || input.tapBip32Derivation.length === 0) {
41
+ throw new Error('Need tapBip32Derivation to sign with HD');
42
+ }
43
+ const myDerivations = input.tapBip32Derivation
44
+ .map(bipDv => {
45
+ if ((0, uint8array_tools_1.compare)(bipDv.masterFingerprint, hdKeyPair.fingerprint) === 0) {
46
+ return bipDv;
47
+ }
48
+ else {
49
+ return;
50
+ }
51
+ })
52
+ .filter(v => !!v);
53
+ if (myDerivations.length === 0) {
54
+ throw new Error('Need one tapBip32Derivation masterFingerprint to match the HDSigner fingerprint');
55
+ }
56
+ const signers = myDerivations.map(bipDv => {
57
+ const node = hdKeyPair.derivePath(bipDv.path);
58
+ if ((0, uint8array_tools_1.compare)(bipDv.pubkey, toXOnly(node.publicKey)) !== 0) {
59
+ throw new Error('pubkey did not match tapBip32Derivation');
60
+ }
61
+ //FIX BITCOINERLAB:
62
+ //The 3 lines below detect script-path spends and disable key-path tweaking.
63
+ //Reasoning:
64
+ //- In Taproot, key-path spends require tweaking the internal key.
65
+ //- Script-path spends MUST NOT tweak the key; signatures use the raw internal key.
66
+ const input = inputs[inputIndex];
67
+ if (!input)
68
+ throw new Error('could not find the input');
69
+ if (input.tapLeafScript && input.tapLeafScript.length > 0)
70
+ return node;
71
+ const h = calculateScriptTreeMerkleRoot(bipDv.leafHashes);
72
+ const tweakValue = (0, bitcoinjs_lib_internals_1.tapTweakHash)(toXOnly(node.publicKey), h);
73
+ return node.tweak(tweakValue);
74
+ });
75
+ return signers;
76
+ }
77
+ function getSignersFromHD(inputIndex, inputs, hdKeyPair) {
78
+ const input = (0, bip174_1.checkForInput)(inputs, inputIndex);
79
+ if ((0, bitcoinjs_lib_internals_1.isTaprootInput)(input)) {
80
+ return getTweakSignersFromHD(inputIndex, inputs, hdKeyPair);
81
+ }
82
+ if (!input.bip32Derivation || input.bip32Derivation.length === 0) {
83
+ throw new Error('Need bip32Derivation to sign with HD');
84
+ }
85
+ const myDerivations = input.bip32Derivation
86
+ .map(bipDv => {
87
+ if ((0, uint8array_tools_1.compare)(bipDv.masterFingerprint, hdKeyPair.fingerprint) === 0) {
88
+ return bipDv;
89
+ }
90
+ else {
91
+ return;
92
+ }
93
+ })
94
+ .filter(v => !!v);
95
+ if (myDerivations.length === 0) {
96
+ throw new Error('Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint');
97
+ }
98
+ const signers = myDerivations.map(bipDv => {
99
+ const node = hdKeyPair.derivePath(bipDv.path);
100
+ if ((0, uint8array_tools_1.compare)(bipDv.pubkey, node.publicKey) !== 0) {
101
+ throw new Error('pubkey did not match bip32Derivation');
102
+ }
103
+ return node;
104
+ });
105
+ return signers;
106
+ }
107
+ const applyPR2137 = (psbt) => {
108
+ psbt.signInputHD = function signInputHD(inputIndex, hdKeyPair, sighashTypes) {
109
+ if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
110
+ throw new Error('Need HDSigner to sign input');
111
+ }
112
+ const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair);
113
+ const results = [];
114
+ for (const signer of signers) {
115
+ try {
116
+ this.signInput(inputIndex, signer, sighashTypes);
117
+ results.push(true);
118
+ }
119
+ catch (err) {
120
+ void err;
121
+ results.push(false);
122
+ }
123
+ }
124
+ if (results.every(v => v === false)) {
125
+ throw new Error('No inputs were signed');
126
+ }
127
+ return this;
128
+ };
129
+ psbt.signAllInputsHD = function signAllInputsHD(hdKeyPair, sighashTypes) {
130
+ if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
131
+ throw new Error('Need HDSigner to sign input');
132
+ }
133
+ const results = [];
134
+ for (const i of range(psbt.data.inputs.length)) {
135
+ try {
136
+ psbt.signInputHD(i, hdKeyPair, sighashTypes);
137
+ results.push(true);
138
+ }
139
+ catch (err) {
140
+ void err;
141
+ results.push(false);
142
+ }
143
+ }
144
+ if (results.every(v => v === false)) {
145
+ throw new Error('No inputs were signed');
146
+ }
147
+ return psbt;
148
+ };
149
+ };
150
+ exports.applyPR2137 = applyPR2137;
@@ -0,0 +1,8 @@
1
+ import type { TinySecp256k1Interface } from '../types';
2
+ import type { BitcoinLib } from '../bitcoinLib';
3
+ /**
4
+ * Create a BitcoinLib backed by bitcoinjs-lib.
5
+ *
6
+ * @param ecc A TinySecp256k1Interface (e.g. `@bitcoinerlab/secp256k1`).
7
+ */
8
+ export declare function createBitcoinjsLib(ecc: TinySecp256k1Interface): BitcoinLib;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ // Copyright (c) 2026 Jose-Luis Landabaso - https://bitcoinerlab.com
3
+ // Distributed under the MIT software license
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.createBitcoinjsLib = createBitcoinjsLib;
6
+ /**
7
+ * bitcoinjs-lib adapter for BitcoinLib.
8
+ *
9
+ * Wraps bitcoinjs-lib, ecpair, bip32 and related packages into the
10
+ * BitcoinLib interface. This is the default backend and should produce
11
+ * identical behaviour to the pre-refactor library.
12
+ */
13
+ const bitcoinjs_lib_1 = require("bitcoinjs-lib");
14
+ const bip32_1 = require("bip32");
15
+ const ecpair_1 = require("ecpair");
16
+ /**
17
+ * Create a BitcoinLib backed by bitcoinjs-lib.
18
+ *
19
+ * @param ecc A TinySecp256k1Interface (e.g. `@bitcoinerlab/secp256k1`).
20
+ */
21
+ function createBitcoinjsLib(ecc) {
22
+ (0, bitcoinjs_lib_1.initEccLib)(ecc);
23
+ const ECPair = (0, ecpair_1.ECPairFactory)(ecc);
24
+ const BIP32 = (0, bip32_1.BIP32Factory)(ecc);
25
+ if (!ecc.verifySchnorr)
26
+ throw new Error('TinySecp256k1Interface is not initialized properly: verifySchnorr is missing.');
27
+ return {
28
+ payments: bitcoinjs_lib_1.payments,
29
+ script: bitcoinjs_lib_1.script,
30
+ Transaction: bitcoinjs_lib_1.Transaction,
31
+ address: bitcoinjs_lib_1.address,
32
+ ECPair,
33
+ BIP32,
34
+ verifySchnorr: ecc.verifySchnorr
35
+ };
36
+ }
@@ -0,0 +1,2 @@
1
+ import type { BitcoinLib } from '../../bitcoinLib';
2
+ export declare function createScureAddressAdapter(): BitcoinLib['address'];
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ // Copyright (c) 2026 Jose-Luis Landabaso - https://bitcoinerlab.com
3
+ // Distributed under the MIT software license
4
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
+ if (k2 === undefined) k2 = k;
6
+ var desc = Object.getOwnPropertyDescriptor(m, k);
7
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
+ desc = { enumerable: true, get: function() { return m[k]; } };
9
+ }
10
+ Object.defineProperty(o, k2, desc);
11
+ }) : (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ o[k2] = m[k];
14
+ }));
15
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
17
+ }) : function(o, v) {
18
+ o["default"] = v;
19
+ });
20
+ var __importStar = (this && this.__importStar) || (function () {
21
+ var ownKeys = function(o) {
22
+ ownKeys = Object.getOwnPropertyNames || function (o) {
23
+ var ar = [];
24
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
25
+ return ar;
26
+ };
27
+ return ownKeys(o);
28
+ };
29
+ return function (mod) {
30
+ if (mod && mod.__esModule) return mod;
31
+ var result = {};
32
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
33
+ __setModuleDefault(result, mod);
34
+ return result;
35
+ };
36
+ })();
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.createScureAddressAdapter = createScureAddressAdapter;
39
+ const btc = __importStar(require("@scure/btc-signer"));
40
+ const networks_1 = require("../../networks");
41
+ const common_1 = require("./common");
42
+ function createScureAddressAdapter() {
43
+ return {
44
+ toOutputScript(addr, network) {
45
+ const net = (0, common_1.toBtcSignerNetwork)(network ?? networks_1.networks.bitcoin);
46
+ const decoded = btc.Address(net).decode(addr);
47
+ return btc.OutScript.encode(decoded);
48
+ }
49
+ };
50
+ }
@@ -0,0 +1,2 @@
1
+ import type { BitcoinLib } from '../../bitcoinLib';
2
+ export declare function createScureBIP32Adapter(): BitcoinLib['BIP32'];
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ // Copyright (c) 2026 Jose-Luis Landabaso - https://bitcoinerlab.com
3
+ // Distributed under the MIT software license
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.createScureBIP32Adapter = createScureBIP32Adapter;
6
+ const bip32_1 = require("@scure/bip32");
7
+ const scureKeys_1 = require("../scureKeys");
8
+ const common_1 = require("./common");
9
+ function createScureBIP32Adapter() {
10
+ return {
11
+ fromBase58(inString, network) {
12
+ const hd = bip32_1.HDKey.fromExtendedKey(inString, (0, common_1.scureVersions)(network));
13
+ return (0, scureKeys_1.wrapScureHDKey)(hd);
14
+ }
15
+ };
16
+ }
@@ -0,0 +1,14 @@
1
+ import { type Network } from '../../networks';
2
+ /** Convert our Network to the format expected by @scure/btc-signer */
3
+ export declare function toBtcSignerNetwork(network: Network): {
4
+ bech32: string;
5
+ pubKeyHash: number;
6
+ scriptHash: number;
7
+ wif: number;
8
+ };
9
+ export declare function scureVersions(network?: Network): {
10
+ public: number;
11
+ private: number;
12
+ };
13
+ export declare function uint32ToBytesBE(value: number): Uint8Array;
14
+ export declare function uint32FromBytesBE(bytes: Uint8Array): number;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ // Copyright (c) 2026 Jose-Luis Landabaso - https://bitcoinerlab.com
3
+ // Distributed under the MIT software license
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.toBtcSignerNetwork = toBtcSignerNetwork;
6
+ exports.scureVersions = scureVersions;
7
+ exports.uint32ToBytesBE = uint32ToBytesBE;
8
+ exports.uint32FromBytesBE = uint32FromBytesBE;
9
+ const networks_1 = require("../../networks");
10
+ const uint8array_tools_1 = require("uint8array-tools");
11
+ /** Convert our Network to the format expected by @scure/btc-signer */
12
+ function toBtcSignerNetwork(network) {
13
+ return {
14
+ bech32: network.bech32,
15
+ pubKeyHash: network.pubKeyHash,
16
+ scriptHash: network.scriptHash,
17
+ wif: network.wif
18
+ };
19
+ }
20
+ function scureVersions(network) {
21
+ const net = network ?? networks_1.networks.bitcoin;
22
+ return {
23
+ public: net.bip32.public,
24
+ private: net.bip32.private
25
+ };
26
+ }
27
+ function uint32ToBytesBE(value) {
28
+ const bytes = new Uint8Array(4);
29
+ (0, uint8array_tools_1.writeUInt32)(bytes, 0, value, 'BE');
30
+ return bytes;
31
+ }
32
+ function uint32FromBytesBE(bytes) {
33
+ if (bytes.length !== 4)
34
+ throw new Error('Expected 4-byte fingerprint');
35
+ return (0, uint8array_tools_1.readUInt32)(bytes, 0, 'BE');
36
+ }
@@ -0,0 +1,2 @@
1
+ import type { BitcoinLib } from '../../bitcoinLib';
2
+ export declare function createScureECPairAdapter(): BitcoinLib['ECPair'];
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ // Copyright (c) 2026 Jose-Luis Landabaso - https://bitcoinerlab.com
3
+ // Distributed under the MIT software license
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.createScureECPairAdapter = createScureECPairAdapter;
6
+ const base_1 = require("@scure/base");
7
+ const secp256k1_js_1 = require("@noble/curves/secp256k1.js");
8
+ const uint8array_tools_1 = require("uint8array-tools");
9
+ const crypto_1 = require("../../crypto");
10
+ const scureKeys_1 = require("../scureKeys");
11
+ function decodeWIF(wifString, network) {
12
+ const raw = base_1.base58.decode(wifString);
13
+ if (!(raw.length === 37 || raw.length === 38)) {
14
+ throw new Error('Wrong WIF length');
15
+ }
16
+ const payload = raw.slice(0, raw.length - 4);
17
+ const checksum = raw.slice(raw.length - 4);
18
+ const expected = (0, crypto_1.sha256)((0, crypto_1.sha256)(payload)).slice(0, 4);
19
+ if ((0, uint8array_tools_1.compare)(checksum, expected) !== 0) {
20
+ throw new Error('Invalid WIF checksum');
21
+ }
22
+ const version = payload[0];
23
+ if (version === undefined)
24
+ throw new Error('Invalid WIF payload');
25
+ if (Array.isArray(network)) {
26
+ if (!network.some(net => net.wif === version)) {
27
+ throw new Error('Invalid network version');
28
+ }
29
+ }
30
+ else if (network && network.wif !== version) {
31
+ throw new Error('Invalid network version');
32
+ }
33
+ if (!(payload.length === 33 || payload.length === 34)) {
34
+ throw new Error('Wrong WIF length');
35
+ }
36
+ if (payload.length === 34 && payload[33] !== 0x01) {
37
+ throw new Error('Invalid WIF compression flag');
38
+ }
39
+ return {
40
+ privateKey: payload.slice(1, 33),
41
+ compressed: payload.length === 34
42
+ };
43
+ }
44
+ function createScureECPairAdapter() {
45
+ return {
46
+ isPoint(maybePoint) {
47
+ return (maybePoint instanceof Uint8Array &&
48
+ secp256k1_js_1.secp256k1.utils.isValidPublicKey(maybePoint));
49
+ },
50
+ fromPublicKey(buffer, _options) {
51
+ return (0, scureKeys_1.wrapScurePublicKey)(buffer);
52
+ },
53
+ fromWIF(wifString, network) {
54
+ const { privateKey, compressed } = decodeWIF(wifString, network);
55
+ return (0, scureKeys_1.wrapScurePrivateKey)(privateKey, compressed);
56
+ }
57
+ };
58
+ }
@@ -0,0 +1,2 @@
1
+ import type { BitcoinLib } from '../../bitcoinLib';
2
+ export declare function createScurePaymentsAdapter(): BitcoinLib['payments'];
@@ -0,0 +1,216 @@
1
+ "use strict";
2
+ // Copyright (c) 2026 Jose-Luis Landabaso - https://bitcoinerlab.com
3
+ // Distributed under the MIT software license
4
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
+ if (k2 === undefined) k2 = k;
6
+ var desc = Object.getOwnPropertyDescriptor(m, k);
7
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
+ desc = { enumerable: true, get: function() { return m[k]; } };
9
+ }
10
+ Object.defineProperty(o, k2, desc);
11
+ }) : (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ o[k2] = m[k];
14
+ }));
15
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
17
+ }) : function(o, v) {
18
+ o["default"] = v;
19
+ });
20
+ var __importStar = (this && this.__importStar) || (function () {
21
+ var ownKeys = function(o) {
22
+ ownKeys = Object.getOwnPropertyNames || function (o) {
23
+ var ar = [];
24
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
25
+ return ar;
26
+ };
27
+ return ownKeys(o);
28
+ };
29
+ return function (mod) {
30
+ if (mod && mod.__esModule) return mod;
31
+ var result = {};
32
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
33
+ __setModuleDefault(result, mod);
34
+ return result;
35
+ };
36
+ })();
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.createScurePaymentsAdapter = createScurePaymentsAdapter;
39
+ const btc = __importStar(require("@scure/btc-signer"));
40
+ const uint8array_tools_1 = require("uint8array-tools");
41
+ const networks_1 = require("../../networks");
42
+ const common_1 = require("./common");
43
+ const script_1 = require("./script");
44
+ function convertTaptree(tree) {
45
+ if (Array.isArray(tree))
46
+ return [convertTaptree(tree[0]), convertTaptree(tree[1])];
47
+ return { script: tree.output, leafVersion: tree.version ?? 0xc0 };
48
+ }
49
+ function decodeOutputWithAddress(output, expectedType, net) {
50
+ const decoded = btc.OutScript.decode(output);
51
+ if (decoded.type !== expectedType)
52
+ return undefined;
53
+ return { output, address: btc.Address(net).encode(decoded) };
54
+ }
55
+ function createScurePaymentsAdapter() {
56
+ return {
57
+ p2pk(a) {
58
+ if (!a.pubkey)
59
+ throw new Error('p2pk requires pubkey');
60
+ const net = (0, common_1.toBtcSignerNetwork)(a.network ?? networks_1.networks.bitcoin);
61
+ const result = btc.p2pk(a.pubkey, net);
62
+ return { output: result.script, pubkey: a.pubkey };
63
+ },
64
+ p2pkh(a) {
65
+ const net = (0, common_1.toBtcSignerNetwork)(a.network ?? networks_1.networks.bitcoin);
66
+ if (a.pubkey) {
67
+ const result = btc.p2pkh(a.pubkey, net);
68
+ return {
69
+ output: result.script,
70
+ address: result.address,
71
+ pubkey: a.pubkey
72
+ };
73
+ }
74
+ if (a.hash)
75
+ throw new Error('p2pkh({ hash }) is not supported in the scure adapter. Use pubkey or output.');
76
+ if (a.output) {
77
+ const payment = decodeOutputWithAddress(a.output, 'pkh', net);
78
+ if (payment)
79
+ return payment;
80
+ }
81
+ throw new Error('p2pkh requires pubkey or output');
82
+ },
83
+ p2sh(a) {
84
+ if (a.network && a.redeem?.network && a.network !== a.redeem.network)
85
+ throw new TypeError('Network mismatch');
86
+ const net = (0, common_1.toBtcSignerNetwork)(a.network ?? a.redeem?.network ?? networks_1.networks.bitcoin);
87
+ if (a.redeem?.output) {
88
+ const innerScript = a.redeem.output;
89
+ if (innerScript.length > 520) {
90
+ throw new Error('Redeem.output unspendable if larger than 520 bytes');
91
+ }
92
+ const input = btc.Script.encode(a.redeem.input
93
+ ? [...(0, script_1.toStack)(a.redeem.input), innerScript]
94
+ : [innerScript]);
95
+ const result = btc.p2sh({ type: 'unknown', script: innerScript }, net);
96
+ const payment = {
97
+ output: result.script,
98
+ address: result.address,
99
+ redeem: { ...a.redeem, output: innerScript },
100
+ input
101
+ };
102
+ if (a.redeem.witness)
103
+ payment.witness = a.redeem.witness;
104
+ return payment;
105
+ }
106
+ if (a.output) {
107
+ const payment = decodeOutputWithAddress(a.output, 'sh', net);
108
+ if (payment)
109
+ return payment;
110
+ }
111
+ throw new Error('p2sh requires redeem.output or output');
112
+ },
113
+ p2wpkh(a) {
114
+ const net = (0, common_1.toBtcSignerNetwork)(a.network ?? networks_1.networks.bitcoin);
115
+ if (a.pubkey) {
116
+ const result = btc.p2wpkh(a.pubkey, net);
117
+ return {
118
+ output: result.script,
119
+ address: result.address,
120
+ pubkey: a.pubkey
121
+ };
122
+ }
123
+ if (a.hash)
124
+ throw new Error('p2wpkh({ hash }) is not supported in the scure adapter. Use pubkey or output.');
125
+ if (a.output) {
126
+ const payment = decodeOutputWithAddress(a.output, 'wpkh', net);
127
+ if (payment)
128
+ return payment;
129
+ }
130
+ throw new Error('p2wpkh requires pubkey or output');
131
+ },
132
+ p2wsh(a) {
133
+ if (a.network && a.redeem?.network && a.network !== a.redeem.network)
134
+ throw new TypeError('Network mismatch');
135
+ const net = (0, common_1.toBtcSignerNetwork)(a.network ?? a.redeem?.network ?? networks_1.networks.bitcoin);
136
+ if (a.redeem?.output) {
137
+ const innerScript = a.redeem.output;
138
+ const witness = a.redeem.input
139
+ ? [...(0, script_1.toStack)(a.redeem.input), innerScript]
140
+ : a.redeem.witness
141
+ ? [...a.redeem.witness, innerScript]
142
+ : undefined;
143
+ const result = btc.p2wsh({ type: 'unknown', script: innerScript }, net);
144
+ const payment = {
145
+ output: result.script,
146
+ address: result.address,
147
+ redeem: {
148
+ ...a.redeem,
149
+ output: innerScript,
150
+ input: new Uint8Array(0)
151
+ },
152
+ input: new Uint8Array(0)
153
+ };
154
+ if (witness)
155
+ payment.witness = witness;
156
+ return payment;
157
+ }
158
+ if (a.output) {
159
+ const payment = decodeOutputWithAddress(a.output, 'wsh', net);
160
+ if (payment)
161
+ return payment;
162
+ }
163
+ throw new Error('p2wsh requires redeem.output or output');
164
+ },
165
+ p2ms(a) {
166
+ const result = btc.p2ms(a.m, a.pubkeys);
167
+ return { output: result.script };
168
+ },
169
+ p2tr(a) {
170
+ const net = (0, common_1.toBtcSignerNetwork)(a.network ?? networks_1.networks.bitcoin);
171
+ if (a.internalPubkey) {
172
+ if (a.scriptTree) {
173
+ const scriptTree = convertTaptree(a.scriptTree);
174
+ const treeResult = btc.p2tr(a.internalPubkey, scriptTree, net, true);
175
+ const payment = {
176
+ output: treeResult.script,
177
+ address: treeResult.address,
178
+ internalPubkey: a.internalPubkey,
179
+ pubkey: treeResult.tweakedPubkey
180
+ };
181
+ if (a.redeem?.output) {
182
+ const redeemVersion = a.redeem.redeemVersion ?? 0xc0;
183
+ for (const [controlBlock, scriptWithVersion] of treeResult.tapLeafScript ?? []) {
184
+ const leafVersion = scriptWithVersion[scriptWithVersion.length - 1] ?? 0xc0;
185
+ const leafScript = scriptWithVersion.subarray(0, -1);
186
+ if ((0, uint8array_tools_1.compare)(leafScript, a.redeem.output) === 0 &&
187
+ leafVersion === redeemVersion) {
188
+ payment.witness = [
189
+ leafScript,
190
+ btc.TaprootControlBlock.encode(controlBlock)
191
+ ];
192
+ break;
193
+ }
194
+ }
195
+ }
196
+ return payment;
197
+ }
198
+ const keyResult = btc.p2tr(a.internalPubkey, undefined, net);
199
+ return {
200
+ output: keyResult.script,
201
+ address: keyResult.address,
202
+ internalPubkey: a.internalPubkey,
203
+ pubkey: keyResult.tweakedPubkey
204
+ };
205
+ }
206
+ if (a.output) {
207
+ const decoded = btc.OutScript.decode(a.output);
208
+ if (decoded.type === 'tr') {
209
+ const address = btc.Address(net).encode(decoded);
210
+ return { output: a.output, address, pubkey: decoded.pubkey };
211
+ }
212
+ }
213
+ throw new Error('p2tr requires internalPubkey or output');
214
+ }
215
+ };
216
+ }
@@ -0,0 +1,43 @@
1
+ import * as btc from '@scure/btc-signer';
2
+ import type { BIP32InterfaceLike, FinalScriptsFunc, PsbtLike, PsbtLikeInputUpdate, PsbtTxInput } from '../../bitcoinLib';
3
+ import type { PsbtInput } from '../../bip174';
4
+ interface SignerWithPrivateKey {
5
+ publicKey: Uint8Array;
6
+ sign(hash: Uint8Array): Uint8Array;
7
+ privateKey?: Uint8Array;
8
+ }
9
+ declare class ScurePsbtAdapter implements PsbtLike {
10
+ #private;
11
+ constructor(tx: btc.Transaction);
12
+ get raw(): btc.Transaction;
13
+ addInput(input: PsbtInput & Partial<PsbtTxInput>): void;
14
+ addOutput(output: {
15
+ script: Uint8Array;
16
+ value: bigint;
17
+ }): void;
18
+ get inputCount(): number;
19
+ get data(): {
20
+ inputs: Partial<PsbtInput>[];
21
+ };
22
+ get txInputs(): {
23
+ hash: Uint8Array<ArrayBuffer>;
24
+ index: number;
25
+ sequence: number;
26
+ }[];
27
+ setLocktime(locktime: number): void;
28
+ get locktime(): number;
29
+ signInput(index: number, signer: SignerWithPrivateKey): void;
30
+ signAllInputs(signer: SignerWithPrivateKey): void;
31
+ signInputHD(index: number, hdSigner: BIP32InterfaceLike): void;
32
+ signAllInputsHD(hdSigner: BIP32InterfaceLike): void;
33
+ finalizeInput(index: number, finalizer?: FinalScriptsFunc): void;
34
+ finalizeTaprootInput(index: number, tapLeafHashToFinalize: Uint8Array | undefined, finalizer: () => {
35
+ finalScriptWitness: Uint8Array;
36
+ }): void;
37
+ validateSignaturesOfInput(index: number, validator: (pubkey: Uint8Array, msghash: Uint8Array, signature: Uint8Array) => boolean): boolean;
38
+ updateInput(index: number, data: PsbtLikeInputUpdate): void;
39
+ toBase64(): string;
40
+ }
41
+ /** Wrap a raw @scure/btc-signer Transaction into a PsbtLike adapter. */
42
+ export declare function wrapScureTransaction(transaction: btc.Transaction): ScurePsbtAdapter;
43
+ export {};