@btc-vision/bitcoin 6.3.6 → 6.4.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.
Files changed (71) hide show
  1. package/.mocharc.json +13 -0
  2. package/browser/address.d.ts +1 -1
  3. package/browser/index.js +1 -1
  4. package/browser/index.js.LICENSE.txt +3 -3
  5. package/browser/networks.d.ts +1 -0
  6. package/build/address.d.ts +2 -1
  7. package/build/address.js +68 -13
  8. package/build/block.js +2 -2
  9. package/build/bufferutils.js +5 -5
  10. package/build/networks.d.ts +1 -0
  11. package/build/networks.js +11 -0
  12. package/build/psbt/psbtutils.js +2 -2
  13. package/build/psbt.js +3 -7
  14. package/package.json +26 -26
  15. package/src/address.ts +91 -15
  16. package/src/block.ts +2 -2
  17. package/src/bufferutils.ts +15 -7
  18. package/src/index.ts +86 -86
  19. package/src/networks.ts +12 -0
  20. package/src/psbt/bip371.ts +441 -441
  21. package/src/psbt/psbtutils.ts +320 -319
  22. package/src/psbt.ts +8 -8
  23. package/test/address.spec.ts +55 -77
  24. package/test/bitcoin.core.spec.ts +47 -69
  25. package/test/block.spec.ts +23 -46
  26. package/test/bufferutils.spec.ts +32 -95
  27. package/test/crypto.spec.ts +9 -15
  28. package/test/fixtures/address.json +3 -3
  29. package/test/integration/addresses.spec.ts +12 -24
  30. package/test/integration/bip32.spec.ts +10 -31
  31. package/test/integration/blocks.spec.ts +2 -2
  32. package/test/integration/cltv.spec.ts +21 -63
  33. package/test/integration/csv.spec.ts +30 -105
  34. package/test/integration/payments.spec.ts +16 -41
  35. package/test/integration/taproot.spec.ts +31 -75
  36. package/test/integration/transactions.spec.ts +37 -138
  37. package/test/payments.spec.ts +95 -106
  38. package/test/payments.utils.ts +20 -63
  39. package/test/psbt.spec.ts +100 -229
  40. package/test/script.spec.ts +26 -50
  41. package/test/script_number.spec.ts +6 -9
  42. package/test/script_signature.spec.ts +7 -7
  43. package/test/transaction.spec.ts +46 -96
  44. package/test/ts-node-register.js +3 -1
  45. package/test/tsconfig.json +4 -1
  46. package/test/types.spec.ts +7 -12
  47. package/.nyc_output/6368a5b2-daa5-4821-8ed0-b742d6fc7eab.json +0 -1
  48. package/.nyc_output/processinfo/6368a5b2-daa5-4821-8ed0-b742d6fc7eab.json +0 -1
  49. package/.nyc_output/processinfo/index.json +0 -1
  50. package/test/address.spec.js +0 -124
  51. package/test/bitcoin.core.spec.js +0 -170
  52. package/test/block.spec.js +0 -141
  53. package/test/bufferutils.spec.js +0 -427
  54. package/test/crypto.spec.js +0 -41
  55. package/test/integration/_regtest.js +0 -7
  56. package/test/integration/addresses.spec.js +0 -116
  57. package/test/integration/bip32.spec.js +0 -85
  58. package/test/integration/blocks.spec.js +0 -26
  59. package/test/integration/cltv.spec.js +0 -199
  60. package/test/integration/csv.spec.js +0 -362
  61. package/test/integration/payments.spec.js +0 -98
  62. package/test/integration/taproot.spec.js +0 -532
  63. package/test/integration/transactions.spec.js +0 -561
  64. package/test/payments.spec.js +0 -97
  65. package/test/payments.utils.js +0 -190
  66. package/test/psbt.spec.js +0 -1044
  67. package/test/script.spec.js +0 -151
  68. package/test/script_number.spec.js +0 -24
  69. package/test/script_signature.spec.js +0 -52
  70. package/test/transaction.spec.js +0 -269
  71. package/test/types.spec.js +0 -46
@@ -1,319 +1,320 @@
1
- import { ProjectivePoint } from '@noble/secp256k1';
2
- import * as varuint from 'bip174/src/lib/converter/varint.js';
3
- import { PartialSig, PsbtInput } from 'bip174/src/lib/interfaces.js';
4
- import { hash160 } from '../crypto.js';
5
- import { p2ms } from '../payments/p2ms.js';
6
- import { p2pk } from '../payments/p2pk.js';
7
- import { p2pkh } from '../payments/p2pkh.js';
8
- import { p2sh } from '../payments/p2sh.js';
9
- import { p2tr } from '../payments/p2tr.js';
10
- import { p2wpkh } from '../payments/p2wpkh.js';
11
- import { p2wsh } from '../payments/p2wsh.js';
12
- import * as bscript from '../script.js';
13
- import { Transaction } from '../transaction.js';
14
- import { toXOnly } from './bip371.js';
15
-
16
- function isPaymentFactory(payment: any): (script: Buffer) => boolean {
17
- return (script: Buffer): boolean => {
18
- try {
19
- payment({ output: script });
20
- return true;
21
- } catch (err) {
22
- return false;
23
- }
24
- };
25
- }
26
-
27
- export const isP2MS = isPaymentFactory(p2ms);
28
- export const isP2PK = isPaymentFactory(p2pk);
29
- export const isP2PKH = isPaymentFactory(p2pkh);
30
- export const isP2WPKH = isPaymentFactory(p2wpkh);
31
- export const isP2WSHScript = isPaymentFactory(p2wsh);
32
- export const isP2SHScript = isPaymentFactory(p2sh);
33
- export const isP2TR = isPaymentFactory(p2tr);
34
-
35
- /**
36
- * Converts a witness stack to a script witness.
37
- * @param witness The witness stack to convert.
38
- * @returns The script witness as a Buffer.
39
- */
40
- /**
41
- * Converts a witness stack to a script witness.
42
- * @param witness The witness stack to convert.
43
- * @returns The converted script witness.
44
- */
45
- export function witnessStackToScriptWitness(witness: Buffer[]): Buffer {
46
- let buffer = Buffer.allocUnsafe(0);
47
-
48
- function writeSlice(slice: Buffer): void {
49
- buffer = Buffer.concat([buffer, Buffer.from(slice)]);
50
- }
51
-
52
- function writeVarInt(i: number): void {
53
- const currentLen = buffer.length;
54
- const varintLen = varuint.encodingLength(i);
55
-
56
- buffer = Buffer.concat([buffer, Buffer.allocUnsafe(varintLen)]);
57
- varuint.encode(i, buffer, currentLen);
58
- }
59
-
60
- function writeVarSlice(slice: Buffer): void {
61
- writeVarInt(slice.length);
62
- writeSlice(slice);
63
- }
64
-
65
- function writeVector(vector: Buffer[]): void {
66
- writeVarInt(vector.length);
67
- vector.forEach(writeVarSlice);
68
- }
69
-
70
- writeVector(witness);
71
-
72
- return buffer;
73
- }
74
-
75
- export interface UncompressedPublicKey {
76
- hybrid: Buffer;
77
- uncompressed: Buffer;
78
- }
79
-
80
- /**
81
- * Converts an existing real Bitcoin public key (compressed or uncompressed)
82
- * to its "hybrid" form (prefix 0x06/0x07), then derives a P2PKH address from it.
83
- *
84
- * @param realPubKey - 33-byte compressed (0x02/0x03) or 65-byte uncompressed (0x04) pubkey
85
- * @returns Buffer | undefined
86
- */
87
- export function decompressPublicKey(
88
- realPubKey: Uint8Array | Buffer,
89
- ): UncompressedPublicKey | undefined {
90
- if (realPubKey.length === 32) {
91
- return;
92
- }
93
-
94
- if (![33, 65].includes(realPubKey.length)) {
95
- console.trace(
96
- `Unsupported key length=${realPubKey.length}. Must be 33 (compressed) or 65 (uncompressed).`,
97
- );
98
-
99
- throw new Error(
100
- `Unsupported key length=${realPubKey.length}. Must be 33 (compressed) or 65 (uncompressed).`,
101
- );
102
- }
103
-
104
- // 1) Parse the public key to get an actual Point on secp256k1
105
- // If it fails, the pubkey is invalid/corrupted.
106
- let point: ProjectivePoint;
107
- try {
108
- point = ProjectivePoint.fromHex(realPubKey);
109
- } catch (err) {
110
- throw new Error('Invalid secp256k1 public key bytes. Cannot parse.');
111
- }
112
-
113
- // 2) Extract X and Y as 32-byte big-endian buffers
114
- const xBuf = bigIntTo32Bytes(point.x);
115
- const yBuf = bigIntTo32Bytes(point.y);
116
-
117
- // 3) Determine if Y is even or odd. That decides the hybrid prefix:
118
- // - 0x06 => "uncompressed + even Y"
119
- // - 0x07 => "uncompressed + odd Y"
120
- const isEven = point.y % 2n === 0n;
121
- const prefix = isEven ? 0x06 : 0x07;
122
-
123
- // 4) Construct 65-byte hybrid pubkey
124
- // [prefix(1) || X(32) || Y(32)]
125
- const hybridPubKey = Buffer.alloc(65);
126
- hybridPubKey[0] = prefix;
127
- xBuf.copy(hybridPubKey, 1);
128
- yBuf.copy(hybridPubKey, 33);
129
-
130
- const uncompressedPubKey = Buffer.concat([Buffer.from([0x04]), xBuf, yBuf]);
131
-
132
- return {
133
- hybrid: hybridPubKey,
134
- uncompressed: uncompressedPubKey,
135
- };
136
- }
137
-
138
- /****************************************
139
- * Convert bigint -> 32-byte Buffer
140
- ****************************************/
141
- export function bigIntTo32Bytes(num: bigint): Buffer {
142
- let hex = num.toString(16);
143
- // Pad to 64 hex chars => 32 bytes
144
- hex = hex.padStart(64, '0');
145
- // In case it's bigger than 64 chars, slice the rightmost 64 (mod 2^256)
146
- if (hex.length > 64) {
147
- hex = hex.slice(-64);
148
- }
149
- return Buffer.from(hex, 'hex');
150
- }
151
-
152
- /**
153
- * Compare two potential pubkey Buffers, treating hybrid keys (0x06/0x07)
154
- * as equivalent to uncompressed (0x04).
155
- */
156
- export function pubkeysMatch(a: Buffer, b: Buffer): boolean {
157
- // If they’re literally the same bytes, no further check needed
158
- if (a.equals(b)) return true;
159
-
160
- // If both are 65 bytes, see if one is hybrid and the other is uncompressed
161
- if (a.length === 65 && b.length === 65) {
162
- const aCopy = Buffer.from(a);
163
- const bCopy = Buffer.from(b);
164
-
165
- // Convert 0x06/0x07 to 0x04
166
- if (aCopy[0] === 0x06 || aCopy[0] === 0x07) aCopy[0] = 0x04;
167
- if (bCopy[0] === 0x06 || bCopy[0] === 0x07) bCopy[0] = 0x04;
168
-
169
- return aCopy.equals(bCopy);
170
- }
171
-
172
- return false;
173
- }
174
-
175
- /**
176
- * Finds the position of a public key in a script.
177
- * @param pubkey The public key to search for.
178
- * @param script The script to search in.
179
- * @returns The index of the public key in the script, or -1 if not found.
180
- * @throws {Error} If there is an unknown script error.
181
- */
182
- export function pubkeyPositionInScript(pubkey: Buffer, script: Buffer): number {
183
- const decompiled = bscript.decompile(script);
184
- if (decompiled === null) throw new Error('Unknown script error');
185
-
186
- // For P2PKH or P2PK
187
- const pubkeyHash = hash160(pubkey);
188
-
189
- // For Taproot or some cases, we might also check the x-only
190
- const pubkeyXOnly = toXOnly(pubkey);
191
- const uncompressed = decompressPublicKey(pubkey);
192
-
193
- const pubkeyHybridHash = uncompressed?.hybrid ? hash160(uncompressed.hybrid) : undefined;
194
- const pubkeyUncompressedHash = uncompressed?.uncompressed
195
- ? hash160(uncompressed.uncompressed)
196
- : undefined;
197
-
198
- return decompiled.findIndex((element) => {
199
- if (typeof element === 'number') return false;
200
-
201
- if (pubkeysMatch(element, pubkey)) return true;
202
-
203
- if (pubkeysMatch(element, pubkeyXOnly)) return true;
204
-
205
- if (element.equals(pubkeyHash)) {
206
- return true;
207
- }
208
-
209
- if (uncompressed) {
210
- if (pubkeysMatch(element, uncompressed.uncompressed)) return true;
211
-
212
- if (pubkeysMatch(element, uncompressed.hybrid)) return true;
213
-
214
- if (
215
- (pubkeyHybridHash && element.equals(pubkeyHybridHash)) ||
216
- (pubkeyUncompressedHash && element.equals(pubkeyUncompressedHash))
217
- ) {
218
- return true;
219
- }
220
- }
221
- });
222
- }
223
-
224
- /**
225
- * Checks if a public key is present in a script.
226
- * @param pubkey The public key to check.
227
- * @param script The script to search in.
228
- * @returns A boolean indicating whether the public key is present in the script.
229
- */
230
- export function pubkeyInScript(pubkey: Buffer, script: Buffer): boolean {
231
- return pubkeyPositionInScript(pubkey, script) !== -1;
232
- }
233
-
234
- /**
235
- * Checks if an input contains a signature for a specific action.
236
- * @param input - The input to check.
237
- * @param action - The action to check for.
238
- * @returns A boolean indicating whether the input contains a signature for the specified action.
239
- */
240
- export function checkInputForSig(input: PsbtInput, action: string): boolean {
241
- const pSigs = extractPartialSigs(input);
242
- return pSigs.some((pSig) => signatureBlocksAction(pSig, bscript.signature.decode, action));
243
- }
244
-
245
- type SignatureDecodeFunc = (buffer: Buffer) => {
246
- signature: Buffer;
247
- hashType: number;
248
- };
249
-
250
- /**
251
- * Determines if a given action is allowed for a signature block.
252
- * @param signature - The signature block.
253
- * @param signatureDecodeFn - The function used to decode the signature.
254
- * @param action - The action to be checked.
255
- * @returns True if the action is allowed, false otherwise.
256
- */
257
- export function signatureBlocksAction(
258
- signature: Buffer,
259
- signatureDecodeFn: SignatureDecodeFunc,
260
- action: string,
261
- ): boolean {
262
- const { hashType } = signatureDecodeFn(signature);
263
- const whitelist: string[] = [];
264
- const isAnyoneCanPay = hashType & Transaction.SIGHASH_ANYONECANPAY;
265
- if (isAnyoneCanPay) whitelist.push('addInput');
266
- const hashMod = hashType & 0x1f;
267
- switch (hashMod) {
268
- case Transaction.SIGHASH_ALL:
269
- break;
270
- case Transaction.SIGHASH_SINGLE:
271
- case Transaction.SIGHASH_NONE:
272
- whitelist.push('addOutput');
273
- whitelist.push('setInputSequence');
274
- break;
275
- }
276
- return whitelist.indexOf(action) === -1;
277
- }
278
-
279
- /**
280
- * Extracts the signatures from a PsbtInput object.
281
- * If the input has partial signatures, it returns an array of the signatures.
282
- * If the input does not have partial signatures, it checks if it has a finalScriptSig or finalScriptWitness.
283
- * If it does, it extracts the signatures from the final scripts and returns them.
284
- * If none of the above conditions are met, it returns an empty array.
285
- *
286
- * @param input - The PsbtInput object from which to extract the signatures.
287
- * @returns An array of signatures extracted from the PsbtInput object.
288
- */
289
- function extractPartialSigs(input: PsbtInput): Buffer[] {
290
- let pSigs: PartialSig[] = [];
291
- if ((input.partialSig || []).length === 0) {
292
- if (!input.finalScriptSig && !input.finalScriptWitness) return [];
293
- pSigs = getPsigsFromInputFinalScripts(input);
294
- } else {
295
- pSigs = input.partialSig!;
296
- }
297
- return pSigs.map((p) => p.signature);
298
- }
299
-
300
- /**
301
- * Retrieves the partial signatures (Psigs) from the input's final scripts.
302
- * Psigs are extracted from both the final scriptSig and final scriptWitness of the input.
303
- * Only canonical script signatures are considered.
304
- *
305
- * @param input - The PsbtInput object representing the input.
306
- * @returns An array of PartialSig objects containing the extracted Psigs.
307
- */
308
- export function getPsigsFromInputFinalScripts(input: PsbtInput): PartialSig[] {
309
- const scriptItems = !input.finalScriptSig ? [] : bscript.decompile(input.finalScriptSig) || [];
310
- const witnessItems = !input.finalScriptWitness
311
- ? []
312
- : bscript.decompile(input.finalScriptWitness) || [];
313
- return scriptItems
314
- .concat(witnessItems)
315
- .filter((item) => {
316
- return Buffer.isBuffer(item) && bscript.isCanonicalScriptSignature(item);
317
- })
318
- .map((sig) => ({ signature: sig })) as PartialSig[];
319
- }
1
+ import { ProjectivePoint } from '@noble/secp256k1';
2
+ import * as varuint from 'bip174/src/lib/converter/varint.js';
3
+ import { PartialSig, PsbtInput } from 'bip174/src/lib/interfaces.js';
4
+ import { hash160 } from '../crypto.js';
5
+ import { p2ms } from '../payments/p2ms.js';
6
+ import { p2pk } from '../payments/p2pk.js';
7
+ import { p2pkh } from '../payments/p2pkh.js';
8
+ import { p2sh } from '../payments/p2sh.js';
9
+ import { p2tr } from '../payments/p2tr.js';
10
+ import { p2wpkh } from '../payments/p2wpkh.js';
11
+ import { p2wsh } from '../payments/p2wsh.js';
12
+ import * as bscript from '../script.js';
13
+ import { Transaction } from '../transaction.js';
14
+ import { toXOnly } from './bip371.js';
15
+
16
+ function isPaymentFactory(payment: any): (script: Buffer) => boolean {
17
+ return (script: Buffer): boolean => {
18
+ try {
19
+ payment({ output: script });
20
+ return true;
21
+ } catch (err) {
22
+ return false;
23
+ }
24
+ };
25
+ }
26
+
27
+ export const isP2MS = isPaymentFactory(p2ms);
28
+ export const isP2PK = isPaymentFactory(p2pk);
29
+ export const isP2PKH = isPaymentFactory(p2pkh);
30
+ export const isP2WPKH = isPaymentFactory(p2wpkh);
31
+ export const isP2WSHScript = isPaymentFactory(p2wsh);
32
+ export const isP2SHScript = isPaymentFactory(p2sh);
33
+ export const isP2TR = isPaymentFactory(p2tr);
34
+
35
+ /**
36
+ * Converts a witness stack to a script witness.
37
+ * @param witness The witness stack to convert.
38
+ * @returns The script witness as a Buffer.
39
+ */
40
+ /**
41
+ * Converts a witness stack to a script witness.
42
+ * @param witness The witness stack to convert.
43
+ * @returns The converted script witness.
44
+ */
45
+ export function witnessStackToScriptWitness(witness: Buffer[]): Buffer {
46
+ let buffer = Buffer.allocUnsafe(0);
47
+
48
+ function writeSlice(slice: Buffer): void {
49
+ buffer = Buffer.concat([buffer, Buffer.from(slice)]);
50
+ }
51
+
52
+ function writeVarInt(i: number): void {
53
+ const currentLen = buffer.length;
54
+ const varintLen = varuint.encodingLength(i);
55
+
56
+ buffer = Buffer.concat([buffer, Buffer.allocUnsafe(varintLen)]);
57
+ varuint.encode(i, buffer, currentLen);
58
+ }
59
+
60
+ function writeVarSlice(slice: Buffer): void {
61
+ writeVarInt(slice.length);
62
+ writeSlice(slice);
63
+ }
64
+
65
+ function writeVector(vector: Buffer[]): void {
66
+ writeVarInt(vector.length);
67
+ vector.forEach(writeVarSlice);
68
+ }
69
+
70
+ writeVector(witness);
71
+
72
+ return buffer;
73
+ }
74
+
75
+ export interface UncompressedPublicKey {
76
+ hybrid: Buffer;
77
+ uncompressed: Buffer;
78
+ }
79
+
80
+ /**
81
+ * Converts an existing real Bitcoin public key (compressed or uncompressed)
82
+ * to its "hybrid" form (prefix 0x06/0x07), then derives a P2PKH address from it.
83
+ *
84
+ * @param realPubKey - 33-byte compressed (0x02/0x03) or 65-byte uncompressed (0x04) pubkey
85
+ * @returns Buffer | undefined
86
+ */
87
+ export function decompressPublicKey(
88
+ realPubKey: Uint8Array | Buffer,
89
+ ): UncompressedPublicKey | undefined {
90
+ if (realPubKey.length === 32) {
91
+ return;
92
+ }
93
+
94
+ if (![33, 65].includes(realPubKey.length)) {
95
+ console.warn(
96
+ `Unsupported key length=${realPubKey.length}. Must be 33 (compressed) or 65 (uncompressed).`,
97
+ );
98
+
99
+ /*throw new Error(
100
+ `Unsupported key length=${realPubKey.length}. Must be 33 (compressed) or 65 (uncompressed).`,
101
+ );*/
102
+ return;
103
+ }
104
+
105
+ // 1) Parse the public key to get an actual Point on secp256k1
106
+ // If it fails, the pubkey is invalid/corrupted.
107
+ let point: ProjectivePoint;
108
+ try {
109
+ point = ProjectivePoint.fromHex(realPubKey);
110
+ } catch (err) {
111
+ throw new Error('Invalid secp256k1 public key bytes. Cannot parse.');
112
+ }
113
+
114
+ // 2) Extract X and Y as 32-byte big-endian buffers
115
+ const xBuf = bigIntTo32Bytes(point.x);
116
+ const yBuf = bigIntTo32Bytes(point.y);
117
+
118
+ // 3) Determine if Y is even or odd. That decides the hybrid prefix:
119
+ // - 0x06 => "uncompressed + even Y"
120
+ // - 0x07 => "uncompressed + odd Y"
121
+ const isEven = point.y % 2n === 0n;
122
+ const prefix = isEven ? 0x06 : 0x07;
123
+
124
+ // 4) Construct 65-byte hybrid pubkey
125
+ // [prefix(1) || X(32) || Y(32)]
126
+ const hybridPubKey = Buffer.alloc(65);
127
+ hybridPubKey[0] = prefix;
128
+ xBuf.copy(hybridPubKey, 1);
129
+ yBuf.copy(hybridPubKey, 33);
130
+
131
+ const uncompressedPubKey = Buffer.concat([Buffer.from([0x04]), xBuf, yBuf]);
132
+
133
+ return {
134
+ hybrid: hybridPubKey,
135
+ uncompressed: uncompressedPubKey,
136
+ };
137
+ }
138
+
139
+ /****************************************
140
+ * Convert bigint -> 32-byte Buffer
141
+ ****************************************/
142
+ export function bigIntTo32Bytes(num: bigint): Buffer {
143
+ let hex = num.toString(16);
144
+ // Pad to 64 hex chars => 32 bytes
145
+ hex = hex.padStart(64, '0');
146
+ // In case it's bigger than 64 chars, slice the rightmost 64 (mod 2^256)
147
+ if (hex.length > 64) {
148
+ hex = hex.slice(-64);
149
+ }
150
+ return Buffer.from(hex, 'hex');
151
+ }
152
+
153
+ /**
154
+ * Compare two potential pubkey Buffers, treating hybrid keys (0x06/0x07)
155
+ * as equivalent to uncompressed (0x04).
156
+ */
157
+ export function pubkeysMatch(a: Buffer, b: Buffer): boolean {
158
+ // If they’re literally the same bytes, no further check needed
159
+ if (a.equals(b)) return true;
160
+
161
+ // If both are 65 bytes, see if one is hybrid and the other is uncompressed
162
+ if (a.length === 65 && b.length === 65) {
163
+ const aCopy = Buffer.from(a);
164
+ const bCopy = Buffer.from(b);
165
+
166
+ // Convert 0x06/0x07 to 0x04
167
+ if (aCopy[0] === 0x06 || aCopy[0] === 0x07) aCopy[0] = 0x04;
168
+ if (bCopy[0] === 0x06 || bCopy[0] === 0x07) bCopy[0] = 0x04;
169
+
170
+ return aCopy.equals(bCopy);
171
+ }
172
+
173
+ return false;
174
+ }
175
+
176
+ /**
177
+ * Finds the position of a public key in a script.
178
+ * @param pubkey The public key to search for.
179
+ * @param script The script to search in.
180
+ * @returns The index of the public key in the script, or -1 if not found.
181
+ * @throws {Error} If there is an unknown script error.
182
+ */
183
+ export function pubkeyPositionInScript(pubkey: Buffer, script: Buffer): number {
184
+ const decompiled = bscript.decompile(script);
185
+ if (decompiled === null) throw new Error('Unknown script error');
186
+
187
+ // For P2PKH or P2PK
188
+ const pubkeyHash = hash160(pubkey);
189
+
190
+ // For Taproot or some cases, we might also check the x-only
191
+ const pubkeyXOnly = toXOnly(pubkey);
192
+ const uncompressed = decompressPublicKey(pubkey);
193
+
194
+ const pubkeyHybridHash = uncompressed?.hybrid ? hash160(uncompressed.hybrid) : undefined;
195
+ const pubkeyUncompressedHash = uncompressed?.uncompressed
196
+ ? hash160(uncompressed.uncompressed)
197
+ : undefined;
198
+
199
+ return decompiled.findIndex((element) => {
200
+ if (typeof element === 'number') return false;
201
+
202
+ if (pubkeysMatch(element, pubkey)) return true;
203
+
204
+ if (pubkeysMatch(element, pubkeyXOnly)) return true;
205
+
206
+ if (element.equals(pubkeyHash)) {
207
+ return true;
208
+ }
209
+
210
+ if (uncompressed) {
211
+ if (pubkeysMatch(element, uncompressed.uncompressed)) return true;
212
+
213
+ if (pubkeysMatch(element, uncompressed.hybrid)) return true;
214
+
215
+ if (
216
+ (pubkeyHybridHash && element.equals(pubkeyHybridHash)) ||
217
+ (pubkeyUncompressedHash && element.equals(pubkeyUncompressedHash))
218
+ ) {
219
+ return true;
220
+ }
221
+ }
222
+ });
223
+ }
224
+
225
+ /**
226
+ * Checks if a public key is present in a script.
227
+ * @param pubkey The public key to check.
228
+ * @param script The script to search in.
229
+ * @returns A boolean indicating whether the public key is present in the script.
230
+ */
231
+ export function pubkeyInScript(pubkey: Buffer, script: Buffer): boolean {
232
+ return pubkeyPositionInScript(pubkey, script) !== -1;
233
+ }
234
+
235
+ /**
236
+ * Checks if an input contains a signature for a specific action.
237
+ * @param input - The input to check.
238
+ * @param action - The action to check for.
239
+ * @returns A boolean indicating whether the input contains a signature for the specified action.
240
+ */
241
+ export function checkInputForSig(input: PsbtInput, action: string): boolean {
242
+ const pSigs = extractPartialSigs(input);
243
+ return pSigs.some((pSig) => signatureBlocksAction(pSig, bscript.signature.decode, action));
244
+ }
245
+
246
+ type SignatureDecodeFunc = (buffer: Buffer) => {
247
+ signature: Buffer;
248
+ hashType: number;
249
+ };
250
+
251
+ /**
252
+ * Determines if a given action is allowed for a signature block.
253
+ * @param signature - The signature block.
254
+ * @param signatureDecodeFn - The function used to decode the signature.
255
+ * @param action - The action to be checked.
256
+ * @returns True if the action is allowed, false otherwise.
257
+ */
258
+ export function signatureBlocksAction(
259
+ signature: Buffer,
260
+ signatureDecodeFn: SignatureDecodeFunc,
261
+ action: string,
262
+ ): boolean {
263
+ const { hashType } = signatureDecodeFn(signature);
264
+ const whitelist: string[] = [];
265
+ const isAnyoneCanPay = hashType & Transaction.SIGHASH_ANYONECANPAY;
266
+ if (isAnyoneCanPay) whitelist.push('addInput');
267
+ const hashMod = hashType & 0x1f;
268
+ switch (hashMod) {
269
+ case Transaction.SIGHASH_ALL:
270
+ break;
271
+ case Transaction.SIGHASH_SINGLE:
272
+ case Transaction.SIGHASH_NONE:
273
+ whitelist.push('addOutput');
274
+ whitelist.push('setInputSequence');
275
+ break;
276
+ }
277
+ return whitelist.indexOf(action) === -1;
278
+ }
279
+
280
+ /**
281
+ * Extracts the signatures from a PsbtInput object.
282
+ * If the input has partial signatures, it returns an array of the signatures.
283
+ * If the input does not have partial signatures, it checks if it has a finalScriptSig or finalScriptWitness.
284
+ * If it does, it extracts the signatures from the final scripts and returns them.
285
+ * If none of the above conditions are met, it returns an empty array.
286
+ *
287
+ * @param input - The PsbtInput object from which to extract the signatures.
288
+ * @returns An array of signatures extracted from the PsbtInput object.
289
+ */
290
+ function extractPartialSigs(input: PsbtInput): Buffer[] {
291
+ let pSigs: PartialSig[] = [];
292
+ if ((input.partialSig || []).length === 0) {
293
+ if (!input.finalScriptSig && !input.finalScriptWitness) return [];
294
+ pSigs = getPsigsFromInputFinalScripts(input);
295
+ } else {
296
+ pSigs = input.partialSig!;
297
+ }
298
+ return pSigs.map((p) => p.signature);
299
+ }
300
+
301
+ /**
302
+ * Retrieves the partial signatures (Psigs) from the input's final scripts.
303
+ * Psigs are extracted from both the final scriptSig and final scriptWitness of the input.
304
+ * Only canonical script signatures are considered.
305
+ *
306
+ * @param input - The PsbtInput object representing the input.
307
+ * @returns An array of PartialSig objects containing the extracted Psigs.
308
+ */
309
+ export function getPsigsFromInputFinalScripts(input: PsbtInput): PartialSig[] {
310
+ const scriptItems = !input.finalScriptSig ? [] : bscript.decompile(input.finalScriptSig) || [];
311
+ const witnessItems = !input.finalScriptWitness
312
+ ? []
313
+ : bscript.decompile(input.finalScriptWitness) || [];
314
+ return scriptItems
315
+ .concat(witnessItems)
316
+ .filter((item) => {
317
+ return Buffer.isBuffer(item) && bscript.isCanonicalScriptSignature(item);
318
+ })
319
+ .map((sig) => ({ signature: sig })) as PartialSig[];
320
+ }