bitcoin-main-lib 0.0.1-security → 7.0.1

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