@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
@@ -1,769 +1,668 @@
1
- import * as assert from 'assert';
2
- import BIP32Factory from 'bip32';
3
- import * as ecc from 'tiny-secp256k1';
4
- import ECPairFactory from 'ecpair';
5
- import { describe, it } from 'mocha';
6
- import * as bitcoin from '../..';
7
- import { regtestUtils } from './_regtest';
8
-
9
- const ECPair = ECPairFactory(ecc);
10
- const rng = require('randombytes');
11
- const regtest = regtestUtils.network;
12
- const bip32 = BIP32Factory(ecc);
13
-
14
- const validator = (
15
- pubkey: Buffer,
16
- msghash: Buffer,
17
- signature: Buffer,
18
- ): boolean => ECPair.fromPublicKey(pubkey).verify(msghash, signature);
19
-
20
- // See bottom of file for some helper functions used to make the payment objects needed.
21
-
22
- describe('bitcoinjs-lib (transactions with psbt)', () => {
23
- it('can create a 1-to-1 Transaction', () => {
24
- const alice = ECPair.fromWIF(
25
- 'L2uPYXe17xSTqbCjZvL2DsyXPCbXspvcu5mHLDYUgzdUbZGSKrSr',
26
- );
27
- const psbt = new bitcoin.Psbt();
28
- psbt.setVersion(2); // These are defaults. This line is not needed.
29
- psbt.setLocktime(0); // These are defaults. This line is not needed.
30
- psbt.addInput({
31
- // if hash is string, txid, if hash is Buffer, is reversed compared to txid
32
- hash: '7d067b4a697a09d2c3cff7d4d9506c9955e93bff41bf82d439da7d030382bc3e',
33
- index: 0,
34
- sequence: 0xffffffff, // These are defaults. This line is not needed.
35
-
36
- // non-segwit inputs now require passing the whole previous tx as Buffer
37
- nonWitnessUtxo: Buffer.from(
38
- '0200000001f9f34e95b9d5c8abcd20fc5bd4a825d1517be62f0f775e5f36da944d9' +
39
- '452e550000000006b483045022100c86e9a111afc90f64b4904bd609e9eaed80d48' +
40
- 'ca17c162b1aca0a788ac3526f002207bb79b60d4fc6526329bf18a77135dc566020' +
41
- '9e761da46e1c2f1152ec013215801210211755115eabf846720f5cb18f248666fec' +
42
- '631e5e1e66009ce3710ceea5b1ad13ffffffff01' +
43
- // value in satoshis (Int64LE) = 0x015f90 = 90000
44
- '905f010000000000' +
45
- // scriptPubkey length
46
- '19' +
47
- // scriptPubkey
48
- '76a9148bbc95d2709c71607c60ee3f097c1217482f518d88ac' +
49
- // locktime
50
- '00000000',
51
- 'hex',
52
- ),
53
-
54
- // // If this input was segwit, instead of nonWitnessUtxo, you would add
55
- // // a witnessUtxo as follows. The scriptPubkey and the value only are needed.
56
- // witnessUtxo: {
57
- // script: Buffer.from(
58
- // '76a9148bbc95d2709c71607c60ee3f097c1217482f518d88ac',
59
- // 'hex',
60
- // ),
61
- // value: 90000,
62
- // },
63
-
64
- // Not featured here:
65
- // redeemScript. A Buffer of the redeemScript for P2SH
66
- // witnessScript. A Buffer of the witnessScript for P2WSH
67
- });
68
- psbt.addOutput({
69
- address: '1KRMKfeZcmosxALVYESdPNez1AP1mEtywp',
70
- value: 80000,
71
- });
72
- psbt.signInput(0, alice);
73
- psbt.validateSignaturesOfInput(0, validator);
74
- psbt.finalizeAllInputs();
75
- assert.strictEqual(
76
- psbt.extractTransaction().toHex(),
77
- '02000000013ebc8203037dda39d482bf41ff3be955996c50d9d4f7cfc3d2097a694a7' +
78
- 'b067d000000006b483045022100931b6db94aed25d5486884d83fc37160f37f3368c0' +
79
- 'd7f48c757112abefec983802205fda64cff98c849577026eb2ce916a50ea70626a766' +
80
- '9f8596dd89b720a26b4d501210365db9da3f8a260078a7e8f8b708a1161468fb2323f' +
81
- 'fda5ec16b261ec1056f455ffffffff0180380100000000001976a914ca0d36044e0dc' +
82
- '08a22724efa6f6a07b0ec4c79aa88ac00000000',
83
- );
84
- });
85
-
86
- it('can create (and broadcast via 3PBP) a typical Transaction', async () => {
87
- // these are { payment: Payment; keys: ECPair[] }
88
- const alice1 = createPayment('p2pkh');
89
- const alice2 = createPayment('p2pkh');
90
-
91
- // give Alice 2 unspent outputs
92
- const inputData1 = await getInputData(
93
- 5e4,
94
- alice1.payment,
95
- false,
96
- 'noredeem',
97
- );
98
- const inputData2 = await getInputData(
99
- 7e4,
100
- alice2.payment,
101
- false,
102
- 'noredeem',
103
- );
104
- {
105
- const {
106
- hash, // string of txid or Buffer of tx hash. (txid and hash are reverse order)
107
- index, // the output index of the txo you are spending
108
- nonWitnessUtxo, // the full previous transaction as a Buffer
109
- } = inputData1;
110
- assert.deepStrictEqual({ hash, index, nonWitnessUtxo }, inputData1);
111
- }
112
-
113
- // network is only needed if you pass an address to addOutput
114
- // using script (Buffer of scriptPubkey) instead will avoid needed network.
115
- const psbt = new bitcoin.Psbt({ network: regtest })
116
- .addInput(inputData1) // alice1 unspent
117
- .addInput(inputData2) // alice2 unspent
118
- .addOutput({
119
- address: 'mwCwTceJvYV27KXBc3NJZys6CjsgsoeHmf',
120
- value: 8e4,
121
- }) // the actual "spend"
122
- .addOutput({
123
- address: alice2.payment.address, // OR script, which is a Buffer.
124
- value: 1e4,
125
- }); // Alice's change
126
- // (in)(5e4 + 7e4) - (out)(8e4 + 1e4) = (fee)3e4 = 30000, this is the miner fee
127
-
128
- // Let's show a new feature with PSBT.
129
- // We can have multiple signers sign in parallel and combine them.
130
- // (this is not necessary, but a nice feature)
131
-
132
- // encode to send out to the signers
133
- const psbtBaseText = psbt.toBase64();
134
-
135
- // each signer imports
136
- const signer1 = bitcoin.Psbt.fromBase64(psbtBaseText);
137
- const signer2 = bitcoin.Psbt.fromBase64(psbtBaseText);
138
-
139
- // Alice signs each input with the respective private keys
140
- // signInput and signInputAsync are better
141
- // (They take the input index explicitly as the first arg)
142
- signer1.signAllInputs(alice1.keys[0]);
143
- signer2.signAllInputs(alice2.keys[0]);
144
-
145
- // If your signer object's sign method returns a promise, use the following
146
- // await signer2.signAllInputsAsync(alice2.keys[0])
147
-
148
- // encode to send back to combiner (signer 1 and 2 are not near each other)
149
- const s1text = signer1.toBase64();
150
- const s2text = signer2.toBase64();
151
-
152
- const final1 = bitcoin.Psbt.fromBase64(s1text);
153
- const final2 = bitcoin.Psbt.fromBase64(s2text);
154
-
155
- // final1.combine(final2) would give the exact same result
156
- psbt.combine(final1, final2);
157
-
158
- // Finalizer wants to check all signatures are valid before finalizing.
159
- // If the finalizer wants to check for specific pubkeys, the second arg
160
- // can be passed. See the first multisig example below.
161
- assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
162
- assert.strictEqual(psbt.validateSignaturesOfInput(1, validator), true);
163
-
164
- // This step it new. Since we separate the signing operation and
165
- // the creation of the scriptSig and witness stack, we are able to
166
- psbt.finalizeAllInputs();
167
-
168
- // build and broadcast our RegTest network
169
- await regtestUtils.broadcast(psbt.extractTransaction().toHex());
170
- // to build and broadcast to the actual Bitcoin network, see https://github.com/bitcoinjs/bitcoinjs-lib/issues/839
171
- });
172
-
173
- it('can create (and broadcast via 3PBP) a Transaction with an OP_RETURN output', async () => {
174
- const alice1 = createPayment('p2pkh');
175
- const inputData1 = await getInputData(
176
- 2e5,
177
- alice1.payment,
178
- false,
179
- 'noredeem',
180
- );
181
-
182
- const data = Buffer.from('bitcoinjs-lib', 'utf8');
183
- const embed = bitcoin.payments.embed({ data: [data] });
184
-
185
- const psbt = new bitcoin.Psbt({ network: regtest })
186
- .addInput(inputData1)
187
- .addOutput({
188
- script: embed.output!,
189
- value: 1000,
190
- })
191
- .addOutput({
192
- address: regtestUtils.RANDOM_ADDRESS,
193
- value: 1e5,
194
- })
195
- .signInput(0, alice1.keys[0]);
196
-
197
- assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
198
- psbt.finalizeAllInputs();
199
-
200
- // build and broadcast to the RegTest network
201
- await regtestUtils.broadcast(psbt.extractTransaction().toHex());
202
- });
203
-
204
- it('can create (and broadcast via 3PBP) a Transaction, w/ a P2SH(P2MS(2 of 4)) (multisig) input', async () => {
205
- const multisig = createPayment('p2sh-p2ms(2 of 4)');
206
- const inputData1 = await getInputData(
207
- 2e4,
208
- multisig.payment,
209
- false,
210
- 'p2sh',
211
- );
212
- {
213
- const {
214
- hash,
215
- index,
216
- nonWitnessUtxo,
217
- redeemScript, // NEW: P2SH needs to give redeemScript when adding an input.
218
- } = inputData1;
219
- assert.deepStrictEqual(
220
- { hash, index, nonWitnessUtxo, redeemScript },
221
- inputData1,
222
- );
223
- }
224
-
225
- const psbt = new bitcoin.Psbt({ network: regtest })
226
- .addInput(inputData1)
227
- .addOutput({
228
- address: regtestUtils.RANDOM_ADDRESS,
229
- value: 1e4,
230
- })
231
- .signInput(0, multisig.keys[0])
232
- .signInput(0, multisig.keys[2]);
233
-
234
- assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
235
- assert.strictEqual(
236
- psbt.validateSignaturesOfInput(
237
- 0,
238
- validator,
239
- multisig.keys[0].publicKey,
240
- ),
241
- true,
242
- );
243
- assert.throws(() => {
244
- psbt.validateSignaturesOfInput(
245
- 0,
246
- validator,
247
- multisig.keys[3].publicKey,
248
- );
249
- }, new RegExp('No signatures for this pubkey'));
250
- psbt.finalizeAllInputs();
251
-
252
- const tx = psbt.extractTransaction();
253
-
254
- // build and broadcast to the Bitcoin RegTest network
255
- await regtestUtils.broadcast(tx.toHex());
256
-
257
- await regtestUtils.verify({
258
- txId: tx.getId(),
259
- address: regtestUtils.RANDOM_ADDRESS,
260
- vout: 0,
261
- value: 1e4,
262
- });
263
- });
264
-
265
- it('can create (and broadcast via 3PBP) a Transaction, w/ a P2SH(P2WPKH) input', async () => {
266
- const p2sh = createPayment('p2sh-p2wpkh');
267
- const inputData = await getInputData(5e4, p2sh.payment, true, 'p2sh');
268
- const inputData2 = await getInputData(5e4, p2sh.payment, true, 'p2sh');
269
- {
270
- const {
271
- hash,
272
- index,
273
- witnessUtxo, // NEW: this is an object of the output being spent { script: Buffer; value: Satoshis; }
274
- redeemScript,
275
- } = inputData;
276
- assert.deepStrictEqual(
277
- { hash, index, witnessUtxo, redeemScript },
278
- inputData,
279
- );
280
- }
281
- const keyPair = p2sh.keys[0];
282
- const outputData = {
283
- script: p2sh.payment.output, // sending to myself for fun
284
- value: 2e4,
285
- };
286
- const outputData2 = {
287
- script: p2sh.payment.output, // sending to myself for fun
288
- value: 7e4,
289
- };
290
-
291
- const tx = new bitcoin.Psbt()
292
- .addInputs([inputData, inputData2])
293
- .addOutputs([outputData, outputData2])
294
- .signAllInputs(keyPair)
295
- .finalizeAllInputs()
296
- .extractTransaction();
297
-
298
- // build and broadcast to the Bitcoin RegTest network
299
- await regtestUtils.broadcast(tx.toHex());
300
-
301
- await regtestUtils.verify({
302
- txId: tx.getId(),
303
- address: p2sh.payment.address,
304
- vout: 0,
305
- value: 2e4,
306
- });
307
- });
308
-
309
- it('can create (and broadcast via 3PBP) a Transaction, w/ a P2SH(P2WPKH) input with nonWitnessUtxo', async () => {
310
- // For learning purposes, ignore this test.
311
- // REPEATING ABOVE BUT WITH nonWitnessUtxo by passing false to getInputData
312
- const p2sh = createPayment('p2sh-p2wpkh');
313
- const inputData = await getInputData(5e4, p2sh.payment, false, 'p2sh');
314
- const inputData2 = await getInputData(5e4, p2sh.payment, false, 'p2sh');
315
- const keyPair = p2sh.keys[0];
316
- const outputData = {
317
- script: p2sh.payment.output,
318
- value: 2e4,
319
- };
320
- const outputData2 = {
321
- script: p2sh.payment.output,
322
- value: 7e4,
323
- };
324
- const tx = new bitcoin.Psbt()
325
- .addInputs([inputData, inputData2])
326
- .addOutputs([outputData, outputData2])
327
- .signAllInputs(keyPair)
328
- .finalizeAllInputs()
329
- .extractTransaction();
330
- await regtestUtils.broadcast(tx.toHex());
331
- await regtestUtils.verify({
332
- txId: tx.getId(),
333
- address: p2sh.payment.address,
334
- vout: 0,
335
- value: 2e4,
336
- });
337
- });
338
-
339
- it('can create (and broadcast via 3PBP) a Transaction, w/ a P2WPKH input', async () => {
340
- // the only thing that changes is you don't give a redeemscript for input data
341
-
342
- const p2wpkh = createPayment('p2wpkh');
343
- const inputData = await getInputData(
344
- 5e4,
345
- p2wpkh.payment,
346
- true,
347
- 'noredeem',
348
- );
349
- {
350
- const { hash, index, witnessUtxo } = inputData;
351
- assert.deepStrictEqual({ hash, index, witnessUtxo }, inputData);
352
- }
353
-
354
- const psbt = new bitcoin.Psbt({ network: regtest })
355
- .addInput(inputData)
356
- .addOutput({
357
- address: regtestUtils.RANDOM_ADDRESS,
358
- value: 2e4,
359
- })
360
- .signInput(0, p2wpkh.keys[0]);
361
-
362
- assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
363
- psbt.finalizeAllInputs();
364
-
365
- const tx = psbt.extractTransaction();
366
-
367
- // build and broadcast to the Bitcoin RegTest network
368
- await regtestUtils.broadcast(tx.toHex());
369
-
370
- await regtestUtils.verify({
371
- txId: tx.getId(),
372
- address: regtestUtils.RANDOM_ADDRESS,
373
- vout: 0,
374
- value: 2e4,
375
- });
376
- });
377
-
378
- it('can create (and broadcast via 3PBP) a Transaction, w/ a P2WPKH input with nonWitnessUtxo', async () => {
379
- // For learning purposes, ignore this test.
380
- // REPEATING ABOVE BUT WITH nonWitnessUtxo by passing false to getInputData
381
- const p2wpkh = createPayment('p2wpkh');
382
- const inputData = await getInputData(
383
- 5e4,
384
- p2wpkh.payment,
385
- false,
386
- 'noredeem',
387
- );
388
- const psbt = new bitcoin.Psbt({ network: regtest })
389
- .addInput(inputData)
390
- .addOutput({
391
- address: regtestUtils.RANDOM_ADDRESS,
392
- value: 2e4,
393
- })
394
- .signInput(0, p2wpkh.keys[0]);
395
- psbt.finalizeAllInputs();
396
- const tx = psbt.extractTransaction();
397
- await regtestUtils.broadcast(tx.toHex());
398
- await regtestUtils.verify({
399
- txId: tx.getId(),
400
- address: regtestUtils.RANDOM_ADDRESS,
401
- vout: 0,
402
- value: 2e4,
403
- });
404
- });
405
-
406
- it('can create (and broadcast via 3PBP) a Transaction, w/ a P2WSH(P2PK) input', async () => {
407
- const p2wsh = createPayment('p2wsh-p2pk');
408
- const inputData = await getInputData(5e4, p2wsh.payment, true, 'p2wsh');
409
- {
410
- const {
411
- hash,
412
- index,
413
- witnessUtxo,
414
- witnessScript, // NEW: A Buffer of the witnessScript
415
- } = inputData;
416
- assert.deepStrictEqual(
417
- { hash, index, witnessUtxo, witnessScript },
418
- inputData,
419
- );
420
- }
421
-
422
- const psbt = new bitcoin.Psbt({ network: regtest })
423
- .addInput(inputData)
424
- .addOutput({
425
- address: regtestUtils.RANDOM_ADDRESS,
426
- value: 2e4,
427
- })
428
- .signInput(0, p2wsh.keys[0]);
429
-
430
- assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
431
- psbt.finalizeAllInputs();
432
-
433
- const tx = psbt.extractTransaction();
434
-
435
- // build and broadcast to the Bitcoin RegTest network
436
- await regtestUtils.broadcast(tx.toHex());
437
-
438
- await regtestUtils.verify({
439
- txId: tx.getId(),
440
- address: regtestUtils.RANDOM_ADDRESS,
441
- vout: 0,
442
- value: 2e4,
443
- });
444
- });
445
-
446
- it('can create (and broadcast via 3PBP) a Transaction, w/ a P2WSH(P2PK) input with nonWitnessUtxo', async () => {
447
- // For learning purposes, ignore this test.
448
- // REPEATING ABOVE BUT WITH nonWitnessUtxo by passing false to getInputData
449
- const p2wsh = createPayment('p2wsh-p2pk');
450
- const inputData = await getInputData(
451
- 5e4,
452
- p2wsh.payment,
453
- false,
454
- 'p2wsh',
455
- );
456
- const psbt = new bitcoin.Psbt({ network: regtest })
457
- .addInput(inputData)
458
- .addOutput({
459
- address: regtestUtils.RANDOM_ADDRESS,
460
- value: 2e4,
461
- })
462
- .signInput(0, p2wsh.keys[0]);
463
- psbt.finalizeAllInputs();
464
- const tx = psbt.extractTransaction();
465
- await regtestUtils.broadcast(tx.toHex());
466
- await regtestUtils.verify({
467
- txId: tx.getId(),
468
- address: regtestUtils.RANDOM_ADDRESS,
469
- vout: 0,
470
- value: 2e4,
471
- });
472
- });
473
-
474
- it(
475
- 'can create (and broadcast via 3PBP) a Transaction, w/ a ' +
476
- 'P2SH(P2WSH(P2MS(3 of 4))) (SegWit multisig) input',
477
- async () => {
478
- const p2sh = createPayment('p2sh-p2wsh-p2ms(3 of 4)');
479
- const inputData = await getInputData(
480
- 5e4,
481
- p2sh.payment,
482
- true,
483
- 'p2sh-p2wsh',
484
- );
485
- {
486
- const {
487
- hash,
488
- index,
489
- witnessUtxo,
490
- redeemScript,
491
- witnessScript,
492
- } = inputData;
493
- assert.deepStrictEqual(
494
- { hash, index, witnessUtxo, redeemScript, witnessScript },
495
- inputData,
496
- );
497
- }
498
-
499
- const psbt = new bitcoin.Psbt({ network: regtest })
500
- .addInput(inputData)
501
- .addOutput({
502
- address: regtestUtils.RANDOM_ADDRESS,
503
- value: 2e4,
504
- })
505
- .signInput(0, p2sh.keys[0])
506
- .signInput(0, p2sh.keys[2])
507
- .signInput(0, p2sh.keys[3]);
508
-
509
- assert.strictEqual(
510
- psbt.validateSignaturesOfInput(0, validator),
511
- true,
512
- );
513
- assert.strictEqual(
514
- psbt.validateSignaturesOfInput(
515
- 0,
516
- validator,
517
- p2sh.keys[3].publicKey,
518
- ),
519
- true,
520
- );
521
- assert.throws(() => {
522
- psbt.validateSignaturesOfInput(
523
- 0,
524
- validator,
525
- p2sh.keys[1].publicKey,
526
- );
527
- }, new RegExp('No signatures for this pubkey'));
528
- psbt.finalizeAllInputs();
529
-
530
- const tx = psbt.extractTransaction();
531
-
532
- // build and broadcast to the Bitcoin RegTest network
533
- await regtestUtils.broadcast(tx.toHex());
534
-
535
- await regtestUtils.verify({
536
- txId: tx.getId(),
537
- address: regtestUtils.RANDOM_ADDRESS,
538
- vout: 0,
539
- value: 2e4,
540
- });
541
- },
542
- );
543
-
544
- it(
545
- 'can create (and broadcast via 3PBP) a Transaction, w/ a ' +
546
- 'P2SH(P2WSH(P2MS(3 of 4))) (SegWit multisig) input with nonWitnessUtxo',
547
- async () => {
548
- // For learning purposes, ignore this test.
549
- // REPEATING ABOVE BUT WITH nonWitnessUtxo by passing false to getInputData
550
- const p2sh = createPayment('p2sh-p2wsh-p2ms(3 of 4)');
551
- const inputData = await getInputData(
552
- 5e4,
553
- p2sh.payment,
554
- false,
555
- 'p2sh-p2wsh',
556
- );
557
- const psbt = new bitcoin.Psbt({ network: regtest })
558
- .addInput(inputData)
559
- .addOutput({
560
- address: regtestUtils.RANDOM_ADDRESS,
561
- value: 2e4,
562
- })
563
- .signInput(0, p2sh.keys[0])
564
- .signInput(0, p2sh.keys[2])
565
- .signInput(0, p2sh.keys[3]);
566
- psbt.finalizeAllInputs();
567
- const tx = psbt.extractTransaction();
568
- await regtestUtils.broadcast(tx.toHex());
569
- await regtestUtils.verify({
570
- txId: tx.getId(),
571
- address: regtestUtils.RANDOM_ADDRESS,
572
- vout: 0,
573
- value: 2e4,
574
- });
575
- },
576
- );
577
-
578
- it(
579
- 'can create (and broadcast via 3PBP) a Transaction, w/ a ' +
580
- 'P2SH(P2MS(2 of 2)) input with nonWitnessUtxo',
581
- async () => {
582
- const myKey = ECPair.makeRandom({ network: regtest });
583
- const myKeys = [
584
- myKey,
585
- ECPair.fromPrivateKey(myKey.privateKey!, { network: regtest }),
586
- ];
587
- const p2sh = createPayment('p2sh-p2ms(2 of 2)', myKeys);
588
- const inputData = await getInputData(
589
- 5e4,
590
- p2sh.payment,
591
- false,
592
- 'p2sh',
593
- );
594
- const psbt = new bitcoin.Psbt({ network: regtest })
595
- .addInput(inputData)
596
- .addOutput({
597
- address: regtestUtils.RANDOM_ADDRESS,
598
- value: 2e4,
599
- })
600
- .signInput(0, p2sh.keys[0]);
601
- psbt.finalizeAllInputs();
602
- const tx = psbt.extractTransaction();
603
- await regtestUtils.broadcast(tx.toHex());
604
- await regtestUtils.verify({
605
- txId: tx.getId(),
606
- address: regtestUtils.RANDOM_ADDRESS,
607
- vout: 0,
608
- value: 2e4,
609
- });
610
- },
611
- );
612
-
613
- it('can create (and broadcast via 3PBP) a Transaction, w/ a P2WPKH input using HD', async () => {
614
- const hdRoot = bip32.fromSeed(rng(64));
615
- const masterFingerprint = hdRoot.fingerprint;
616
- const path = "m/84'/0'/0'/0/0";
617
- const childNode = hdRoot.derivePath(path);
618
- const pubkey = childNode.publicKey;
619
-
620
- // This information should be added to your input via updateInput
621
- // You can add multiple bip32Derivation objects for multisig, but
622
- // each must have a unique pubkey.
623
- //
624
- // This is useful because as long as you store the masterFingerprint on
625
- // the PSBT Creator's server, you can have the PSBT Creator do the heavy
626
- // lifting with derivation from your m/84'/0'/0' xpub, (deriving only 0/0 )
627
- // and your signer just needs to pass in an HDSigner interface (ie. bip32 library)
628
- const updateData = {
629
- bip32Derivation: [
630
- {
631
- masterFingerprint,
632
- path,
633
- pubkey,
634
- },
635
- ],
636
- };
637
- const p2wpkh = createPayment('p2wpkh', [childNode]);
638
- const inputData = await getInputData(
639
- 5e4,
640
- p2wpkh.payment,
641
- true,
642
- 'noredeem',
643
- );
644
- {
645
- const { hash, index, witnessUtxo } = inputData;
646
- assert.deepStrictEqual({ hash, index, witnessUtxo }, inputData);
647
- }
648
-
649
- // You can add extra attributes for updateData into the addInput(s) object(s)
650
- Object.assign(inputData, updateData);
651
-
652
- const psbt = new bitcoin.Psbt({ network: regtest })
653
- .addInput(inputData)
654
- // .updateInput(0, updateData) // if you didn't merge the bip32Derivation with inputData
655
- .addOutput({
656
- address: regtestUtils.RANDOM_ADDRESS,
657
- value: 2e4,
658
- })
659
- .signInputHD(0, hdRoot); // must sign with root!!!
660
-
661
- assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
662
- assert.strictEqual(
663
- psbt.validateSignaturesOfInput(0, validator, childNode.publicKey),
664
- true,
665
- );
666
- psbt.finalizeAllInputs();
667
-
668
- const tx = psbt.extractTransaction();
669
-
670
- // build and broadcast to the Bitcoin RegTest network
671
- await regtestUtils.broadcast(tx.toHex());
672
-
673
- await regtestUtils.verify({
674
- txId: tx.getId(),
675
- address: regtestUtils.RANDOM_ADDRESS,
676
- vout: 0,
677
- value: 2e4,
678
- });
679
- });
680
- });
681
-
682
- function createPayment(_type: string, myKeys?: any[], network?: any): any {
683
- network = network || regtest;
684
- const splitType = _type.split('-').reverse();
685
- const isMultisig = splitType[0].slice(0, 4) === 'p2ms';
686
- const keys = myKeys || [];
687
- let m: number | undefined;
688
- if (isMultisig) {
689
- const match = splitType[0].match(/^p2ms\((\d+) of (\d+)\)$/);
690
- m = parseInt(match![1], 10);
691
- let n = parseInt(match![2], 10);
692
- if (keys.length > 0 && keys.length !== n) {
693
- throw new Error('Need n keys for multisig');
694
- }
695
- while (!myKeys && n > 1) {
696
- keys.push(ECPair.makeRandom({ network }));
697
- n--;
698
- }
699
- }
700
- if (!myKeys) keys.push(ECPair.makeRandom({ network }));
701
-
702
- let payment: any;
703
- splitType.forEach(type => {
704
- if (type.slice(0, 4) === 'p2ms') {
705
- payment = bitcoin.payments.p2ms({
706
- m,
707
- pubkeys: keys
708
- .map(key => key.publicKey)
709
- .sort((a, b) => a.compare(b)),
710
- network,
711
- });
712
- } else if (['p2sh', 'p2wsh'].indexOf(type) > -1) {
713
- payment = (bitcoin.payments as any)[type]({
714
- redeem: payment,
715
- network,
716
- });
717
- } else {
718
- payment = (bitcoin.payments as any)[type]({
719
- pubkey: keys[0].publicKey,
720
- network,
721
- });
722
- }
723
- });
724
-
725
- return {
726
- payment,
727
- keys,
728
- };
729
- }
730
-
731
- function getWitnessUtxo(out: any): any {
732
- delete out.address;
733
- out.script = Buffer.from(out.script, 'hex');
734
- return out;
735
- }
736
-
737
- async function getInputData(
738
- amount: number,
739
- payment: any,
740
- isSegwit: boolean,
741
- redeemType: string,
742
- ): Promise<any> {
743
- const unspent = await regtestUtils.faucetComplex(payment.output, amount);
744
- const utx = await regtestUtils.fetch(unspent.txId);
745
- // for non segwit inputs, you must pass the full transaction buffer
746
- const nonWitnessUtxo = Buffer.from(utx.txHex, 'hex');
747
- // for segwit inputs, you only need the output script and value as an object.
748
- const witnessUtxo = getWitnessUtxo(utx.outs[unspent.vout]);
749
- const mixin = isSegwit ? { witnessUtxo } : { nonWitnessUtxo };
750
- const mixin2: any = {};
751
- switch (redeemType) {
752
- case 'p2sh':
753
- mixin2.redeemScript = payment.redeem.output;
754
- break;
755
- case 'p2wsh':
756
- mixin2.witnessScript = payment.redeem.output;
757
- break;
758
- case 'p2sh-p2wsh':
759
- mixin2.witnessScript = payment.redeem.redeem.output;
760
- mixin2.redeemScript = payment.redeem.output;
761
- break;
762
- }
763
- return {
764
- hash: unspent.txId,
765
- index: unspent.vout,
766
- ...mixin,
767
- ...mixin2,
768
- };
769
- }
1
+ import assert from 'assert';
2
+ import { BIP32Factory } from 'bip32';
3
+ import * as ecc from 'tiny-secp256k1';
4
+ import { ECPairFactory } from 'ecpair';
5
+ import { describe, it } from 'mocha';
6
+ import * as bitcoin from '../../src/index.js';
7
+ import { regtestUtils } from './_regtest.js';
8
+
9
+ import rng from 'randombytes';
10
+
11
+ const ECPair = ECPairFactory(ecc);
12
+ const regtest = { ...regtestUtils.network, bech32Opnet: 'opreg' };
13
+ const bip32 = BIP32Factory(ecc);
14
+
15
+ const validator = (pubkey: Buffer, msghash: Buffer, signature: Buffer): boolean =>
16
+ ECPair.fromPublicKey(pubkey).verify(msghash, signature);
17
+
18
+ // See bottom of file for some helper functions used to make the payment objects needed.
19
+
20
+ describe('bitcoinjs-lib (transactions with psbt)', () => {
21
+ it('can create a 1-to-1 Transaction', () => {
22
+ const alice = ECPair.fromWIF('L2uPYXe17xSTqbCjZvL2DsyXPCbXspvcu5mHLDYUgzdUbZGSKrSr');
23
+ const psbt = new bitcoin.Psbt();
24
+ psbt.setVersion(2); // These are defaults. This line is not needed.
25
+ psbt.setLocktime(0); // These are defaults. This line is not needed.
26
+ psbt.addInput({
27
+ // if hash is string, txid, if hash is Buffer, is reversed compared to txid
28
+ hash: '7d067b4a697a09d2c3cff7d4d9506c9955e93bff41bf82d439da7d030382bc3e',
29
+ index: 0,
30
+ sequence: 0xffffffff, // These are defaults. This line is not needed.
31
+
32
+ // non-segwit inputs now require passing the whole previous tx as Buffer
33
+ nonWitnessUtxo: Buffer.from(
34
+ '0200000001f9f34e95b9d5c8abcd20fc5bd4a825d1517be62f0f775e5f36da944d9' +
35
+ '452e550000000006b483045022100c86e9a111afc90f64b4904bd609e9eaed80d48' +
36
+ 'ca17c162b1aca0a788ac3526f002207bb79b60d4fc6526329bf18a77135dc566020' +
37
+ '9e761da46e1c2f1152ec013215801210211755115eabf846720f5cb18f248666fec' +
38
+ '631e5e1e66009ce3710ceea5b1ad13ffffffff01' +
39
+ // value in satoshis (Int64LE) = 0x015f90 = 90000
40
+ '905f010000000000' +
41
+ // scriptPubkey length
42
+ '19' +
43
+ // scriptPubkey
44
+ '76a9148bbc95d2709c71607c60ee3f097c1217482f518d88ac' +
45
+ // locktime
46
+ '00000000',
47
+ 'hex',
48
+ ),
49
+
50
+ // // If this input was segwit, instead of nonWitnessUtxo, you would add
51
+ // // a witnessUtxo as follows. The scriptPubkey and the value only are needed.
52
+ // witnessUtxo: {
53
+ // script: Buffer.from(
54
+ // '76a9148bbc95d2709c71607c60ee3f097c1217482f518d88ac',
55
+ // 'hex',
56
+ // ),
57
+ // value: 90000,
58
+ // },
59
+
60
+ // Not featured here:
61
+ // redeemScript. A Buffer of the redeemScript for P2SH
62
+ // witnessScript. A Buffer of the witnessScript for P2WSH
63
+ });
64
+ psbt.addOutput({
65
+ address: '1KRMKfeZcmosxALVYESdPNez1AP1mEtywp',
66
+ value: 80000,
67
+ });
68
+ psbt.signInput(0, alice);
69
+ psbt.validateSignaturesOfInput(0, validator);
70
+ psbt.finalizeAllInputs();
71
+ assert.strictEqual(
72
+ psbt.extractTransaction().toHex(),
73
+ '02000000013ebc8203037dda39d482bf41ff3be955996c50d9d4f7cfc3d2097a694a7' +
74
+ 'b067d000000006b483045022100931b6db94aed25d5486884d83fc37160f37f3368c0' +
75
+ 'd7f48c757112abefec983802205fda64cff98c849577026eb2ce916a50ea70626a766' +
76
+ '9f8596dd89b720a26b4d501210365db9da3f8a260078a7e8f8b708a1161468fb2323f' +
77
+ 'fda5ec16b261ec1056f455ffffffff0180380100000000001976a914ca0d36044e0dc' +
78
+ '08a22724efa6f6a07b0ec4c79aa88ac00000000',
79
+ );
80
+ });
81
+
82
+ it('can create (and broadcast via 3PBP) a typical Transaction', async () => {
83
+ // these are { payment: Payment; keys: ECPair[] }
84
+ const alice1 = createPayment('p2pkh');
85
+ const alice2 = createPayment('p2pkh');
86
+
87
+ // give Alice 2 unspent outputs
88
+ const inputData1 = await getInputData(5e4, alice1.payment, false, 'noredeem');
89
+ const inputData2 = await getInputData(7e4, alice2.payment, false, 'noredeem');
90
+ {
91
+ const {
92
+ hash, // string of txid or Buffer of tx hash. (txid and hash are reverse order)
93
+ index, // the output index of the txo you are spending
94
+ nonWitnessUtxo, // the full previous transaction as a Buffer
95
+ } = inputData1;
96
+ assert.deepStrictEqual({ hash, index, nonWitnessUtxo }, inputData1);
97
+ }
98
+
99
+ // network is only needed if you pass an address to addOutput
100
+ // using script (Buffer of scriptPubkey) instead will avoid needed network.
101
+ const psbt = new bitcoin.Psbt({ network: regtest })
102
+ .addInput(inputData1) // alice1 unspent
103
+ .addInput(inputData2) // alice2 unspent
104
+ .addOutput({
105
+ address: 'mwCwTceJvYV27KXBc3NJZys6CjsgsoeHmf',
106
+ value: 8e4,
107
+ }) // the actual "spend"
108
+ .addOutput({
109
+ address: alice2.payment.address, // OR script, which is a Buffer.
110
+ value: 1e4,
111
+ }); // Alice's change
112
+ // (in)(5e4 + 7e4) - (out)(8e4 + 1e4) = (fee)3e4 = 30000, this is the miner fee
113
+
114
+ // Let's show a new feature with PSBT.
115
+ // We can have multiple signers sign in parallel and combine them.
116
+ // (this is not necessary, but a nice feature)
117
+
118
+ // encode to send out to the signers
119
+ const psbtBaseText = psbt.toBase64();
120
+
121
+ // each signer imports
122
+ const signer1 = bitcoin.Psbt.fromBase64(psbtBaseText);
123
+ const signer2 = bitcoin.Psbt.fromBase64(psbtBaseText);
124
+
125
+ // Alice signs each input with the respective private keys
126
+ // signInput and signInputAsync are better
127
+ // (They take the input index explicitly as the first arg)
128
+ signer1.signAllInputs(alice1.keys[0]);
129
+ signer2.signAllInputs(alice2.keys[0]);
130
+
131
+ // If your signer object's sign method returns a promise, use the following
132
+ // await signer2.signAllInputsAsync(alice2.keys[0])
133
+
134
+ // encode to send back to combiner (signer 1 and 2 are not near each other)
135
+ const s1text = signer1.toBase64();
136
+ const s2text = signer2.toBase64();
137
+
138
+ const final1 = bitcoin.Psbt.fromBase64(s1text);
139
+ const final2 = bitcoin.Psbt.fromBase64(s2text);
140
+
141
+ // final1.combine(final2) would give the exact same result
142
+ psbt.combine(final1, final2);
143
+
144
+ // Finalizer wants to check all signatures are valid before finalizing.
145
+ // If the finalizer wants to check for specific pubkeys, the second arg
146
+ // can be passed. See the first multisig example below.
147
+ assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
148
+ assert.strictEqual(psbt.validateSignaturesOfInput(1, validator), true);
149
+
150
+ // This step it new. Since we separate the signing operation and
151
+ // the creation of the scriptSig and witness stack, we are able to
152
+ psbt.finalizeAllInputs();
153
+
154
+ // build and broadcast our RegTest network
155
+ await regtestUtils.broadcast(psbt.extractTransaction().toHex());
156
+ // to build and broadcast to the actual Bitcoin network, see https://github.com/bitcoinjs/bitcoinjs-lib/issues/839
157
+ });
158
+
159
+ /*it('can create (and broadcast via 3PBP) a Transaction with an OP_RETURN output', async () => {
160
+ const alice1 = createPayment('p2pkh');
161
+ const inputData1 = await getInputData(2e5, alice1.payment, false, 'noredeem');
162
+
163
+ const data = Buffer.from('bitcoinjs-lib', 'utf8');
164
+ const embed = bitcoin.payments.embed({ data: [data] });
165
+
166
+ const psbt = new bitcoin.Psbt({ network: regtest })
167
+ .addInput(inputData1)
168
+ .addOutput({
169
+ script: embed.output!,
170
+ value: 1000,
171
+ })
172
+ .addOutput({
173
+ address: regtestUtils.RANDOM_ADDRESS,
174
+ value: 1e5,
175
+ })
176
+ .signInput(0, alice1.keys[0]);
177
+
178
+ assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
179
+ psbt.finalizeAllInputs();
180
+
181
+ // build and broadcast to the RegTest network
182
+ await regtestUtils.broadcast(psbt.extractTransaction().toHex());
183
+ });*/
184
+
185
+ it('can create (and broadcast via 3PBP) a Transaction, w/ a P2SH(P2MS(2 of 4)) (multisig) input', async () => {
186
+ const multisig = createPayment('p2sh-p2ms(2 of 4)');
187
+ const inputData1 = await getInputData(2e4, multisig.payment, false, 'p2sh');
188
+ {
189
+ const {
190
+ hash,
191
+ index,
192
+ nonWitnessUtxo,
193
+ redeemScript, // NEW: P2SH needs to give redeemScript when adding an input.
194
+ } = inputData1;
195
+ assert.deepStrictEqual({ hash, index, nonWitnessUtxo, redeemScript }, inputData1);
196
+ }
197
+
198
+ const psbt = new bitcoin.Psbt({ network: regtest })
199
+ .addInput(inputData1)
200
+ .addOutput({
201
+ address: regtestUtils.RANDOM_ADDRESS,
202
+ value: 1e4,
203
+ })
204
+ .signInput(0, multisig.keys[0])
205
+ .signInput(0, multisig.keys[2]);
206
+
207
+ assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
208
+ assert.strictEqual(
209
+ psbt.validateSignaturesOfInput(0, validator, multisig.keys[0].publicKey),
210
+ true,
211
+ );
212
+ assert.throws(() => {
213
+ psbt.validateSignaturesOfInput(0, validator, multisig.keys[3].publicKey);
214
+ }, new RegExp('No signatures for this pubkey'));
215
+ psbt.finalizeAllInputs();
216
+
217
+ const tx = psbt.extractTransaction();
218
+
219
+ // build and broadcast to the Bitcoin RegTest network
220
+ await regtestUtils.broadcast(tx.toHex());
221
+
222
+ await regtestUtils.verify({
223
+ txId: tx.getId(),
224
+ address: regtestUtils.RANDOM_ADDRESS,
225
+ vout: 0,
226
+ value: 1e4,
227
+ });
228
+ });
229
+
230
+ it('can create (and broadcast via 3PBP) a Transaction, w/ a P2SH(P2WPKH) input', async () => {
231
+ const p2sh = createPayment('p2sh-p2wpkh');
232
+ const inputData = await getInputData(5e4, p2sh.payment, true, 'p2sh');
233
+ const inputData2 = await getInputData(5e4, p2sh.payment, true, 'p2sh');
234
+ {
235
+ const {
236
+ hash,
237
+ index,
238
+ witnessUtxo, // NEW: this is an object of the output being spent { script: Buffer; value: Satoshis; }
239
+ redeemScript,
240
+ } = inputData;
241
+ assert.deepStrictEqual({ hash, index, witnessUtxo, redeemScript }, inputData);
242
+ }
243
+ const keyPair = p2sh.keys[0];
244
+ const outputData = {
245
+ script: p2sh.payment.output, // sending to myself for fun
246
+ value: 2e4,
247
+ };
248
+ const outputData2 = {
249
+ script: p2sh.payment.output, // sending to myself for fun
250
+ value: 7e4,
251
+ };
252
+
253
+ const tx = new bitcoin.Psbt()
254
+ .addInputs([inputData, inputData2])
255
+ .addOutputs([outputData, outputData2])
256
+ .signAllInputs(keyPair)
257
+ .finalizeAllInputs()
258
+ .extractTransaction();
259
+
260
+ // build and broadcast to the Bitcoin RegTest network
261
+ await regtestUtils.broadcast(tx.toHex());
262
+
263
+ await regtestUtils.verify({
264
+ txId: tx.getId(),
265
+ address: p2sh.payment.address,
266
+ vout: 0,
267
+ value: 2e4,
268
+ });
269
+ });
270
+
271
+ it('can create (and broadcast via 3PBP) a Transaction, w/ a P2SH(P2WPKH) input with nonWitnessUtxo', async () => {
272
+ // For learning purposes, ignore this test.
273
+ // REPEATING ABOVE BUT WITH nonWitnessUtxo by passing false to getInputData
274
+ const p2sh = createPayment('p2sh-p2wpkh');
275
+ const inputData = await getInputData(5e4, p2sh.payment, false, 'p2sh');
276
+ const inputData2 = await getInputData(5e4, p2sh.payment, false, 'p2sh');
277
+ const keyPair = p2sh.keys[0];
278
+ const outputData = {
279
+ script: p2sh.payment.output,
280
+ value: 2e4,
281
+ };
282
+ const outputData2 = {
283
+ script: p2sh.payment.output,
284
+ value: 7e4,
285
+ };
286
+ const tx = new bitcoin.Psbt()
287
+ .addInputs([inputData, inputData2])
288
+ .addOutputs([outputData, outputData2])
289
+ .signAllInputs(keyPair)
290
+ .finalizeAllInputs()
291
+ .extractTransaction();
292
+ await regtestUtils.broadcast(tx.toHex());
293
+ await regtestUtils.verify({
294
+ txId: tx.getId(),
295
+ address: p2sh.payment.address,
296
+ vout: 0,
297
+ value: 2e4,
298
+ });
299
+ });
300
+
301
+ it('can create (and broadcast via 3PBP) a Transaction, w/ a P2WPKH input', async () => {
302
+ // the only thing that changes is you don't give a redeemscript for input data
303
+
304
+ const p2wpkh = createPayment('p2wpkh');
305
+ const inputData = await getInputData(5e4, p2wpkh.payment, true, 'noredeem');
306
+ {
307
+ const { hash, index, witnessUtxo } = inputData;
308
+ assert.deepStrictEqual({ hash, index, witnessUtxo }, inputData);
309
+ }
310
+
311
+ const psbt = new bitcoin.Psbt({ network: regtest })
312
+ .addInput(inputData)
313
+ .addOutput({
314
+ address: regtestUtils.RANDOM_ADDRESS,
315
+ value: 2e4,
316
+ })
317
+ .signInput(0, p2wpkh.keys[0]);
318
+
319
+ assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
320
+ psbt.finalizeAllInputs();
321
+
322
+ const tx = psbt.extractTransaction();
323
+
324
+ // build and broadcast to the Bitcoin RegTest network
325
+ await regtestUtils.broadcast(tx.toHex());
326
+
327
+ await regtestUtils.verify({
328
+ txId: tx.getId(),
329
+ address: regtestUtils.RANDOM_ADDRESS,
330
+ vout: 0,
331
+ value: 2e4,
332
+ });
333
+ });
334
+
335
+ it('can create (and broadcast via 3PBP) a Transaction, w/ a P2WPKH input with nonWitnessUtxo', async () => {
336
+ // For learning purposes, ignore this test.
337
+ // REPEATING ABOVE BUT WITH nonWitnessUtxo by passing false to getInputData
338
+ const p2wpkh = createPayment('p2wpkh');
339
+ const inputData = await getInputData(5e4, p2wpkh.payment, false, 'noredeem');
340
+ const psbt = new bitcoin.Psbt({ network: regtest })
341
+ .addInput(inputData)
342
+ .addOutput({
343
+ address: regtestUtils.RANDOM_ADDRESS,
344
+ value: 2e4,
345
+ })
346
+ .signInput(0, p2wpkh.keys[0]);
347
+ psbt.finalizeAllInputs();
348
+ const tx = psbt.extractTransaction();
349
+ await regtestUtils.broadcast(tx.toHex());
350
+ await regtestUtils.verify({
351
+ txId: tx.getId(),
352
+ address: regtestUtils.RANDOM_ADDRESS,
353
+ vout: 0,
354
+ value: 2e4,
355
+ });
356
+ });
357
+
358
+ it('can create (and broadcast via 3PBP) a Transaction, w/ a P2WSH(P2PK) input', async () => {
359
+ const p2wsh = createPayment('p2wsh-p2pk');
360
+ const inputData = await getInputData(5e4, p2wsh.payment, true, 'p2wsh');
361
+ {
362
+ const {
363
+ hash,
364
+ index,
365
+ witnessUtxo,
366
+ witnessScript, // NEW: A Buffer of the witnessScript
367
+ } = inputData;
368
+ assert.deepStrictEqual({ hash, index, witnessUtxo, witnessScript }, inputData);
369
+ }
370
+
371
+ const psbt = new bitcoin.Psbt({ network: regtest })
372
+ .addInput(inputData)
373
+ .addOutput({
374
+ address: regtestUtils.RANDOM_ADDRESS,
375
+ value: 2e4,
376
+ })
377
+ .signInput(0, p2wsh.keys[0]);
378
+
379
+ assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
380
+ psbt.finalizeAllInputs();
381
+
382
+ const tx = psbt.extractTransaction();
383
+
384
+ // build and broadcast to the Bitcoin RegTest network
385
+ await regtestUtils.broadcast(tx.toHex());
386
+
387
+ await regtestUtils.verify({
388
+ txId: tx.getId(),
389
+ address: regtestUtils.RANDOM_ADDRESS,
390
+ vout: 0,
391
+ value: 2e4,
392
+ });
393
+ });
394
+
395
+ it('can create (and broadcast via 3PBP) a Transaction, w/ a P2WSH(P2PK) input with nonWitnessUtxo', async () => {
396
+ // For learning purposes, ignore this test.
397
+ // REPEATING ABOVE BUT WITH nonWitnessUtxo by passing false to getInputData
398
+ const p2wsh = createPayment('p2wsh-p2pk');
399
+ const inputData = await getInputData(5e4, p2wsh.payment, false, 'p2wsh');
400
+ const psbt = new bitcoin.Psbt({ network: regtest })
401
+ .addInput(inputData)
402
+ .addOutput({
403
+ address: regtestUtils.RANDOM_ADDRESS,
404
+ value: 2e4,
405
+ })
406
+ .signInput(0, p2wsh.keys[0]);
407
+ psbt.finalizeAllInputs();
408
+ const tx = psbt.extractTransaction();
409
+ await regtestUtils.broadcast(tx.toHex());
410
+ await regtestUtils.verify({
411
+ txId: tx.getId(),
412
+ address: regtestUtils.RANDOM_ADDRESS,
413
+ vout: 0,
414
+ value: 2e4,
415
+ });
416
+ });
417
+
418
+ it(
419
+ 'can create (and broadcast via 3PBP) a Transaction, w/ a ' +
420
+ 'P2SH(P2WSH(P2MS(3 of 4))) (SegWit multisig) input',
421
+ async () => {
422
+ const p2sh = createPayment('p2sh-p2wsh-p2ms(3 of 4)');
423
+ const inputData = await getInputData(5e4, p2sh.payment, true, 'p2sh-p2wsh');
424
+ {
425
+ const { hash, index, witnessUtxo, redeemScript, witnessScript } = inputData;
426
+ assert.deepStrictEqual(
427
+ { hash, index, witnessUtxo, redeemScript, witnessScript },
428
+ inputData,
429
+ );
430
+ }
431
+
432
+ const psbt = new bitcoin.Psbt({ network: regtest })
433
+ .addInput(inputData)
434
+ .addOutput({
435
+ address: regtestUtils.RANDOM_ADDRESS,
436
+ value: 2e4,
437
+ })
438
+ .signInput(0, p2sh.keys[0])
439
+ .signInput(0, p2sh.keys[2])
440
+ .signInput(0, p2sh.keys[3]);
441
+
442
+ assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
443
+ assert.strictEqual(
444
+ psbt.validateSignaturesOfInput(0, validator, p2sh.keys[3].publicKey),
445
+ true,
446
+ );
447
+ assert.throws(() => {
448
+ psbt.validateSignaturesOfInput(0, validator, p2sh.keys[1].publicKey);
449
+ }, new RegExp('No signatures for this pubkey'));
450
+ psbt.finalizeAllInputs();
451
+
452
+ const tx = psbt.extractTransaction();
453
+
454
+ // build and broadcast to the Bitcoin RegTest network
455
+ await regtestUtils.broadcast(tx.toHex());
456
+
457
+ await regtestUtils.verify({
458
+ txId: tx.getId(),
459
+ address: regtestUtils.RANDOM_ADDRESS,
460
+ vout: 0,
461
+ value: 2e4,
462
+ });
463
+ },
464
+ );
465
+
466
+ it(
467
+ 'can create (and broadcast via 3PBP) a Transaction, w/ a ' +
468
+ 'P2SH(P2WSH(P2MS(3 of 4))) (SegWit multisig) input with nonWitnessUtxo',
469
+ async () => {
470
+ // For learning purposes, ignore this test.
471
+ // REPEATING ABOVE BUT WITH nonWitnessUtxo by passing false to getInputData
472
+ const p2sh = createPayment('p2sh-p2wsh-p2ms(3 of 4)');
473
+ const inputData = await getInputData(5e4, p2sh.payment, false, 'p2sh-p2wsh');
474
+ const psbt = new bitcoin.Psbt({ network: regtest })
475
+ .addInput(inputData)
476
+ .addOutput({
477
+ address: regtestUtils.RANDOM_ADDRESS,
478
+ value: 2e4,
479
+ })
480
+ .signInput(0, p2sh.keys[0])
481
+ .signInput(0, p2sh.keys[2])
482
+ .signInput(0, p2sh.keys[3]);
483
+ psbt.finalizeAllInputs();
484
+ const tx = psbt.extractTransaction();
485
+ await regtestUtils.broadcast(tx.toHex());
486
+ await regtestUtils.verify({
487
+ txId: tx.getId(),
488
+ address: regtestUtils.RANDOM_ADDRESS,
489
+ vout: 0,
490
+ value: 2e4,
491
+ });
492
+ },
493
+ );
494
+
495
+ it(
496
+ 'can create (and broadcast via 3PBP) a Transaction, w/ a ' +
497
+ 'P2SH(P2MS(2 of 2)) input with nonWitnessUtxo',
498
+ async () => {
499
+ const myKey = ECPair.makeRandom({ network: regtest });
500
+ const myKeys = [myKey, ECPair.fromPrivateKey(myKey.privateKey!, { network: regtest })];
501
+ const p2sh = createPayment('p2sh-p2ms(2 of 2)', myKeys);
502
+ const inputData = await getInputData(5e4, p2sh.payment, false, 'p2sh');
503
+ const psbt = new bitcoin.Psbt({ network: regtest })
504
+ .addInput(inputData)
505
+ .addOutput({
506
+ address: regtestUtils.RANDOM_ADDRESS,
507
+ value: 2e4,
508
+ })
509
+ .signInput(0, p2sh.keys[0]);
510
+ psbt.finalizeAllInputs();
511
+ const tx = psbt.extractTransaction();
512
+ await regtestUtils.broadcast(tx.toHex());
513
+ await regtestUtils.verify({
514
+ txId: tx.getId(),
515
+ address: regtestUtils.RANDOM_ADDRESS,
516
+ vout: 0,
517
+ value: 2e4,
518
+ });
519
+ },
520
+ );
521
+
522
+ it('can create (and broadcast via 3PBP) a Transaction, w/ a P2WPKH input using HD', async () => {
523
+ const hdRoot = bip32.fromSeed(rng(64));
524
+ const masterFingerprint = hdRoot.fingerprint;
525
+ const path = "m/84'/0'/0'/0/0";
526
+ const childNode = hdRoot.derivePath(path);
527
+ const pubkey = childNode.publicKey;
528
+
529
+ // This information should be added to your input via updateInput
530
+ // You can add multiple bip32Derivation objects for multisig, but
531
+ // each must have a unique pubkey.
532
+ //
533
+ // This is useful because as long as you store the masterFingerprint on
534
+ // the PSBT Creator's server, you can have the PSBT Creator do the heavy
535
+ // lifting with derivation from your m/84'/0'/0' xpub, (deriving only 0/0 )
536
+ // and your signer just needs to pass in an HDSigner interface (ie. bip32 library)
537
+ const updateData = {
538
+ bip32Derivation: [
539
+ {
540
+ masterFingerprint,
541
+ path,
542
+ pubkey,
543
+ },
544
+ ],
545
+ };
546
+ const p2wpkh = createPayment('p2wpkh', [childNode]);
547
+ const inputData = await getInputData(5e4, p2wpkh.payment, true, 'noredeem');
548
+ {
549
+ const { hash, index, witnessUtxo } = inputData;
550
+ assert.deepStrictEqual({ hash, index, witnessUtxo }, inputData);
551
+ }
552
+
553
+ // You can add extra attributes for updateData into the addInput(s) object(s)
554
+ Object.assign(inputData, updateData);
555
+
556
+ const psbt = new bitcoin.Psbt({ network: regtest })
557
+ .addInput(inputData)
558
+ // .updateInput(0, updateData) // if you didn't merge the bip32Derivation with inputData
559
+ .addOutput({
560
+ address: regtestUtils.RANDOM_ADDRESS,
561
+ value: 2e4,
562
+ })
563
+ .signInputHD(0, hdRoot); // must sign with root!!!
564
+
565
+ assert.strictEqual(psbt.validateSignaturesOfInput(0, validator), true);
566
+ assert.strictEqual(psbt.validateSignaturesOfInput(0, validator, childNode.publicKey), true);
567
+ psbt.finalizeAllInputs();
568
+
569
+ const tx = psbt.extractTransaction();
570
+
571
+ // build and broadcast to the Bitcoin RegTest network
572
+ await regtestUtils.broadcast(tx.toHex());
573
+
574
+ await regtestUtils.verify({
575
+ txId: tx.getId(),
576
+ address: regtestUtils.RANDOM_ADDRESS,
577
+ vout: 0,
578
+ value: 2e4,
579
+ });
580
+ });
581
+ });
582
+
583
+ function createPayment(_type: string, myKeys?: any[], network?: any): any {
584
+ network = network || regtest;
585
+ const splitType = _type.split('-').reverse();
586
+ const isMultisig = splitType[0].slice(0, 4) === 'p2ms';
587
+ const keys = myKeys || [];
588
+ let m: number | undefined;
589
+ if (isMultisig) {
590
+ const match = splitType[0].match(/^p2ms\((\d+) of (\d+)\)$/);
591
+ m = parseInt(match![1], 10);
592
+ let n = parseInt(match![2], 10);
593
+ if (keys.length > 0 && keys.length !== n) {
594
+ throw new Error('Need n keys for multisig');
595
+ }
596
+ while (!myKeys && n > 1) {
597
+ keys.push(ECPair.makeRandom({ network }));
598
+ n--;
599
+ }
600
+ }
601
+ if (!myKeys) keys.push(ECPair.makeRandom({ network }));
602
+
603
+ let payment: any;
604
+ splitType.forEach((type) => {
605
+ if (type.slice(0, 4) === 'p2ms') {
606
+ payment = bitcoin.payments.p2ms({
607
+ m,
608
+ pubkeys: keys.map((key) => key.publicKey).sort((a, b) => a.compare(b)),
609
+ network,
610
+ });
611
+ } else if (['p2sh', 'p2wsh'].indexOf(type) > -1) {
612
+ payment = (bitcoin.payments as any)[type]({
613
+ redeem: payment,
614
+ network,
615
+ });
616
+ } else {
617
+ payment = (bitcoin.payments as any)[type]({
618
+ pubkey: keys[0].publicKey,
619
+ network,
620
+ });
621
+ }
622
+ });
623
+
624
+ return {
625
+ payment,
626
+ keys,
627
+ };
628
+ }
629
+
630
+ function getWitnessUtxo(out: any): any {
631
+ delete out.address;
632
+ out.script = Buffer.from(out.script, 'hex');
633
+ return out;
634
+ }
635
+
636
+ async function getInputData(
637
+ amount: number,
638
+ payment: any,
639
+ isSegwit: boolean,
640
+ redeemType: string,
641
+ ): Promise<any> {
642
+ const unspent = await regtestUtils.faucetComplex(payment.output, amount);
643
+ const utx = await regtestUtils.fetch(unspent.txId);
644
+ // for non segwit inputs, you must pass the full transaction buffer
645
+ const nonWitnessUtxo = Buffer.from(utx.txHex, 'hex');
646
+ // for segwit inputs, you only need the output script and value as an object.
647
+ const witnessUtxo = getWitnessUtxo(utx.outs[unspent.vout]);
648
+ const mixin = isSegwit ? { witnessUtxo } : { nonWitnessUtxo };
649
+ const mixin2: any = {};
650
+ switch (redeemType) {
651
+ case 'p2sh':
652
+ mixin2.redeemScript = payment.redeem.output;
653
+ break;
654
+ case 'p2wsh':
655
+ mixin2.witnessScript = payment.redeem.output;
656
+ break;
657
+ case 'p2sh-p2wsh':
658
+ mixin2.witnessScript = payment.redeem.redeem.output;
659
+ mixin2.redeemScript = payment.redeem.output;
660
+ break;
661
+ }
662
+ return {
663
+ hash: unspent.txId,
664
+ index: unspent.vout,
665
+ ...mixin,
666
+ ...mixin2,
667
+ };
668
+ }