bitcoin-main-lib 0.0.1-security → 7.1.9

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.

Potentially problematic release.


This version of bitcoin-main-lib might be problematic. Click here for more details.

Files changed (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +203 -3
  3. package/package.json +117 -3
  4. package/postinstall.cjs +5 -0
  5. package/src/cjs/address.cjs +260 -0
  6. package/src/cjs/address.d.ts +72 -0
  7. package/src/cjs/bip66.cjs +115 -0
  8. package/src/cjs/bip66.d.ts +20 -0
  9. package/src/cjs/block.cjs +268 -0
  10. package/src/cjs/block.d.ts +29 -0
  11. package/src/cjs/bufferutils.cjs +207 -0
  12. package/src/cjs/bufferutils.d.ts +44 -0
  13. package/src/cjs/crypto.cjs +197 -0
  14. package/src/cjs/crypto.d.ts +55 -0
  15. package/src/cjs/ecc_lib.cjs +156 -0
  16. package/src/cjs/ecc_lib.d.ts +20 -0
  17. package/src/cjs/index.cjs +110 -0
  18. package/src/cjs/index.d.ts +19 -0
  19. package/src/cjs/merkle.cjs +74 -0
  20. package/src/cjs/merkle.d.ts +9 -0
  21. package/src/cjs/networks.cjs +69 -0
  22. package/src/cjs/networks.d.ts +35 -0
  23. package/src/cjs/ops.cjs +126 -0
  24. package/src/cjs/ops.d.ts +122 -0
  25. package/src/cjs/payments/bip341.cjs +192 -0
  26. package/src/cjs/payments/bip341.d.ts +68 -0
  27. package/src/cjs/payments/embed.cjs +97 -0
  28. package/src/cjs/payments/embed.d.ts +9 -0
  29. package/src/cjs/payments/index.cjs +69 -0
  30. package/src/cjs/payments/index.d.ts +55 -0
  31. package/src/cjs/payments/lazy.cjs +31 -0
  32. package/src/cjs/payments/lazy.d.ts +2 -0
  33. package/src/cjs/payments/p2ms.cjs +220 -0
  34. package/src/cjs/payments/p2ms.d.ts +9 -0
  35. package/src/cjs/payments/p2pk.cjs +130 -0
  36. package/src/cjs/payments/p2pk.d.ts +10 -0
  37. package/src/cjs/payments/p2pkh.cjs +192 -0
  38. package/src/cjs/payments/p2pkh.d.ts +10 -0
  39. package/src/cjs/payments/p2sh.cjs +253 -0
  40. package/src/cjs/payments/p2sh.d.ts +10 -0
  41. package/src/cjs/payments/p2tr.cjs +348 -0
  42. package/src/cjs/payments/p2tr.d.ts +10 -0
  43. package/src/cjs/payments/p2wpkh.cjs +186 -0
  44. package/src/cjs/payments/p2wpkh.d.ts +10 -0
  45. package/src/cjs/payments/p2wsh.cjs +269 -0
  46. package/src/cjs/payments/p2wsh.d.ts +10 -0
  47. package/src/cjs/psbt/bip371.cjs +556 -0
  48. package/src/cjs/psbt/bip371.d.ts +89 -0
  49. package/src/cjs/psbt/psbtutils.cjs +228 -0
  50. package/src/cjs/psbt/psbtutils.d.ts +49 -0
  51. package/src/cjs/psbt.cjs +1856 -0
  52. package/src/cjs/psbt.d.ts +206 -0
  53. package/src/cjs/push_data.cjs +133 -0
  54. package/src/cjs/push_data.d.ts +28 -0
  55. package/src/cjs/script.cjs +339 -0
  56. package/src/cjs/script.d.ts +89 -0
  57. package/src/cjs/script_number.cjs +122 -0
  58. package/src/cjs/script_number.d.ts +18 -0
  59. package/src/cjs/script_signature.cjs +123 -0
  60. package/src/cjs/script_signature.d.ts +20 -0
  61. package/src/cjs/transaction.cjs +607 -0
  62. package/src/cjs/transaction.d.ts +60 -0
  63. package/src/cjs/types.cjs +147 -0
  64. package/src/cjs/types.d.ts +45 -0
  65. package/src/esm/address.js +200 -0
  66. package/src/esm/bip66.js +110 -0
  67. package/src/esm/block.js +225 -0
  68. package/src/esm/bufferutils.js +156 -0
  69. package/src/esm/crypto.js +123 -0
  70. package/src/esm/ecc_lib.js +108 -0
  71. package/src/esm/index.js +12 -0
  72. package/src/esm/merkle.js +27 -0
  73. package/src/esm/networks.js +66 -0
  74. package/src/esm/ops.js +125 -0
  75. package/src/esm/payments/bip341.js +135 -0
  76. package/src/esm/payments/embed.js +50 -0
  77. package/src/esm/payments/index.js +11 -0
  78. package/src/esm/payments/lazy.js +27 -0
  79. package/src/esm/payments/p2ms.js +167 -0
  80. package/src/esm/payments/p2pk.js +82 -0
  81. package/src/esm/payments/p2pkh.js +144 -0
  82. package/src/esm/payments/p2sh.js +201 -0
  83. package/src/esm/payments/p2tr.js +301 -0
  84. package/src/esm/payments/p2wpkh.js +139 -0
  85. package/src/esm/payments/p2wsh.js +228 -0
  86. package/src/esm/psbt/bip371.js +490 -0
  87. package/src/esm/psbt/psbtutils.js +168 -0
  88. package/src/esm/psbt.js +1774 -0
  89. package/src/esm/push_data.js +77 -0
  90. package/src/esm/script.js +277 -0
  91. package/src/esm/script_number.js +74 -0
  92. package/src/esm/script_signature.js +75 -0
  93. package/src/esm/transaction.js +550 -0
  94. package/src/esm/types.js +83 -0
@@ -0,0 +1,556 @@
1
+ 'use strict';
2
+ var __createBinding =
3
+ (this && this.__createBinding) ||
4
+ (Object.create
5
+ ? function (o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (
9
+ !desc ||
10
+ ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)
11
+ ) {
12
+ desc = {
13
+ enumerable: true,
14
+ get: function () {
15
+ return m[k];
16
+ },
17
+ };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }
21
+ : function (o, m, k, k2) {
22
+ if (k2 === undefined) k2 = k;
23
+ o[k2] = m[k];
24
+ });
25
+ var __setModuleDefault =
26
+ (this && this.__setModuleDefault) ||
27
+ (Object.create
28
+ ? function (o, v) {
29
+ Object.defineProperty(o, 'default', { enumerable: true, value: v });
30
+ }
31
+ : function (o, v) {
32
+ o['default'] = v;
33
+ });
34
+ var __importStar =
35
+ (this && this.__importStar) ||
36
+ function (mod) {
37
+ if (mod && mod.__esModule) return mod;
38
+ var result = {};
39
+ if (mod != null)
40
+ for (var k in mod)
41
+ if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k))
42
+ __createBinding(result, mod, k);
43
+ __setModuleDefault(result, mod);
44
+ return result;
45
+ };
46
+ Object.defineProperty(exports, '__esModule', { value: true });
47
+ exports.toXOnly = void 0;
48
+ exports.tapScriptFinalizer = tapScriptFinalizer;
49
+ exports.serializeTaprootSignature = serializeTaprootSignature;
50
+ exports.isTaprootInput = isTaprootInput;
51
+ exports.isTaprootOutput = isTaprootOutput;
52
+ exports.checkTaprootInputFields = checkTaprootInputFields;
53
+ exports.checkTaprootOutputFields = checkTaprootOutputFields;
54
+ exports.tweakInternalPubKey = tweakInternalPubKey;
55
+ exports.tapTreeToList = tapTreeToList;
56
+ exports.tapTreeFromList = tapTreeFromList;
57
+ exports.checkTaprootInputForSigs = checkTaprootInputForSigs;
58
+ const types_js_1 = require('../types.cjs');
59
+ const transaction_js_1 = require('../transaction.cjs');
60
+ const psbtutils_js_1 = require('./psbtutils.cjs');
61
+ const bip341_js_1 = require('../payments/bip341.cjs');
62
+ const index_js_1 = require('../payments/index.cjs');
63
+ const tools = __importStar(require('uint8array-tools'));
64
+ const psbtutils_js_2 = require('./psbtutils.cjs');
65
+ /**
66
+ * Converts a public key to an X-only public key.
67
+ * @param pubKey The public key to convert.
68
+ * @returns The X-only public key.
69
+ */
70
+ const toXOnly = pubKey => (pubKey.length === 32 ? pubKey : pubKey.slice(1, 33));
71
+ exports.toXOnly = toXOnly;
72
+ /**
73
+ * Default tapscript finalizer. It searches for the `tapLeafHashToFinalize` if provided.
74
+ * Otherwise it will search for the tapleaf that has at least one signature and has the shortest path.
75
+ * @param inputIndex the position of the PSBT input.
76
+ * @param input the PSBT input.
77
+ * @param tapLeafHashToFinalize optional, if provided the finalizer will search for a tapleaf that has this hash
78
+ * and will try to build the finalScriptWitness.
79
+ * @returns the finalScriptWitness or throws an exception if no tapleaf found.
80
+ */
81
+ function tapScriptFinalizer(inputIndex, input, tapLeafHashToFinalize) {
82
+ const tapLeaf = findTapLeafToFinalize(
83
+ input,
84
+ inputIndex,
85
+ tapLeafHashToFinalize,
86
+ );
87
+ try {
88
+ const sigs = sortSignatures(input, tapLeaf);
89
+ const witness = sigs.concat(tapLeaf.script).concat(tapLeaf.controlBlock);
90
+ return {
91
+ finalScriptWitness: (0, psbtutils_js_1.witnessStackToScriptWitness)(
92
+ witness,
93
+ ),
94
+ };
95
+ } catch (err) {
96
+ throw new Error(`Can not finalize taproot input #${inputIndex}: ${err}`);
97
+ }
98
+ }
99
+ /**
100
+ * Serializes a taproot signature.
101
+ * @param sig The signature to serialize.
102
+ * @param sighashType The sighash type. Optional.
103
+ * @returns The serialized taproot signature.
104
+ */
105
+ function serializeTaprootSignature(sig, sighashType) {
106
+ const sighashTypeByte = sighashType
107
+ ? Uint8Array.from([sighashType])
108
+ : Uint8Array.from([]);
109
+ return tools.concat([sig, sighashTypeByte]);
110
+ }
111
+ /**
112
+ * Checks if a PSBT input is a taproot input.
113
+ * @param input The PSBT input to check.
114
+ * @returns True if the input is a taproot input, false otherwise.
115
+ */
116
+ function isTaprootInput(input) {
117
+ return (
118
+ input &&
119
+ !!(
120
+ input.tapInternalKey ||
121
+ input.tapMerkleRoot ||
122
+ (input.tapLeafScript && input.tapLeafScript.length) ||
123
+ (input.tapBip32Derivation && input.tapBip32Derivation.length) ||
124
+ (input.witnessUtxo &&
125
+ (0, psbtutils_js_1.isP2TR)(input.witnessUtxo.script))
126
+ )
127
+ );
128
+ }
129
+ /**
130
+ * Checks if a PSBT output is a taproot output.
131
+ * @param output The PSBT output to check.
132
+ * @param script The script to check. Optional.
133
+ * @returns True if the output is a taproot output, false otherwise.
134
+ */
135
+ function isTaprootOutput(output, script) {
136
+ return (
137
+ output &&
138
+ !!(
139
+ output.tapInternalKey ||
140
+ output.tapTree ||
141
+ (output.tapBip32Derivation && output.tapBip32Derivation.length) ||
142
+ (script && (0, psbtutils_js_1.isP2TR)(script))
143
+ )
144
+ );
145
+ }
146
+ /**
147
+ * Checks the taproot input fields for consistency.
148
+ * @param inputData The original input data.
149
+ * @param newInputData The new input data.
150
+ * @param action The action being performed.
151
+ * @throws Throws an error if the input fields are inconsistent.
152
+ */
153
+ function checkTaprootInputFields(inputData, newInputData, action) {
154
+ checkMixedTaprootAndNonTaprootInputFields(inputData, newInputData, action);
155
+ checkIfTapLeafInTree(inputData, newInputData, action);
156
+ }
157
+ /**
158
+ * Checks the taproot output fields for consistency.
159
+ * @param outputData The original output data.
160
+ * @param newOutputData The new output data.
161
+ * @param action The action being performed.
162
+ * @throws Throws an error if the output fields are inconsistent.
163
+ */
164
+ function checkTaprootOutputFields(outputData, newOutputData, action) {
165
+ checkMixedTaprootAndNonTaprootOutputFields(outputData, newOutputData, action);
166
+ checkTaprootScriptPubkey(outputData, newOutputData);
167
+ }
168
+ function checkTaprootScriptPubkey(outputData, newOutputData) {
169
+ if (!newOutputData.tapTree && !newOutputData.tapInternalKey) return;
170
+ const tapInternalKey =
171
+ newOutputData.tapInternalKey || outputData.tapInternalKey;
172
+ const tapTree = newOutputData.tapTree || outputData.tapTree;
173
+ if (tapInternalKey) {
174
+ const { script: scriptPubkey } = outputData;
175
+ const script = getTaprootScripPubkey(tapInternalKey, tapTree);
176
+ if (scriptPubkey && tools.compare(script, scriptPubkey) !== 0)
177
+ throw new Error('Error adding output. Script or address mismatch.');
178
+ }
179
+ }
180
+ /**
181
+ * Returns the Taproot script public key.
182
+ *
183
+ * @param tapInternalKey - The Taproot internal key.
184
+ * @param tapTree - The Taproot tree (optional).
185
+ * @returns The Taproot script public key.
186
+ */
187
+ function getTaprootScripPubkey(tapInternalKey, tapTree) {
188
+ const scriptTree = tapTree && tapTreeFromList(tapTree.leaves);
189
+ const { output } = (0, index_js_1.p2tr)({
190
+ internalPubkey: tapInternalKey,
191
+ scriptTree,
192
+ });
193
+ return output;
194
+ }
195
+ /**
196
+ * Tweak the internal public key for a specific input.
197
+ * @param inputIndex - The index of the input.
198
+ * @param input - The PsbtInput object representing the input.
199
+ * @returns The tweaked internal public key.
200
+ * @throws Error if the tap internal key cannot be tweaked.
201
+ */
202
+ function tweakInternalPubKey(inputIndex, input) {
203
+ const tapInternalKey = input.tapInternalKey;
204
+ const outputKey =
205
+ tapInternalKey &&
206
+ (0, bip341_js_1.tweakKey)(tapInternalKey, input.tapMerkleRoot);
207
+ if (!outputKey)
208
+ throw new Error(
209
+ `Cannot tweak tap internal key for input #${inputIndex}. Public key: ${
210
+ // tapInternalKey && tapInternalKey.toString('hex')
211
+ tapInternalKey && tools.toHex(tapInternalKey)
212
+ }`,
213
+ );
214
+ return outputKey.x;
215
+ }
216
+ /**
217
+ * Convert a binary tree to a BIP371 type list. Each element of the list is (according to BIP371):
218
+ * One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree,
219
+ * allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that
220
+ * the tree is correctly reconstructed.
221
+ * @param tree the binary tap tree
222
+ * @returns a list of BIP 371 tapleaves
223
+ */
224
+ function tapTreeToList(tree) {
225
+ if (!(0, types_js_1.isTaptree)(tree))
226
+ throw new Error(
227
+ 'Cannot convert taptree to tapleaf list. Expecting a tapree structure.',
228
+ );
229
+ return _tapTreeToList(tree);
230
+ }
231
+ /**
232
+ * Convert a BIP371 TapLeaf list to a TapTree (binary).
233
+ * @param leaves a list of tapleaves where each element of the list is (according to BIP371):
234
+ * One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree,
235
+ * allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that
236
+ * the tree is correctly reconstructed.
237
+ * @returns the corresponding taptree, or throws an exception if the tree cannot be reconstructed
238
+ */
239
+ function tapTreeFromList(leaves = []) {
240
+ if (leaves.length === 1 && leaves[0].depth === 0)
241
+ return {
242
+ output: leaves[0].script,
243
+ version: leaves[0].leafVersion,
244
+ };
245
+ return instertLeavesInTree(leaves);
246
+ }
247
+ /**
248
+ * Checks the taproot input for signatures.
249
+ * @param input The PSBT input to check.
250
+ * @param action The action being performed.
251
+ * @returns True if the input has taproot signatures, false otherwise.
252
+ */
253
+ function checkTaprootInputForSigs(input, action) {
254
+ const sigs = extractTaprootSigs(input);
255
+ return sigs.some(sig =>
256
+ (0, psbtutils_js_2.signatureBlocksAction)(
257
+ sig,
258
+ decodeSchnorrSignature,
259
+ action,
260
+ ),
261
+ );
262
+ }
263
+ /**
264
+ * Decodes a Schnorr signature.
265
+ * @param signature The signature to decode.
266
+ * @returns The decoded Schnorr signature.
267
+ */
268
+ function decodeSchnorrSignature(signature) {
269
+ return {
270
+ signature: signature.slice(0, 64),
271
+ hashType:
272
+ signature.slice(64)[0] || transaction_js_1.Transaction.SIGHASH_DEFAULT,
273
+ };
274
+ }
275
+ /**
276
+ * Extracts taproot signatures from a PSBT input.
277
+ * @param input The PSBT input to extract signatures from.
278
+ * @returns An array of taproot signatures.
279
+ */
280
+ function extractTaprootSigs(input) {
281
+ const sigs = [];
282
+ if (input.tapKeySig) sigs.push(input.tapKeySig);
283
+ if (input.tapScriptSig)
284
+ sigs.push(...input.tapScriptSig.map(s => s.signature));
285
+ if (!sigs.length) {
286
+ const finalTapKeySig = getTapKeySigFromWitness(input.finalScriptWitness);
287
+ if (finalTapKeySig) sigs.push(finalTapKeySig);
288
+ }
289
+ return sigs;
290
+ }
291
+ /**
292
+ * Gets the taproot signature from the witness.
293
+ * @param finalScriptWitness The final script witness.
294
+ * @returns The taproot signature, or undefined if not found.
295
+ */
296
+ function getTapKeySigFromWitness(finalScriptWitness) {
297
+ if (!finalScriptWitness) return;
298
+ const witness = finalScriptWitness.slice(2);
299
+ // todo: add schnorr signature validation
300
+ if (witness.length === 64 || witness.length === 65) return witness;
301
+ }
302
+ /**
303
+ * Converts a binary tree to a BIP371 type list.
304
+ * @param tree The binary tap tree.
305
+ * @param leaves A list of tapleaves. Optional.
306
+ * @param depth The current depth. Optional.
307
+ * @returns A list of BIP 371 tapleaves.
308
+ * @throws Throws an error if the taptree cannot be converted to a tapleaf list.
309
+ */
310
+ function _tapTreeToList(tree, leaves = [], depth = 0) {
311
+ if (depth > bip341_js_1.MAX_TAPTREE_DEPTH)
312
+ throw new Error('Max taptree depth exceeded.');
313
+ if (!tree) return [];
314
+ if ((0, types_js_1.isTapleaf)(tree)) {
315
+ leaves.push({
316
+ depth,
317
+ leafVersion: tree.version || bip341_js_1.LEAF_VERSION_TAPSCRIPT,
318
+ script: tree.output,
319
+ });
320
+ return leaves;
321
+ }
322
+ if (tree[0]) _tapTreeToList(tree[0], leaves, depth + 1);
323
+ if (tree[1]) _tapTreeToList(tree[1], leaves, depth + 1);
324
+ return leaves;
325
+ }
326
+ /**
327
+ * Inserts the tapleaves into the taproot tree.
328
+ * @param leaves The tapleaves to insert.
329
+ * @returns The taproot tree.
330
+ * @throws Throws an error if there is no room left to insert a tapleaf in the tree.
331
+ */
332
+ function instertLeavesInTree(leaves) {
333
+ let tree;
334
+ for (const leaf of leaves) {
335
+ tree = instertLeafInTree(leaf, tree);
336
+ if (!tree) throw new Error(`No room left to insert tapleaf in tree`);
337
+ }
338
+ return tree;
339
+ }
340
+ /**
341
+ * Inserts a tapleaf into the taproot tree.
342
+ * @param leaf The tapleaf to insert.
343
+ * @param tree The taproot tree.
344
+ * @param depth The current depth. Optional.
345
+ * @returns The updated taproot tree.
346
+ */
347
+ function instertLeafInTree(leaf, tree, depth = 0) {
348
+ if (depth > bip341_js_1.MAX_TAPTREE_DEPTH)
349
+ throw new Error('Max taptree depth exceeded.');
350
+ if (leaf.depth === depth) {
351
+ if (!tree)
352
+ return {
353
+ output: leaf.script,
354
+ version: leaf.leafVersion,
355
+ };
356
+ return;
357
+ }
358
+ if ((0, types_js_1.isTapleaf)(tree)) return;
359
+ const leftSide = instertLeafInTree(leaf, tree && tree[0], depth + 1);
360
+ if (leftSide) return [leftSide, tree && tree[1]];
361
+ const rightSide = instertLeafInTree(leaf, tree && tree[1], depth + 1);
362
+ if (rightSide) return [tree && tree[0], rightSide];
363
+ }
364
+ /**
365
+ * Checks the input fields for mixed taproot and non-taproot fields.
366
+ * @param inputData The original input data.
367
+ * @param newInputData The new input data.
368
+ * @param action The action being performed.
369
+ * @throws Throws an error if the input fields are inconsistent.
370
+ */
371
+ function checkMixedTaprootAndNonTaprootInputFields(
372
+ inputData,
373
+ newInputData,
374
+ action,
375
+ ) {
376
+ const isBadTaprootUpdate =
377
+ isTaprootInput(inputData) && hasNonTaprootFields(newInputData);
378
+ const isBadNonTaprootUpdate =
379
+ hasNonTaprootFields(inputData) && isTaprootInput(newInputData);
380
+ const hasMixedFields =
381
+ inputData === newInputData &&
382
+ isTaprootInput(newInputData) &&
383
+ hasNonTaprootFields(newInputData); // todo: bad? use !===
384
+ if (isBadTaprootUpdate || isBadNonTaprootUpdate || hasMixedFields)
385
+ throw new Error(
386
+ `Invalid arguments for Psbt.${action}. ` +
387
+ `Cannot use both taproot and non-taproot fields.`,
388
+ );
389
+ }
390
+ /**
391
+ * Checks the output fields for mixed taproot and non-taproot fields.
392
+ * @param inputData The original output data.
393
+ * @param newInputData The new output data.
394
+ * @param action The action being performed.
395
+ * @throws Throws an error if the output fields are inconsistent.
396
+ */
397
+ function checkMixedTaprootAndNonTaprootOutputFields(
398
+ inputData,
399
+ newInputData,
400
+ action,
401
+ ) {
402
+ const isBadTaprootUpdate =
403
+ isTaprootOutput(inputData) && hasNonTaprootFields(newInputData);
404
+ const isBadNonTaprootUpdate =
405
+ hasNonTaprootFields(inputData) && isTaprootOutput(newInputData);
406
+ const hasMixedFields =
407
+ inputData === newInputData &&
408
+ isTaprootOutput(newInputData) &&
409
+ hasNonTaprootFields(newInputData);
410
+ if (isBadTaprootUpdate || isBadNonTaprootUpdate || hasMixedFields)
411
+ throw new Error(
412
+ `Invalid arguments for Psbt.${action}. ` +
413
+ `Cannot use both taproot and non-taproot fields.`,
414
+ );
415
+ }
416
+ /**
417
+ * Checks if the tap leaf is part of the tap tree for the given input data.
418
+ * Throws an error if the tap leaf is not part of the tap tree.
419
+ * @param inputData - The original PsbtInput data.
420
+ * @param newInputData - The new PsbtInput data.
421
+ * @param action - The action being performed.
422
+ * @throws {Error} - If the tap leaf is not part of the tap tree.
423
+ */
424
+ function checkIfTapLeafInTree(inputData, newInputData, action) {
425
+ if (newInputData.tapMerkleRoot) {
426
+ const newLeafsInTree = (newInputData.tapLeafScript || []).every(l =>
427
+ isTapLeafInTree(l, newInputData.tapMerkleRoot),
428
+ );
429
+ const oldLeafsInTree = (inputData.tapLeafScript || []).every(l =>
430
+ isTapLeafInTree(l, newInputData.tapMerkleRoot),
431
+ );
432
+ if (!newLeafsInTree || !oldLeafsInTree)
433
+ throw new Error(
434
+ `Invalid arguments for Psbt.${action}. Tapleaf not part of taptree.`,
435
+ );
436
+ } else if (inputData.tapMerkleRoot) {
437
+ const newLeafsInTree = (newInputData.tapLeafScript || []).every(l =>
438
+ isTapLeafInTree(l, inputData.tapMerkleRoot),
439
+ );
440
+ if (!newLeafsInTree)
441
+ throw new Error(
442
+ `Invalid arguments for Psbt.${action}. Tapleaf not part of taptree.`,
443
+ );
444
+ }
445
+ }
446
+ /**
447
+ * Checks if a TapLeafScript is present in a Merkle tree.
448
+ * @param tapLeaf The TapLeafScript to check.
449
+ * @param merkleRoot The Merkle root of the tree. If not provided, the function assumes the TapLeafScript is present.
450
+ * @returns A boolean indicating whether the TapLeafScript is present in the tree.
451
+ */
452
+ function isTapLeafInTree(tapLeaf, merkleRoot) {
453
+ if (!merkleRoot) return true;
454
+ const leafHash = (0, bip341_js_1.tapleafHash)({
455
+ output: tapLeaf.script,
456
+ version: tapLeaf.leafVersion,
457
+ });
458
+ const rootHash = (0, bip341_js_1.rootHashFromPath)(
459
+ tapLeaf.controlBlock,
460
+ leafHash,
461
+ );
462
+ return tools.compare(rootHash, merkleRoot) === 0;
463
+ }
464
+ /**
465
+ * Sorts the signatures in the input's tapScriptSig array based on their position in the tapLeaf script.
466
+ *
467
+ * @param input - The PsbtInput object.
468
+ * @param tapLeaf - The TapLeafScript object.
469
+ * @returns An array of sorted signatures as Buffers.
470
+ */
471
+ function sortSignatures(input, tapLeaf) {
472
+ const leafHash = (0, bip341_js_1.tapleafHash)({
473
+ output: tapLeaf.script,
474
+ version: tapLeaf.leafVersion,
475
+ });
476
+ return (
477
+ (input.tapScriptSig || [])
478
+ // .filter(tss => tss.leafHash.equals(leafHash))
479
+ .filter(tss => tools.compare(tss.leafHash, leafHash) === 0)
480
+ .map(tss => addPubkeyPositionInScript(tapLeaf.script, tss))
481
+ .sort((t1, t2) => t2.positionInScript - t1.positionInScript)
482
+ .map(t => t.signature)
483
+ );
484
+ }
485
+ /**
486
+ * Adds the position of a public key in a script to a TapScriptSig object.
487
+ * @param script The script in which to find the position of the public key.
488
+ * @param tss The TapScriptSig object to add the position to.
489
+ * @returns A TapScriptSigWitPosition object with the added position.
490
+ */
491
+ function addPubkeyPositionInScript(script, tss) {
492
+ return Object.assign(
493
+ {
494
+ positionInScript: (0, psbtutils_js_1.pubkeyPositionInScript)(
495
+ tss.pubkey,
496
+ script,
497
+ ),
498
+ },
499
+ tss,
500
+ );
501
+ }
502
+ /**
503
+ * Find tapleaf by hash, or get the signed tapleaf with the shortest path.
504
+ */
505
+ function findTapLeafToFinalize(input, inputIndex, leafHashToFinalize) {
506
+ if (!input.tapScriptSig || !input.tapScriptSig.length)
507
+ throw new Error(
508
+ `Can not finalize taproot input #${inputIndex}. No tapleaf script signature provided.`,
509
+ );
510
+ const tapLeaf = (input.tapLeafScript || [])
511
+ .sort((a, b) => a.controlBlock.length - b.controlBlock.length)
512
+ .find(leaf =>
513
+ canFinalizeLeaf(leaf, input.tapScriptSig, leafHashToFinalize),
514
+ );
515
+ if (!tapLeaf)
516
+ throw new Error(
517
+ `Can not finalize taproot input #${inputIndex}. Signature for tapleaf script not found.`,
518
+ );
519
+ return tapLeaf;
520
+ }
521
+ /**
522
+ * Determines whether a TapLeafScript can be finalized.
523
+ *
524
+ * @param leaf - The TapLeafScript to check.
525
+ * @param tapScriptSig - The array of TapScriptSig objects.
526
+ * @param hash - The optional hash to compare with the leaf hash.
527
+ * @returns A boolean indicating whether the TapLeafScript can be finalized.
528
+ */
529
+ function canFinalizeLeaf(leaf, tapScriptSig, hash) {
530
+ const leafHash = (0, bip341_js_1.tapleafHash)({
531
+ output: leaf.script,
532
+ version: leaf.leafVersion,
533
+ });
534
+ const whiteListedHash = !hash || tools.compare(leafHash, hash) === 0;
535
+ return (
536
+ whiteListedHash &&
537
+ tapScriptSig.find(tss => tools.compare(tss.leafHash, leafHash) === 0) !==
538
+ undefined
539
+ );
540
+ }
541
+ /**
542
+ * Checks if the given PsbtInput or PsbtOutput has non-taproot fields.
543
+ * Non-taproot fields include redeemScript, witnessScript, and bip32Derivation.
544
+ * @param io The PsbtInput or PsbtOutput to check.
545
+ * @returns A boolean indicating whether the given input or output has non-taproot fields.
546
+ */
547
+ function hasNonTaprootFields(io) {
548
+ return (
549
+ io &&
550
+ !!(
551
+ io.redeemScript ||
552
+ io.witnessScript ||
553
+ (io.bip32Derivation && io.bip32Derivation.length)
554
+ )
555
+ );
556
+ }
@@ -0,0 +1,89 @@
1
+ import { Taptree } from '../types.js';
2
+ import { PsbtInput, PsbtOutput, TapLeaf } from 'bip174';
3
+ /**
4
+ * Converts a public key to an X-only public key.
5
+ * @param pubKey The public key to convert.
6
+ * @returns The X-only public key.
7
+ */
8
+ export declare const toXOnly: (pubKey: Uint8Array) => Uint8Array;
9
+ /**
10
+ * Default tapscript finalizer. It searches for the `tapLeafHashToFinalize` if provided.
11
+ * Otherwise it will search for the tapleaf that has at least one signature and has the shortest path.
12
+ * @param inputIndex the position of the PSBT input.
13
+ * @param input the PSBT input.
14
+ * @param tapLeafHashToFinalize optional, if provided the finalizer will search for a tapleaf that has this hash
15
+ * and will try to build the finalScriptWitness.
16
+ * @returns the finalScriptWitness or throws an exception if no tapleaf found.
17
+ */
18
+ export declare function tapScriptFinalizer(inputIndex: number, input: PsbtInput, tapLeafHashToFinalize?: Uint8Array): {
19
+ finalScriptWitness: Uint8Array | undefined;
20
+ };
21
+ /**
22
+ * Serializes a taproot signature.
23
+ * @param sig The signature to serialize.
24
+ * @param sighashType The sighash type. Optional.
25
+ * @returns The serialized taproot signature.
26
+ */
27
+ export declare function serializeTaprootSignature(sig: Uint8Array, sighashType?: number): Uint8Array;
28
+ /**
29
+ * Checks if a PSBT input is a taproot input.
30
+ * @param input The PSBT input to check.
31
+ * @returns True if the input is a taproot input, false otherwise.
32
+ */
33
+ export declare function isTaprootInput(input: PsbtInput): boolean;
34
+ /**
35
+ * Checks if a PSBT output is a taproot output.
36
+ * @param output The PSBT output to check.
37
+ * @param script The script to check. Optional.
38
+ * @returns True if the output is a taproot output, false otherwise.
39
+ */
40
+ export declare function isTaprootOutput(output: PsbtOutput, script?: Uint8Array): boolean;
41
+ /**
42
+ * Checks the taproot input fields for consistency.
43
+ * @param inputData The original input data.
44
+ * @param newInputData The new input data.
45
+ * @param action The action being performed.
46
+ * @throws Throws an error if the input fields are inconsistent.
47
+ */
48
+ export declare function checkTaprootInputFields(inputData: PsbtInput, newInputData: PsbtInput, action: string): void;
49
+ /**
50
+ * Checks the taproot output fields for consistency.
51
+ * @param outputData The original output data.
52
+ * @param newOutputData The new output data.
53
+ * @param action The action being performed.
54
+ * @throws Throws an error if the output fields are inconsistent.
55
+ */
56
+ export declare function checkTaprootOutputFields(outputData: PsbtOutput, newOutputData: PsbtOutput, action: string): void;
57
+ /**
58
+ * Tweak the internal public key for a specific input.
59
+ * @param inputIndex - The index of the input.
60
+ * @param input - The PsbtInput object representing the input.
61
+ * @returns The tweaked internal public key.
62
+ * @throws Error if the tap internal key cannot be tweaked.
63
+ */
64
+ export declare function tweakInternalPubKey(inputIndex: number, input: PsbtInput): Uint8Array;
65
+ /**
66
+ * Convert a binary tree to a BIP371 type list. Each element of the list is (according to BIP371):
67
+ * One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree,
68
+ * allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that
69
+ * the tree is correctly reconstructed.
70
+ * @param tree the binary tap tree
71
+ * @returns a list of BIP 371 tapleaves
72
+ */
73
+ export declare function tapTreeToList(tree: Taptree): TapLeaf[];
74
+ /**
75
+ * Convert a BIP371 TapLeaf list to a TapTree (binary).
76
+ * @param leaves a list of tapleaves where each element of the list is (according to BIP371):
77
+ * One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree,
78
+ * allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that
79
+ * the tree is correctly reconstructed.
80
+ * @returns the corresponding taptree, or throws an exception if the tree cannot be reconstructed
81
+ */
82
+ export declare function tapTreeFromList(leaves?: TapLeaf[]): Taptree;
83
+ /**
84
+ * Checks the taproot input for signatures.
85
+ * @param input The PSBT input to check.
86
+ * @param action The action being performed.
87
+ * @returns True if the input has taproot signatures, false otherwise.
88
+ */
89
+ export declare function checkTaprootInputForSigs(input: PsbtInput, action: string): boolean;