@btc-vision/bitcoin 6.3.6 → 6.4.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 (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 +1 -1
  7. package/build/address.js +12 -5
  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 +20 -6
  16. package/src/block.ts +233 -233
  17. package/src/bufferutils.ts +188 -180
  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 +4 -3
  22. package/src/psbt.ts +2187 -2187
  23. package/test/address.spec.ts +155 -177
  24. package/test/bitcoin.core.spec.ts +212 -234
  25. package/test/block.spec.ts +171 -194
  26. package/test/bufferutils.spec.ts +450 -513
  27. package/test/crypto.spec.ts +49 -55
  28. package/test/fixtures/address.json +3 -3
  29. package/test/integration/addresses.spec.ts +142 -154
  30. package/test/integration/bip32.spec.ts +130 -151
  31. package/test/integration/blocks.spec.ts +28 -28
  32. package/test/integration/cltv.spec.ts +241 -283
  33. package/test/integration/csv.spec.ts +452 -527
  34. package/test/integration/payments.spec.ts +110 -135
  35. package/test/integration/taproot.spec.ts +663 -707
  36. package/test/integration/transactions.spec.ts +668 -769
  37. package/test/payments.spec.ts +114 -125
  38. package/test/payments.utils.ts +165 -208
  39. package/test/psbt.spec.ts +1285 -1414
  40. package/test/script.spec.ts +186 -210
  41. package/test/script_number.spec.ts +26 -29
  42. package/test/script_signature.spec.ts +66 -66
  43. package/test/transaction.spec.ts +337 -387
  44. package/test/ts-node-register.js +7 -5
  45. package/test/tsconfig.json +4 -1
  46. package/test/types.spec.ts +53 -58
  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
package/test/psbt.spec.ts CHANGED
@@ -1,1414 +1,1285 @@
1
- import * as assert from 'assert';
2
- import BIP32Factory from 'bip32';
3
- import * as ecc from 'tiny-secp256k1';
4
- import * as crypto from 'crypto';
5
- import ECPairFactory from 'ecpair';
6
- import { describe, it } from 'mocha';
7
-
8
- import { convertScriptTree } from './payments.utils';
9
- import { LEAF_VERSION_TAPSCRIPT } from '../src/payments/bip341';
10
- import { tapTreeFromList, tapTreeToList } from '../src/psbt/bip371';
11
- import { Taptree } from '../src/types';
12
- import { initEccLib } from '../src';
13
- import { networks as NETWORKS, payments, Psbt, Signer, SignerAsync } from '..';
14
-
15
- import * as preFixtures from './fixtures/psbt.json';
16
- import * as taprootFixtures from './fixtures/p2tr.json';
17
-
18
- const bip32 = BIP32Factory(ecc);
19
- const ECPair = ECPairFactory(ecc);
20
-
21
- const validator = (
22
- pubkey: Buffer,
23
- msghash: Buffer,
24
- signature: Buffer,
25
- ): boolean => ECPair.fromPublicKey(pubkey).verify(msghash, signature);
26
-
27
- const schnorrValidator = (
28
- pubkey: Buffer,
29
- msghash: Buffer,
30
- signature: Buffer,
31
- ): boolean => ecc.verifySchnorr(msghash, pubkey, signature);
32
-
33
- const initBuffers = (object: any): typeof preFixtures =>
34
- JSON.parse(JSON.stringify(object), (_, value) => {
35
- const regex = new RegExp(/^Buffer.from\(['"](.*)['"], ['"](.*)['"]\)$/);
36
- const result = regex.exec(value);
37
- if (!result) return value;
38
-
39
- const data = result[1];
40
- const encoding = result[2];
41
-
42
- return Buffer.from(data, encoding as BufferEncoding);
43
- });
44
-
45
- const fixtures = initBuffers(preFixtures);
46
-
47
- const upperCaseFirstLetter = (str: string): string =>
48
- str.replace(/^./, s => s.toUpperCase());
49
-
50
- const toAsyncSigner = (signer: Signer): SignerAsync => {
51
- return {
52
- publicKey: signer.publicKey,
53
- sign: (hash: Buffer, lowerR: boolean | undefined): Promise<Buffer> => {
54
- return new Promise((resolve, rejects): void => {
55
- setTimeout(() => {
56
- try {
57
- const r = signer.sign(hash, lowerR);
58
- resolve(r);
59
- } catch (e) {
60
- rejects(e);
61
- }
62
- }, 10);
63
- });
64
- },
65
- };
66
- };
67
- const failedAsyncSigner = (publicKey: Buffer): SignerAsync => {
68
- return <SignerAsync>{
69
- publicKey,
70
- sign: (__: Buffer): Promise<Buffer> => {
71
- return new Promise((_, reject): void => {
72
- setTimeout(() => {
73
- reject(new Error('sign failed'));
74
- }, 10);
75
- });
76
- },
77
- };
78
- };
79
- // const b = (hex: string) => Buffer.from(hex, 'hex');
80
-
81
- describe(`Psbt`, () => {
82
- beforeEach(() => {
83
- // provide the ECC lib only when required
84
- initEccLib(undefined);
85
- });
86
- describe('BIP174 Test Vectors', () => {
87
- fixtures.bip174.invalid.forEach(f => {
88
- it(`Invalid: ${f.description}`, () => {
89
- assert.throws(() => {
90
- Psbt.fromBase64(f.psbt);
91
- }, new RegExp(f.errorMessage));
92
- });
93
- });
94
-
95
- fixtures.bip174.valid.forEach(f => {
96
- it(`Valid: ${f.description}`, () => {
97
- assert.doesNotThrow(() => {
98
- Psbt.fromBase64(f.psbt);
99
- });
100
- });
101
- });
102
-
103
- fixtures.bip174.failSignChecks.forEach(f => {
104
- const keyPair = ECPair.makeRandom();
105
- it(`Fails Signer checks: ${f.description}`, () => {
106
- const psbt = Psbt.fromBase64(f.psbt);
107
- assert.throws(() => {
108
- psbt.signInput(f.inputToCheck, keyPair);
109
- }, new RegExp(f.errorMessage));
110
- });
111
- });
112
-
113
- fixtures.bip174.creator.forEach(f => {
114
- it('Creates expected PSBT', () => {
115
- const psbt = new Psbt();
116
- for (const input of f.inputs) {
117
- psbt.addInput(input);
118
- }
119
- for (const output of f.outputs) {
120
- const script = Buffer.from(output.script, 'hex');
121
- psbt.addOutput({ ...output, script });
122
- }
123
- assert.strictEqual(psbt.toBase64(), f.result);
124
- });
125
- });
126
-
127
- fixtures.bip174.updater.forEach(f => {
128
- it('Updates PSBT to the expected result', () => {
129
- if (f.isTaproot) initEccLib(ecc);
130
- const psbt = Psbt.fromBase64(f.psbt);
131
-
132
- for (const inputOrOutput of ['input', 'output']) {
133
- const fixtureData = (f as any)[`${inputOrOutput}Data`];
134
- if (fixtureData) {
135
- for (const [i, data] of fixtureData.entries()) {
136
- const txt = upperCaseFirstLetter(inputOrOutput);
137
- (psbt as any)[`update${txt}`](i, data);
138
- }
139
- }
140
- }
141
-
142
- assert.strictEqual(psbt.toBase64(), f.result);
143
- });
144
- });
145
-
146
- fixtures.bip174.signer.forEach(f => {
147
- it('Signs PSBT to the expected result', () => {
148
- if (f.isTaproot) initEccLib(ecc);
149
- const psbt = Psbt.fromBase64(f.psbt);
150
-
151
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
152
- // @ts-ignore // cannot find tapLeafHashToSign
153
- f.keys.forEach(({ inputToSign, tapLeafHashToSign, WIF }) => {
154
- const keyPair = ECPair.fromWIF(WIF, NETWORKS.testnet);
155
- if (tapLeafHashToSign)
156
- psbt.signTaprootInput(
157
- inputToSign,
158
- keyPair,
159
- Buffer.from(tapLeafHashToSign, 'hex'),
160
- );
161
- else psbt.signInput(inputToSign, keyPair);
162
- });
163
-
164
- assert.strictEqual(psbt.toBase64(), f.result);
165
- });
166
- });
167
-
168
- fixtures.bip174.combiner.forEach(f => {
169
- it('Combines two PSBTs to the expected result', () => {
170
- const psbts = f.psbts.map(psbt => Psbt.fromBase64(psbt));
171
-
172
- psbts[0].combine(psbts[1]);
173
-
174
- // Produces a different Base64 string due to implemetation specific key-value ordering.
175
- // That means this test will fail:
176
- // assert.strictEqual(psbts[0].toBase64(), f.result)
177
- // However, if we compare the actual PSBT properties we can see they are logically identical:
178
- assert.deepStrictEqual(psbts[0], Psbt.fromBase64(f.result));
179
- });
180
- });
181
-
182
- fixtures.bip174.finalizer.forEach(f => {
183
- it('Finalizes inputs and gives the expected PSBT', () => {
184
- if (f.isTaproot) initEccLib(ecc);
185
- const psbt = Psbt.fromBase64(f.psbt);
186
-
187
- psbt.finalizeAllInputs();
188
-
189
- assert.strictEqual(psbt.toBase64(), f.result);
190
- });
191
- });
192
-
193
- fixtures.bip174.extractor.forEach(f => {
194
- it('Extracts the expected transaction from a PSBT', () => {
195
- const psbt1 = Psbt.fromBase64(f.psbt);
196
- const transaction1 = psbt1.extractTransaction(true).toHex();
197
-
198
- const psbt2 = Psbt.fromBase64(f.psbt);
199
- const transaction2 = psbt2.extractTransaction().toHex();
200
-
201
- assert.strictEqual(transaction1, transaction2);
202
- assert.strictEqual(transaction1, f.transaction);
203
-
204
- const psbt3 = Psbt.fromBase64(f.psbt);
205
- delete psbt3.data.inputs[0].finalScriptSig;
206
- delete psbt3.data.inputs[0].finalScriptWitness;
207
- assert.throws(() => {
208
- psbt3.extractTransaction();
209
- }, new RegExp('Not finalized'));
210
-
211
- const psbt4 = Psbt.fromBase64(f.psbt);
212
- psbt4.setMaximumFeeRate(1);
213
- assert.throws(() => {
214
- psbt4.extractTransaction();
215
- }, new RegExp('Warning: You are paying around [\\d.]+ in fees'));
216
-
217
- const psbt5 = Psbt.fromBase64(f.psbt);
218
- psbt5.extractTransaction(true);
219
- const fr1 = psbt5.getFeeRate();
220
- const fr2 = psbt5.getFeeRate();
221
- assert.strictEqual(fr1, fr2);
222
-
223
- const psbt6 = Psbt.fromBase64(f.psbt);
224
- const f1 = psbt6.getFee();
225
- const f2 = psbt6.getFee();
226
- assert.strictEqual(f1, f2);
227
- });
228
- });
229
- });
230
-
231
- describe('signInputAsync', () => {
232
- fixtures.signInput.checks.forEach(f => {
233
- it(f.description, async () => {
234
- if (f.isTaproot) initEccLib(ecc);
235
- if (f.shouldSign) {
236
- const psbtThatShouldsign = Psbt.fromBase64(
237
- f.shouldSign.psbt,
238
- );
239
- await assert.doesNotReject(async () => {
240
- await psbtThatShouldsign.signInputAsync(
241
- f.shouldSign.inputToCheck,
242
- ECPair.fromWIF(f.shouldSign.WIF),
243
- f.shouldSign.sighashTypes || undefined,
244
- );
245
- if (f.shouldSign.result) {
246
- assert.strictEqual(
247
- psbtThatShouldsign.toBase64(),
248
- f.shouldSign.result,
249
- );
250
- }
251
- });
252
- const failMessage = f.isTaproot
253
- ? /Need Schnorr Signer to sign taproot input #0./
254
- : /sign failed/;
255
- await assert.rejects(async () => {
256
- await psbtThatShouldsign.signInputAsync(
257
- f.shouldSign.inputToCheck,
258
- failedAsyncSigner(
259
- ECPair.fromWIF(f.shouldSign.WIF).publicKey,
260
- ),
261
- f.shouldSign.sighashTypes || undefined,
262
- );
263
- }, failMessage);
264
- }
265
-
266
- if (f.shouldThrow) {
267
- const psbtThatShouldThrow = Psbt.fromBase64(
268
- f.shouldThrow.psbt,
269
- );
270
- await assert.rejects(async () => {
271
- await psbtThatShouldThrow.signInputAsync(
272
- f.shouldThrow.inputToCheck,
273
- ECPair.fromWIF(f.shouldThrow.WIF),
274
- (f.shouldThrow as any).sighashTypes || undefined,
275
- );
276
- }, new RegExp(f.shouldThrow.errorMessage));
277
- await assert.rejects(async () => {
278
- await psbtThatShouldThrow.signInputAsync(
279
- f.shouldThrow.inputToCheck,
280
- toAsyncSigner(ECPair.fromWIF(f.shouldThrow.WIF)),
281
- (f.shouldThrow as any).sighashTypes || undefined,
282
- );
283
- }, new RegExp(f.shouldThrow.errorMessage));
284
- await assert.rejects(async () => {
285
- await (psbtThatShouldThrow.signInputAsync as any)(
286
- f.shouldThrow.inputToCheck,
287
- );
288
- }, new RegExp('Need Signer to sign input'));
289
- }
290
- });
291
- });
292
- });
293
-
294
- describe('signInput', () => {
295
- fixtures.signInput.checks.forEach(f => {
296
- it(f.description, () => {
297
- if (f.isTaproot) initEccLib(ecc);
298
- if (f.shouldSign) {
299
- const psbtThatShouldsign = Psbt.fromBase64(
300
- f.shouldSign.psbt,
301
- );
302
- assert.doesNotThrow(() => {
303
- psbtThatShouldsign.signInput(
304
- f.shouldSign.inputToCheck,
305
- ECPair.fromWIF(f.shouldSign.WIF),
306
- f.shouldSign.sighashTypes || undefined,
307
- );
308
- });
309
- }
310
-
311
- if (f.shouldThrow) {
312
- const psbtThatShouldThrow = Psbt.fromBase64(
313
- f.shouldThrow.psbt,
314
- );
315
- assert.throws(() => {
316
- psbtThatShouldThrow.signInput(
317
- f.shouldThrow.inputToCheck,
318
- ECPair.fromWIF(f.shouldThrow.WIF),
319
- (f.shouldThrow as any).sighashTypes || undefined,
320
- );
321
- }, new RegExp(f.shouldThrow.errorMessage));
322
- assert.throws(() => {
323
- (psbtThatShouldThrow.signInput as any)(
324
- f.shouldThrow.inputToCheck,
325
- );
326
- }, new RegExp('Need Signer to sign input'));
327
- }
328
- });
329
- });
330
- });
331
-
332
- describe('signAllInputsAsync', () => {
333
- fixtures.signInput.checks.forEach(f => {
334
- if (f.description === 'checks the input exists') return;
335
- it(f.description, async () => {
336
- if (f.isTaproot) initEccLib(ecc);
337
- if (f.shouldSign) {
338
- const psbtThatShouldsign = Psbt.fromBase64(
339
- f.shouldSign.psbt,
340
- );
341
- await assert.doesNotReject(async () => {
342
- await psbtThatShouldsign.signAllInputsAsync(
343
- ECPair.fromWIF(f.shouldSign.WIF),
344
- f.shouldSign.sighashTypes || undefined,
345
- );
346
- });
347
- }
348
-
349
- if (f.shouldThrow) {
350
- const psbtThatShouldThrow = Psbt.fromBase64(
351
- f.shouldThrow.psbt,
352
- );
353
- await assert.rejects(async () => {
354
- await psbtThatShouldThrow.signAllInputsAsync(
355
- ECPair.fromWIF(f.shouldThrow.WIF),
356
- (f.shouldThrow as any).sighashTypes || undefined,
357
- );
358
- }, new RegExp('No inputs were signed'));
359
- await assert.rejects(async () => {
360
- await (psbtThatShouldThrow.signAllInputsAsync as any)();
361
- }, new RegExp('Need Signer to sign input'));
362
- }
363
- });
364
- });
365
- });
366
-
367
- describe('signAllInputs', () => {
368
- fixtures.signInput.checks.forEach(f => {
369
- if (f.description === 'checks the input exists') return;
370
- it(f.description, () => {
371
- if (f.isTaproot) initEccLib(ecc);
372
- if (f.shouldSign) {
373
- const psbtThatShouldsign = Psbt.fromBase64(
374
- f.shouldSign.psbt,
375
- );
376
- assert.doesNotThrow(() => {
377
- psbtThatShouldsign.signAllInputs(
378
- ECPair.fromWIF(f.shouldSign.WIF),
379
- f.shouldSign.sighashTypes || undefined,
380
- );
381
- });
382
- }
383
-
384
- if (f.shouldThrow) {
385
- const psbtThatShouldThrow = Psbt.fromBase64(
386
- f.shouldThrow.psbt,
387
- );
388
- assert.throws(() => {
389
- psbtThatShouldThrow.signAllInputs(
390
- ECPair.fromWIF(f.shouldThrow.WIF),
391
- (f.shouldThrow as any).sighashTypes || undefined,
392
- );
393
- }, new RegExp('No inputs were signed'));
394
- assert.throws(() => {
395
- (psbtThatShouldThrow.signAllInputs as any)();
396
- }, new RegExp('Need Signer to sign input'));
397
- }
398
- });
399
- });
400
- });
401
-
402
- describe('signInputHDAsync', () => {
403
- fixtures.signInputHD.checks.forEach(f => {
404
- it(f.description, async () => {
405
- if (f.shouldSign) {
406
- const psbtThatShouldsign = Psbt.fromBase64(
407
- f.shouldSign.psbt,
408
- );
409
- await assert.doesNotReject(async () => {
410
- await psbtThatShouldsign.signInputHDAsync(
411
- f.shouldSign.inputToCheck,
412
- bip32.fromBase58(f.shouldSign.xprv),
413
- (f.shouldSign as any).sighashTypes || undefined,
414
- );
415
- });
416
- }
417
-
418
- if (f.shouldThrow) {
419
- const psbtThatShouldThrow = Psbt.fromBase64(
420
- f.shouldThrow.psbt,
421
- );
422
- await assert.rejects(async () => {
423
- await psbtThatShouldThrow.signInputHDAsync(
424
- f.shouldThrow.inputToCheck,
425
- bip32.fromBase58(f.shouldThrow.xprv),
426
- (f.shouldThrow as any).sighashTypes || undefined,
427
- );
428
- }, new RegExp(f.shouldThrow.errorMessage));
429
- await assert.rejects(async () => {
430
- await (psbtThatShouldThrow.signInputHDAsync as any)(
431
- f.shouldThrow.inputToCheck,
432
- );
433
- }, new RegExp('Need HDSigner to sign input'));
434
- }
435
- });
436
- });
437
- });
438
-
439
- describe('signInputHD', () => {
440
- fixtures.signInputHD.checks.forEach(f => {
441
- it(f.description, () => {
442
- if (f.shouldSign) {
443
- const psbtThatShouldsign = Psbt.fromBase64(
444
- f.shouldSign.psbt,
445
- );
446
- assert.doesNotThrow(() => {
447
- psbtThatShouldsign.signInputHD(
448
- f.shouldSign.inputToCheck,
449
- bip32.fromBase58(f.shouldSign.xprv),
450
- (f.shouldSign as any).sighashTypes || undefined,
451
- );
452
- });
453
- }
454
-
455
- if (f.shouldThrow) {
456
- const psbtThatShouldThrow = Psbt.fromBase64(
457
- f.shouldThrow.psbt,
458
- );
459
- assert.throws(() => {
460
- psbtThatShouldThrow.signInputHD(
461
- f.shouldThrow.inputToCheck,
462
- bip32.fromBase58(f.shouldThrow.xprv),
463
- (f.shouldThrow as any).sighashTypes || undefined,
464
- );
465
- }, new RegExp(f.shouldThrow.errorMessage));
466
- assert.throws(() => {
467
- (psbtThatShouldThrow.signInputHD as any)(
468
- f.shouldThrow.inputToCheck,
469
- );
470
- }, new RegExp('Need HDSigner to sign input'));
471
- }
472
- });
473
- });
474
- });
475
-
476
- describe('signAllInputsHDAsync', () => {
477
- fixtures.signInputHD.checks.forEach(f => {
478
- it(f.description, async () => {
479
- if (f.shouldSign) {
480
- const psbtThatShouldsign = Psbt.fromBase64(
481
- f.shouldSign.psbt,
482
- );
483
- await assert.doesNotReject(async () => {
484
- await psbtThatShouldsign.signAllInputsHDAsync(
485
- bip32.fromBase58(f.shouldSign.xprv),
486
- (f.shouldSign as any).sighashTypes || undefined,
487
- );
488
- });
489
- }
490
-
491
- if (f.shouldThrow) {
492
- const psbtThatShouldThrow = Psbt.fromBase64(
493
- f.shouldThrow.psbt,
494
- );
495
- await assert.rejects(async () => {
496
- await psbtThatShouldThrow.signAllInputsHDAsync(
497
- bip32.fromBase58(f.shouldThrow.xprv),
498
- (f.shouldThrow as any).sighashTypes || undefined,
499
- );
500
- }, new RegExp('No inputs were signed'));
501
- await assert.rejects(async () => {
502
- await (
503
- psbtThatShouldThrow.signAllInputsHDAsync as any
504
- )();
505
- }, new RegExp('Need HDSigner to sign input'));
506
- }
507
- });
508
- });
509
- });
510
-
511
- describe('signAllInputsHD', () => {
512
- fixtures.signInputHD.checks.forEach(f => {
513
- it(f.description, () => {
514
- if (f.shouldSign) {
515
- const psbtThatShouldsign = Psbt.fromBase64(
516
- f.shouldSign.psbt,
517
- );
518
- assert.doesNotThrow(() => {
519
- psbtThatShouldsign.signAllInputsHD(
520
- bip32.fromBase58(f.shouldSign.xprv),
521
- (f.shouldSign as any).sighashTypes || undefined,
522
- );
523
- });
524
- }
525
-
526
- if (f.shouldThrow) {
527
- const psbtThatShouldThrow = Psbt.fromBase64(
528
- f.shouldThrow.psbt,
529
- );
530
- assert.throws(() => {
531
- psbtThatShouldThrow.signAllInputsHD(
532
- bip32.fromBase58(f.shouldThrow.xprv),
533
- (f.shouldThrow as any).sighashTypes || undefined,
534
- );
535
- }, new RegExp('No inputs were signed'));
536
- assert.throws(() => {
537
- (psbtThatShouldThrow.signAllInputsHD as any)();
538
- }, new RegExp('Need HDSigner to sign input'));
539
- }
540
- });
541
- });
542
- });
543
-
544
- describe('finalizeInput', () => {
545
- it(`Finalizes tapleaf by hash`, () => {
546
- const f = fixtures.finalizeInput.finalizeTapleafByHash;
547
- const psbt = Psbt.fromBase64(f.psbt);
548
-
549
- psbt.finalizeTaprootInput(f.index, Buffer.from(f.leafHash, 'hex'));
550
-
551
- assert.strictEqual(psbt.toBase64(), f.result);
552
- });
553
-
554
- it(`fails if tapleaf hash not found`, () => {
555
- const f = fixtures.finalizeInput.finalizeTapleafByHash;
556
- const psbt = Psbt.fromBase64(f.psbt);
557
-
558
- assert.throws(() => {
559
- psbt.finalizeTaprootInput(
560
- f.index,
561
- Buffer.from(f.leafHash, 'hex').reverse(),
562
- );
563
- }, new RegExp('Can not finalize taproot input #0. Signature for tapleaf script not found.'));
564
- });
565
-
566
- it(`fails if trying to finalzie non-taproot input`, () => {
567
- const psbt = new Psbt();
568
- psbt.addInput({
569
- hash: '0000000000000000000000000000000000000000000000000000000000000000',
570
- index: 0,
571
- });
572
-
573
- assert.throws(() => {
574
- psbt.finalizeTaprootInput(0);
575
- }, new RegExp('Cannot finalize input #0. Not Taproot.'));
576
- });
577
- });
578
-
579
- describe('finalizeAllInputs', () => {
580
- fixtures.finalizeAllInputs.forEach(f => {
581
- it(`Finalizes inputs of type "${f.type}"`, () => {
582
- const psbt = Psbt.fromBase64(f.psbt);
583
-
584
- psbt.finalizeAllInputs();
585
-
586
- assert.strictEqual(psbt.toBase64(), f.result);
587
- });
588
- });
589
- it('fails if no script found', () => {
590
- const psbt = new Psbt();
591
- psbt.addInput({
592
- hash: '0000000000000000000000000000000000000000000000000000000000000000',
593
- index: 0,
594
- });
595
- assert.throws(() => {
596
- psbt.finalizeAllInputs();
597
- }, new RegExp('No script found for input #0'));
598
- psbt.updateInput(0, {
599
- witnessUtxo: {
600
- script: Buffer.from(
601
- '0014d85c2b71d0060b09c9886aeb815e50991dda124d',
602
- 'hex',
603
- ),
604
- value: 2e5,
605
- },
606
- });
607
- assert.throws(() => {
608
- psbt.finalizeAllInputs();
609
- }, new RegExp('Can not finalize input #0'));
610
- });
611
- });
612
-
613
- describe('addInput', () => {
614
- fixtures.addInput.checks.forEach(f => {
615
- it(f.description, () => {
616
- const psbt = new Psbt();
617
-
618
- if (f.exception) {
619
- assert.throws(() => {
620
- psbt.addInput(f.inputData as any);
621
- }, new RegExp(f.exception));
622
- assert.throws(() => {
623
- psbt.addInputs([f.inputData as any]);
624
- }, new RegExp(f.exception));
625
- } else {
626
- assert.doesNotThrow(() => {
627
- psbt.addInputs([f.inputData as any]);
628
- if (f.equals) {
629
- assert.strictEqual(psbt.toBase64(), f.equals);
630
- }
631
- });
632
- assert.throws(() => {
633
- psbt.addInput(f.inputData as any);
634
- }, new RegExp('Duplicate input detected.'));
635
- }
636
- });
637
- });
638
- });
639
-
640
- describe('updateInput', () => {
641
- fixtures.updateInput.checks.forEach(f => {
642
- it(f.description, () => {
643
- const psbt = Psbt.fromBase64(f.psbt);
644
-
645
- if (f.exception) {
646
- assert.throws(() => {
647
- psbt.updateInput(f.index, f.inputData as any);
648
- }, new RegExp(f.exception));
649
- }
650
- });
651
- });
652
- });
653
-
654
- describe('addOutput', () => {
655
- fixtures.addOutput.checks.forEach(f => {
656
- it(f.description, () => {
657
- if (f.isTaproot) initEccLib(ecc);
658
- const psbt = f.psbt ? Psbt.fromBase64(f.psbt) : new Psbt();
659
-
660
- if (f.exception) {
661
- assert.throws(() => {
662
- psbt.addOutput(f.outputData as any);
663
- }, new RegExp(f.exception));
664
- assert.throws(() => {
665
- psbt.addOutputs([f.outputData as any]);
666
- }, new RegExp(f.exception));
667
- } else {
668
- assert.doesNotThrow(() => {
669
- psbt.addOutput(f.outputData as any);
670
- });
671
- if (f.result) {
672
- assert.strictEqual(psbt.toBase64(), f.result);
673
- }
674
- assert.doesNotThrow(() => {
675
- psbt.addOutputs([f.outputData as any]);
676
- });
677
- }
678
- });
679
- });
680
- });
681
-
682
- describe('setVersion', () => {
683
- it('Sets the version value of the unsigned transaction', () => {
684
- const psbt = new Psbt();
685
-
686
- assert.strictEqual(psbt.extractTransaction().version, 2);
687
- psbt.setVersion(1);
688
- assert.strictEqual(psbt.extractTransaction().version, 1);
689
- });
690
- });
691
-
692
- describe('setLocktime', () => {
693
- it('Sets the nLockTime value of the unsigned transaction', () => {
694
- const psbt = new Psbt();
695
-
696
- assert.strictEqual(psbt.extractTransaction().locktime, 0);
697
- psbt.setLocktime(1);
698
- assert.strictEqual(psbt.extractTransaction().locktime, 1);
699
- });
700
- });
701
-
702
- describe('setInputSequence', () => {
703
- it('Sets the sequence number for a given input', () => {
704
- const psbt = new Psbt();
705
- psbt.addInput({
706
- hash: '0000000000000000000000000000000000000000000000000000000000000000',
707
- index: 0,
708
- });
709
-
710
- assert.strictEqual(psbt.inputCount, 1);
711
- assert.strictEqual(psbt.txInputs[0].sequence, 0xffffffff);
712
- psbt.setInputSequence(0, 0);
713
- assert.strictEqual(psbt.txInputs[0].sequence, 0);
714
- });
715
-
716
- it('throws if input index is too high', () => {
717
- const psbt = new Psbt();
718
- psbt.addInput({
719
- hash: '0000000000000000000000000000000000000000000000000000000000000000',
720
- index: 0,
721
- });
722
-
723
- assert.throws(() => {
724
- psbt.setInputSequence(1, 0);
725
- }, new RegExp('Input index too high'));
726
- });
727
- });
728
-
729
- describe('getInputType', () => {
730
- const key = ECPair.makeRandom();
731
- const { publicKey } = key;
732
- const p2wpkhPub = (pubkey: Buffer): Buffer =>
733
- payments.p2wpkh({
734
- pubkey,
735
- }).output!;
736
- const p2pkhPub = (pubkey: Buffer): Buffer =>
737
- payments.p2pkh({
738
- pubkey,
739
- }).output!;
740
- const p2shOut = (output: Buffer): Buffer =>
741
- payments.p2sh({
742
- redeem: { output },
743
- }).output!;
744
- const p2wshOut = (output: Buffer): Buffer =>
745
- payments.p2wsh({
746
- redeem: { output },
747
- }).output!;
748
- const p2shp2wshOut = (output: Buffer): Buffer =>
749
- p2shOut(p2wshOut(output));
750
- const noOuter = (output: Buffer): Buffer => output;
751
-
752
- function getInputTypeTest({
753
- innerScript,
754
- outerScript,
755
- redeemGetter,
756
- witnessGetter,
757
- expectedType,
758
- finalize,
759
- }: any): void {
760
- const psbt = new Psbt();
761
- psbt.addInput({
762
- hash: '0000000000000000000000000000000000000000000000000000000000000000',
763
- index: 0,
764
- witnessUtxo: {
765
- script: outerScript(innerScript(publicKey)),
766
- value: 2e3,
767
- },
768
- ...(redeemGetter
769
- ? { redeemScript: redeemGetter(publicKey) }
770
- : {}),
771
- ...(witnessGetter
772
- ? { witnessScript: witnessGetter(publicKey) }
773
- : {}),
774
- }).addOutput({
775
- script: Buffer.from(
776
- '0014d85c2b71d0060b09c9886aeb815e50991dda124d',
777
- ),
778
- value: 1800,
779
- });
780
- if (finalize) psbt.signInput(0, key).finalizeInput(0);
781
- const type = psbt.getInputType(0);
782
- assert.strictEqual(type, expectedType, 'incorrect input type');
783
- }
784
-
785
- [
786
- {
787
- innerScript: p2pkhPub,
788
- outerScript: noOuter,
789
- redeemGetter: null,
790
- witnessGetter: null,
791
- expectedType: 'pubkeyhash',
792
- },
793
- {
794
- innerScript: p2wpkhPub,
795
- outerScript: noOuter,
796
- redeemGetter: null,
797
- witnessGetter: null,
798
- expectedType: 'witnesspubkeyhash',
799
- },
800
- {
801
- innerScript: p2pkhPub,
802
- outerScript: p2shOut,
803
- redeemGetter: p2pkhPub,
804
- witnessGetter: null,
805
- expectedType: 'p2sh-pubkeyhash',
806
- },
807
- {
808
- innerScript: p2wpkhPub,
809
- outerScript: p2shOut,
810
- redeemGetter: p2wpkhPub,
811
- witnessGetter: null,
812
- expectedType: 'p2sh-witnesspubkeyhash',
813
- finalize: true,
814
- },
815
- {
816
- innerScript: p2pkhPub,
817
- outerScript: p2wshOut,
818
- redeemGetter: null,
819
- witnessGetter: p2pkhPub,
820
- expectedType: 'p2wsh-pubkeyhash',
821
- finalize: true,
822
- },
823
- {
824
- innerScript: p2pkhPub,
825
- outerScript: p2shp2wshOut,
826
- redeemGetter: (pk: Buffer): Buffer => p2wshOut(p2pkhPub(pk)),
827
- witnessGetter: p2pkhPub,
828
- expectedType: 'p2sh-p2wsh-pubkeyhash',
829
- },
830
- ].forEach(getInputTypeTest);
831
- });
832
-
833
- describe('inputHasHDKey', () => {
834
- it('should return true if HD key is present', () => {
835
- const root = bip32.fromSeed(crypto.randomBytes(32));
836
- const root2 = bip32.fromSeed(crypto.randomBytes(32));
837
- const path = "m/0'/0";
838
- const psbt = new Psbt();
839
- psbt.addInput({
840
- hash: '0000000000000000000000000000000000000000000000000000000000000000',
841
- index: 0,
842
- bip32Derivation: [
843
- {
844
- masterFingerprint: root.fingerprint,
845
- path,
846
- pubkey: root.derivePath(path).publicKey,
847
- },
848
- ],
849
- });
850
- assert.strictEqual(psbt.inputHasHDKey(0, root), true);
851
- assert.strictEqual(psbt.inputHasHDKey(0, root2), false);
852
- });
853
- });
854
-
855
- describe('inputHasPubkey', () => {
856
- it('should throw', () => {
857
- const psbt = new Psbt();
858
- psbt.addInput({
859
- hash: '0000000000000000000000000000000000000000000000000000000000000000',
860
- index: 0,
861
- });
862
-
863
- assert.throws(() => {
864
- psbt.inputHasPubkey(0, Buffer.from([]));
865
- }, new RegExp("Can't find pubkey in input without Utxo data"));
866
-
867
- psbt.updateInput(0, {
868
- witnessUtxo: {
869
- value: 1337,
870
- script: payments.p2sh({
871
- redeem: { output: Buffer.from([0x51]) },
872
- }).output!,
873
- },
874
- });
875
-
876
- assert.throws(() => {
877
- psbt.inputHasPubkey(0, Buffer.from([]));
878
- }, new RegExp('scriptPubkey is P2SH but redeemScript missing'));
879
-
880
- delete psbt.data.inputs[0].witnessUtxo;
881
-
882
- psbt.updateInput(0, {
883
- witnessUtxo: {
884
- value: 1337,
885
- script: payments.p2wsh({
886
- redeem: { output: Buffer.from([0x51]) },
887
- }).output!,
888
- },
889
- });
890
-
891
- assert.throws(() => {
892
- psbt.inputHasPubkey(0, Buffer.from([]));
893
- }, new RegExp('scriptPubkey or redeemScript is P2WSH but witnessScript missing'));
894
-
895
- delete psbt.data.inputs[0].witnessUtxo;
896
-
897
- psbt.updateInput(0, {
898
- witnessUtxo: {
899
- value: 1337,
900
- script: payments.p2sh({
901
- redeem: payments.p2wsh({
902
- redeem: { output: Buffer.from([0x51]) },
903
- }),
904
- }).output!,
905
- },
906
- redeemScript: payments.p2wsh({
907
- redeem: { output: Buffer.from([0x51]) },
908
- }).output!,
909
- });
910
-
911
- assert.throws(() => {
912
- psbt.inputHasPubkey(0, Buffer.from([]));
913
- }, new RegExp('scriptPubkey or redeemScript is P2WSH but witnessScript missing'));
914
-
915
- psbt.updateInput(0, {
916
- witnessScript: Buffer.from([0x51]),
917
- });
918
-
919
- assert.doesNotThrow(() => {
920
- psbt.inputHasPubkey(0, Buffer.from([0x51]));
921
- });
922
- });
923
- });
924
-
925
- describe('outputHasHDKey', () => {
926
- it('should return true if HD key is present', () => {
927
- const root = bip32.fromSeed(crypto.randomBytes(32));
928
- const root2 = bip32.fromSeed(crypto.randomBytes(32));
929
- const path = "m/0'/0";
930
- const psbt = new Psbt();
931
- psbt.addInput({
932
- hash: '0000000000000000000000000000000000000000000000000000000000000000',
933
- index: 0,
934
- }).addOutput({
935
- script: Buffer.from(
936
- '0014000102030405060708090a0b0c0d0e0f00010203',
937
- 'hex',
938
- ),
939
- value: 2000,
940
- bip32Derivation: [
941
- {
942
- masterFingerprint: root.fingerprint,
943
- path,
944
- pubkey: root.derivePath(path).publicKey,
945
- },
946
- ],
947
- });
948
- assert.strictEqual(psbt.outputHasHDKey(0, root), true);
949
- assert.strictEqual(psbt.outputHasHDKey(0, root2), false);
950
- });
951
- });
952
-
953
- describe('outputHasPubkey', () => {
954
- it('should throw', () => {
955
- const psbt = new Psbt();
956
- psbt.addInput({
957
- hash: '0000000000000000000000000000000000000000000000000000000000000000',
958
- index: 0,
959
- }).addOutput({
960
- script: payments.p2sh({
961
- redeem: { output: Buffer.from([0x51]) },
962
- }).output!,
963
- value: 1337,
964
- });
965
-
966
- assert.throws(() => {
967
- psbt.outputHasPubkey(0, Buffer.from([]));
968
- }, new RegExp('scriptPubkey is P2SH but redeemScript missing'));
969
-
970
- (psbt as any).__CACHE.__TX.outs[0].script = payments.p2wsh({
971
- redeem: { output: Buffer.from([0x51]) },
972
- }).output!;
973
-
974
- assert.throws(() => {
975
- psbt.outputHasPubkey(0, Buffer.from([]));
976
- }, new RegExp('scriptPubkey or redeemScript is P2WSH but witnessScript missing'));
977
-
978
- (psbt as any).__CACHE.__TX.outs[0].script = payments.p2sh({
979
- redeem: payments.p2wsh({
980
- redeem: { output: Buffer.from([0x51]) },
981
- }),
982
- }).output!;
983
-
984
- psbt.updateOutput(0, {
985
- redeemScript: payments.p2wsh({
986
- redeem: { output: Buffer.from([0x51]) },
987
- }).output!,
988
- });
989
-
990
- assert.throws(() => {
991
- psbt.outputHasPubkey(0, Buffer.from([]));
992
- }, new RegExp('scriptPubkey or redeemScript is P2WSH but witnessScript missing'));
993
-
994
- delete psbt.data.outputs[0].redeemScript;
995
-
996
- psbt.updateOutput(0, {
997
- witnessScript: Buffer.from([0x51]),
998
- });
999
-
1000
- assert.throws(() => {
1001
- psbt.outputHasPubkey(0, Buffer.from([]));
1002
- }, new RegExp('scriptPubkey is P2SH but redeemScript missing'));
1003
-
1004
- psbt.updateOutput(0, {
1005
- redeemScript: payments.p2wsh({
1006
- redeem: { output: Buffer.from([0x51]) },
1007
- }).output!,
1008
- });
1009
-
1010
- assert.doesNotThrow(() => {
1011
- psbt.outputHasPubkey(0, Buffer.from([0x51]));
1012
- });
1013
- });
1014
- });
1015
-
1016
- describe('clone', () => {
1017
- it('Should clone a psbt exactly with no reference', () => {
1018
- const f = fixtures.clone;
1019
- const psbt = Psbt.fromBase64(f.psbt);
1020
- const notAClone = Object.assign(new Psbt(), psbt); // references still active
1021
- const clone = psbt.clone();
1022
-
1023
- assert.strictEqual(
1024
- psbt.validateSignaturesOfAllInputs(validator),
1025
- true,
1026
- );
1027
-
1028
- assert.strictEqual(clone.toBase64(), psbt.toBase64());
1029
- assert.strictEqual(clone.toBase64(), notAClone.toBase64());
1030
- assert.strictEqual(psbt.toBase64(), notAClone.toBase64());
1031
- (psbt as any).__CACHE.__TX.version |= 0xff0000;
1032
- assert.notStrictEqual(clone.toBase64(), psbt.toBase64());
1033
- assert.notStrictEqual(clone.toBase64(), notAClone.toBase64());
1034
- assert.strictEqual(psbt.toBase64(), notAClone.toBase64());
1035
- });
1036
- });
1037
-
1038
- describe('setMaximumFeeRate', () => {
1039
- it('Sets the maximumFeeRate value', () => {
1040
- const psbt = new Psbt();
1041
-
1042
- assert.strictEqual((psbt as any).opts.maximumFeeRate, 5000);
1043
- psbt.setMaximumFeeRate(6000);
1044
- assert.strictEqual((psbt as any).opts.maximumFeeRate, 6000);
1045
- });
1046
- });
1047
-
1048
- describe('validateSignaturesOfInput', () => {
1049
- const f = fixtures.validateSignaturesOfInput;
1050
- it('Correctly validates a signature', () => {
1051
- const psbt = Psbt.fromBase64(f.psbt);
1052
-
1053
- assert.strictEqual(
1054
- psbt.validateSignaturesOfInput(f.index, validator),
1055
- true,
1056
- );
1057
- assert.throws(() => {
1058
- psbt.validateSignaturesOfInput(f.nonExistantIndex, validator);
1059
- }, new RegExp('No signatures to validate'));
1060
- });
1061
-
1062
- it('Correctly validates a signature against a pubkey', () => {
1063
- const psbt = Psbt.fromBase64(f.psbt);
1064
- assert.strictEqual(
1065
- psbt.validateSignaturesOfInput(
1066
- f.index,
1067
- validator,
1068
- f.pubkey as any,
1069
- ),
1070
- true,
1071
- );
1072
- assert.throws(() => {
1073
- psbt.validateSignaturesOfInput(
1074
- f.index,
1075
- validator,
1076
- f.incorrectPubkey as any,
1077
- );
1078
- }, new RegExp('No signatures for this pubkey'));
1079
- });
1080
- });
1081
-
1082
- describe('validateSignaturesOfTapKeyInput', () => {
1083
- const f = fixtures.validateSignaturesOfTapKeyInput;
1084
- it('Correctly validates all signatures', () => {
1085
- initEccLib(ecc);
1086
- const psbt = Psbt.fromBase64(f.psbt);
1087
- assert.strictEqual(
1088
- psbt.validateSignaturesOfInput(f.index, schnorrValidator),
1089
- true,
1090
- );
1091
- });
1092
-
1093
- it('Correctly validates a signature against a pubkey', () => {
1094
- initEccLib(ecc);
1095
- const psbt = Psbt.fromBase64(f.psbt);
1096
- assert.strictEqual(
1097
- psbt.validateSignaturesOfInput(
1098
- f.index,
1099
- schnorrValidator,
1100
- f.pubkey as any,
1101
- ),
1102
- true,
1103
- );
1104
- assert.throws(() => {
1105
- psbt.validateSignaturesOfInput(
1106
- f.index,
1107
- schnorrValidator,
1108
- f.incorrectPubkey as any,
1109
- );
1110
- }, new RegExp('No signatures for this pubkey'));
1111
- });
1112
- });
1113
-
1114
- describe('validateSignaturesOfTapScriptInput', () => {
1115
- const f = fixtures.validateSignaturesOfTapScriptInput;
1116
- it('Correctly validates all signatures', () => {
1117
- initEccLib(ecc);
1118
- const psbt = Psbt.fromBase64(f.psbt);
1119
- assert.strictEqual(
1120
- psbt.validateSignaturesOfInput(f.index, schnorrValidator),
1121
- true,
1122
- );
1123
- });
1124
-
1125
- it('Correctly validates a signature against a pubkey', () => {
1126
- initEccLib(ecc);
1127
- const psbt = Psbt.fromBase64(f.psbt);
1128
- assert.strictEqual(
1129
- psbt.validateSignaturesOfInput(
1130
- f.index,
1131
- schnorrValidator,
1132
- f.pubkey as any,
1133
- ),
1134
- true,
1135
- );
1136
- assert.throws(() => {
1137
- psbt.validateSignaturesOfInput(
1138
- f.index,
1139
- schnorrValidator,
1140
- f.incorrectPubkey as any,
1141
- );
1142
- }, new RegExp('No signatures for this pubkey'));
1143
- });
1144
- });
1145
-
1146
- describe('tapTreeToList/tapTreeFromList', () => {
1147
- it('Correctly converts a Taptree to a Tapleaf list and back', () => {
1148
- taprootFixtures.valid
1149
- .filter(f => f.arguments.scriptTree)
1150
- .map(f => f.arguments.scriptTree)
1151
- .forEach(scriptTree => {
1152
- const originalTree = convertScriptTree(
1153
- scriptTree,
1154
- LEAF_VERSION_TAPSCRIPT,
1155
- );
1156
- const list = tapTreeToList(originalTree);
1157
- const treeFromList = tapTreeFromList(list);
1158
-
1159
- assert.deepStrictEqual(treeFromList, originalTree);
1160
- });
1161
- });
1162
-
1163
- it('Throws if too many leaves on a given level', () => {
1164
- const list = Array.from({ length: 5 }).map(() => ({
1165
- depth: 2,
1166
- leafVersion: LEAF_VERSION_TAPSCRIPT,
1167
- script: Buffer.from([]),
1168
- }));
1169
- assert.throws(() => {
1170
- tapTreeFromList(list);
1171
- }, new RegExp('No room left to insert tapleaf in tree'));
1172
- });
1173
-
1174
- it('Throws if taptree depth is exceeded', () => {
1175
- let tree: Taptree = [
1176
- { output: Buffer.from([]) },
1177
- { output: Buffer.from([]) },
1178
- ];
1179
- Array.from({ length: 129 }).forEach(
1180
- () => (tree = [tree, { output: Buffer.from([]) }]),
1181
- );
1182
- assert.throws(() => {
1183
- tapTreeToList(tree as Taptree);
1184
- }, new RegExp('Max taptree depth exceeded.'));
1185
- });
1186
-
1187
- it('Throws if tapleaf depth is to high', () => {
1188
- const list = [
1189
- {
1190
- depth: 129,
1191
- leafVersion: LEAF_VERSION_TAPSCRIPT,
1192
- script: Buffer.from([]),
1193
- },
1194
- ];
1195
- assert.throws(() => {
1196
- tapTreeFromList(list);
1197
- }, new RegExp('Max taptree depth exceeded.'));
1198
- });
1199
-
1200
- it('Throws if not a valid taptree structure', () => {
1201
- const tree = Array.from({ length: 3 }).map(() => ({
1202
- output: Buffer.from([]),
1203
- }));
1204
-
1205
- assert.throws(() => {
1206
- tapTreeToList(tree as Taptree);
1207
- }, new RegExp('Cannot convert taptree to tapleaf list. Expecting a tapree structure.'));
1208
- });
1209
- });
1210
-
1211
- describe('getFeeRate', () => {
1212
- it('Throws error if called before inputs are finalized', () => {
1213
- const f = fixtures.getFeeRate;
1214
- const psbt = Psbt.fromBase64(f.psbt);
1215
-
1216
- assert.throws(() => {
1217
- psbt.getFeeRate();
1218
- }, new RegExp('PSBT must be finalized to calculate fee rate'));
1219
-
1220
- psbt.finalizeAllInputs();
1221
-
1222
- assert.strictEqual(psbt.getFeeRate(), f.fee);
1223
- (psbt as any).__CACHE.__FEE_RATE = undefined;
1224
- assert.strictEqual(psbt.getFeeRate(), f.fee);
1225
- });
1226
- });
1227
-
1228
- describe('create 1-to-1 transaction', () => {
1229
- const alice = ECPair.fromWIF(
1230
- 'L2uPYXe17xSTqbCjZvL2DsyXPCbXspvcu5mHLDYUgzdUbZGSKrSr',
1231
- );
1232
- const psbt = new Psbt();
1233
- psbt.addInput({
1234
- hash: '7d067b4a697a09d2c3cff7d4d9506c9955e93bff41bf82d439da7d030382bc3e',
1235
- index: 0,
1236
- nonWitnessUtxo: Buffer.from(
1237
- '0200000001f9f34e95b9d5c8abcd20fc5bd4a825d1517be62f0f775e5f36da944d9' +
1238
- '452e550000000006b483045022100c86e9a111afc90f64b4904bd609e9eaed80d48' +
1239
- 'ca17c162b1aca0a788ac3526f002207bb79b60d4fc6526329bf18a77135dc566020' +
1240
- '9e761da46e1c2f1152ec013215801210211755115eabf846720f5cb18f248666fec' +
1241
- '631e5e1e66009ce3710ceea5b1ad13ffffffff01905f0100000000001976a9148bb' +
1242
- 'c95d2709c71607c60ee3f097c1217482f518d88ac00000000',
1243
- 'hex',
1244
- ),
1245
- sighashType: 1,
1246
- });
1247
- psbt.addOutput({
1248
- address: '1KRMKfeZcmosxALVYESdPNez1AP1mEtywp',
1249
- value: 80000,
1250
- });
1251
- psbt.signInput(0, alice);
1252
- assert.throws(() => {
1253
- psbt.setVersion(3);
1254
- }, new RegExp('Can not modify transaction, signatures exist.'));
1255
- psbt.validateSignaturesOfInput(0, validator);
1256
- psbt.finalizeAllInputs();
1257
- assert.throws(() => {
1258
- psbt.setVersion(3);
1259
- }, new RegExp('Can not modify transaction, signatures exist.'));
1260
- assert.strictEqual(psbt.inputHasPubkey(0, alice.publicKey), true);
1261
- assert.strictEqual(psbt.outputHasPubkey(0, alice.publicKey), false);
1262
- assert.strictEqual(
1263
- psbt.extractTransaction().toHex(),
1264
- '02000000013ebc8203037dda39d482bf41ff3be955996c50d9d4f7cfc3d2097a694a7' +
1265
- 'b067d000000006b483045022100931b6db94aed25d5486884d83fc37160f37f3368c0' +
1266
- 'd7f48c757112abefec983802205fda64cff98c849577026eb2ce916a50ea70626a766' +
1267
- '9f8596dd89b720a26b4d501210365db9da3f8a260078a7e8f8b708a1161468fb2323f' +
1268
- 'fda5ec16b261ec1056f455ffffffff0180380100000000001976a914ca0d36044e0dc' +
1269
- '08a22724efa6f6a07b0ec4c79aa88ac00000000',
1270
- );
1271
- });
1272
-
1273
- describe('Method return types', () => {
1274
- it('fromBuffer returns Psbt type (not base class)', () => {
1275
- const psbt = Psbt.fromBuffer(
1276
- Buffer.from(
1277
- '70736274ff01000a01000000000000000000000000',
1278
- 'hex', // cHNidP8BAAoBAAAAAAAAAAAAAAAA
1279
- ),
1280
- );
1281
- assert.strictEqual(psbt instanceof Psbt, true);
1282
- assert.ok((psbt as any).__CACHE.__TX);
1283
- });
1284
- it('fromBase64 returns Psbt type (not base class)', () => {
1285
- const psbt = Psbt.fromBase64('cHNidP8BAAoBAAAAAAAAAAAAAAAA');
1286
- assert.strictEqual(psbt instanceof Psbt, true);
1287
- assert.ok((psbt as any).__CACHE.__TX);
1288
- });
1289
- it('fromHex returns Psbt type (not base class)', () => {
1290
- const psbt = Psbt.fromHex(
1291
- '70736274ff01000a01000000000000000000000000',
1292
- );
1293
- assert.strictEqual(psbt instanceof Psbt, true);
1294
- assert.ok((psbt as any).__CACHE.__TX);
1295
- });
1296
- });
1297
-
1298
- describe('Cache', () => {
1299
- it('non-witness UTXOs are cached', () => {
1300
- const f = fixtures.cache.nonWitnessUtxo;
1301
- const psbt = Psbt.fromBase64(f.psbt);
1302
- const index = f.inputIndex;
1303
-
1304
- // Cache is empty
1305
- assert.strictEqual(
1306
- (psbt as any).__CACHE.__NON_WITNESS_UTXO_BUF_CACHE[index],
1307
- undefined,
1308
- );
1309
-
1310
- // Cache is populated
1311
- psbt.updateInput(index, {
1312
- nonWitnessUtxo: f.nonWitnessUtxo as any,
1313
- });
1314
- const value = psbt.data.inputs[index].nonWitnessUtxo;
1315
- assert.ok(
1316
- (psbt as any).__CACHE.__NON_WITNESS_UTXO_BUF_CACHE[
1317
- index
1318
- ].equals(value),
1319
- );
1320
- assert.ok(
1321
- (psbt as any).__CACHE.__NON_WITNESS_UTXO_BUF_CACHE[
1322
- index
1323
- ].equals(f.nonWitnessUtxo),
1324
- );
1325
-
1326
- // Cache is rebuilt from internal transaction object when cleared
1327
- psbt.data.inputs[index].nonWitnessUtxo = Buffer.from([1, 2, 3]);
1328
- (psbt as any).__CACHE.__NON_WITNESS_UTXO_BUF_CACHE[index] =
1329
- undefined;
1330
- assert.ok(
1331
- (psbt as any).data.inputs[index].nonWitnessUtxo.equals(value),
1332
- );
1333
- });
1334
- });
1335
-
1336
- describe('Transaction properties', () => {
1337
- it('.version is exposed and is settable', () => {
1338
- const psbt = new Psbt();
1339
-
1340
- assert.strictEqual(psbt.version, 2);
1341
- assert.strictEqual(
1342
- psbt.version,
1343
- (psbt as any).__CACHE.__TX.version,
1344
- );
1345
-
1346
- psbt.version = 1;
1347
- assert.strictEqual(psbt.version, 1);
1348
- assert.strictEqual(
1349
- psbt.version,
1350
- (psbt as any).__CACHE.__TX.version,
1351
- );
1352
- });
1353
-
1354
- it('.locktime is exposed and is settable', () => {
1355
- const psbt = new Psbt();
1356
-
1357
- assert.strictEqual(psbt.locktime, 0);
1358
- assert.strictEqual(
1359
- psbt.locktime,
1360
- (psbt as any).__CACHE.__TX.locktime,
1361
- );
1362
-
1363
- psbt.locktime = 123;
1364
- assert.strictEqual(psbt.locktime, 123);
1365
- assert.strictEqual(
1366
- psbt.locktime,
1367
- (psbt as any).__CACHE.__TX.locktime,
1368
- );
1369
- });
1370
-
1371
- it('.txInputs is exposed as a readonly clone', () => {
1372
- const psbt = new Psbt();
1373
- const hash = Buffer.alloc(32);
1374
- const index = 0;
1375
- psbt.addInput({ hash, index });
1376
-
1377
- const input = psbt.txInputs[0];
1378
- const internalInput = (psbt as any).__CACHE.__TX.ins[0];
1379
-
1380
- assert.ok(input.hash.equals(internalInput.hash));
1381
- assert.strictEqual(input.index, internalInput.index);
1382
- assert.strictEqual(input.sequence, internalInput.sequence);
1383
-
1384
- input.hash[0] = 123;
1385
- input.index = 123;
1386
- input.sequence = 123;
1387
-
1388
- assert.ok(!input.hash.equals(internalInput.hash));
1389
- assert.notEqual(input.index, internalInput.index);
1390
- assert.notEqual(input.sequence, internalInput.sequence);
1391
- });
1392
-
1393
- it('.txOutputs is exposed as a readonly clone', () => {
1394
- const psbt = new Psbt();
1395
- const address = '1LukeQU5jwebXbMLDVydeH4vFSobRV9rkj';
1396
- const value = 100000;
1397
- psbt.addOutput({ address, value });
1398
-
1399
- const output = psbt.txOutputs[0];
1400
- const internalInput = (psbt as any).__CACHE.__TX.outs[0];
1401
-
1402
- assert.strictEqual(output.address, address);
1403
-
1404
- assert.ok(output.script.equals(internalInput.script));
1405
- assert.strictEqual(output.value, internalInput.value);
1406
-
1407
- output.script[0] = 123;
1408
- output.value = 123;
1409
-
1410
- assert.ok(!output.script.equals(internalInput.script));
1411
- assert.notEqual(output.value, internalInput.value);
1412
- });
1413
- });
1414
- });
1
+ import assert from 'assert';
2
+ import { BIP32Factory } from 'bip32';
3
+ import * as ecc from 'tiny-secp256k1';
4
+ import * as crypto from 'crypto';
5
+ import { ECPairFactory } from 'ecpair';
6
+ import { describe, it } from 'mocha';
7
+
8
+ import { convertScriptTree } from './payments.utils.js';
9
+ import { LEAF_VERSION_TAPSCRIPT } from '../src/payments/bip341.js';
10
+ import { tapTreeFromList, tapTreeToList } from '../src/psbt/bip371.js';
11
+ import { Taptree } from '../src/types.js';
12
+ import {
13
+ initEccLib,
14
+ networks as NETWORKS,
15
+ payments,
16
+ Psbt,
17
+ Signer,
18
+ SignerAsync,
19
+ } from '../src/index.js';
20
+
21
+ import preFixtures from './fixtures/psbt.json' with { type: 'json' };
22
+ import taprootFixtures from './fixtures/p2tr.json' with { type: 'json' };
23
+
24
+ const bip32 = BIP32Factory(ecc);
25
+ const ECPair = ECPairFactory(ecc);
26
+
27
+ const validator = (pubkey: Buffer, msghash: Buffer, signature: Buffer): boolean =>
28
+ ECPair.fromPublicKey(pubkey).verify(msghash, signature);
29
+
30
+ const schnorrValidator = (pubkey: Buffer, msghash: Buffer, signature: Buffer): boolean =>
31
+ ecc.verifySchnorr(msghash, pubkey, signature);
32
+
33
+ const initBuffers = (object: any): typeof preFixtures =>
34
+ JSON.parse(JSON.stringify(object), (_, value) => {
35
+ const regex = new RegExp(/^Buffer.from\(['"](.*)['"], ['"](.*)['"]\)$/);
36
+ const result = regex.exec(value);
37
+ if (!result) return value;
38
+
39
+ const data = result[1];
40
+ const encoding = result[2];
41
+
42
+ return Buffer.from(data, encoding as BufferEncoding);
43
+ });
44
+
45
+ const fixtures = initBuffers(preFixtures);
46
+
47
+ const upperCaseFirstLetter = (str: string): string => str.replace(/^./, (s) => s.toUpperCase());
48
+
49
+ const toAsyncSigner = (signer: Signer): SignerAsync => {
50
+ return {
51
+ publicKey: signer.publicKey,
52
+ sign: (hash: Buffer, lowerR: boolean | undefined): Promise<Buffer> => {
53
+ return new Promise((resolve, rejects): void => {
54
+ setTimeout(() => {
55
+ try {
56
+ const r = signer.sign(hash, lowerR);
57
+ resolve(r);
58
+ } catch (e) {
59
+ rejects(e as Error);
60
+ }
61
+ }, 10);
62
+ });
63
+ },
64
+ };
65
+ };
66
+ const failedAsyncSigner = (publicKey: Buffer): SignerAsync => {
67
+ return <SignerAsync>{
68
+ publicKey,
69
+ sign: (__: Buffer): Promise<Buffer> => {
70
+ return new Promise((_, reject): void => {
71
+ setTimeout(() => {
72
+ reject(new Error('sign failed'));
73
+ }, 10);
74
+ });
75
+ },
76
+ };
77
+ };
78
+ // const b = (hex: string) => Buffer.from(hex, 'hex');
79
+
80
+ describe(`Psbt`, () => {
81
+ beforeEach(() => {
82
+ // provide the ECC lib only when required
83
+ initEccLib(undefined);
84
+ });
85
+ describe('BIP174 Test Vectors', () => {
86
+ fixtures.bip174.invalid.forEach((f) => {
87
+ it(`Invalid: ${f.description}`, () => {
88
+ assert.throws(() => {
89
+ Psbt.fromBase64(f.psbt);
90
+ }, new RegExp(f.errorMessage));
91
+ });
92
+ });
93
+
94
+ fixtures.bip174.valid.forEach((f) => {
95
+ it(`Valid: ${f.description}`, () => {
96
+ assert.doesNotThrow(() => {
97
+ Psbt.fromBase64(f.psbt);
98
+ });
99
+ });
100
+ });
101
+
102
+ fixtures.bip174.failSignChecks.forEach((f) => {
103
+ const keyPair = ECPair.makeRandom();
104
+ it(`Fails Signer checks: ${f.description}`, () => {
105
+ const psbt = Psbt.fromBase64(f.psbt);
106
+ assert.throws(() => {
107
+ psbt.signInput(f.inputToCheck, keyPair);
108
+ }, new RegExp(f.errorMessage));
109
+ });
110
+ });
111
+
112
+ fixtures.bip174.creator.forEach((f) => {
113
+ it('Creates expected PSBT', () => {
114
+ const psbt = new Psbt();
115
+ for (const input of f.inputs) {
116
+ psbt.addInput(input);
117
+ }
118
+ for (const output of f.outputs) {
119
+ const script = Buffer.from(output.script, 'hex');
120
+ psbt.addOutput({ ...output, script });
121
+ }
122
+ assert.strictEqual(psbt.toBase64(), f.result);
123
+ });
124
+ });
125
+
126
+ fixtures.bip174.updater.forEach((f) => {
127
+ it('Updates PSBT to the expected result', () => {
128
+ if (f.isTaproot) initEccLib(ecc);
129
+ const psbt = Psbt.fromBase64(f.psbt);
130
+
131
+ for (const inputOrOutput of ['input', 'output']) {
132
+ const fixtureData = (f as any)[`${inputOrOutput}Data`];
133
+ if (fixtureData) {
134
+ for (const [i, data] of fixtureData.entries()) {
135
+ const txt = upperCaseFirstLetter(inputOrOutput);
136
+ (psbt as any)[`update${txt}`](i, data);
137
+ }
138
+ }
139
+ }
140
+
141
+ assert.strictEqual(psbt.toBase64(), f.result);
142
+ });
143
+ });
144
+
145
+ fixtures.bip174.signer.forEach((f) => {
146
+ it('Signs PSBT to the expected result', () => {
147
+ if (f.isTaproot) initEccLib(ecc);
148
+ const psbt = Psbt.fromBase64(f.psbt);
149
+
150
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
151
+ // @ts-ignore // cannot find tapLeafHashToSign
152
+ f.keys.forEach(({ inputToSign, tapLeafHashToSign, WIF }) => {
153
+ const keyPair = ECPair.fromWIF(WIF, NETWORKS.testnet);
154
+ if (tapLeafHashToSign)
155
+ psbt.signTaprootInput(
156
+ inputToSign,
157
+ keyPair,
158
+ Buffer.from(tapLeafHashToSign, 'hex'),
159
+ );
160
+ else psbt.signInput(inputToSign, keyPair);
161
+ });
162
+
163
+ assert.strictEqual(psbt.toBase64(), f.result);
164
+ });
165
+ });
166
+
167
+ fixtures.bip174.combiner.forEach((f) => {
168
+ it('Combines two PSBTs to the expected result', () => {
169
+ const psbts = f.psbts.map((psbt) => Psbt.fromBase64(psbt));
170
+
171
+ psbts[0].combine(psbts[1]);
172
+
173
+ // Produces a different Base64 string due to implemetation specific key-value ordering.
174
+ // That means this test will fail:
175
+ // assert.strictEqual(psbts[0].toBase64(), f.result)
176
+ // However, if we compare the actual PSBT properties we can see they are logically identical:
177
+ assert.deepStrictEqual(psbts[0], Psbt.fromBase64(f.result));
178
+ });
179
+ });
180
+
181
+ fixtures.bip174.finalizer.forEach((f) => {
182
+ it('Finalizes inputs and gives the expected PSBT', () => {
183
+ if (f.isTaproot) initEccLib(ecc);
184
+ const psbt = Psbt.fromBase64(f.psbt);
185
+
186
+ psbt.finalizeAllInputs();
187
+
188
+ assert.strictEqual(psbt.toBase64(), f.result);
189
+ });
190
+ });
191
+
192
+ fixtures.bip174.extractor.forEach((f) => {
193
+ it('Extracts the expected transaction from a PSBT', () => {
194
+ const psbt1 = Psbt.fromBase64(f.psbt);
195
+ const transaction1 = psbt1.extractTransaction(true).toHex();
196
+
197
+ const psbt2 = Psbt.fromBase64(f.psbt);
198
+ const transaction2 = psbt2.extractTransaction().toHex();
199
+
200
+ assert.strictEqual(transaction1, transaction2);
201
+ assert.strictEqual(transaction1, f.transaction);
202
+
203
+ const psbt3 = Psbt.fromBase64(f.psbt);
204
+ delete psbt3.data.inputs[0].finalScriptSig;
205
+ delete psbt3.data.inputs[0].finalScriptWitness;
206
+ assert.throws(() => {
207
+ psbt3.extractTransaction();
208
+ }, new RegExp('Not finalized'));
209
+
210
+ const psbt4 = Psbt.fromBase64(f.psbt);
211
+ psbt4.setMaximumFeeRate(1);
212
+ assert.throws(() => {
213
+ psbt4.extractTransaction();
214
+ }, new RegExp('Warning: You are paying around [\\d.]+ in fees'));
215
+
216
+ const psbt5 = Psbt.fromBase64(f.psbt);
217
+ psbt5.extractTransaction(true);
218
+ const fr1 = psbt5.getFeeRate();
219
+ const fr2 = psbt5.getFeeRate();
220
+ assert.strictEqual(fr1, fr2);
221
+
222
+ const psbt6 = Psbt.fromBase64(f.psbt);
223
+ const f1 = psbt6.getFee();
224
+ const f2 = psbt6.getFee();
225
+ assert.strictEqual(f1, f2);
226
+ });
227
+ });
228
+ });
229
+
230
+ describe('signInputAsync', () => {
231
+ fixtures.signInput.checks.forEach((f) => {
232
+ it(f.description, async () => {
233
+ if (f.isTaproot) initEccLib(ecc);
234
+ if (f.shouldSign) {
235
+ const psbtThatShouldsign = Psbt.fromBase64(f.shouldSign.psbt);
236
+ await assert.doesNotReject(async () => {
237
+ await psbtThatShouldsign.signInputAsync(
238
+ f.shouldSign.inputToCheck,
239
+ ECPair.fromWIF(f.shouldSign.WIF),
240
+ f.shouldSign.sighashTypes || undefined,
241
+ );
242
+ if (f.shouldSign.result) {
243
+ assert.strictEqual(psbtThatShouldsign.toBase64(), f.shouldSign.result);
244
+ }
245
+ });
246
+ const failMessage = f.isTaproot
247
+ ? /Need Schnorr Signer to sign taproot input #0./
248
+ : /sign failed/;
249
+ await assert.rejects(async () => {
250
+ await psbtThatShouldsign.signInputAsync(
251
+ f.shouldSign.inputToCheck,
252
+ failedAsyncSigner(ECPair.fromWIF(f.shouldSign.WIF).publicKey),
253
+ f.shouldSign.sighashTypes || undefined,
254
+ );
255
+ }, failMessage);
256
+ }
257
+
258
+ if (f.shouldThrow) {
259
+ const psbtThatShouldThrow = Psbt.fromBase64(f.shouldThrow.psbt);
260
+ await assert.rejects(async () => {
261
+ await psbtThatShouldThrow.signInputAsync(
262
+ f.shouldThrow.inputToCheck,
263
+ ECPair.fromWIF(f.shouldThrow.WIF),
264
+ (f.shouldThrow as any).sighashTypes || undefined,
265
+ );
266
+ }, new RegExp(f.shouldThrow.errorMessage));
267
+ await assert.rejects(async () => {
268
+ await psbtThatShouldThrow.signInputAsync(
269
+ f.shouldThrow.inputToCheck,
270
+ toAsyncSigner(ECPair.fromWIF(f.shouldThrow.WIF)),
271
+ (f.shouldThrow as any).sighashTypes || undefined,
272
+ );
273
+ }, new RegExp(f.shouldThrow.errorMessage));
274
+ await assert.rejects(async () => {
275
+ await (psbtThatShouldThrow.signInputAsync as any)(
276
+ f.shouldThrow.inputToCheck,
277
+ );
278
+ }, new RegExp('Need Signer to sign input'));
279
+ }
280
+ });
281
+ });
282
+ });
283
+
284
+ describe('signInput', () => {
285
+ fixtures.signInput.checks.forEach((f) => {
286
+ it(f.description, () => {
287
+ if (f.isTaproot) initEccLib(ecc);
288
+ if (f.shouldSign) {
289
+ const psbtThatShouldsign = Psbt.fromBase64(f.shouldSign.psbt);
290
+ assert.doesNotThrow(() => {
291
+ psbtThatShouldsign.signInput(
292
+ f.shouldSign.inputToCheck,
293
+ ECPair.fromWIF(f.shouldSign.WIF),
294
+ f.shouldSign.sighashTypes || undefined,
295
+ );
296
+ });
297
+ }
298
+
299
+ if (f.shouldThrow) {
300
+ const psbtThatShouldThrow = Psbt.fromBase64(f.shouldThrow.psbt);
301
+ assert.throws(() => {
302
+ psbtThatShouldThrow.signInput(
303
+ f.shouldThrow.inputToCheck,
304
+ ECPair.fromWIF(f.shouldThrow.WIF),
305
+ (f.shouldThrow as any).sighashTypes || undefined,
306
+ );
307
+ }, new RegExp(f.shouldThrow.errorMessage));
308
+ assert.throws(() => {
309
+ (psbtThatShouldThrow.signInput as any)(f.shouldThrow.inputToCheck);
310
+ }, new RegExp('Need Signer to sign input'));
311
+ }
312
+ });
313
+ });
314
+ });
315
+
316
+ describe('signAllInputsAsync', () => {
317
+ fixtures.signInput.checks.forEach((f) => {
318
+ if (f.description === 'checks the input exists') return;
319
+ it(f.description, async () => {
320
+ if (f.isTaproot) initEccLib(ecc);
321
+ if (f.shouldSign) {
322
+ const psbtThatShouldsign = Psbt.fromBase64(f.shouldSign.psbt);
323
+ await assert.doesNotReject(async () => {
324
+ await psbtThatShouldsign.signAllInputsAsync(
325
+ ECPair.fromWIF(f.shouldSign.WIF),
326
+ f.shouldSign.sighashTypes || undefined,
327
+ );
328
+ });
329
+ }
330
+
331
+ if (f.shouldThrow) {
332
+ const psbtThatShouldThrow = Psbt.fromBase64(f.shouldThrow.psbt);
333
+ await assert.rejects(async () => {
334
+ await psbtThatShouldThrow.signAllInputsAsync(
335
+ ECPair.fromWIF(f.shouldThrow.WIF),
336
+ (f.shouldThrow as any).sighashTypes || undefined,
337
+ );
338
+ }, new RegExp('No inputs were signed'));
339
+ await assert.rejects(async () => {
340
+ await (psbtThatShouldThrow.signAllInputsAsync as any)();
341
+ }, new RegExp('Need Signer to sign input'));
342
+ }
343
+ });
344
+ });
345
+ });
346
+
347
+ describe('signAllInputs', () => {
348
+ fixtures.signInput.checks.forEach((f) => {
349
+ if (f.description === 'checks the input exists') return;
350
+ it(f.description, () => {
351
+ if (f.isTaproot) initEccLib(ecc);
352
+ if (f.shouldSign) {
353
+ const psbtThatShouldsign = Psbt.fromBase64(f.shouldSign.psbt);
354
+ assert.doesNotThrow(() => {
355
+ psbtThatShouldsign.signAllInputs(
356
+ ECPair.fromWIF(f.shouldSign.WIF),
357
+ f.shouldSign.sighashTypes || undefined,
358
+ );
359
+ });
360
+ }
361
+
362
+ if (f.shouldThrow) {
363
+ const psbtThatShouldThrow = Psbt.fromBase64(f.shouldThrow.psbt);
364
+ assert.throws(() => {
365
+ psbtThatShouldThrow.signAllInputs(
366
+ ECPair.fromWIF(f.shouldThrow.WIF),
367
+ (f.shouldThrow as any).sighashTypes || undefined,
368
+ );
369
+ }, new RegExp('No inputs were signed'));
370
+ assert.throws(() => {
371
+ (psbtThatShouldThrow.signAllInputs as any)();
372
+ }, new RegExp('Need Signer to sign input'));
373
+ }
374
+ });
375
+ });
376
+ });
377
+
378
+ describe('signInputHDAsync', () => {
379
+ fixtures.signInputHD.checks.forEach((f) => {
380
+ it(f.description, async () => {
381
+ if (f.shouldSign) {
382
+ const psbtThatShouldsign = Psbt.fromBase64(f.shouldSign.psbt);
383
+ await assert.doesNotReject(async () => {
384
+ await psbtThatShouldsign.signInputHDAsync(
385
+ f.shouldSign.inputToCheck,
386
+ bip32.fromBase58(f.shouldSign.xprv),
387
+ (f.shouldSign as any).sighashTypes || undefined,
388
+ );
389
+ });
390
+ }
391
+
392
+ if (f.shouldThrow) {
393
+ const psbtThatShouldThrow = Psbt.fromBase64(f.shouldThrow.psbt);
394
+ await assert.rejects(async () => {
395
+ await psbtThatShouldThrow.signInputHDAsync(
396
+ f.shouldThrow.inputToCheck,
397
+ bip32.fromBase58(f.shouldThrow.xprv),
398
+ (f.shouldThrow as any).sighashTypes || undefined,
399
+ );
400
+ }, new RegExp(f.shouldThrow.errorMessage));
401
+ await assert.rejects(async () => {
402
+ await (psbtThatShouldThrow.signInputHDAsync as any)(
403
+ f.shouldThrow.inputToCheck,
404
+ );
405
+ }, new RegExp('Need HDSigner to sign input'));
406
+ }
407
+ });
408
+ });
409
+ });
410
+
411
+ describe('signInputHD', () => {
412
+ fixtures.signInputHD.checks.forEach((f) => {
413
+ it(f.description, () => {
414
+ if (f.shouldSign) {
415
+ const psbtThatShouldsign = Psbt.fromBase64(f.shouldSign.psbt);
416
+ assert.doesNotThrow(() => {
417
+ psbtThatShouldsign.signInputHD(
418
+ f.shouldSign.inputToCheck,
419
+ bip32.fromBase58(f.shouldSign.xprv),
420
+ (f.shouldSign as any).sighashTypes || undefined,
421
+ );
422
+ });
423
+ }
424
+
425
+ if (f.shouldThrow) {
426
+ const psbtThatShouldThrow = Psbt.fromBase64(f.shouldThrow.psbt);
427
+ assert.throws(() => {
428
+ psbtThatShouldThrow.signInputHD(
429
+ f.shouldThrow.inputToCheck,
430
+ bip32.fromBase58(f.shouldThrow.xprv),
431
+ (f.shouldThrow as any).sighashTypes || undefined,
432
+ );
433
+ }, new RegExp(f.shouldThrow.errorMessage));
434
+ assert.throws(() => {
435
+ (psbtThatShouldThrow.signInputHD as any)(f.shouldThrow.inputToCheck);
436
+ }, new RegExp('Need HDSigner to sign input'));
437
+ }
438
+ });
439
+ });
440
+ });
441
+
442
+ describe('signAllInputsHDAsync', () => {
443
+ fixtures.signInputHD.checks.forEach((f) => {
444
+ it(f.description, async () => {
445
+ if (f.shouldSign) {
446
+ const psbtThatShouldsign = Psbt.fromBase64(f.shouldSign.psbt);
447
+ await assert.doesNotReject(async () => {
448
+ await psbtThatShouldsign.signAllInputsHDAsync(
449
+ bip32.fromBase58(f.shouldSign.xprv),
450
+ (f.shouldSign as any).sighashTypes || undefined,
451
+ );
452
+ });
453
+ }
454
+
455
+ if (f.shouldThrow) {
456
+ const psbtThatShouldThrow = Psbt.fromBase64(f.shouldThrow.psbt);
457
+ await assert.rejects(async () => {
458
+ await psbtThatShouldThrow.signAllInputsHDAsync(
459
+ bip32.fromBase58(f.shouldThrow.xprv),
460
+ (f.shouldThrow as any).sighashTypes || undefined,
461
+ );
462
+ }, new RegExp('No inputs were signed'));
463
+ await assert.rejects(async () => {
464
+ await (psbtThatShouldThrow.signAllInputsHDAsync as any)();
465
+ }, new RegExp('Need HDSigner to sign input'));
466
+ }
467
+ });
468
+ });
469
+ });
470
+
471
+ describe('signAllInputsHD', () => {
472
+ fixtures.signInputHD.checks.forEach((f) => {
473
+ it(f.description, () => {
474
+ if (f.shouldSign) {
475
+ const psbtThatShouldsign = Psbt.fromBase64(f.shouldSign.psbt);
476
+ assert.doesNotThrow(() => {
477
+ psbtThatShouldsign.signAllInputsHD(
478
+ bip32.fromBase58(f.shouldSign.xprv),
479
+ (f.shouldSign as any).sighashTypes || undefined,
480
+ );
481
+ });
482
+ }
483
+
484
+ if (f.shouldThrow) {
485
+ const psbtThatShouldThrow = Psbt.fromBase64(f.shouldThrow.psbt);
486
+ assert.throws(() => {
487
+ psbtThatShouldThrow.signAllInputsHD(
488
+ bip32.fromBase58(f.shouldThrow.xprv),
489
+ (f.shouldThrow as any).sighashTypes || undefined,
490
+ );
491
+ }, new RegExp('No inputs were signed'));
492
+ assert.throws(() => {
493
+ (psbtThatShouldThrow.signAllInputsHD as any)();
494
+ }, new RegExp('Need HDSigner to sign input'));
495
+ }
496
+ });
497
+ });
498
+ });
499
+
500
+ describe('finalizeInput', () => {
501
+ it(`Finalizes tapleaf by hash`, () => {
502
+ const f = fixtures.finalizeInput.finalizeTapleafByHash;
503
+ const psbt = Psbt.fromBase64(f.psbt);
504
+
505
+ psbt.finalizeTaprootInput(f.index, Buffer.from(f.leafHash, 'hex'));
506
+
507
+ assert.strictEqual(psbt.toBase64(), f.result);
508
+ });
509
+
510
+ it(`fails if tapleaf hash not found`, () => {
511
+ const f = fixtures.finalizeInput.finalizeTapleafByHash;
512
+ const psbt = Psbt.fromBase64(f.psbt);
513
+
514
+ assert.throws(() => {
515
+ psbt.finalizeTaprootInput(f.index, Buffer.from(f.leafHash, 'hex').reverse());
516
+ }, new RegExp('Can not finalize taproot input #0. Signature for tapleaf script not found.'));
517
+ });
518
+
519
+ it(`fails if trying to finalzie non-taproot input`, () => {
520
+ const psbt = new Psbt();
521
+ psbt.addInput({
522
+ hash: '0000000000000000000000000000000000000000000000000000000000000000',
523
+ index: 0,
524
+ });
525
+
526
+ assert.throws(() => {
527
+ psbt.finalizeTaprootInput(0);
528
+ }, new RegExp('Cannot finalize input #0. Not Taproot.'));
529
+ });
530
+ });
531
+
532
+ describe('finalizeAllInputs', () => {
533
+ fixtures.finalizeAllInputs.forEach((f) => {
534
+ it(`Finalizes inputs of type "${f.type}"`, () => {
535
+ const psbt = Psbt.fromBase64(f.psbt);
536
+
537
+ psbt.finalizeAllInputs();
538
+
539
+ assert.strictEqual(psbt.toBase64(), f.result);
540
+ });
541
+ });
542
+ it('fails if no script found', () => {
543
+ const psbt = new Psbt();
544
+ psbt.addInput({
545
+ hash: '0000000000000000000000000000000000000000000000000000000000000000',
546
+ index: 0,
547
+ });
548
+ assert.throws(() => {
549
+ psbt.finalizeAllInputs();
550
+ }, new RegExp('No script found for input #0'));
551
+ psbt.updateInput(0, {
552
+ witnessUtxo: {
553
+ script: Buffer.from('0014d85c2b71d0060b09c9886aeb815e50991dda124d', 'hex'),
554
+ value: 2e5,
555
+ },
556
+ });
557
+ assert.throws(() => {
558
+ psbt.finalizeAllInputs();
559
+ }, new RegExp('Can not finalize input #0'));
560
+ });
561
+ });
562
+
563
+ describe('addInput', () => {
564
+ fixtures.addInput.checks.forEach((f) => {
565
+ it(f.description, () => {
566
+ const psbt = new Psbt();
567
+
568
+ if (f.exception) {
569
+ assert.throws(() => {
570
+ psbt.addInput(f.inputData as any);
571
+ }, new RegExp(f.exception));
572
+ assert.throws(() => {
573
+ psbt.addInputs([f.inputData as any]);
574
+ }, new RegExp(f.exception));
575
+ } else {
576
+ assert.doesNotThrow(() => {
577
+ psbt.addInputs([f.inputData as any]);
578
+ if (f.equals) {
579
+ assert.strictEqual(psbt.toBase64(), f.equals);
580
+ }
581
+ });
582
+ assert.throws(() => {
583
+ psbt.addInput(f.inputData as any);
584
+ }, new RegExp('Duplicate input detected.'));
585
+ }
586
+ });
587
+ });
588
+ });
589
+
590
+ describe('updateInput', () => {
591
+ fixtures.updateInput.checks.forEach((f) => {
592
+ it(f.description, () => {
593
+ const psbt = Psbt.fromBase64(f.psbt);
594
+
595
+ if (f.exception) {
596
+ assert.throws(() => {
597
+ psbt.updateInput(f.index, f.inputData as any);
598
+ }, new RegExp(f.exception));
599
+ }
600
+ });
601
+ });
602
+ });
603
+
604
+ describe('addOutput', () => {
605
+ fixtures.addOutput.checks.forEach((f) => {
606
+ it(f.description, () => {
607
+ if (f.isTaproot) initEccLib(ecc);
608
+ const psbt = f.psbt ? Psbt.fromBase64(f.psbt) : new Psbt();
609
+
610
+ if (f.exception) {
611
+ assert.throws(() => {
612
+ psbt.addOutput(f.outputData as any);
613
+ }, new RegExp(f.exception));
614
+ assert.throws(() => {
615
+ psbt.addOutputs([f.outputData as any]);
616
+ }, new RegExp(f.exception));
617
+ } else {
618
+ assert.doesNotThrow(() => {
619
+ psbt.addOutput(f.outputData as any);
620
+ });
621
+ if (f.result) {
622
+ assert.strictEqual(psbt.toBase64(), f.result);
623
+ }
624
+ assert.doesNotThrow(() => {
625
+ psbt.addOutputs([f.outputData as any]);
626
+ });
627
+ }
628
+ });
629
+ });
630
+ });
631
+
632
+ describe('setVersion', () => {
633
+ it('Sets the version value of the unsigned transaction', () => {
634
+ const psbt = new Psbt();
635
+
636
+ assert.strictEqual(psbt.extractTransaction().version, 2);
637
+ psbt.setVersion(1);
638
+ assert.strictEqual(psbt.extractTransaction().version, 1);
639
+ });
640
+ });
641
+
642
+ describe('setLocktime', () => {
643
+ it('Sets the nLockTime value of the unsigned transaction', () => {
644
+ const psbt = new Psbt();
645
+
646
+ assert.strictEqual(psbt.extractTransaction().locktime, 0);
647
+ psbt.setLocktime(1);
648
+ assert.strictEqual(psbt.extractTransaction().locktime, 1);
649
+ });
650
+ });
651
+
652
+ describe('setInputSequence', () => {
653
+ it('Sets the sequence number for a given input', () => {
654
+ const psbt = new Psbt();
655
+ psbt.addInput({
656
+ hash: '0000000000000000000000000000000000000000000000000000000000000000',
657
+ index: 0,
658
+ });
659
+
660
+ assert.strictEqual(psbt.inputCount, 1);
661
+ assert.strictEqual(psbt.txInputs[0].sequence, 0xffffffff);
662
+ psbt.setInputSequence(0, 0);
663
+ assert.strictEqual(psbt.txInputs[0].sequence, 0);
664
+ });
665
+
666
+ it('throws if input index is too high', () => {
667
+ const psbt = new Psbt();
668
+ psbt.addInput({
669
+ hash: '0000000000000000000000000000000000000000000000000000000000000000',
670
+ index: 0,
671
+ });
672
+
673
+ assert.throws(() => {
674
+ psbt.setInputSequence(1, 0);
675
+ }, new RegExp('Input index too high'));
676
+ });
677
+ });
678
+
679
+ describe('getInputType', () => {
680
+ const key = ECPair.makeRandom();
681
+ const { publicKey } = key;
682
+ const p2wpkhPub = (pubkey: Buffer): Buffer =>
683
+ payments.p2wpkh({
684
+ pubkey,
685
+ }).output!;
686
+ const p2pkhPub = (pubkey: Buffer): Buffer =>
687
+ payments.p2pkh({
688
+ pubkey,
689
+ }).output!;
690
+ const p2shOut = (output: Buffer): Buffer =>
691
+ payments.p2sh({
692
+ redeem: { output },
693
+ }).output!;
694
+ const p2wshOut = (output: Buffer): Buffer =>
695
+ payments.p2wsh({
696
+ redeem: { output },
697
+ }).output!;
698
+ const p2shp2wshOut = (output: Buffer): Buffer => p2shOut(p2wshOut(output));
699
+ const noOuter = (output: Buffer): Buffer => output;
700
+
701
+ function getInputTypeTest({
702
+ innerScript,
703
+ outerScript,
704
+ redeemGetter,
705
+ witnessGetter,
706
+ expectedType,
707
+ finalize,
708
+ }: any): void {
709
+ const psbt = new Psbt();
710
+ psbt.addInput({
711
+ hash: '0000000000000000000000000000000000000000000000000000000000000000',
712
+ index: 0,
713
+ witnessUtxo: {
714
+ script: outerScript(innerScript(publicKey)),
715
+ value: 2e3,
716
+ },
717
+ ...(redeemGetter ? { redeemScript: redeemGetter(publicKey) } : {}),
718
+ ...(witnessGetter ? { witnessScript: witnessGetter(publicKey) } : {}),
719
+ }).addOutput({
720
+ script: Buffer.from('0014d85c2b71d0060b09c9886aeb815e50991dda124d'),
721
+ value: 1800,
722
+ });
723
+ if (finalize) psbt.signInput(0, key).finalizeInput(0);
724
+ const type = psbt.getInputType(0);
725
+ assert.strictEqual(type, expectedType, 'incorrect input type');
726
+ }
727
+
728
+ [
729
+ {
730
+ innerScript: p2pkhPub,
731
+ outerScript: noOuter,
732
+ redeemGetter: null,
733
+ witnessGetter: null,
734
+ expectedType: 'pubkeyhash',
735
+ },
736
+ {
737
+ innerScript: p2wpkhPub,
738
+ outerScript: noOuter,
739
+ redeemGetter: null,
740
+ witnessGetter: null,
741
+ expectedType: 'witnesspubkeyhash',
742
+ },
743
+ {
744
+ innerScript: p2pkhPub,
745
+ outerScript: p2shOut,
746
+ redeemGetter: p2pkhPub,
747
+ witnessGetter: null,
748
+ expectedType: 'p2sh-pubkeyhash',
749
+ },
750
+ {
751
+ innerScript: p2wpkhPub,
752
+ outerScript: p2shOut,
753
+ redeemGetter: p2wpkhPub,
754
+ witnessGetter: null,
755
+ expectedType: 'p2sh-witnesspubkeyhash',
756
+ finalize: true,
757
+ },
758
+ {
759
+ innerScript: p2pkhPub,
760
+ outerScript: p2wshOut,
761
+ redeemGetter: null,
762
+ witnessGetter: p2pkhPub,
763
+ expectedType: 'p2wsh-pubkeyhash',
764
+ finalize: true,
765
+ },
766
+ {
767
+ innerScript: p2pkhPub,
768
+ outerScript: p2shp2wshOut,
769
+ redeemGetter: (pk: Buffer): Buffer => p2wshOut(p2pkhPub(pk)),
770
+ witnessGetter: p2pkhPub,
771
+ expectedType: 'p2sh-p2wsh-pubkeyhash',
772
+ },
773
+ ].forEach(getInputTypeTest);
774
+ });
775
+
776
+ describe('inputHasHDKey', () => {
777
+ it('should return true if HD key is present', () => {
778
+ const root = bip32.fromSeed(crypto.randomBytes(32));
779
+ const root2 = bip32.fromSeed(crypto.randomBytes(32));
780
+ const path = "m/0'/0";
781
+ const psbt = new Psbt();
782
+ psbt.addInput({
783
+ hash: '0000000000000000000000000000000000000000000000000000000000000000',
784
+ index: 0,
785
+ bip32Derivation: [
786
+ {
787
+ masterFingerprint: root.fingerprint,
788
+ path,
789
+ pubkey: root.derivePath(path).publicKey,
790
+ },
791
+ ],
792
+ });
793
+ assert.strictEqual(psbt.inputHasHDKey(0, root), true);
794
+ assert.strictEqual(psbt.inputHasHDKey(0, root2), false);
795
+ });
796
+ });
797
+
798
+ describe('inputHasPubkey', () => {
799
+ it('should throw', () => {
800
+ const psbt = new Psbt();
801
+ psbt.addInput({
802
+ hash: '0000000000000000000000000000000000000000000000000000000000000000',
803
+ index: 0,
804
+ });
805
+
806
+ assert.throws(() => {
807
+ psbt.inputHasPubkey(0, Buffer.from([]));
808
+ }, new RegExp("Can't find pubkey in input without Utxo data"));
809
+
810
+ psbt.updateInput(0, {
811
+ witnessUtxo: {
812
+ value: 1337,
813
+ script: payments.p2sh({
814
+ redeem: { output: Buffer.from([0x51]) },
815
+ }).output!,
816
+ },
817
+ });
818
+
819
+ assert.throws(() => {
820
+ psbt.inputHasPubkey(0, Buffer.from([]));
821
+ }, new RegExp('scriptPubkey is P2SH but redeemScript missing'));
822
+
823
+ delete psbt.data.inputs[0].witnessUtxo;
824
+
825
+ psbt.updateInput(0, {
826
+ witnessUtxo: {
827
+ value: 1337,
828
+ script: payments.p2wsh({
829
+ redeem: { output: Buffer.from([0x51]) },
830
+ }).output!,
831
+ },
832
+ });
833
+
834
+ assert.throws(() => {
835
+ psbt.inputHasPubkey(0, Buffer.from([]));
836
+ }, new RegExp('scriptPubkey or redeemScript is P2WSH but witnessScript missing'));
837
+
838
+ delete psbt.data.inputs[0].witnessUtxo;
839
+
840
+ psbt.updateInput(0, {
841
+ witnessUtxo: {
842
+ value: 1337,
843
+ script: payments.p2sh({
844
+ redeem: payments.p2wsh({
845
+ redeem: { output: Buffer.from([0x51]) },
846
+ }),
847
+ }).output!,
848
+ },
849
+ redeemScript: payments.p2wsh({
850
+ redeem: { output: Buffer.from([0x51]) },
851
+ }).output!,
852
+ });
853
+
854
+ assert.throws(() => {
855
+ psbt.inputHasPubkey(0, Buffer.from([]));
856
+ }, new RegExp('scriptPubkey or redeemScript is P2WSH but witnessScript missing'));
857
+
858
+ psbt.updateInput(0, {
859
+ witnessScript: Buffer.from([0x51]),
860
+ });
861
+
862
+ assert.doesNotThrow(() => {
863
+ psbt.inputHasPubkey(0, Buffer.from([0x51]));
864
+ });
865
+ });
866
+ });
867
+
868
+ describe('outputHasHDKey', () => {
869
+ it('should return true if HD key is present', () => {
870
+ const root = bip32.fromSeed(crypto.randomBytes(32));
871
+ const root2 = bip32.fromSeed(crypto.randomBytes(32));
872
+ const path = "m/0'/0";
873
+ const psbt = new Psbt();
874
+ psbt.addInput({
875
+ hash: '0000000000000000000000000000000000000000000000000000000000000000',
876
+ index: 0,
877
+ }).addOutput({
878
+ script: Buffer.from('0014000102030405060708090a0b0c0d0e0f00010203', 'hex'),
879
+ value: 2000,
880
+ bip32Derivation: [
881
+ {
882
+ masterFingerprint: root.fingerprint,
883
+ path,
884
+ pubkey: root.derivePath(path).publicKey,
885
+ },
886
+ ],
887
+ });
888
+ assert.strictEqual(psbt.outputHasHDKey(0, root), true);
889
+ assert.strictEqual(psbt.outputHasHDKey(0, root2), false);
890
+ });
891
+ });
892
+
893
+ describe('outputHasPubkey', () => {
894
+ it('should throw', () => {
895
+ const psbt = new Psbt();
896
+ psbt.addInput({
897
+ hash: '0000000000000000000000000000000000000000000000000000000000000000',
898
+ index: 0,
899
+ }).addOutput({
900
+ script: payments.p2sh({
901
+ redeem: { output: Buffer.from([0x51]) },
902
+ }).output!,
903
+ value: 1337,
904
+ });
905
+
906
+ assert.throws(() => {
907
+ psbt.outputHasPubkey(0, Buffer.from([]));
908
+ }, new RegExp('scriptPubkey is P2SH but redeemScript missing'));
909
+
910
+ (psbt as any).__CACHE.__TX.outs[0].script = payments.p2wsh({
911
+ redeem: { output: Buffer.from([0x51]) },
912
+ }).output!;
913
+
914
+ assert.throws(() => {
915
+ psbt.outputHasPubkey(0, Buffer.from([]));
916
+ }, new RegExp('scriptPubkey or redeemScript is P2WSH but witnessScript missing'));
917
+
918
+ (psbt as any).__CACHE.__TX.outs[0].script = payments.p2sh({
919
+ redeem: payments.p2wsh({
920
+ redeem: { output: Buffer.from([0x51]) },
921
+ }),
922
+ }).output!;
923
+
924
+ psbt.updateOutput(0, {
925
+ redeemScript: payments.p2wsh({
926
+ redeem: { output: Buffer.from([0x51]) },
927
+ }).output!,
928
+ });
929
+
930
+ assert.throws(() => {
931
+ psbt.outputHasPubkey(0, Buffer.from([]));
932
+ }, new RegExp('scriptPubkey or redeemScript is P2WSH but witnessScript missing'));
933
+
934
+ delete psbt.data.outputs[0].redeemScript;
935
+
936
+ psbt.updateOutput(0, {
937
+ witnessScript: Buffer.from([0x51]),
938
+ });
939
+
940
+ assert.throws(() => {
941
+ psbt.outputHasPubkey(0, Buffer.from([]));
942
+ }, new RegExp('scriptPubkey is P2SH but redeemScript missing'));
943
+
944
+ psbt.updateOutput(0, {
945
+ redeemScript: payments.p2wsh({
946
+ redeem: { output: Buffer.from([0x51]) },
947
+ }).output!,
948
+ });
949
+
950
+ assert.doesNotThrow(() => {
951
+ psbt.outputHasPubkey(0, Buffer.from([0x51]));
952
+ });
953
+ });
954
+ });
955
+
956
+ describe('clone', () => {
957
+ it('Should clone a psbt exactly with no reference', () => {
958
+ const f = fixtures.clone;
959
+ const psbt = Psbt.fromBase64(f.psbt);
960
+ const notAClone = Object.assign(new Psbt(), psbt); // references still active
961
+ const clone = psbt.clone();
962
+
963
+ assert.strictEqual(psbt.validateSignaturesOfAllInputs(validator), true);
964
+
965
+ assert.strictEqual(clone.toBase64(), psbt.toBase64());
966
+ assert.strictEqual(clone.toBase64(), notAClone.toBase64());
967
+ assert.strictEqual(psbt.toBase64(), notAClone.toBase64());
968
+ (psbt as any).__CACHE.__TX.version |= 0xff0000;
969
+ assert.notStrictEqual(clone.toBase64(), psbt.toBase64());
970
+ assert.notStrictEqual(clone.toBase64(), notAClone.toBase64());
971
+ assert.strictEqual(psbt.toBase64(), notAClone.toBase64());
972
+ });
973
+ });
974
+
975
+ describe('setMaximumFeeRate', () => {
976
+ it('Sets the maximumFeeRate value', () => {
977
+ const psbt = new Psbt();
978
+
979
+ assert.strictEqual((psbt as any).opts.maximumFeeRate, 5000);
980
+ psbt.setMaximumFeeRate(6000);
981
+ assert.strictEqual((psbt as any).opts.maximumFeeRate, 6000);
982
+ });
983
+ });
984
+
985
+ describe('validateSignaturesOfInput', () => {
986
+ const f = fixtures.validateSignaturesOfInput;
987
+ it('Correctly validates a signature', () => {
988
+ const psbt = Psbt.fromBase64(f.psbt);
989
+
990
+ assert.strictEqual(psbt.validateSignaturesOfInput(f.index, validator), true);
991
+ assert.throws(() => {
992
+ psbt.validateSignaturesOfInput(f.nonExistantIndex, validator);
993
+ }, new RegExp('No signatures to validate'));
994
+ });
995
+
996
+ it('Correctly validates a signature against a pubkey', () => {
997
+ const psbt = Psbt.fromBase64(f.psbt);
998
+ assert.strictEqual(
999
+ psbt.validateSignaturesOfInput(f.index, validator, f.pubkey as any),
1000
+ true,
1001
+ );
1002
+ assert.throws(() => {
1003
+ psbt.validateSignaturesOfInput(f.index, validator, f.incorrectPubkey as any);
1004
+ }, new RegExp('No signatures for this pubkey'));
1005
+ });
1006
+ });
1007
+
1008
+ describe('validateSignaturesOfTapKeyInput', () => {
1009
+ const f = fixtures.validateSignaturesOfTapKeyInput;
1010
+ it('Correctly validates all signatures', () => {
1011
+ initEccLib(ecc);
1012
+ const psbt = Psbt.fromBase64(f.psbt);
1013
+ assert.strictEqual(psbt.validateSignaturesOfInput(f.index, schnorrValidator), true);
1014
+ });
1015
+
1016
+ it('Correctly validates a signature against a pubkey', () => {
1017
+ initEccLib(ecc);
1018
+ const psbt = Psbt.fromBase64(f.psbt);
1019
+ assert.strictEqual(
1020
+ psbt.validateSignaturesOfInput(f.index, schnorrValidator, f.pubkey as any),
1021
+ true,
1022
+ );
1023
+ assert.throws(() => {
1024
+ psbt.validateSignaturesOfInput(f.index, schnorrValidator, f.incorrectPubkey as any);
1025
+ }, new RegExp('No signatures for this pubkey'));
1026
+ });
1027
+ });
1028
+
1029
+ describe('validateSignaturesOfTapScriptInput', () => {
1030
+ const f = fixtures.validateSignaturesOfTapScriptInput;
1031
+ it('Correctly validates all signatures', () => {
1032
+ initEccLib(ecc);
1033
+ const psbt = Psbt.fromBase64(f.psbt);
1034
+ assert.strictEqual(psbt.validateSignaturesOfInput(f.index, schnorrValidator), true);
1035
+ });
1036
+
1037
+ it('Correctly validates a signature against a pubkey', () => {
1038
+ initEccLib(ecc);
1039
+ const psbt = Psbt.fromBase64(f.psbt);
1040
+ assert.strictEqual(
1041
+ psbt.validateSignaturesOfInput(f.index, schnorrValidator, f.pubkey as any),
1042
+ true,
1043
+ );
1044
+ assert.throws(() => {
1045
+ psbt.validateSignaturesOfInput(f.index, schnorrValidator, f.incorrectPubkey as any);
1046
+ }, new RegExp('No signatures for this pubkey'));
1047
+ });
1048
+ });
1049
+
1050
+ describe('tapTreeToList/tapTreeFromList', () => {
1051
+ it('Correctly converts a Taptree to a Tapleaf list and back', () => {
1052
+ taprootFixtures.valid
1053
+ .filter((f) => f.arguments.scriptTree)
1054
+ .map((f) => f.arguments.scriptTree)
1055
+ .forEach((scriptTree) => {
1056
+ const originalTree = convertScriptTree(scriptTree, LEAF_VERSION_TAPSCRIPT);
1057
+ const list = tapTreeToList(originalTree);
1058
+ const treeFromList = tapTreeFromList(list);
1059
+
1060
+ assert.deepStrictEqual(treeFromList, originalTree);
1061
+ });
1062
+ });
1063
+
1064
+ it('Throws if too many leaves on a given level', () => {
1065
+ const list = Array.from({ length: 5 }).map(() => ({
1066
+ depth: 2,
1067
+ leafVersion: LEAF_VERSION_TAPSCRIPT,
1068
+ script: Buffer.from([]),
1069
+ }));
1070
+ assert.throws(() => {
1071
+ tapTreeFromList(list);
1072
+ }, new RegExp('No room left to insert tapleaf in tree'));
1073
+ });
1074
+
1075
+ it('Throws if taptree depth is exceeded', () => {
1076
+ let tree: Taptree = [{ output: Buffer.from([]) }, { output: Buffer.from([]) }];
1077
+ Array.from({ length: 129 }).forEach(() => (tree = [tree, { output: Buffer.from([]) }]));
1078
+ assert.throws(() => {
1079
+ tapTreeToList(tree as Taptree);
1080
+ }, new RegExp('Max taptree depth exceeded.'));
1081
+ });
1082
+
1083
+ it('Throws if tapleaf depth is to high', () => {
1084
+ const list = [
1085
+ {
1086
+ depth: 129,
1087
+ leafVersion: LEAF_VERSION_TAPSCRIPT,
1088
+ script: Buffer.from([]),
1089
+ },
1090
+ ];
1091
+ assert.throws(() => {
1092
+ tapTreeFromList(list);
1093
+ }, new RegExp('Max taptree depth exceeded.'));
1094
+ });
1095
+
1096
+ it('Throws if not a valid taptree structure', () => {
1097
+ const tree = Array.from({ length: 3 }).map(() => ({
1098
+ output: Buffer.from([]),
1099
+ }));
1100
+
1101
+ assert.throws(() => {
1102
+ tapTreeToList(tree as Taptree);
1103
+ }, new RegExp('Cannot convert taptree to tapleaf list. Expecting a tapree structure.'));
1104
+ });
1105
+ });
1106
+
1107
+ describe('getFeeRate', () => {
1108
+ it('Throws error if called before inputs are finalized', () => {
1109
+ const f = fixtures.getFeeRate;
1110
+ const psbt = Psbt.fromBase64(f.psbt);
1111
+
1112
+ assert.throws(() => {
1113
+ psbt.getFeeRate();
1114
+ }, new RegExp('PSBT must be finalized to calculate fee rate'));
1115
+
1116
+ psbt.finalizeAllInputs();
1117
+
1118
+ assert.strictEqual(psbt.getFeeRate(), f.fee);
1119
+ (psbt as any).__CACHE.__FEE_RATE = undefined;
1120
+ assert.strictEqual(psbt.getFeeRate(), f.fee);
1121
+ });
1122
+ });
1123
+
1124
+ describe('create 1-to-1 transaction', () => {
1125
+ const alice = ECPair.fromWIF('L2uPYXe17xSTqbCjZvL2DsyXPCbXspvcu5mHLDYUgzdUbZGSKrSr');
1126
+ const psbt = new Psbt();
1127
+ psbt.addInput({
1128
+ hash: '7d067b4a697a09d2c3cff7d4d9506c9955e93bff41bf82d439da7d030382bc3e',
1129
+ index: 0,
1130
+ nonWitnessUtxo: Buffer.from(
1131
+ '0200000001f9f34e95b9d5c8abcd20fc5bd4a825d1517be62f0f775e5f36da944d9' +
1132
+ '452e550000000006b483045022100c86e9a111afc90f64b4904bd609e9eaed80d48' +
1133
+ 'ca17c162b1aca0a788ac3526f002207bb79b60d4fc6526329bf18a77135dc566020' +
1134
+ '9e761da46e1c2f1152ec013215801210211755115eabf846720f5cb18f248666fec' +
1135
+ '631e5e1e66009ce3710ceea5b1ad13ffffffff01905f0100000000001976a9148bb' +
1136
+ 'c95d2709c71607c60ee3f097c1217482f518d88ac00000000',
1137
+ 'hex',
1138
+ ),
1139
+ sighashType: 1,
1140
+ });
1141
+ psbt.addOutput({
1142
+ address: '1KRMKfeZcmosxALVYESdPNez1AP1mEtywp',
1143
+ value: 80000,
1144
+ });
1145
+ psbt.signInput(0, alice);
1146
+ assert.throws(() => {
1147
+ psbt.setVersion(3);
1148
+ }, new RegExp('Can not modify transaction, signatures exist.'));
1149
+ psbt.validateSignaturesOfInput(0, validator);
1150
+ psbt.finalizeAllInputs();
1151
+ assert.throws(() => {
1152
+ psbt.setVersion(3);
1153
+ }, new RegExp('Can not modify transaction, signatures exist.'));
1154
+ assert.strictEqual(psbt.inputHasPubkey(0, alice.publicKey), true);
1155
+ assert.strictEqual(psbt.outputHasPubkey(0, alice.publicKey), false);
1156
+ assert.strictEqual(
1157
+ psbt.extractTransaction().toHex(),
1158
+ '02000000013ebc8203037dda39d482bf41ff3be955996c50d9d4f7cfc3d2097a694a7' +
1159
+ 'b067d000000006b483045022100931b6db94aed25d5486884d83fc37160f37f3368c0' +
1160
+ 'd7f48c757112abefec983802205fda64cff98c849577026eb2ce916a50ea70626a766' +
1161
+ '9f8596dd89b720a26b4d501210365db9da3f8a260078a7e8f8b708a1161468fb2323f' +
1162
+ 'fda5ec16b261ec1056f455ffffffff0180380100000000001976a914ca0d36044e0dc' +
1163
+ '08a22724efa6f6a07b0ec4c79aa88ac00000000',
1164
+ );
1165
+ });
1166
+
1167
+ describe('Method return types', () => {
1168
+ it('fromBuffer returns Psbt type (not base class)', () => {
1169
+ const psbt = Psbt.fromBuffer(
1170
+ Buffer.from(
1171
+ '70736274ff01000a01000000000000000000000000',
1172
+ 'hex', // cHNidP8BAAoBAAAAAAAAAAAAAAAA
1173
+ ),
1174
+ );
1175
+ assert.strictEqual(psbt instanceof Psbt, true);
1176
+ assert.ok((psbt as any).__CACHE.__TX);
1177
+ });
1178
+ it('fromBase64 returns Psbt type (not base class)', () => {
1179
+ const psbt = Psbt.fromBase64('cHNidP8BAAoBAAAAAAAAAAAAAAAA');
1180
+ assert.strictEqual(psbt instanceof Psbt, true);
1181
+ assert.ok((psbt as any).__CACHE.__TX);
1182
+ });
1183
+ it('fromHex returns Psbt type (not base class)', () => {
1184
+ const psbt = Psbt.fromHex('70736274ff01000a01000000000000000000000000');
1185
+ assert.strictEqual(psbt instanceof Psbt, true);
1186
+ assert.ok((psbt as any).__CACHE.__TX);
1187
+ });
1188
+ });
1189
+
1190
+ describe('Cache', () => {
1191
+ it('non-witness UTXOs are cached', () => {
1192
+ const f = fixtures.cache.nonWitnessUtxo;
1193
+ const psbt = Psbt.fromBase64(f.psbt);
1194
+ const index = f.inputIndex;
1195
+
1196
+ // Cache is empty
1197
+ assert.strictEqual(
1198
+ (psbt as any).__CACHE.__NON_WITNESS_UTXO_BUF_CACHE[index],
1199
+ undefined,
1200
+ );
1201
+
1202
+ // Cache is populated
1203
+ psbt.updateInput(index, {
1204
+ nonWitnessUtxo: f.nonWitnessUtxo as any,
1205
+ });
1206
+ const value = psbt.data.inputs[index].nonWitnessUtxo;
1207
+ assert.ok((psbt as any).__CACHE.__NON_WITNESS_UTXO_BUF_CACHE[index].equals(value));
1208
+ assert.ok(
1209
+ (psbt as any).__CACHE.__NON_WITNESS_UTXO_BUF_CACHE[index].equals(f.nonWitnessUtxo),
1210
+ );
1211
+
1212
+ // Cache is rebuilt from internal transaction object when cleared
1213
+ psbt.data.inputs[index].nonWitnessUtxo = Buffer.from([1, 2, 3]);
1214
+ (psbt as any).__CACHE.__NON_WITNESS_UTXO_BUF_CACHE[index] = undefined;
1215
+ assert.ok((psbt as any).data.inputs[index].nonWitnessUtxo.equals(value));
1216
+ });
1217
+ });
1218
+
1219
+ describe('Transaction properties', () => {
1220
+ it('.version is exposed and is settable', () => {
1221
+ const psbt = new Psbt();
1222
+
1223
+ assert.strictEqual(psbt.version, 2);
1224
+ assert.strictEqual(psbt.version, (psbt as any).__CACHE.__TX.version);
1225
+
1226
+ psbt.version = 1;
1227
+ assert.strictEqual(psbt.version, 1);
1228
+ assert.strictEqual(psbt.version, (psbt as any).__CACHE.__TX.version);
1229
+ });
1230
+
1231
+ it('.locktime is exposed and is settable', () => {
1232
+ const psbt = new Psbt();
1233
+
1234
+ assert.strictEqual(psbt.locktime, 0);
1235
+ assert.strictEqual(psbt.locktime, (psbt as any).__CACHE.__TX.locktime);
1236
+
1237
+ psbt.locktime = 123;
1238
+ assert.strictEqual(psbt.locktime, 123);
1239
+ assert.strictEqual(psbt.locktime, (psbt as any).__CACHE.__TX.locktime);
1240
+ });
1241
+
1242
+ it('.txInputs is exposed as a readonly clone', () => {
1243
+ const psbt = new Psbt();
1244
+ const hash = Buffer.alloc(32);
1245
+ const index = 0;
1246
+ psbt.addInput({ hash, index });
1247
+
1248
+ const input = psbt.txInputs[0];
1249
+ const internalInput = (psbt as any).__CACHE.__TX.ins[0];
1250
+
1251
+ assert.ok(input.hash.equals(internalInput.hash));
1252
+ assert.strictEqual(input.index, internalInput.index);
1253
+ assert.strictEqual(input.sequence, internalInput.sequence);
1254
+
1255
+ input.hash[0] = 123;
1256
+ input.index = 123;
1257
+ input.sequence = 123;
1258
+
1259
+ assert.ok(!input.hash.equals(internalInput.hash));
1260
+ assert.notEqual(input.index, internalInput.index);
1261
+ assert.notEqual(input.sequence, internalInput.sequence);
1262
+ });
1263
+
1264
+ it('.txOutputs is exposed as a readonly clone', () => {
1265
+ const psbt = new Psbt();
1266
+ const address = '1LukeQU5jwebXbMLDVydeH4vFSobRV9rkj';
1267
+ const value = 100000;
1268
+ psbt.addOutput({ address, value });
1269
+
1270
+ const output = psbt.txOutputs[0];
1271
+ const internalInput = (psbt as any).__CACHE.__TX.outs[0];
1272
+
1273
+ assert.strictEqual(output.address, address);
1274
+
1275
+ assert.ok(output.script.equals(internalInput.script));
1276
+ assert.strictEqual(output.value, internalInput.value);
1277
+
1278
+ output.script[0] = 123;
1279
+ output.value = 123;
1280
+
1281
+ assert.ok(!output.script.equals(internalInput.script));
1282
+ assert.notEqual(output.value, internalInput.value);
1283
+ });
1284
+ });
1285
+ });