-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
csv.spec.ts
519 lines (467 loc) · 15.1 KB
/
csv.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
import * as assert from 'assert';
import { PsbtInput } from 'bip174';
import ECPairFactory from 'ecpair';
import * as ecc from 'tiny-secp256k1';
import { before, describe, it } from 'mocha';
import * as bitcoin from 'bitcoinjs-lib';
import { regtestUtils } from './_regtest.js';
import { reverseBuffer } from 'bitcoinjs-lib/src/bufferutils';
import * as tools from 'uint8array-tools';
const ECPair = ECPairFactory(ecc);
const regtest = regtestUtils.network;
import bip68 from 'bip68';
import * as varuint from 'varuint-bitcoin';
function toOutputScript(address: string): Uint8Array {
return bitcoin.address.toOutputScript(address, regtest);
}
function idToHash(txid: string): Uint8Array {
return reverseBuffer(tools.fromHex(txid));
}
const alice = ECPair.fromWIF(
'cScfkGjbzzoeewVWmU2hYPUHeVGJRDdFt7WhmrVVGkxpmPP8BHWe',
regtest,
);
const bob = ECPair.fromWIF(
'cMkopUXKWsEzAjfa1zApksGRwjVpJRB3831qM9W4gKZsLwjHXA9x',
regtest,
);
const charles = ECPair.fromWIF(
'cMkopUXKWsEzAjfa1zApksGRwjVpJRB3831qM9W4gKZsMSb4Ubnf',
regtest,
);
const dave = ECPair.fromWIF(
'cMkopUXKWsEzAjfa1zApksGRwjVpJRB3831qM9W4gKZsMwS4pqnx',
regtest,
);
describe('bitcoinjs-lib (transactions w/ CSV)', () => {
// force update MTP
before(async () => {
await regtestUtils.mine(11);
});
const hashType = bitcoin.Transaction.SIGHASH_ALL;
interface KeyPair {
publicKey: Uint8Array;
}
// IF MTP (from when confirmed) > seconds, _alice can redeem
function csvCheckSigOutput(
_alice: KeyPair,
_bob: KeyPair,
sequence: number,
): Uint8Array {
return bitcoin.script.fromASM(
`
OP_IF
${tools.toHex(bitcoin.script.number.encode(sequence))}
OP_CHECKSEQUENCEVERIFY
OP_DROP
OP_ELSE
${tools.toHex(_bob.publicKey)}
OP_CHECKSIGVERIFY
OP_ENDIF
${tools.toHex(_alice.publicKey)}
OP_CHECKSIG
`
.trim()
.replace(/\s+/g, ' '),
);
}
// 2 of 3 multisig of _bob, _charles, _dave,
// but after sequence1 time, _alice can allow the multisig to become 1 of 3.
// but after sequence2 time, _alice can sign for the output all by themself.
// Ref: https://github.com/bitcoinbook/bitcoinbook/blob/f8b883dcd4e3d1b9adf40fed59b7e898fbd9241f/ch07.asciidoc#complex-script-example
// Note: bitcoinjs-lib will not offer specific support for problems with
// advanced script usages such as below. Use at your own risk.
function complexCsvOutput(
_alice: KeyPair,
_bob: KeyPair,
_charles: KeyPair,
_dave: KeyPair,
sequence1: number,
sequence2: number,
): Uint8Array {
return bitcoin.script.fromASM(
`
OP_IF
OP_IF
OP_2
OP_ELSE
${tools.toHex(bitcoin.script.number.encode(sequence1))}
OP_CHECKSEQUENCEVERIFY
OP_DROP
${tools.toHex(_alice.publicKey)}
OP_CHECKSIGVERIFY
OP_1
OP_ENDIF
${tools.toHex(_bob.publicKey)}
${tools.toHex(_charles.publicKey)}
${tools.toHex(_dave.publicKey)}
OP_3
OP_CHECKMULTISIG
OP_ELSE
${tools.toHex(bitcoin.script.number.encode(sequence2))}
OP_CHECKSEQUENCEVERIFY
OP_DROP
${tools.toHex(_alice.publicKey)}
OP_CHECKSIG
OP_ENDIF
`
.trim()
.replace(/\s+/g, ' '),
);
}
// expiry will pass, {Alice's signature} OP_TRUE
it(
'can create (and broadcast via 3PBP) a Transaction where Alice can redeem ' +
'the output after the expiry (in the future) (simple CHECKSEQUENCEVERIFY)',
async () => {
// 5 blocks from now
const sequence = bip68.encode({ blocks: 5 });
const p2sh = bitcoin.payments.p2sh({
redeem: {
output: csvCheckSigOutput(alice, bob, sequence),
},
network: regtest,
});
// fund the P2SH(CSV) address
const unspent = await regtestUtils.faucet(p2sh.address!, 1e5);
const utx = await regtestUtils.fetch(unspent.txId);
// for non segwit inputs, you must pass the full transaction buffer
const nonWitnessUtxo = Buffer.from(utx.txHex, 'hex');
// This is an example of using the finalizeInput second parameter to
// define how you finalize the inputs, allowing for any type of script.
const tx = new bitcoin.Psbt({ network: regtest })
.setVersion(2)
.addInput({
hash: unspent.txId,
index: unspent.vout,
sequence,
redeemScript: p2sh.redeem!.output!,
nonWitnessUtxo,
})
.addOutput({
address: regtestUtils.RANDOM_ADDRESS,
value: BigInt(7e4),
})
.signInput(0, alice)
.finalizeInput(0, csvGetFinalScripts) // See csvGetFinalScripts below
.extractTransaction();
// TODO: test that it failures _prior_ to expiry, unfortunately, race conditions when run concurrently
// ...
// into the future!
await regtestUtils.mine(10);
await regtestUtils.broadcast(tx.toHex());
await regtestUtils.verify({
txId: tx.getId(),
address: regtestUtils.RANDOM_ADDRESS,
vout: 0,
value: 7e4,
});
},
).timeout(8000);
// expiry in the future, {Alice's signature} OP_TRUE
it(
'can create (but fail to broadcast via 3PBP) a Transaction where Alice ' +
'attempts to redeem before the expiry (simple CHECKSEQUENCEVERIFY)',
async () => {
// two hours after confirmation
const sequence = bip68.encode({ seconds: 7168 });
const p2sh = bitcoin.payments.p2sh({
network: regtest,
redeem: {
output: csvCheckSigOutput(alice, bob, sequence),
},
});
// fund the P2SH(CSV) address
const unspent = await regtestUtils.faucet(p2sh.address!, 2e4);
const tx = new bitcoin.Transaction();
tx.version = 2;
tx.addInput(idToHash(unspent.txId), unspent.vout, sequence);
tx.addOutput(toOutputScript(regtestUtils.RANDOM_ADDRESS), BigInt(1e4));
// {Alice's signature} OP_TRUE
const signatureHash = tx.hashForSignature(
0,
p2sh.redeem!.output!,
hashType,
);
const redeemScriptSig = bitcoin.payments.p2sh({
network: regtest,
redeem: {
network: regtest,
output: p2sh.redeem!.output,
input: bitcoin.script.compile([
bitcoin.script.signature.encode(
alice.sign(signatureHash),
hashType,
),
bitcoin.script.signature.encode(bob.sign(signatureHash), hashType),
bitcoin.opcodes.OP_TRUE,
]),
},
}).input;
tx.setInputScript(0, redeemScriptSig!);
await regtestUtils.broadcast(tx.toHex()).catch(err => {
assert.throws(() => {
if (err) throw err;
}, /Error: non-BIP68-final/);
});
},
).timeout(8000);
// Check first combination of complex CSV, 2 of 3
it(
'can create (and broadcast via 3PBP) a Transaction where Bob and Charles ' +
'can send (complex CHECKSEQUENCEVERIFY)',
async () => {
// 2 blocks from now
const sequence1 = bip68.encode({ blocks: 2 });
// 5 blocks from now
const sequence2 = bip68.encode({ blocks: 5 });
const p2sh = bitcoin.payments.p2sh({
redeem: {
output: complexCsvOutput(
alice,
bob,
charles,
dave,
sequence1,
sequence2,
),
},
network: regtest,
});
// fund the P2SH(CCSV) address
const unspent = await regtestUtils.faucet(p2sh.address!, 1e5);
const tx = new bitcoin.Transaction();
tx.version = 2;
tx.addInput(idToHash(unspent.txId), unspent.vout);
tx.addOutput(toOutputScript(regtestUtils.RANDOM_ADDRESS), BigInt(7e4));
// OP_0 {Bob sig} {Charles sig} OP_TRUE OP_TRUE
const signatureHash = tx.hashForSignature(
0,
p2sh.redeem!.output!,
hashType,
);
const redeemScriptSig = bitcoin.payments.p2sh({
network: regtest,
redeem: {
network: regtest,
output: p2sh.redeem!.output,
input: bitcoin.script.compile([
bitcoin.opcodes.OP_0,
bitcoin.script.signature.encode(bob.sign(signatureHash), hashType),
bitcoin.script.signature.encode(
charles.sign(signatureHash),
hashType,
),
bitcoin.opcodes.OP_TRUE,
bitcoin.opcodes.OP_TRUE,
]),
},
}).input;
tx.setInputScript(0, redeemScriptSig!);
await regtestUtils.broadcast(tx.toHex());
await regtestUtils.verify({
txId: tx.getId(),
address: regtestUtils.RANDOM_ADDRESS,
vout: 0,
value: 7e4,
});
},
).timeout(8000);
// Check first combination of complex CSV, mediator + 1 of 3 after 2 blocks
it(
'can create (and broadcast via 3PBP) a Transaction where Alice (mediator) ' +
'and Bob can send after 2 blocks (complex CHECKSEQUENCEVERIFY)',
async () => {
// 2 blocks from now
const sequence1 = bip68.encode({ blocks: 2 });
// 5 blocks from now
const sequence2 = bip68.encode({ blocks: 5 });
const p2sh = bitcoin.payments.p2sh({
redeem: {
output: complexCsvOutput(
alice,
bob,
charles,
dave,
sequence1,
sequence2,
),
},
network: regtest,
});
// fund the P2SH(CCSV) address
const unspent = await regtestUtils.faucet(p2sh.address!, 1e5);
const tx = new bitcoin.Transaction();
tx.version = 2;
tx.addInput(idToHash(unspent.txId), unspent.vout, sequence1); // Set sequence1 for input
tx.addOutput(toOutputScript(regtestUtils.RANDOM_ADDRESS), BigInt(7e4));
// OP_0 {Bob sig} {Alice mediator sig} OP_FALSE OP_TRUE
const signatureHash = tx.hashForSignature(
0,
p2sh.redeem!.output!,
hashType,
);
const redeemScriptSig = bitcoin.payments.p2sh({
network: regtest,
redeem: {
network: regtest,
output: p2sh.redeem!.output,
input: bitcoin.script.compile([
bitcoin.opcodes.OP_0,
bitcoin.script.signature.encode(bob.sign(signatureHash), hashType),
bitcoin.script.signature.encode(
alice.sign(signatureHash),
hashType,
),
bitcoin.opcodes.OP_0,
bitcoin.opcodes.OP_TRUE,
]),
},
}).input;
tx.setInputScript(0, redeemScriptSig!);
// Wait 2 blocks
await regtestUtils.mine(2);
await regtestUtils.broadcast(tx.toHex());
await regtestUtils.verify({
txId: tx.getId(),
address: regtestUtils.RANDOM_ADDRESS,
vout: 0,
value: 7e4,
});
},
).timeout(8000);
// Check first combination of complex CSV, mediator after 5 blocks
it(
'can create (and broadcast via 3PBP) a Transaction where Alice (mediator) ' +
'can send after 5 blocks (complex CHECKSEQUENCEVERIFY)',
async () => {
// 2 blocks from now
const sequence1 = bip68.encode({ blocks: 2 });
// 5 blocks from now
const sequence2 = bip68.encode({ blocks: 5 });
const p2sh = bitcoin.payments.p2sh({
redeem: {
output: complexCsvOutput(
alice,
bob,
charles,
dave,
sequence1,
sequence2,
),
},
network: regtest,
});
// fund the P2SH(CCSV) address
const unspent = await regtestUtils.faucet(p2sh.address!, 1e5);
const tx = new bitcoin.Transaction();
tx.version = 2;
tx.addInput(idToHash(unspent.txId), unspent.vout, sequence2); // Set sequence2 for input
tx.addOutput(toOutputScript(regtestUtils.RANDOM_ADDRESS), BigInt(7e4));
// {Alice mediator sig} OP_FALSE
const signatureHash = tx.hashForSignature(
0,
p2sh.redeem!.output!,
hashType,
);
const redeemScriptSig = bitcoin.payments.p2sh({
network: regtest,
redeem: {
network: regtest,
output: p2sh.redeem!.output,
input: bitcoin.script.compile([
bitcoin.script.signature.encode(
alice.sign(signatureHash),
hashType,
),
bitcoin.opcodes.OP_0,
]),
},
}).input;
tx.setInputScript(0, redeemScriptSig!);
// Wait 5 blocks
await regtestUtils.mine(5);
await regtestUtils.broadcast(tx.toHex());
await regtestUtils.verify({
txId: tx.getId(),
address: regtestUtils.RANDOM_ADDRESS,
vout: 0,
value: 7e4,
});
},
).timeout(8000);
});
// This function is used to finalize a CSV transaction using PSBT.
// See first test above.
function csvGetFinalScripts(
inputIndex: number,
input: PsbtInput,
script: Uint8Array,
isSegwit: boolean,
isP2SH: boolean,
isP2WSH: boolean,
): {
finalScriptSig: Uint8Array | undefined;
finalScriptWitness: Uint8Array | undefined;
} {
// Step 1: Check to make sure the meaningful script matches what you expect.
const decompiled = bitcoin.script.decompile(script);
// Checking if first OP is OP_IF... should do better check in production!
// You may even want to check the public keys in the script against a
// whitelist depending on the circumstances!!!
// You also want to check the contents of the input to see if you have enough
// info to actually construct the scriptSig and Witnesses.
if (!decompiled || decompiled[0] !== bitcoin.opcodes.OP_IF) {
throw new Error(`Can not finalize input #${inputIndex}`);
}
// Step 2: Create final scripts
let payment: bitcoin.Payment = {
network: regtest,
output: script,
// This logic should be more strict and make sure the pubkeys in the
// meaningful script are the ones signing in the PSBT etc.
input: bitcoin.script.compile([
input.partialSig![0].signature,
bitcoin.opcodes.OP_TRUE,
]),
};
if (isP2WSH && isSegwit)
payment = bitcoin.payments.p2wsh({
network: regtest,
redeem: payment,
});
if (isP2SH)
payment = bitcoin.payments.p2sh({
network: regtest,
redeem: payment,
});
function witnessStackToScriptWitness(witness: Uint8Array[]): Uint8Array {
let buffer = new Uint8Array(0);
function writeSlice(slice: Uint8Array): void {
buffer = Buffer.concat([buffer, slice]);
}
function writeVarInt(i: number): void {
const currentLen = buffer.length;
const varintLen = varuint.encodingLength(i);
buffer = Buffer.concat([buffer, Buffer.allocUnsafe(varintLen)]);
varuint.encode(i, buffer, currentLen);
}
function writeVarSlice(slice: Uint8Array): void {
writeVarInt(slice.length);
writeSlice(slice);
}
function writeVector(vector: Uint8Array[]): void {
writeVarInt(vector.length);
vector.forEach(writeVarSlice);
}
writeVector(witness);
return buffer;
}
return {
finalScriptSig: payment.input,
finalScriptWitness:
payment.witness && payment.witness.length > 0
? witnessStackToScriptWitness(payment.witness)
: undefined,
};
}