-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.html
758 lines (714 loc) · 52.1 KB
/
index.html
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no">
<!--
<script src="https://unpkg.com/@cmdcode/tapscript"></script>
<script src="https://supertestnet.github.io/hedgehog/noble-secp256k1.js"></script>
<script src="https://supertestnet.github.io/hedgehog/rmd160.js"></script>
<script src="file:///home/supertestnet/hedgehog_project/tapscript.js"></script>
<script src="file:///home/supertestnet/hedgehog_project/noble-secp256k1.js"></script>
<script src="file:///home/supertestnet/hedgehog_project/rmd160.js"></script>
-->
<script src="https://supertestnet.github.io/hedgehog-advanced/tapscript.js"></script>
<script src="https://supertestnet.github.io/hedgehog-advanced/noble-secp256k1.js"></script>
<script src="https://supertestnet.github.io/hedgehog-advanced/rmd160.js"></script>
<script>
var hedgehog = {
network: "regtest",
state: {},
keypairs: {},
state_obj: {
alices_privkey: null,
bobs_privkey: null,
alices_pubkey: null,
bobs_pubkey: null,
multisig_script: null,
multisig_tree: null,
multisig_utxo_info: {},
i_was_last_to_send: false,
alice_can_revoke: [],
bob_can_revoke: [],
balances: [],
balances_before_most_recent_send: [],
balances_before_most_recent_receive: [],
alices_revocation_preimages: [],
alices_revocation_hashes: [],
bobs_revocation_preimages: [],
bobs_revocation_hashes: [],
txids_to_watch_for: {},
latest_force_close_txs: [],
extra_outputs: [],
},
hexToBytes: hex => Uint8Array.from( hex.match( /.{1,2}/g ).map( byte => parseInt( byte, 16 ) ) ),
bytesToHex: bytes => bytes.reduce( ( str, byte ) => str + byte.toString( 16 ).padStart( 2, "0" ), "" ),
rmd160: s => {
if ( typeof s == "string" ) s = new TextEncoder().encode( s );
var hash = RIPEMD160.create();
hash.update( new Uint8Array( s ) );
return hedgehog.bytesToHex( hash.digest() );
},
isValidHex: hex => {
if ( !hex ) return;
var length = hex.length;
if ( length % 2 ) return;
try {
var bigint = BigInt( "0x" + hex, "hex" );
} catch( e ) {
return;
}
var prepad = bigint.toString( 16 );
var i; for ( i=0; i<length; i++ ) prepad = "0" + prepad;
var padding = prepad.slice( -Math.abs( length ) );
return ( padding === hex );
},
getVin: ( txid, vout, amnt, addy, sequence ) => {
var input = {
txid,
vout,
prevout: {
value: amnt,
scriptPubKey: tapscript.Address.toScriptPubKey( addy ),
},
}
if ( sequence ) input[ "sequence" ] = sequence;
return input;
},
getVout: ( amnt, addy ) => ({
value: amnt,
scriptPubKey: tapscript.Address.toScriptPubKey( addy ),
}),
makeAddress: ( chan_id, scripts ) => {
var tree = scripts.map( s => tapscript.Tap.encodeScript( s ) );
var pubkey = "ab".repeat( 32 );
var [ tpubkey ] = tapscript.Tap.getPubKey( pubkey, { tree });
return tapscript.Address.p2tr.fromPubKey( tpubkey, hedgehog.network );
},
makeAlicesRevocationScript: chan_id => ([
[ hedgehog.state[ chan_id ].alices_pubkey, "OP_CHECKSIG", hedgehog.state[ chan_id ].bobs_pubkey, "OP_CHECKSIGADD", 2, "OP_EQUAL" ],
[ "OP_RIPEMD160", hedgehog.state[ chan_id ].alices_revocation_hashes[ hedgehog.state[ chan_id ].alices_revocation_hashes.length - 1 ], "OP_EQUALVERIFY", hedgehog.state[ chan_id ].bobs_pubkey, "OP_CHECKSIG" ],
//TODO: change the 10 to 4032
[ 10, "OP_CHECKSEQUENCEVERIFY", "OP_DROP", hedgehog.state[ chan_id ].bobs_pubkey, "OP_CHECKSIG" ],
]),
makeBobsRevocationScript: chan_id => ([
[ hedgehog.state[ chan_id ].alices_pubkey, "OP_CHECKSIG", hedgehog.state[ chan_id ].bobs_pubkey, "OP_CHECKSIGADD", 2, "OP_EQUAL" ],
[ "OP_RIPEMD160", hedgehog.state[ chan_id ].bobs_revocation_hashes[ hedgehog.state[ chan_id ].bobs_revocation_hashes.length - 1 ], "OP_EQUALVERIFY", hedgehog.state[ chan_id ].alices_pubkey, "OP_CHECKSIG" ],
//TODO: change the 10 to 4032
[ 10, "OP_CHECKSEQUENCEVERIFY", "OP_DROP", hedgehog.state[ chan_id ].alices_pubkey, "OP_CHECKSIG" ],
]),
openChannel: async push_all_funds_to_counterparty => {
//there are three ways to open a channel:
//the first way is as Bob, opening a channel to Alice unilaterally
//the code for that after this "if" statement because a
//unilateral channel open requires pushing all funds to your counterparty
//the second way is as Alice, accepting a channel Bob already unilaterally opened
//the third way is as Alice, opening a new channel cooperatively with Bob
//the second and third ways are handled in the first "if" statement below
//in theory there are two more ways: Bob could open a channel to Alice cooperatively
//and thus keep some or all of the funds on his side, or Alice could open a channel
//to Bob unilaterally and thus push all funds to Bob's side. To do these examples,
//just have Alice open a channel with push_all_funds_to_counterparty set to true
//or have Bob open a channel with push_all_funds_to_counterparty set to false
if ( !push_all_funds_to_counterparty ) {
var has_data = confirm( `Click ok if someone sent you channel opening info or cancel if you are opening this channel yourself` );
if ( has_data ) {
var data = JSON.parse( prompt( `Enter the data your counterparty sent you` ) );
//TODO: validate the data so you don't acccidentally accept irredeemable coins
//or crash your wallet
//create the state object
var pubkey = data[ "recipient_pubkey" ];
if ( !( pubkey in hedgehog.keypairs ) ) return alert( `Your counterparty tried to scam you! Do not interact with them any further` );
var privkey = hedgehog.keypairs[ pubkey ][ "privkey" ];
var preimage = hedgehog.keypairs[ pubkey ][ "preimage" ];
var chan_id = data[ "chan_id" ];
hedgehog.state[ chan_id ] = hedgehog.state_obj;
hedgehog.state[ chan_id ][ "alices_privkey" ] = privkey;
hedgehog.state[ chan_id ][ "alices_pubkey" ] = pubkey;
hedgehog.state[ chan_id ][ "bobs_pubkey" ] = data[ "sender_pubkey" ];
hedgehog.state[ chan_id ][ "multisig_utxo_info" ] = data[ "utxo_info" ];
hedgehog.state[ chan_id ].alices_revocation_preimages.push( preimage );
var hash = hedgehog.rmd160( hedgehog.hexToBytes( preimage ) );
hedgehog.state[ chan_id ].alices_revocation_hashes.push( hash );
hedgehog.state[ chan_id ].alices_address = tapscript.Address.fromScriptPubKey( [ "OP_1", hedgehog.state[ chan_id ].alices_pubkey ], hedgehog.network );
hedgehog.state[ chan_id ].bobs_address = tapscript.Address.fromScriptPubKey( [ "OP_1", hedgehog.state[ chan_id ].bobs_pubkey ], hedgehog.network );
var multisig_script = [ hedgehog.state[ chan_id ].alices_pubkey, "OP_CHECKSIG", hedgehog.state[ chan_id ].bobs_pubkey, "OP_CHECKSIGADD", 2, "OP_EQUAL" ];
var multisig_tree = [ tapscript.Tap.encodeScript( multisig_script ) ];
hedgehog.state[ chan_id ].multisig_script = multisig_script;
hedgehog.state[ chan_id ].multisig_tree = multisig_tree;
hedgehog.state[ chan_id ].multisig = hedgehog.makeAddress( chan_id, [ multisig_script ] );
//temporarily pretend the entire balance is on Bob's side so he can
//send it to Alice using the regular send command
var amnt = data[ "amnt" ];
hedgehog.state[ chan_id ].balances = [ 0, amnt ];
var opening = true;
//validate the initial state using the regular "receive" function
var opened = await hedgehog.receive( {amnt: amnt - 500 - 500, sig_1: data[ "sig_1" ], sig_3: data[ "sig_3" ], chan_id: data[ "chan_id" ], hash: data[ "hash" ]} );
if ( opened !== true ) return;
//update the state to reflect alice's ability to withdraw 100%
hedgehog.state[ chan_id ].balances = [ amnt, 0 ];
//update the send/receive/close buttons to use this channel
$( '.send_btn' ).onclick = () => {console.log( "send this data to your recipient:" );console.log( JSON.stringify( hedgehog.send( chan_id ) ) );}
$( '.receive_btn' ).onclick = () => {hedgehog.receive();}
$( '.close_channel' ).onclick = () => {hedgehog.closeChannel( chan_id );}
alert( `yay, your channel is open!` );
}
return;
}
//handle the case where Bob opens a channel to Alice unilaterally
//start by preparing the state object
var chan_id = hedgehog.bytesToHex( nobleSecp256k1.utils.randomPrivateKey() ).substring( 0, 32 );
hedgehog.state[ chan_id ] = hedgehog.state_obj;
hedgehog.state[ chan_id ].bobs_privkey = hedgehog.bytesToHex( nobleSecp256k1.utils.randomPrivateKey() );
hedgehog.state[ chan_id ].bobs_pubkey = nobleSecp256k1.getPublicKey( hedgehog.state[ chan_id ].bobs_privkey, true ).substring( 2 );
var alices_pubkey_and_hash = JSON.parse( prompt( `Enter Alice's pubkey and revocation hash` ) );
hedgehog.state[ chan_id ].alices_pubkey = alices_pubkey_and_hash[ 0 ];
hedgehog.state[ chan_id ].alices_revocation_hashes.push( alices_pubkey_and_hash[ 1 ] );
hedgehog.state[ chan_id ].alices_address = tapscript.Address.fromScriptPubKey( [ "OP_1", hedgehog.state[ chan_id ].alices_pubkey ], hedgehog.network );
hedgehog.state[ chan_id ].bobs_address = tapscript.Address.fromScriptPubKey( [ "OP_1", hedgehog.state[ chan_id ].bobs_pubkey ], hedgehog.network );
var multisig_script = [ hedgehog.state[ chan_id ].alices_pubkey, "OP_CHECKSIG", hedgehog.state[ chan_id ].bobs_pubkey, "OP_CHECKSIGADD", 2, "OP_EQUAL" ];
var multisig_tree = [ tapscript.Tap.encodeScript( multisig_script ) ];
hedgehog.state[ chan_id ].multisig_script = multisig_script;
hedgehog.state[ chan_id ].multisig_tree = multisig_tree;
hedgehog.state[ chan_id ].multisig = hedgehog.makeAddress( chan_id, [ multisig_script ] );
console.log( "address:", hedgehog.state[ chan_id ].multisig );
var txid = prompt( `send some sats to this address and give the txid:\n\n${hedgehog.state[ chan_id ].multisig}` );
var vout = Number( prompt( `and the vout` ) );
var amnt = Number( prompt( `and the amount` ) );
hedgehog.state[ chan_id ].multisig_utxo_info = {
txid,
vout,
amnt,
}
//temporarily pretend the entire balance is on Bob's side so he can
//send it to Alice using the regular send command
hedgehog.state[ chan_id ].balances = [ 0, amnt ];
//prepare the transaction that moves all funds to Alice's side
var opening = true;
var sigs_and_stuff = hedgehog.send( chan_id, amnt - 500 - 500, opening );
sigs_and_stuff[ "amnt" ] = amnt;
console.log( "send this data to your recipient:" );
console.log( JSON.stringify( sigs_and_stuff ) );
//update the state to reflect alice's ability to withdraw 100%
hedgehog.state[ chan_id ].balances = [ amnt, 0 ];
hedgehog.state[ chan_id ].balances_before_most_recent_receive = [ amnt, 0 ];
//update the send/receive/close buttons to use this channel
$( '.send_btn' ).onclick = () => {console.log( "send this data to your recipient:" );console.log( JSON.stringify( hedgehog.send( chan_id ) ) );}
$( '.receive_btn' ).onclick = () => {hedgehog.receive();}
$( '.close_channel' ).onclick = () => {hedgehog.closeChannel( chan_id );}
alert( `yay, your channel is funded! send your counterparty the info in your console` );
},
send: ( chan_id, amnt, opening ) => {
//automatically find out if I am Alice or Bob using the chan_id
var am_alice = !!hedgehog.state[ chan_id ].alices_privkey;
//if I am the previous sender, restore the state to what it was before
//I last sent so I can overwrite my previous state update
if ( hedgehog.state[ chan_id ].i_was_last_to_send ) {
var current_balances = JSON.parse( JSON.stringify( hedgehog.state[ chan_id ].balances ) );
hedgehog.state[ chan_id ].balances = hedgehog.state[ chan_id ].balances_before_most_recent_send;
if ( am_alice ) {
hedgehog.state[ chan_id ].bob_can_revoke.pop();
hedgehog.state[ chan_id ].alices_revocation_preimages.pop();
hedgehog.state[ chan_id ].alices_revocation_hashes.pop();
} else {
hedgehog.state[ chan_id ].alice_can_revoke.pop();
hedgehog.state[ chan_id ].bobs_revocation_preimages.pop();
hedgehog.state[ chan_id ].bobs_revocation_hashes.pop();
}
}
//unless an amount is already given, prompt the user to enter an amount
if ( !amnt ) amnt = Number( prompt( `Please enter an amount you want to send to your counterparty` ) );
//update the amnt variable if necessary. For example,
//if the prev balance was 0 for Bob but I sent him 5k,
//current_balances would say he has 5k. If I am now
//sending him 1k, amnt should be 6k, which is
//( current_balances[ 1 ] - prev_balance[ 1 ] ) + amnt
if ( hedgehog.state[ chan_id ].i_was_last_to_send ) {
if ( am_alice ) amnt = ( current_balances[ 1 ] - hedgehog.state[ chan_id ].balances[ 1 ] ) + amnt;
else amnt = ( current_balances[ 0 ] - hedgehog.state[ chan_id ].balances[ 0 ] ) + amnt;
}
//create the revocation scripts so the recipient can revoke this state later
if ( am_alice ) {
var latest_scripts = hedgehog.makeBobsRevocationScript( chan_id );
var revocable_address = hedgehog.makeAddress( chan_id, latest_scripts );
hedgehog.state[ chan_id ].bob_can_revoke.push( [ revocable_address, latest_scripts ] );
} else {
var latest_scripts = hedgehog.makeAlicesRevocationScript( chan_id );
var revocable_address = hedgehog.makeAddress( chan_id, latest_scripts );
hedgehog.state[ chan_id ].alice_can_revoke.push( [ revocable_address, latest_scripts ] );
}
//create and sign the timeout tx in case your counterparty takes
//too long to force close or disappears during a force closure
var utxo_info = hedgehog.state[ chan_id ].multisig_utxo_info;
var balances = hedgehog.state[ chan_id ].balances;
var original_amnt = balances[ 0 ] + balances[ 1 ];
//tx0 sends all the money from the multisig into alice_can_revoke
//or bob_can_revoke (depending on who is sending)
var tx0 = tapscript.Tx.create({
vin: [hedgehog.getVin( utxo_info[ "txid" ], utxo_info[ "vout" ], original_amnt, hedgehog.state[ chan_id ][ "multisig" ] )],
vout: [hedgehog.getVout( original_amnt - 500, revocable_address )],
});
var tx0_id = tapscript.Tx.util.getTxid( tx0 );
var alices_address = hedgehog.state[ chan_id ].alices_address;
var bobs_address = hedgehog.state[ chan_id ].bobs_address;
if ( am_alice ) var my_address = alices_address;
else var my_address = bobs_address;
var timeout_tx = tapscript.Tx.create({
//TODO: change the sequence number (relative timelock) from 10 to 4032
vin: [hedgehog.getVin( tx0_id, 0, original_amnt - 500, revocable_address, 10 )],
vout: [hedgehog.getVout( original_amnt - 500 - 500, my_address )],
});
if ( am_alice ) var privkey = hedgehog.state[ chan_id ].alices_privkey;
else var privkey = hedgehog.state[ chan_id ].bobs_privkey;
var timeout_tx_script = latest_scripts[ 2 ];
var timeout_tx_target = tapscript.Tap.encodeScript( timeout_tx_script );
var timeout_tx_tree = latest_scripts.map( s => tapscript.Tap.encodeScript( s ) );
var timeout_sig = tapscript.Signer.taproot.sign( privkey, timeout_tx, 0, { extension: timeout_tx_target }).hex;
var [ _, cblock ] = tapscript.Tap.getPubKey( "ab".repeat( 32 ), { tree: timeout_tx_tree, target: timeout_tx_target });
timeout_tx.vin[ 0 ].witness = [ timeout_sig, timeout_tx_script, cblock ];
hedgehog.state[ chan_id ].txids_to_watch_for[ tx0_id ] = {
timeout_tx: tapscript.Tx.encode( timeout_tx ).hex,
}
//create tx1 to distribute the funds however the sender wishes to do so
var tx1 = tapscript.Tx.create({
//TODO: change the sequence number (relative timelock) from 5 to 2016
vin: [hedgehog.getVin( tx0_id, 0, original_amnt - 500, revocable_address, 5 )],
vout: [],
});
//increase the recipient's balance by amnt and decrease the sender's by
//amnt and two mining fees
if ( am_alice ) {
var amnt_for_alice = balances[ 0 ] - amnt - 500 - 500;
var amnt_for_bob = balances[ 1 ] + amnt;
} else {
var amnt_for_alice = balances[ 0 ] + amnt;
var amnt_for_bob = balances[ 1 ] - amnt - 500 - 500;
if ( opening ) var amnt_for_bob = 0;
}
if ( am_alice ) {
if ( amnt_for_alice ) tx1.vout.push( hedgehog.getVout( amnt_for_alice, alices_address ) );
if ( amnt_for_bob ) tx1.vout.push( hedgehog.getVout( amnt_for_bob, bobs_address ) );
} else {
if ( amnt_for_alice ) tx1.vout.push( hedgehog.getVout( amnt_for_alice, alices_address ) );
if ( amnt_for_bob ) tx1.vout.push( hedgehog.getVout( amnt_for_bob, bobs_address ) );
}
// console.log( "tx0:", JSON.stringify( tx0 ) );
// console.log( "tx1:", JSON.stringify( tx1 ) );
//Sign both of these transactions, but sign tx1 with a sig that
//is only valid after a relative timelock of 2016 blocks expires.
var tx0_script = hedgehog.state[ chan_id ].multisig_script;
var tx0_target = tapscript.Tap.encodeScript( tx0_script );
var tx0_tree = hedgehog.state[ chan_id ].multisig_tree;
var tx1_script = latest_scripts[ 0 ];
var tx1_target = tapscript.Tap.encodeScript( tx1_script );
var tx1_tree = latest_scripts.map( s => tapscript.Tap.encodeScript( s ) );
var sig_1 = tapscript.Signer.taproot.sign( privkey, tx0, 0, { extension: tx0_target }).hex;
//sig_3 is for tx1 and it has a relative timelock of 2016 blocks
//because tx1's only input (see above) has sequence number 2016
var sig_3 = tapscript.Signer.taproot.sign( privkey, tx1, 0, { extension: tx1_target }).hex;
var sighash_3 = tapscript.Signer.taproot.hash( tx1, 0, { extension: tx1_target }).hex;
//If necessary, create a revocation sig that conditionally revokes
//the prior state
var conditional_revocation_is_necessary = false;
if ( am_alice && hedgehog.state[ chan_id ].alices_revocation_hashes.length ) conditional_revocation_is_necessary = true;
if ( !am_alice && hedgehog.state[ chan_id ].bobs_revocation_hashes.length ) conditional_revocation_is_necessary = true;
if ( conditional_revocation_is_necessary ) {
if ( am_alice ) var prev_address = hedgehog.state[ chan_id ].alice_can_revoke[ hedgehog.state[ chan_id ].alice_can_revoke.length - 1 ][ 0 ];
else var prev_address = hedgehog.state[ chan_id ].bob_can_revoke[ hedgehog.state[ chan_id ].bob_can_revoke.length - 1 ][ 0 ];
if ( am_alice ) var prev_scripts = hedgehog.state[ chan_id ].alice_can_revoke[ hedgehog.state[ chan_id ].alice_can_revoke.length - 1 ][ 1 ];
else var prev_scripts = hedgehog.state[ chan_id ].bob_can_revoke[ hedgehog.state[ chan_id ].bob_can_revoke.length - 1 ][ 1 ];
var prev_tx0 = tapscript.Tx.create({
vin: [hedgehog.getVin( utxo_info[ "txid" ], utxo_info[ "vout" ], original_amnt, hedgehog.state[ chan_id ][ "multisig" ] )],
vout: [hedgehog.getVout( original_amnt - 500, prev_address )],
});
var prev_txid = tapscript.Tx.util.getTxid( prev_tx0 );
var new_tx1 = tapscript.Tx.create({
vin: [hedgehog.getVin( prev_txid, 0, original_amnt - 500, prev_address )],
vout: [],
});
if ( am_alice ) {
if ( amnt_for_alice ) new_tx1.vout.push( hedgehog.getVout( amnt_for_alice, alices_address ) );
if ( amnt_for_bob ) new_tx1.vout.push( hedgehog.getVout( amnt_for_bob, bobs_address ) );
} else {
if ( amnt_for_alice ) new_tx1.vout.push( hedgehog.getVout( amnt_for_alice, alices_address ) );
if ( amnt_for_bob ) new_tx1.vout.push( hedgehog.getVout( amnt_for_bob, bobs_address ) );
}
var new_tx1_script = prev_scripts[ 0 ];
var new_tx1_target = tapscript.Tap.encodeScript( new_tx1_script );
var new_tx1_tree = prev_scripts.map( s => tapscript.Tap.encodeScript( s ) );
var conditional_revocation_sig = tapscript.Signer.taproot.sign( privkey, new_tx1, 0, { extension: new_tx1_target }).hex;
}
//If necessary, prepare to reveal whichever preimage fully revokes
//the state prior to the prior state (yes, doubly prior)
var full_revocation_is_necessary = false;
if ( am_alice && hedgehog.state[ chan_id ].alices_revocation_hashes.length > 1 ) full_revocation_is_necessary = true;
if ( !am_alice && hedgehog.state[ chan_id ].bobs_revocation_hashes.length > 1 ) full_revocation_is_necessary = true;
if ( full_revocation_is_necessary ) {
if ( am_alice ) var full_revocation_preimage = hedgehog.state[ chan_id ].alices_revocation_preimages[ hedgehog.state[ chan_id ].alices_revocation_preimages.length - 2 ];
else var full_revocation_preimage = hedgehog.state[ chan_id ].bobs_revocation_preimages[ hedgehog.state[ chan_id ].bobs_revocation_preimages.length - 2 ];
}
//Prepare a preimage/hash pair for the recipient to use in their
//next state update
var preimage = hedgehog.bytesToHex( nobleSecp256k1.utils.randomPrivateKey() ).substring( 0, 32 );
var hash = hedgehog.rmd160( hedgehog.hexToBytes( preimage ) );
if ( am_alice ) {
hedgehog.state[ chan_id ].alices_revocation_preimages.push( preimage );
hedgehog.state[ chan_id ].alices_revocation_hashes.push( hash );
} else {
hedgehog.state[ chan_id ].bobs_revocation_preimages.push( preimage );
hedgehog.state[ chan_id ].bobs_revocation_hashes.push( hash );
}
//Create an object to send all this data to the recipient
var object = {
sig_1,
sig_3,
hash,
amnt,
chan_id,
}
if ( conditional_revocation_sig ) object[ "conditional_revocation_sig" ] = conditional_revocation_sig;
if ( full_revocation_is_necessary ) object[ "full_revocation_preimage" ] = full_revocation_preimage;
if ( opening ) object[ "utxo_info" ] = utxo_info;
if ( opening ) object[ "sender_pubkey" ] = hedgehog.state[ chan_id ].bobs_pubkey;
if ( opening ) object[ "recipient_pubkey" ] = hedgehog.state[ chan_id ].alices_pubkey;
//update the balances
hedgehog.state[ chan_id ].balances_before_most_recent_send = JSON.parse( JSON.stringify( hedgehog.state[ chan_id ].balances ) );
if ( am_alice ) {
hedgehog.state[ chan_id ].balances = [ balances[ 0 ] - amnt, balances[ 1 ] + amnt ];
hedgehog.state[ chan_id ].balances_before_most_recent_receive = [ balances[ 0 ] - amnt, balances[ 1 ] + amnt ];
} else {
hedgehog.state[ chan_id ].balances = [ balances[ 0 ] + amnt, balances[ 1 ] - amnt ];
hedgehog.state[ chan_id ].balances_before_most_recent_receive = [ balances[ 0 ] + amnt, balances[ 1 ] - amnt ];
}
//update state of who was last to send
hedgehog.state[ chan_id ].i_was_last_to_send = true;
return object;
},
receive: async data => {
var data_was_here_originally = data;
if ( !data ) data = JSON.parse( prompt( `Enter the data from your counterparty` ) );
var chan_id = data[ "chan_id" ];
//automatically find out if I am Alice or Bob using the chan_id
var am_alice = !!hedgehog.state[ chan_id ].alices_privkey;
//if I recently received, restore the state to what it was before
//I last received so I can overwrite my previous state update
//but keep a copy of the old state so that, if the new state is
//invalid, I can restore the old state
if ( !hedgehog.state[ chan_id ].i_was_last_to_send ) {
var current_balances = JSON.parse( JSON.stringify( hedgehog.state[ chan_id ].balances ) );
hedgehog.state[ chan_id ].balances = hedgehog.state[ chan_id ].balances_before_most_recent_receive;
if ( !hedgehog.state[ chan_id ].balances.length ) {
var sum = current_balances[ 0 ] + current_balances[ 1 ];
if ( am_alice ) hedgehog.state[ chan_id ].balances = [ 0, sum ];
else hedgehog.state[ chan_id ].balances = [ sum, 0 ];
}
if ( am_alice ) {
var old_rev_hashes = hedgehog.state[ chan_id ].bobs_revocation_hashes.pop();
var other_rev_info = hedgehog.state[ chan_id ].alice_can_revoke.pop();
} else {
var old_rev_hashes = hedgehog.state[ chan_id ].alices_revocation_hashes.pop();
var other_rev_info = hedgehog.state[ chan_id ].bob_can_revoke.pop();
}
}
//push your counterparty's payment hash to their hashes object
if ( am_alice ) hedgehog.state[ chan_id ].bobs_revocation_hashes.push( data[ "hash" ] );
else hedgehog.state[ chan_id ].alices_revocation_hashes.push( data[ "hash" ] );
//create the revocation scripts so the recipient can revoke this state later
if ( am_alice ) {
var latest_scripts = hedgehog.makeAlicesRevocationScript( chan_id );
var revocable_address = hedgehog.makeAddress( chan_id, latest_scripts );
hedgehog.state[ chan_id ].alice_can_revoke.push( [ revocable_address, latest_scripts ] );
} else {
var latest_scripts = hedgehog.makeBobsRevocationScript( chan_id );
var revocable_address = hedgehog.makeAddress( chan_id, latest_scripts );
hedgehog.state[ chan_id ].bob_can_revoke.push( [ revocable_address, latest_scripts ] );
}
//create tx0 to send all the money from the multisig into alice_can_revoke
//or bob_can_revoke (depending on who is sending)
var utxo_info = hedgehog.state[ chan_id ].multisig_utxo_info;
var amnt = data[ "amnt" ];
var balances = hedgehog.state[ chan_id ].balances;
var alices_address = hedgehog.state[ chan_id ].alices_address;
var bobs_address = hedgehog.state[ chan_id ].bobs_address;
var original_amnt = balances[ 0 ] + balances[ 1 ];
var tx0 = tapscript.Tx.create({
vin: [hedgehog.getVin( utxo_info[ "txid" ], utxo_info[ "vout" ], original_amnt, hedgehog.state[ chan_id ][ "multisig" ] )],
vout: [hedgehog.getVout( original_amnt - 500, revocable_address )],
});
var tx0_id = tapscript.Tx.util.getTxid( tx0 );
//create tx1 to distribute the funds however the sender wishes to do so
var tx1 = tapscript.Tx.create({
//TODO: change the sequence number (relative timelock) from 5 to 2016
vin: [hedgehog.getVin( tx0_id, 0, original_amnt - 500, revocable_address, 5 )],
vout: [],
});
//increase the recipient's balance by amnt and decrease the sender's by
//amnt and two mining fees
if ( am_alice ) {
var amnt_for_alice = balances[ 0 ] + amnt;
var amnt_for_bob = balances[ 1 ] - amnt - 500 - 500;
if ( data_was_here_originally ) var amnt_for_bob = 0;
} else {
var amnt_for_alice = balances[ 0 ] - amnt - 500 - 500;
var amnt_for_bob = balances[ 1 ] + amnt;
}
if ( am_alice ) {
if ( amnt_for_alice ) tx1.vout.push( hedgehog.getVout( amnt_for_alice, alices_address ) );
if ( amnt_for_bob ) tx1.vout.push( hedgehog.getVout( amnt_for_bob, bobs_address ) );
} else {
if ( amnt_for_alice ) tx1.vout.push( hedgehog.getVout( amnt_for_alice, alices_address ) );
if ( amnt_for_bob ) tx1.vout.push( hedgehog.getVout( amnt_for_bob, bobs_address ) );
}
// console.log( "tx0:", JSON.stringify( tx0 ) );
// console.log( "tx1:", JSON.stringify( tx1 ) );
//validate the signatures by which the sender creates the new state
if ( am_alice ) var pubkey_to_validate_against = hedgehog.state[ chan_id ].bobs_pubkey;
else var pubkey_to_validate_against = hedgehog.state[ chan_id ].alices_pubkey;
var tx0_script = hedgehog.state[ chan_id ].multisig_script;
var tx0_target = tapscript.Tap.encodeScript( tx0_script );
var tx0_tree = hedgehog.state[ chan_id ].multisig_tree;
var tx1_script = latest_scripts[ 0 ];
var tx1_target = tapscript.Tap.encodeScript( tx1_script );
var tx1_tree = latest_scripts.map( s => tapscript.Tap.encodeScript( s ) );
var sig_1 = data[ "sig_1" ];
var sighash_1 = tapscript.Signer.taproot.hash( tx0, 0, { extension: tx0_target }).hex;
var is_valid_1 = await nobleSecp256k1.schnorr.verify( sig_1, sighash_1, pubkey_to_validate_against );
var sig_3 = data[ "sig_3" ];
var sighash_3 = tapscript.Signer.taproot.hash( tx1, 0, { extension: tx1_target }).hex;
var is_valid_3 = await nobleSecp256k1.schnorr.verify( sig_3, sighash_3, pubkey_to_validate_against );
if ( !is_valid_1 || !is_valid_3 ) {
//restore old state and inform user this state update was invalid
if ( am_alice ) {
hedgehog.state[ chan_id ].bobs_revocation_hashes.push( old_rev_hashes );
hedgehog.state[ chan_id ].alice_can_revoke.push( other_rev_info );
} else {
hedgehog.state[ chan_id ].alices_revocation_hashes.push( old_rev_hashes );
hedgehog.state[ chan_id ].bob_can_revoke.push( other_rev_info );
}
return alert( `Your counterparty sent you invalid main-sig data so it will be ignored` );
}
//Sign both of these transactions, but sign tx1 with a sig that
//is only valid after a relative timelock of 2016 blocks expires.
if ( am_alice ) var privkey = hedgehog.state[ chan_id ].alices_privkey;
else var privkey = hedgehog.state[ chan_id ].bobs_privkey;
var sig_2 = tapscript.Signer.taproot.sign( privkey, tx0, 0, { extension: tx0_target }).hex;
var sig_4 = tapscript.Signer.taproot.sign( privkey, tx1, 0, { extension: tx1_target }).hex;
//If necessary, validate the signature by which the sender
//conditionally revokes the old state and cosign the revocation
var conditional_revocation_is_necessary = false;
if ( am_alice && hedgehog.state[ chan_id ].bobs_revocation_hashes.length > 1 ) conditional_revocation_is_necessary = true;
if ( !am_alice && hedgehog.state[ chan_id ].alices_revocation_hashes.length > 1 ) conditional_revocation_is_necessary = true;
if ( conditional_revocation_is_necessary ) {
if ( !( "conditional_revocation_sig" in data ) ) {
//restore old state and inform user this state update was invalid
if ( am_alice ) {
hedgehog.state[ chan_id ].bobs_revocation_hashes.push( old_rev_hashes );
hedgehog.state[ chan_id ].alice_can_revoke.push( other_rev_info );
} else {
hedgehog.state[ chan_id ].alices_revocation_hashes.push( old_rev_hashes );
hedgehog.state[ chan_id ].bob_can_revoke.push( other_rev_info );
}
return alert( `Your counterparty sent you invalid cond-sig data (no cond sig) so it will be ignored` );
}
//TODO: ensure checking this sig doesn't crash the app
if ( am_alice ) var prev_address = hedgehog.state[ chan_id ].bob_can_revoke[ hedgehog.state[ chan_id ].bob_can_revoke.length - 1 ][ 0 ];
else var prev_address = hedgehog.state[ chan_id ].alice_can_revoke[ hedgehog.state[ chan_id ].alice_can_revoke.length - 1 ][ 0 ];
if ( am_alice ) var prev_scripts = hedgehog.state[ chan_id ].bob_can_revoke[ hedgehog.state[ chan_id ].bob_can_revoke.length - 1 ][ 1 ];
else var prev_scripts = hedgehog.state[ chan_id ].alice_can_revoke[ hedgehog.state[ chan_id ].alice_can_revoke.length - 1 ][ 1 ];
var prev_tx0 = tapscript.Tx.create({
vin: [hedgehog.getVin( utxo_info[ "txid" ], utxo_info[ "vout" ], original_amnt, hedgehog.state[ chan_id ][ "multisig" ] )],
vout: [hedgehog.getVout( original_amnt - 500, prev_address )],
});
var prev_txid = tapscript.Tx.util.getTxid( prev_tx0 );
var new_tx1 = tapscript.Tx.create({
vin: [hedgehog.getVin( prev_txid, 0, original_amnt - 500, prev_address )],
vout: [],
});
if ( am_alice ) {
if ( amnt_for_alice ) new_tx1.vout.push( hedgehog.getVout( amnt_for_alice, alices_address ) );
if ( amnt_for_bob ) new_tx1.vout.push( hedgehog.getVout( amnt_for_bob, bobs_address ) );
} else {
if ( amnt_for_alice ) new_tx1.vout.push( hedgehog.getVout( amnt_for_alice, alices_address ) );
if ( amnt_for_bob ) new_tx1.vout.push( hedgehog.getVout( amnt_for_bob, bobs_address ) );
}
var new_tx1_script = prev_scripts[ 0 ];
var new_tx1_target = tapscript.Tap.encodeScript( new_tx1_script );
var new_tx1_tree = prev_scripts.map( s => tapscript.Tap.encodeScript( s ) );
var conditional_revocation_sig = data[ "conditional_revocation_sig" ];
var conditional_sighash = tapscript.Signer.taproot.hash( new_tx1, 0, { extension: new_tx1_target }).hex;
var conditional_is_valid = await nobleSecp256k1.schnorr.verify( conditional_revocation_sig, conditional_sighash, pubkey_to_validate_against );
if ( !conditional_is_valid ) {
//restore old state and inform user this state update was invalid
if ( am_alice ) {
hedgehog.state[ chan_id ].bobs_revocation_hashes.push( old_rev_hashes );
hedgehog.state[ chan_id ].alice_can_revoke.push( other_rev_info );
} else {
hedgehog.state[ chan_id ].alices_revocation_hashes.push( old_rev_hashes );
hedgehog.state[ chan_id ].bob_can_revoke.push( other_rev_info );
}
return alert( `Your counterparty sent you invalid cond-sig data (invalid sig) so it will be ignored` );
}
var conditional_cosignature = tapscript.Signer.taproot.sign( privkey, new_tx1, 0, { extension: new_tx1_target }).hex;
}
//If necessary, validate the preimage by which the sender
//fully revokes the old state and sign the revocation
var full_revocation_is_necessary = false;
if ( am_alice && hedgehog.state[ chan_id ].bobs_revocation_hashes.length > 2 ) full_revocation_is_necessary = true;
if ( !am_alice && hedgehog.state[ chan_id ].alices_revocation_hashes.length > 2 ) full_revocation_is_necessary = true;
if ( full_revocation_is_necessary ) {
if ( !( "full_revocation_preimage" in data ) ) {
//restore old state and inform user this state update was invalid
if ( am_alice ) {
hedgehog.state[ chan_id ].bobs_revocation_hashes.push( old_rev_hashes );
hedgehog.state[ chan_id ].alice_can_revoke.push( other_rev_info );
} else {
hedgehog.state[ chan_id ].alices_revocation_hashes.push( old_rev_hashes );
hedgehog.state[ chan_id ].bob_can_revoke.push( other_rev_info );
}
return alert( `Your counterparty sent you invalid full-rev data (no pmg) so it will be ignored` );
}
//TODO: ensure checking this sig doesn't crash the app
if ( am_alice ) var prev_address = hedgehog.state[ chan_id ].bob_can_revoke[ hedgehog.state[ chan_id ].bob_can_revoke.length - 2 ][ 0 ];
else var prev_address = hedgehog.state[ chan_id ].alice_can_revoke[ hedgehog.state[ chan_id ].alice_can_revoke.length - 2 ][ 0 ];
if ( am_alice ) var prev_scripts = hedgehog.state[ chan_id ].bob_can_revoke[ hedgehog.state[ chan_id ].bob_can_revoke.length - 2 ][ 1 ];
else var prev_scripts = hedgehog.state[ chan_id ].alice_can_revoke[ hedgehog.state[ chan_id ].alice_can_revoke.length - 2 ][ 1 ];
var preimage = data[ "full_revocation_preimage" ];
var expected_hash = prev_scripts[ 1 ][ 1 ];
var hash_provided = hedgehog.rmd160( hedgehog.hexToBytes( preimage ) );
if ( hash_provided != expected_hash ) {
//restore old state and inform user this state update was invalid
if ( am_alice ) {
hedgehog.state[ chan_id ].bobs_revocation_hashes.push( old_rev_hashes );
hedgehog.state[ chan_id ].alice_can_revoke.push( other_rev_info );
} else {
hedgehog.state[ chan_id ].alices_revocation_hashes.push( old_rev_hashes );
hedgehog.state[ chan_id ].bob_can_revoke.push( other_rev_info );
}
return alert( `Your counterparty sent you invalid full-rev data (wrg pmg) so it will be ignored` );
}
var prev_tx0 = tapscript.Tx.create({
vin: [hedgehog.getVin( utxo_info[ "txid" ], utxo_info[ "vout" ], original_amnt, hedgehog.state[ chan_id ][ "multisig" ] )],
vout: [hedgehog.getVout( original_amnt - 500, prev_address )],
});
var doubly_prev_txid = tapscript.Tx.util.getTxid( prev_tx0 );
if ( am_alice ) var my_address = alices_address;
else var my_address = bobs_address;
var tx2 = tapscript.Tx.create({
vin: [hedgehog.getVin( doubly_prev_txid, 0, original_amnt - 500, prev_address )],
vout: [hedgehog.getVout( original_amnt - 500 - 500, my_address )],
});
var tx2_script = prev_scripts[ 1 ];
var tx2_target = tapscript.Tap.encodeScript( tx2_script );
var tx2_tree = prev_scripts.map( s => tapscript.Tap.encodeScript( s ) );
var full_revocation_sig = tapscript.Signer.taproot.sign( privkey, tx2, 0, { extension: tx2_target }).hex;
}
//prepare and save the force closure initiation transaction
var [ _, cblock ] = tapscript.Tap.getPubKey( "ab".repeat( 32 ), { tree: tx0_tree, target: tx0_target });
//the order of the pubkeys is Alice first, then Bob, so -- if I am alice --
//the first sig must be sig_2 -- which means it must be in the "last"
//position (i.e. the sig created by Alice must appear right before her pubkey)
if ( am_alice ) tx0.vin[ 0 ].witness = [ sig_1, sig_2, tx0_script, cblock ];
else tx0.vin[ 0 ].witness = [ sig_2, sig_1, tx0_script, cblock ];
//prepare the force closure finalization transaction
var [ _, cblock ] = tapscript.Tap.getPubKey( "ab".repeat( 32 ), { tree: tx1_tree, target: tx1_target });
if ( am_alice ) tx1.vin[ 0 ].witness = [ sig_3, sig_4, tx1_script, cblock ];
else tx1.vin[ 0 ].witness = [ sig_4, sig_3, tx1_script, cblock ];
//if necessary, prepare and save the conditional revocation transaction
if ( conditional_revocation_is_necessary ) {
var [ _, cblock ] = tapscript.Tap.getPubKey( "ab".repeat( 32 ), { tree: new_tx1_tree, target: new_tx1_target });
if ( am_alice ) new_tx1.vin[ 0 ].witness = [ conditional_revocation_sig, conditional_cosignature, new_tx1_script, cblock ];
else new_tx1.vin[ 0 ].witness = [ conditional_cosignature, conditional_revocation_sig, tx1_script, cblock ];
}
//if necessary, prepare and save the conditional revocation transaction
if ( full_revocation_is_necessary ) {
var [ _, cblock ] = tapscript.Tap.getPubKey( "ab".repeat( 32 ), { tree: tx2_tree, target: tx2_target });
tx2.vin[ 0 ].witness = [ full_revocation_sig, preimage, tx2_script, cblock ];
}
//save the transactions
hedgehog.state[ chan_id ].latest_force_close_txs = [
tapscript.Tx.encode( tx0 ).hex,
tapscript.Tx.encode( tx1 ).hex,
];
if ( conditional_revocation_is_necessary ) {
hedgehog.state[ chan_id ].txids_to_watch_for[ prev_txid ] = {
conditional_revocation_tx: tapscript.Tx.encode( new_tx1 ).hex,
}
}
if ( full_revocation_is_necessary ) hedgehog.state[ chan_id ].txids_to_watch_for[ doubly_prev_txid ][ "full_revocation_tx" ] = tapscript.Tx.encode( tx2 ).hex;
//update the balances
if ( am_alice ) {
hedgehog.state[ chan_id ].balances = [ balances[ 0 ] + amnt, balances[ 1 ] - amnt ];
} else {
hedgehog.state[ chan_id ].balances = [ balances[ 0 ] - amnt, balances[ 1 ] + amnt ];
}
//update state of who was last to send
hedgehog.state[ chan_id ].i_was_last_to_send = false;
return true;
},
closeChannel: chan_id => {
console.log( "Broadcast this transaction to initiate a force closure:" );
console.log( hedgehog.state[ chan_id ].latest_force_close_txs[ 0 ] );
//TODO: change the 5 to a 2016
console.log( "Wait 5 blocks and broadcast this transaction to finalize the force closure:" );
console.log( hedgehog.state[ chan_id ].latest_force_close_txs[ 1 ] );
}
}
</script>
<style>
* {
box-sizing: border-box;
font-size: 1.15rem;
font-family: Arial, sans-serif;
}
html {
max-width: 800px;
padding: 3rem 1rem;
margin: auto;
line-height: 1.25;
padding: 0;
}
body {
margin: 3rem 1rem;
}
h1 {
font-size: 2rem;
}
h2 {
font-size: 1.5rem;
}
input {
line-height: 1.25;
width: 100%;
height: 1.8rem;
font-size: 1.15rem;
border: 1px solid grey;
}
@media screen and (max-width: 600px) {
}
</style>
<script>
var $ = document.querySelector.bind( document );
var $$ = document.querySelectorAll.bind( document );
var url_params = new URLSearchParams( window.location.search );
var url_keys = url_params.keys();
var $_GET = {}
for ( var key of url_keys ) $_GET[ key ] = url_params.get( key );
</script>
</head>
<body>
<script>var push_all_funds_to_counterparty = true; if ( $_GET[ "bob" ] != "true" ) push_all_funds_to_counterparty = false;</script>
<h1>Welcome to hedgehog</h1>
<p><button class="send_btn">Send</button><button class="receive_btn">Receive</button><br><button onclick="hedgehog.openChannel( push_all_funds_to_counterparty )" class="open_channel">Open channel</button><br><button class="close_channel">Close channel</button></p>
<script>
if ( $_GET[ "bob" ] != "true" ) {
var privkey = hedgehog.bytesToHex( nobleSecp256k1.utils.randomPrivateKey() );
var pubkey = nobleSecp256k1.getPublicKey( privkey, true ).substring( 2 );
var preimage = hedgehog.bytesToHex( nobleSecp256k1.utils.randomPrivateKey() ).substring( 0, 32 );
var hash = hedgehog.rmd160( hedgehog.hexToBytes( preimage ) );
hedgehog.keypairs[ pubkey ] = {privkey, preimage};
console.log( "Your pubkey/hash pair:" );
console.log( JSON.stringify( [ pubkey, hash ] ) );
}
</script>
</body>
</html>