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