forked from bitcoinops/bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulate_eltoo.py
More file actions
executable file
·2224 lines (1730 loc) · 95 KB
/
Copy pathsimulate_eltoo.py
File metadata and controls
executable file
·2224 lines (1730 loc) · 95 KB
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (c) 2015-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Simulation tests for eltoo payment channel update scheme
"""
from collections import OrderedDict, namedtuple
import copy
from io import BytesIO
import json
from debug_utils import DebugTaprootSignatureHash
from eltoo_scripts import (
get_update_tapscript,
get_settle_tapscript,
get_htlc_claim_tapscript,
get_htlc_refund_tapscript,
get_eltoo_update_script,
get_eltoo_htlc_script,
get_eltoo_htlc_script_witness,
get_p2pkh_script
)
from test_framework.address import program_to_witness
from test_framework.blocktools import (
create_block,
create_coinbase,
WITNESS_SCALE_FACTOR
)
from test_framework.key import (
compute_xonly_pubkey,
generate_privkey,
sign_schnorr,
tweak_add_pubkey,
ECKey,
ECPubKey,
SECP256K1_ORDER
)
from test_framework.messages import (
ser_string,
sha256,
COutPoint,
CScriptWitness,
CTransaction,
CTxIn,
CTxInWitness,
CTxOut
)
from test_framework.p2p import P2PDataStore
from test_framework.script import (
hash160,
sha256,
taproot_construct,
CScript,
KEY_VERSION_ANYPREVOUT,
OP_0,
OP_CHECKSEQUENCEVERIFY,
OP_CHECKSIG,
OP_CHECKSIGADD,
OP_NUMEQUAL,
OP_TRUE,
OP_VERIFY,
SIGHASH_DEFAULT,
SIGHASH_ALL,
SIGHASH_SINGLE,
SIGHASH_ANYONECANPAY,
SIGHASH_ANYPREVOUT,
SIGHASH_ANYPREVOUTANYSCRIPT,
LegacySignatureHash,
TaprootSignatureHash
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_raises_rpc_error
)
import time
import random
NUM_OUTPUTS_TO_COLLECT = 33
CSV_DELAY = 20
DUST_LIMIT = 600
FEE_AMOUNT = 1000
CHANNEL_AMOUNT = 1000000
RELAY_FEE = 100
NUM_SIGNERS = 2
CLTV_START_TIME = 500000000
INVOICE_TIMEOUT = 3600 # 60 minute
BLOCK_TIME = 600 # 10 minutes
MIN_FEE = 50000
DEFAULT_NSEQUENCE = 0xFFFFFFFE # disable nSequence lock
# from bitcoinops script.py
def get_version_tagged_pubkey(pubkey, version):
assert pubkey.is_compressed
assert pubkey.is_valid
# When the version 0xfe is used, the control block may become indistinguishable from annex.
# In such case, use of annex becomes mandatory.
assert 0 <= version < 0xff and not (version & 1)
data = pubkey.get_bytes()
return bytes([data[0] & 1 | version]) + data[1:]
# from bitcoinops util.py
def create_spending_transaction(node, txid, version=1, nSequence=0, nLockTime=0):
"""Construct a CTransaction object that spends the first ouput from txid."""
# Construct transaction
spending_tx = CTransaction()
# Populate the transaction version
spending_tx.nVersion = version
# Populate the locktime
spending_tx.nLockTime = nLockTime
# Populate the transaction inputs
outpoint = COutPoint(int(txid, 16), 0)
spending_tx_in = CTxIn(outpoint=outpoint, nSequence=nSequence)
spending_tx.vin = [spending_tx_in]
dest_addr = node.getnewaddress(address_type="bech32")
scriptpubkey = bytes.fromhex(node.getaddressinfo(dest_addr)['scriptPubKey'])
# Complete output which returns 0.5 BTC to Bitcoin Core wallet
amount_sat = int(0.5 * 100_000_000)
dest_output = CTxOut(nValue=amount_sat, scriptPubKey=scriptpubkey)
spending_tx.vout = [dest_output]
return spending_tx
# from bitcoinops util.py
def generate_and_send_coins(node, address, amount_sat):
"""Generate blocks on node and then send amount_sat to address.
No change output is added to the transaction.
Return a CTransaction object."""
version = node.getnetworkinfo()['subversion']
print("\nClient version is {}\n".format(version))
# Generate 101 blocks and send reward to bech32 address
reward_address = node.getnewaddress(address_type="bech32")
node.generatetoaddress(101, reward_address)
balance = node.getbalance()
print("Balance: {}\n".format(balance))
assert balance > 1
unspent_txid = node.listunspent(1)[-1]["txid"]
inputs = [{"txid": unspent_txid, "vout": 0}]
# Create a raw transaction sending 1 BTC to the address, then sign and send it.
# We won't create a change output, so maxfeerate must be set to 0
# to allow any fee rate.
tx_hex = node.createrawtransaction(inputs=inputs, outputs=[{address: amount_sat / 100_000_000}])
res = node.signrawtransactionwithwallet(hexstring=tx_hex)
tx_hex = res["hex"]
assert res["complete"]
assert 'errors' not in res
txid = node.sendrawtransaction(hexstring=tx_hex, maxfeerate=0)
tx_hex = node.getrawtransaction(txid)
# Reconstruct wallet transaction locally
tx = CTransaction()
tx.deserialize(BytesIO(bytes.fromhex(tx_hex)))
tx.rehash()
return tx
# from bitcoinops util.py
def test_transaction(node, tx, error_message=None):
tx_str = tx.serialize().hex()
ret = node.testmempoolaccept(rawtxs=[tx_str], maxfeerate=0)[0]
print(ret)
if error_message is not None:
assert ret['reject-reason'] == error_message
return ret['allowed']
def flatten(lst):
ret = []
for elem in lst:
if isinstance(elem, list):
ret += flatten(elem)
else:
ret.append(elem)
return ret
def dump_json_test(tx, input_utxos, idx, success, failure):
spender = input_utxos[idx].spender
fields = [
("tx", tx.serialize().hex()),
("prevouts", [x.output.serialize().hex() for x in input_utxos]),
("index", idx)
]
def dump_witness(wit):
return OrderedDict([("scriptSig", wit[0].hex()), ("witness", [x.hex() for x in wit[1]])])
if success is not None:
fields.append(("success", dump_witness(success)))
if failure is not None:
fields.append(("failure", dump_witness(failure)))
# Write the dump to $TEST_DUMP_DIR/x/xyz... where x,y,z,... are the SHA1 sum of the dump (which makes the
# file naming scheme compatible with fuzzing infrastructure).
dump = json.dumps(OrderedDict(fields)) + ",\n"
print(dump)
def get_state_address(inner_pubkey, state):
update_script = get_update_tapscript(state)
settle_script = get_settle_tapscript()
taptree = taproot_construct(inner_pubkey, [
("update", update_script), ("settle", settle_script)
])
tweaked, _ = tweak_add_pubkey(taptree.internal_pubkey, taptree.tweak)
address = program_to_witness(version=0x01, program=tweaked, main=False)
return address
def get_htlc_address(inner_pubkey, preimage_hash, claim_pubkey, expiry, refund_pubkey):
htlc_claim_script = get_htlc_claim_tapscript(preimage_hash, claim_pubkey)
htlc_refund_script = get_htlc_refund_tapscript(expiry, refund_pubkey)
taptree = taproot_construct(inner_pubkey, [
("htlc_claim", htlc_claim_script), ("htlc_refund", htlc_refund_script)
])
tweaked, _ = tweak_add_pubkey(taptree.internal_pubkey, taptree.tweak)
address = program_to_witness(version=0x01, program=tweaked, main=False)
return address
def create_update_tx(node, source_tx, dest_addr, state, amount_sat):
# UPDATE TX
# nlocktime: CLTV_START_TIME + state
# nsequence: 0
# sighash=SINGLE | ANYPREVOUTANYSCRIPT
update_tx = CTransaction()
update_tx.nVersion = 2
update_tx.nLockTime = CLTV_START_TIME + state
# Populate the transaction inputs
source_tx.rehash()
outpoint = COutPoint(int(source_tx.hash, 16), 0)
update_tx.vin = [CTxIn(outpoint=outpoint, nSequence=0)]
scriptpubkey = bytes.fromhex(node.getaddressinfo(dest_addr)['scriptPubKey'])
dest_output = CTxOut(nValue=amount_sat, scriptPubKey=scriptpubkey)
update_tx.vout = [dest_output]
return update_tx
def create_settle_tx(node, source_tx, outputs):
# SETTLE TX
# nlocktime: CLTV_START_TIME + state + 1
# nsequence: CSV_DELAY
# sighash=ALL | ANYPREVOUT (using ANYPREVOUT commits to a specific state because 'n' in the update leaf is commited to in the root hash used as the scriptPubKey)
# output 0: A
# output 1: B
# output 2..n: <HTLCs>
settle_tx = CTransaction()
settle_tx.nVersion = 2
settle_tx.nLockTime = source_tx.nLockTime + 1
# Populate the transaction inputs
source_tx.rehash()
outpoint = COutPoint(int(source_tx.hash, 16), 0)
settle_tx.vin = [CTxIn(outpoint=outpoint, nSequence=CSV_DELAY)]
# Complete output which emits 0.1 BTC to each party and 0.1 to two HTLCs
for dest_addr, amount_sat in outputs:
# dest_addr = node.getnewaddress(address_type="bech32")
scriptpubkey = bytes.fromhex(node.getaddressinfo(dest_addr)['scriptPubKey'])
dest_output = CTxOut(nValue=amount_sat, scriptPubKey=scriptpubkey)
settle_tx.vout.append(dest_output)
return settle_tx
def create_htlc_claim_tx(node, source_tx, dest_addr, htlc_index, amount_sat):
# HTLC CLAIM TX
# nlocktime: 0
# nsequence: DEFAULT_NSEQUENCE
# sighash=SINGLE | ANYONECANPAY
htlc_claim_tx = CTransaction()
htlc_claim_tx.nVersion = 2
htlc_claim_tx.nLockTime = 0
# Populate the transaction inputs, first 2 inputs are settled balances
source_tx.rehash()
outpoint = COutPoint(int(source_tx.hash, 16), htlc_index+2)
htlc_claim_tx.vin = [CTxIn(outpoint=outpoint, nSequence=DEFAULT_NSEQUENCE)]
scriptpubkey = bytes.fromhex(node.getaddressinfo(dest_addr)['scriptPubKey'])
dest_output = CTxOut(nValue=amount_sat, scriptPubKey=scriptpubkey)
htlc_claim_tx.vout = [dest_output]
return htlc_claim_tx
def create_htlc_refund_tx(node, source_tx, dest_addr, htlc_index, amount_sat, expiry):
# HTLC REFUND TX
# nlocktime: expiry
# nsequence: DEFAULT_NSEQUENCE
# sighash=SINGLE | ANYONECANPAY
htlc_refund_tx = CTransaction()
htlc_refund_tx.nVersion = 2
htlc_refund_tx.nLockTime = expiry
# Populate the transaction inputs, first 2 inputs are settled balances
source_tx.rehash()
outpoint = COutPoint(int(source_tx.hash, 16), htlc_index+2)
htlc_refund_tx.vin = [CTxIn(outpoint=outpoint, nSequence=DEFAULT_NSEQUENCE)]
scriptpubkey = bytes.fromhex(node.getaddressinfo(dest_addr)['scriptPubKey'])
dest_output = CTxOut(nValue=amount_sat, scriptPubKey=scriptpubkey)
htlc_refund_tx.vout = [dest_output]
return htlc_refund_tx
def sign_update_tx(tx, funding_tx, privkey, spent_state, sighash_flag=SIGHASH_ANYPREVOUTANYSCRIPT, debug=False):
# Generate taptree for eltoo tx at state 'spend_state'
pubkey, _ = compute_xonly_pubkey(privkey)
update_script = get_update_tapscript(spent_state)
settle_script = get_settle_tapscript()
eltoo_taptree = taproot_construct(pubkey, [
("update", update_script), ("settle", settle_script)
])
# Generate a Taproot signature hash to spend `nValue` from any previous output with any script (ignore prevout's scriptPubKey)
sighash = TaprootSignatureHash(
tx,
[funding_tx.vout[0]],
SIGHASH_SINGLE | sighash_flag,
input_index=0,
scriptpath=True,
script=CScript(),
key_ver=KEY_VERSION_ANYPREVOUT,
)
if debug is True:
DebugTaprootSignatureHash(
tx,
[funding_tx.vout[0]],
SIGHASH_SINGLE | sighash_flag,
input_index=0,
scriptpath=True,
script=CScript(),
key_ver=KEY_VERSION_ANYPREVOUT,
)
# Sign with internal private key
signature = sign_schnorr(privkey, sighash) + bytes([SIGHASH_SINGLE | sighash_flag])
# Control block created from leaf version and merkle branch information and common inner pubkey and it's negative flag
update_leaf = eltoo_taptree.leaves["update"]
update_control_block = bytes([update_leaf.version + eltoo_taptree.negflag]) + eltoo_taptree.internal_pubkey + update_leaf.merklebranch
# Add witness to transaction
inputs = [signature]
witness_elements = [update_script, update_control_block]
tx.wit.vtxinwit.append(CTxInWitness())
tx.wit.vtxinwit[0].scriptWitness.stack = inputs + witness_elements
return signature
def sign_settle_tx(tx, update_tx, privkey, spent_state, sighash_flag=SIGHASH_ANYPREVOUT):
# Generate taptree for eltoo tx at state n
pubkey, _ = compute_xonly_pubkey(privkey)
update_script = get_update_tapscript(spent_state)
settle_script = get_settle_tapscript()
eltoo_taptree = taproot_construct(pubkey, [
("update", update_script), ("settle", settle_script)
])
sighash_flag |= SIGHASH_ALL
# Generate the Taproot Signature Hash for signing
sighash = TaprootSignatureHash(
tx,
[update_tx.vout[0]],
sighash_flag,
input_index=0,
scriptpath=True,
script=settle_script,
key_ver=KEY_VERSION_ANYPREVOUT,
)
# Sign with internal private key
signature = sign_schnorr(privkey, sighash) + bytes([sighash_flag])
# Control block created from leaf version and merkle branch information and common inner pubkey and it's negative flag
settle_leaf = eltoo_taptree.leaves["settle"]
settle_control_block = bytes([settle_leaf.version + eltoo_taptree.negflag]) + eltoo_taptree.internal_pubkey + settle_leaf.merklebranch
# Add witness to transaction
inputs = [signature]
witness_elements = [settle_script, settle_control_block]
tx.wit.vtxinwit.append(CTxInWitness())
tx.wit.vtxinwit[0].scriptWitness.stack = inputs + witness_elements
def sign_htlc_claim_tx(tx, htlc_index, settle_tx, inner_pubkey, preimage, claim_privkey, expiry, refund_pubkey, sighash_flag=SIGHASH_ANYONECANPAY):
preimage_hash = hash160(preimage)
claim_pubkey, _ = compute_xonly_pubkey(claim_privkey)
claim_pubkey = b'\x01'+claim_pubkey
# Generate taptree for htlc tx
htlc_claim_script = get_htlc_claim_tapscript(preimage_hash, claim_pubkey)
htlc_refund_script = get_htlc_refund_tapscript(expiry, refund_pubkey)
htlc_taptree = taproot_construct(inner_pubkey, [
("htlc_claim", htlc_claim_script), ("htlc_refund", htlc_refund_script)
])
# Generate the Taproot Signature Hash for signing
sighash = TaprootSignatureHash(
tx,
[settle_tx.vout[htlc_index+2]],
SIGHASH_SINGLE | sighash_flag,
input_index=0,
scriptpath=True,
script=htlc_claim_script,
key_ver=KEY_VERSION_ANYPREVOUT,
)
# Sign with internal private key
signature = sign_schnorr(claim_privkey, sighash) + bytes([SIGHASH_SINGLE | sighash_flag])
# Control block created from leaf version and merkle branch information and common inner pubkey and it's negative flag
htlc_claim_leaf = htlc_taptree.leaves["htlc_claim"]
htlc_claim_control_block = bytes([htlc_claim_leaf.version + htlc_taptree.negflag]) + htlc_taptree.internal_pubkey + htlc_claim_leaf.merklebranch
# Add witness to transaction
inputs = [signature, preimage]
witness_elements = [htlc_claim_script, htlc_claim_control_block]
tx.wit.vtxinwit.append(CTxInWitness())
tx.wit.vtxinwit[0].scriptWitness.stack = inputs + witness_elements
def sign_htlc_refund_tx(tx, htlc_index, settle_tx, inner_pubkey, preimage_hash, claim_pubkey, expiry, refund_privkey, sighash_flag=SIGHASH_ANYONECANPAY):
refund_pubkey, _ = compute_xonly_pubkey(refund_privkey)
refund_pubkey = b'\x01'+refund_pubkey
# Generate taptree for htlc tx
htlc_claim_script = get_htlc_claim_tapscript(preimage_hash, claim_pubkey)
htlc_refund_script = get_htlc_refund_tapscript(expiry, refund_pubkey)
htlc_taptree = taproot_construct(inner_pubkey, [
("htlc_claim", htlc_claim_script), ("htlc_refund", htlc_refund_script)
])
# Generate the Taproot Signature Hash for signing
sighash = TaprootSignatureHash(
tx,
[settle_tx.vout[htlc_index+2]],
SIGHASH_SINGLE | sighash_flag,
input_index=0,
scriptpath=True,
script=htlc_refund_script,
key_ver=KEY_VERSION_ANYPREVOUT,
)
# Sign with internal private key
signature = sign_schnorr(refund_privkey, sighash) + bytes([SIGHASH_SINGLE | sighash_flag])
# Control block created from leaf version and merkle branch information and common inner pubkey and it's negative flag
htlc_refund_leaf = htlc_taptree.leaves["htlc_refund"]
htlc_refund_control_block = bytes([htlc_refund_leaf.version + htlc_taptree.negflag]) + htlc_taptree.internal_pubkey + htlc_refund_leaf.merklebranch
# Add witness to transaction
inputs = [signature]
witness_elements = [htlc_refund_script, htlc_refund_control_block]
tx.wit.vtxinwit.append(CTxInWitness())
tx.wit.vtxinwit[0].scriptWitness.stack = inputs + witness_elements
class Invoice:
__slots__ = ("id", "preimage_hash", "amount", "expiry")
def __init__(self, id, preimage_hash, amount, expiry):
self.id = id
self.preimage_hash = preimage_hash
self.amount = amount
self.expiry = expiry
def deserialize(self, f):
pass
def serialize(self):
pass
def __repr__(self):
return "Invoice(id=%i hash=%064x amount=%i expiry=%i)" % (self.id, self.preimage_hash, self.amount, self.expiry)
class Witness:
__slots__ = "update_pk", "update_sig", "settle_pk", "settle_sig", "payment_pk"
def __init__(self):
self.update_pk = None
self.update_sig = None
self.settle_pk = None
self.settle_sig = None
self.payment_pk = None
def __eq__(self, other):
match = True
match &= self.update_pk == other.update_pk
match &= self.settle_pk == other.settle_pk
match &= self.payment_pk == other.payment_pk
# do not compare signatures, only public keys
return match
def set_pk(self, keys):
self.update_pk = keys.update_key.get_pubkey().get_bytes()
self.settle_pk = keys.settle_key.get_pubkey().get_bytes()
self.payment_pk = keys.payment_key.get_pubkey().get_bytes()
def __repr__(self):
return "Witness(update_pk=%064x settle_pk=%064x payment_pk=%064x)" % (
self.update_pk, self.settle_pk, self.payment_pk
)
class Keys:
__slots__ = "update_key", "settle_key", "payment_key"
def __init__(self):
self.update_key = ECKey()
self.settle_key = ECKey()
self.payment_key = ECKey()
self.update_key.generate()
self.settle_key.generate()
self.payment_key.generate()
class PaymentChannel:
__slots__ = "state", "witness", "other_witness", "spending_tx", "refund_pk", "payment_pk", "settled_refund_amount", "settled_payment_amount", "received_payments", "offered_payments"
def __init__(self, witness, other_witness):
self.state = 0
self.witness = copy.copy(witness)
self.other_witness = copy.copy(other_witness)
self.spending_tx = None
self.settled_refund_amount = CHANNEL_AMOUNT
self.settled_payment_amount = 0
self.offered_payments = {}
self.received_payments = {}
def total_offered_payments(self):
total = 0
for key, value in self.offered_payments.items():
total += value.amount
return total
def total_received_payments(self):
total = 0
for key, value in self.received_payments.items():
total += value.amount
return total
def __repr__(self):
return "PaymentChannel(spending_tx=%064x settled_refund_amount=%i settled_payment_amount=%i offered_payments=%i received_payments=%i)" % \
(self.spending_tx, self.settled_refund_amount, self.settled_payment_amount, self.total_offered_payments(),
self.total_received_payments())
class UpdateTx(CTransaction):
__slots__ = ("state", "witness", "other_witness")
def __init__(self, payment_channel):
super().__init__(tx=None)
# keep a copy of initialization parameters
self.state = payment_channel.state
self.witness = copy.copy(payment_channel.witness)
self.other_witness = copy.copy(payment_channel.other_witness)
# set tx version 2 for BIP-68 outputs with relative timelocks
self.nVersion = 2
# initialize channel state
self.nLockTime = CLTV_START_TIME + self.state
# build witness program
witness_program = get_eltoo_update_script(self.state, self.witness, self.other_witness)
witness_hash = sha256(witness_program)
script_wsh = CScript([OP_0, witness_hash])
# add channel output
self.vout = [CTxOut(CHANNEL_AMOUNT, script_wsh)] # channel balance
def sign(self, keys):
# add dummy vin, digest only serializes the nSequence value
prevscript = CScript()
self.vin.append(CTxIn(outpoint=COutPoint(prevscript, 0), scriptSig=b"", nSequence=DEFAULT_NSEQUENCE))
tx_hash = SegwitVersion1SignatureHash(prevscript, self, 0, SIGHASH_ANYPREVOUT | SIGHASH_SINGLE, CHANNEL_AMOUNT)
signature = keys.update_key.sign_ecdsa(tx_hash) + bytes([SIGHASH_ANYPREVOUT | SIGHASH_SINGLE])
# remove dummy vin
self.vin.pop()
return signature
def verify(self):
verified = True
witnesses = [self.witness, self.other_witness]
# add dummy vin, digest only serializes the nSequence value
prevscript = CScript()
self.vin.append(CTxIn(outpoint=COutPoint(prevscript, 0), scriptSig=b"", nSequence=DEFAULT_NSEQUENCE))
for witness in witnesses:
pk = ECPubKey()
pk.set(witness.update_pk)
sig = witness.update_sig[0:-1]
sighash = witness.update_sig[-1]
assert sighash == (SIGHASH_ANYPREVOUT | SIGHASH_SINGLE)
tx_hash = SegwitVersion1SignatureHash(prevscript, self, 0, sighash, CHANNEL_AMOUNT)
v = pk.verify_ecdsa(sig, tx_hash)
if v is False:
verified = False
# remove dummy vin
self.vin.pop()
return verified
def add_witness(self, spend_tx):
# witness script to spend update tx to update tx
self.wit.vtxinwit = [CTxInWitness()]
witness_program = get_eltoo_update_script(spend_tx.state, spend_tx.witness, spend_tx.other_witness)
sig1 = self.witness.update_sig
sig2 = self.other_witness.update_sig
self.wit.vtxinwit[0].scriptWitness = CScriptWitness()
self.wit.vtxinwit[0].scriptWitness.stack = [b'', sig1, sig2, witness_program]
assert len(self.vin) == 0
self.vin = [CTxIn(outpoint=COutPoint(spend_tx.sha256, 0), scriptSig=b"", nSequence=DEFAULT_NSEQUENCE)]
class SettleTx(CTransaction):
__slots__ = "payment_channel"
def __init__(self, payment_channel):
super().__init__(tx=None)
self.payment_channel = copy.deepcopy(payment_channel)
# set tx version 2 for BIP-68 outputs with relative timelocks
self.nVersion = 2
# initialize channel state
self.nLockTime = CLTV_START_TIME + self.payment_channel.state
# build witness program
witness_program = get_eltoo_update_script(
self.payment_channel.state,
self.payment_channel.witness,
self.payment_channel.other_witness
)
witness_hash = sha256(witness_program)
script_wsh = CScript([OP_0, witness_hash])
assert self.payment_channel.settled_refund_amount + self.payment_channel.settled_payment_amount + self.payment_channel.total_offered_payments() - CHANNEL_AMOUNT == 0
settled_amounts = [self.payment_channel.settled_refund_amount, self.payment_channel.settled_payment_amount]
signers = [self.payment_channel.witness.payment_pk, self.payment_channel.other_witness.payment_pk]
signer_index = 0
outputs = []
for amount in settled_amounts:
if amount > DUST_LIMIT:
# pay to new p2pkh outputs, TODO: should use p2wpkh
payment_pk = signers[signer_index]
script_pkh = CScript([OP_0, hash160(payment_pk)])
# self.log.debug("add_settle_outputs: state=%s, signer_index=%d, witness hash160(%s)\n", state, signer_index, ToHex(settlement_pubkey))
outputs.append(CTxOut(amount, script_pkh))
signer_index += 1
for htlc_hash, htlc in self.payment_channel.offered_payments.items():
if htlc.amount > DUST_LIMIT:
# refund and pay to p2pkh outputs, TODO: should use p2wpkh
refund_pubkey = self.payment_channel.witness.payment_pk
payment_pubkey = self.payment_channel.other_witness.payment_pk
preimage_hash = self.payment_channel.offered_payments[htlc_hash].preimage_hash
expiry = self.payment_channel.offered_payments[htlc_hash].expiry
# build witness program
witness_program = get_eltoo_htlc_script(refund_pubkey, payment_pubkey, preimage_hash, expiry)
witness_hash = sha256(witness_program)
script_wsh = CScript([OP_0, witness_hash])
# self.log.debug("add_settle_outputs: state=%s, signer_index=%d\n\twitness sha256(%s)=%s\n\twsh sha256(%s)=%s\n", state, signer_index, ToHex(witness_program),
# ToHex(witness_hash), ToHex(script_wsh), ToHex(sha256(script_wsh)))
outputs.append(CTxOut(htlc.amount, script_wsh))
# add settlement outputs to settlement transaction
self.vout = outputs
def sign(self, keys):
# TODO: spending from a SetupTx (first UpdateTx) should not use the NOINPUT sighash
# add dummy vin, digest only serializes the nSequence value
prevscript = CScript()
self.vin.append(CTxIn(outpoint=COutPoint(prevscript, 0), scriptSig=b"", nSequence=CSV_DELAY))
tx_hash = SegwitVersion1SignatureHash(prevscript, self, 0, SIGHASH_ANYPREVOUT | SIGHASH_SINGLE, CHANNEL_AMOUNT)
signature = keys.settle_key.sign_ecdsa(tx_hash) + bytes([SIGHASH_ANYPREVOUT | SIGHASH_SINGLE])
# remove dummy vin
self.vin.pop()
return signature
def verify(self):
verified = True
witnesses = [self.payment_channel.witness, self.payment_channel.other_witness]
# add dummy vin, digest only serializes the nSequence value
prevscript = CScript()
self.vin.append(CTxIn(outpoint=COutPoint(prevscript, 0), scriptSig=b"", nSequence=CSV_DELAY))
for witness in witnesses:
pk = ECPubKey()
pk.set(witness.settle_pk)
sig = witness.settle_sig[0:-1]
sighash = witness.settle_sig[-1]
assert sighash == (SIGHASH_ANYPREVOUT | SIGHASH_SINGLE)
tx_hash = SegwitVersion1SignatureHash(prevscript, self, 0, sighash, CHANNEL_AMOUNT)
v = pk.verify_ecdsa(sig, tx_hash)
verified = verified and pk.verify_ecdsa(sig, tx_hash)
# remove dummy vin
self.vin.pop()
return verified
def add_witness(self, spend_tx):
# witness script to spend update tx to settle tx
assert spend_tx.state == self.payment_channel.state
self.wit.vtxinwit = [CTxInWitness()]
witness_program = get_eltoo_update_script(spend_tx.state, spend_tx.witness, spend_tx.other_witness)
sig1 = self.payment_channel.witness.settle_sig
sig2 = self.payment_channel.other_witness.settle_sig
self.wit.vtxinwit[0].scriptWitness = CScriptWitness()
self.wit.vtxinwit[0].scriptWitness.stack = [b'', sig1, sig2, b'', b'', b'', witness_program]
assert len(self.vin) == 0
self.vin = [CTxIn(outpoint=COutPoint(spend_tx.sha256, 0), scriptSig=b"", nSequence=CSV_DELAY)]
class RedeemTx(CTransaction):
__slots__ = ("payment_channel", "secrets", "is_funder", "settled_only", "include_invalid", "block_time")
def __init__(self, payment_channel, secrets, is_funder, settled_only, include_invalid, block_time):
super().__init__(tx=None)
self.payment_channel = copy.deepcopy(payment_channel)
self.secrets = secrets
self.is_funder = is_funder
self.settled_only = settled_only
self.include_invalid = include_invalid
self.block_time = block_time
# add settled amount (refund or payment)
settled_amount = 0
if self.is_funder:
amount = self.payment_channel.settled_refund_amount
else:
amount = self.payment_channel.settled_payment_amount
if amount > DUST_LIMIT:
settled_amount = amount
# add htlc amounts that are greater than dust and timeout has expired
if not settled_only:
for htlc_hash, htlc in self.payment_channel.offered_payments.items():
if not self.include_invalid and self.is_funder and htlc.expiry > self.block_time:
continue
if not self.include_invalid and not self.is_funder and htlc.preimage_hash not in self.secrets:
continue
if htlc.amount > DUST_LIMIT:
settled_amount += htlc.amount
# remove transaction fee from output amount
settled_amount -= FEE_AMOUNT
assert settled_amount > FEE_AMOUNT
# no csv outputs, so nVersion can be 1 or 2
self.nVersion = 2
# refund outputs to channel funder are only spendable after a specified clock time, all others are unrestricted
if not self.is_funder or settled_only:
self.nLockTime = 0
else:
self.nLockTime = self.block_time
# build witness program for settled output (p2wpkh)
pubkey = self.payment_channel.witness.payment_pk
script_pkh = CScript([OP_0, hash160(pubkey)])
# add channel output
self.vout = [CTxOut(settled_amount, script_pkh)] # channel balance
def sign(self, keys, htlc_index, htlc_hash):
if htlc_hash is not None:
# use witness program for a htlc input (p2wsh)
assert htlc_index < len(self.payment_channel.offered_payments)
invoice = self.payment_channel.offered_payments[htlc_hash]
refund_pubkey = self.payment_channel.witness.payment
payment_pubkey = self.payment_channel.other_witness.payment
witness_program = self.get_eltoo_htlc_script(
refund_pubkey,
payment_pubkey,
invoice.preimage_hash,
invoice.expiry
)
amount = invoice.amount
else:
# use witness program for a settled input (p2wpkh)
if self.is_funder is True:
amount = self.payment_channel.settled_refund_amount
else:
amount = self.payment_channel.settled_payment_amount
privkey = keys.payment_key
tx_hash = SegwitVersion1SignatureHash(witness_program, self, input_index, SIGHASH_SINGLE, amount)
signature = privkey.sign_ecdsa(tx_hash) + bytes([SIGHASH_SINGLE])
pk = ECPubKey()
pk.set(privkey.get_pubkey().get_bytes())
assert pk.verify_ecdsa(signature[0:-1], tx_hash)
return signature
def add_witness(self, keys, spend_tx, settled_only):
if self.is_funder:
signer_index = 0
else:
signer_index = 1
settled_amounts = [self.payment_channel.settled_refund_amount, self.payment_channel.settled_payment_amount]
# add settled input from htlc sender (after a timeout) or htlc receiver (with preimage)
input_index = 0
for amount_index in range(len(settled_amounts)):
if settled_amounts[amount_index] > DUST_LIMIT:
# add input from signer
if amount_index is signer_index:
self.vin.append(
CTxIn(
outpoint=COutPoint(spend_tx.sha256, input_index),
scriptSig=b"",
nSequence=DEFAULT_NSEQUENCE,
)
)
input_index += 1
if not settled_only:
# add htlc inputs, one per htlc
for htlc_hash, htlc in self.payment_channel.offered_payments.items():
if not self.include_invalid and self.is_funder and htlc.expiry > self.block_time:
continue
if not self.include_invalid and not self.is_funder and htlc.preimage_hash not in self.secrets:
continue
if htlc.amount > DUST_LIMIT:
self.vin.append(
CTxIn(
outpoint=COutPoint(spend_tx.sha256, input_index),
scriptSig=b"",
nSequence=DEFAULT_NSEQUENCE,
)
)
input_index += 1
self.wit.vtxinwit = []
# add the p2wpkh witness scripts to spend the settled channel amounts
input_index = 0
for amount_index in range(len(settled_amounts)):
if settled_amounts[amount_index] > DUST_LIMIT:
# add input witness from signer
if amount_index is signer_index:
privkey = keys.payment_key
pubkey = keys.payment_key.get_pubkey().get_bytes()
witness_program = get_p2pkh_script(pubkey=pubkey)
amount = settled_amounts[amount_index]
# sig = self.Sign(keys=keys, htlc_index=-1, input_index=input_index)
tx_hash = SegwitVersion1SignatureHash(witness_program, self, input_index, SIGHASH_SINGLE, amount)
sig = privkey.sign_ecdsa(tx_hash) + bytes([SIGHASH_SINGLE])
self.wit.vtxinwit.append(CTxInWitness())
self.wit.vtxinwit[-1].scriptWitness = CScriptWitness()
self.wit.vtxinwit[-1].scriptWitness.stack = [sig, pubkey]
input_index += 1
if not settled_only:
# add the p2wsh witness scripts to spend the settled channel amounts
for htlc_hash, htlc in self.payment_channel.offered_payments.items():
if not self.include_invalid and self.is_funder and htlc.expiry > self.block_time:
continue
if not self.include_invalid and not self.is_funder and htlc.preimage_hash not in self.secrets:
continue
if htlc.amount > DUST_LIMIT:
# generate signature for current state
privkey = keys.payment_key
refund_pubkey = self.payment_channel.witness.payment_pk
payment_pubkey = self.payment_channel.other_witness.payment_pk
witness_program = get_eltoo_htlc_script(
refund_pubkey,
payment_pubkey,
htlc.preimage_hash,
htlc.expiry,
)
amount = htlc.amount
# sig = self.Sign(keys=keys, htlc_index=htlc_index, input_index=input_index)
tx_hash = SegwitVersion1SignatureHash(witness_program, self, input_index, SIGHASH_SINGLE, amount)
sig = privkey.sign_ecdsa(tx_hash) + bytes([SIGHASH_SINGLE])
self.wit.vtxinwit.append(CTxInWitness())
if self.is_funder:
preimage = None
else:
preimage = self.secrets[htlc.preimage_hash]
self.wit.vtxinwit[-1].scriptWitness = get_eltoo_htlc_script_witness(witness_program, preimage, sig)
witness_hash = sha256(witness_program)
script_wsh = CScript([OP_0, witness_hash])
input_index += 1
class CloseTx(CTransaction):
__slots__ = ("payment_channel", "setup_tx")
def __init__(self, payment_channel, setup_tx):
super().__init__(tx=None)
self.payment_channel = copy.deepcopy(payment_channel)
self.setup_tx = setup_tx
for htlc_hash, htlc in self.payment_channel.offered_payments.items():
# assume payer sweeps all unfulfilled HTLCs
self.payment_channel.refund_amount += htlc.amount
# sanity check
assert self.payment_channel.settled_refund_amount + self.payment_channel.settled_payment_amount == CHANNEL_AMOUNT
self.payment_channel.offered_payments.clear()
# remove transaction fee from output amounts
if self.payment_channel.settled_refund_amount > self.payment_channel.settled_payment_amount:
self.payment_channel.settled_payment_amount -= min(int(FEE_AMOUNT / 2), self.payment_channel.settled_payment_amount)
self.payment_channel.settled_refund_amount = CHANNEL_AMOUNT - self.payment_channel.settled_payment_amount - FEE_AMOUNT
else:
self.payment_channel.settled_refund_amount -= min(int(FEE_AMOUNT / 2), self.payment_channel.settled_refund_amount)
self.payment_channel.settled_payment_amount = CHANNEL_AMOUNT - self.payment_channel.settled_refund_amount - FEE_AMOUNT
assert self.payment_channel.settled_refund_amount + self.payment_channel.settled_payment_amount + FEE_AMOUNT == CHANNEL_AMOUNT
# no csv outputs, so nVersion can be 1 or 2
self.nVersion = 2
# refund outputs to channel partners immediately
self.nLockTime = CLTV_START_TIME + self.payment_channel.state + 1
# add setup_tx vin
self.vin = [CTxIn(outpoint=COutPoint(setup_tx.sha256, 0), scriptSig=b"", nSequence=DEFAULT_NSEQUENCE)]
# build witness program for settled refund output (p2wpkh)
pubkey = self.payment_channel.witness.payment_pk
script_pkh = CScript([OP_0, hash160(pubkey)])
outputs = []
# refund output
if self.payment_channel.settled_refund_amount > DUST_LIMIT:
outputs.append(CTxOut(self.payment_channel.settled_refund_amount, script_pkh))
# build witness program for settled payment output (p2wpkh)
pubkey = self.payment_channel.other_witness.payment_pk
script_pkh = CScript([OP_0, hash160(pubkey)])
# settled output
if self.payment_channel.settled_payment_amount > DUST_LIMIT:
outputs.append(CTxOut(self.payment_channel.settled_payment_amount, script_pkh))
self.vout = outputs
def is_channel_funder(self, keys):
pubkey = keys.update_key.get_pubkey().get_bytes()
if pubkey == self.payment_channel.witness.update_pk:
return True
else:
return False
def sign(self, keys, setup_tx):
# spending from a SetupTx (first UpdateTx) should not use the NOINPUT sighash
witness_program = get_eltoo_update_script(setup_tx.state, setup_tx.witness, setup_tx.other_witness)
tx_hash = SegwitVersion1SignatureHash(witness_program, self, 0, SIGHASH_SINGLE, CHANNEL_AMOUNT)