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
1636 lines (1273 loc) · 71.4 KB
/
simulate_eltoo.py
File metadata and controls
1636 lines (1273 loc) · 71.4 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-2019 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
"""
import copy
from test_framework.base58 import (
b58decode_chk,
b58encode_chk,
)
from test_framework.blocktools import (
create_block,
create_coinbase,
)
from test_framework.descriptors import descsum_create
from test_framework.key import ECKey, ECPubKey
from test_framework.messages import (
COIN,
COutPoint,
CScriptWitness,
CTransaction,
CTxIn,
CTxInWitness,
CTxOut,
FromHex,
ToHex,
)
from test_framework.mininode import P2PDataStore
from test_framework.script import (
CScript,
CScriptNum,
OP_0,
OP_1,
OP_2,
OP_2DUP,
OP_3DUP,
OP_2DROP,
OP_CHECKLOCKTIMEVERIFY,
OP_CHECKMULTISIG,
OP_CHECKMULTISIGVERIFY,
OP_CHECKSEQUENCEVERIFY,
OP_CHECKSIG,
OP_CHECKSIGVERIFY,
OP_DROP,
OP_DUP,
OP_ELSE,
OP_ENDIF,
OP_EQUAL,
OP_EQUALVERIFY,
OP_FALSE,
OP_HASH160,
OP_IF,
OP_INVALIDOPCODE,
OP_NOTIF,
OP_RETURN,
OP_TRUE,
SIGHASH_ALL,
SIGHASH_ANYPREVOUT,
SIGHASH_NONE,
SIGHASH_SINGLE,
SIGHASH_ALLINPUT,
SIGHASH_ANYONECANPAY,
SIGHASH_ANYPREVOUT,
SIGHASH_NOINPUT,
SIGHASH_ANYPREVOUTANYSCRIPT,
SegwitVersion1SignatureHash,
SignatureHash,
hash160,
hash256,
sha256
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_raises_rpc_error,
assert_equal,
hex_str_to_bytes
)
import time
import random
RANDOM_RANGE = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
NUM_OUTPUTS_TO_COLLECT = 33
CSV_DELAY = 20
DUST_LIMIT = 800
FEE_AMOUNT = 1000
PAYMENT_AMOUNT = 10000
CHANNEL_AMOUNT = 1000000
RELAY_FEE = 100
NUM_SIGNERS = 2
CLTV_START_TIME = 500000000
INVOICE_TIMEOUT = 3600 # 60 minute
BLOCK_TIME = 600 # 10 minutes
def int_to_bytes(x) -> bytes:
return x.to_bytes((x.bit_length() + 7) // 8, 'big')
def get_eltoo_update_script(node, state, witness, other_witness):
"""Get the script associated with a P2PKH."""
# or(1@and(older(100),thresh(2,pk(C),pk(C))),
# 9@and(after(1000),thresh(2,pk(C),pk(C)))),
return CScript([
OP_2, witness.GetUpdatePk(node.watch_wallet), other_witness.GetUpdatePk(node.watch_wallet), OP_2, OP_CHECKMULTISIG,
OP_NOTIF,
OP_2, witness.GetSettlePk(node.watch_wallet, state), other_witness.GetSettlePk(node.watch_wallet, state), OP_2, OP_CHECKMULTISIGVERIFY,
CScriptNum(CSV_DELAY), OP_CHECKSEQUENCEVERIFY,
OP_ELSE,
CScriptNum(CLTV_START_TIME+state), OP_CHECKLOCKTIMEVERIFY,
OP_ENDIF,
])
def get_eltoo_update_script_witness(witness_program, is_update, witness, other_witness):
script_witness = CScriptWitness()
if (is_update):
sig1 = witness.update_sig
sig2 = other_witness.update_sig
script_witness.stack = [b'', sig1, sig2, witness_program]
else:
sig1 = witness.settle_sig
sig2 = other_witness.settle_sig
script_witness.stack = [b'', sig1, sig2, b'', b'', b'', witness_program]
return script_witness
def get_eltoo_htlc_script(refund_pubkey, payment_pubkey, preimage_hash, expiry):
return CScript([
OP_IF,
OP_HASH160, preimage_hash, OP_EQUALVERIFY,
payment_pubkey,
OP_ELSE,
CScriptNum(expiry), OP_CHECKLOCKTIMEVERIFY, OP_DROP,
refund_pubkey,
OP_ENDIF,
OP_CHECKSIG,
])
def get_eltoo_htlc_script_witness(witness_program, preimage, sig):
script_witness = CScriptWitness()
# minimal IF requires empty vector or exactly '0x01' value to prevent maleability
if preimage != None:
script_witness.stack = [sig, preimage, int_to_bytes(1), witness_program]
else:
script_witness.stack = [sig, b'', witness_program]
return script_witness
def get_p2pkh_script(pubkey):
"""Get the script associated with a P2PKH."""
return CScript([OP_DUP, OP_HASH160, hash160(pubkey), OP_EQUALVERIFY, OP_CHECKSIG])
def bip32_generate_hdaddresses(key, network="testnet"):
"""Get tprv, tpub for key and chaincode"""
# generate random chaincode
chaincode = random.randrange(0, RANDOM_RANGE).to_bytes(32, 'big')
chaincode_hex = (''.join(format(i, '02x') for i in chaincode))
# get private key and public key bytes
prvkey_bytes = key.get_bytes()
pubkey_bytes = key.get_pubkey().get_bytes()
# create 33B hex keys
prvkey_hex = '00' + (''.join(format(i, '02x') for i in prvkey_bytes))
pubkey_hex= (''.join(format(i, '02x') for i in pubkey_bytes))
# use mainnet or testnet version bytes
if network=="mainnet":
xpub_version = '0488b21E'
xprv_version = '0488ADE4'
else:
xpub_version = '043587CF'
xprv_version = '04358394'
# TODO: generate something other than a master key
depth = '00'
fingerprint = '00000000'
child_index = '00000000'
xprv_decoded_hex = xprv_version + depth + fingerprint + child_index + chaincode_hex + prvkey_hex
xprv_decoded = bytes.fromhex(xprv_decoded_hex)
xprv = b58encode_chk(xprv_decoded)
xpub_decoded_hex = xpub_version + depth + fingerprint + child_index + chaincode_hex + pubkey_hex
xpub_decoded = bytes.fromhex(xpub_decoded_hex)
xpub = b58encode_chk(xpub_decoded)
return xprv, xpub
def bip32_pubkey(wallet, hdaddress, index, path="/1/1/"):
descriptor = descsum_create("wpkh(" + hdaddress + path + str(index) +")")
address = wallet.deriveaddresses(descriptor)[0]
info = wallet.getaddressinfo(address)
if info['solvable'] == False:
result = wallet.importmulti(
[{
"desc": descsum_create("wpkh(" + hdaddress + path + str(index) +")") ,
"timestamp": "now"
}]
)
assert result[0]['success'] == True
info = wallet.getaddressinfo(address)
pubkey_bytes = bytes.fromhex(info['pubkey'])
return pubkey_bytes
def bip32_sign(wallet, tx_hash, hdaddress, index, path="/1/1/"):
descriptor = descsum_create("wpkh(" + hdaddress + path + str(index) +")")
address = wallet.deriveaddresses(descriptor)[0]
info = wallet.getaddressinfo(address)
if info['ismine'] == False:
result = wallet.importmulti(
[{
"desc": descsum_create("wpkh(" + hdaddress + path + str(index) +")") ,
"timestamp": "now"
}]
)
assert result[0]['success'] == True
info = wallet.getaddressinfo(address)
key_wif = wallet.dumpprivkey(address)
key_bytes = b58decode_chk(key_wif)[1:-1] # strip first and last byte
update_key = ECKey()
update_key.set(key_bytes, compressed=True)
sig = update_key.sign_ecdsa(tx_hash)
return sig
def bip32_verify(sig, tx_hash, wallet, hdaddress, state, path="/1/1/"):
pubkey_bytes = bip32_pubkey( wallet, hdaddress, state, path)
pk = ECPubKey()
pk.set( pubkey_bytes )
v = pk.verify_ecdsa( sig, tx_hash )
return v
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__ = "xpub", "state", "update_sig", "settle_sig"
def __init__(self, keys, state=0):
self.xpub = keys.xpub
self.state = 0
self.update_sig = None
self.settle_sig = None
def GetUpdatePk(self, wallet):
return bip32_pubkey(wallet, self.xpub, 0)
def GetSettlePk(self, wallet, state):
return bip32_pubkey(wallet, self.xpub, 2 + state)
def GetPaymentPk(self, wallet):
return bip32_pubkey(wallet, self.xpub, 1)
def __eq__(self, other):
match = True
match &= self.xpub == other.xpub
match &= self.state == other.state
# do not compare signatures, only public keys
return match
def __repr__(self):
return "Witness(xpub=%s, state=%d)" % (self.xpub, self.state)
class Keys:
__slots__ = "key", "xpub", "xprv"
def __init__(self, xpub = None):
if xpub != None:
self.key = None
self.xprv = None
self.xpub = xpub
else:
self.key = ECKey()
self.key.generate()
self.xprv, self.xpub = bip32_generate_hdaddresses(self.key)
def GetUpdatePk(self, wallet):
return bip32_pubkey(wallet, self.xpub, 0)
def GetSettlePk(self, wallet, state):
return bip32_pubkey(wallet, self.xpub, 2 + state)
def GetPaymentPk(self, wallet):
return bip32_pubkey(wallet, self.xpub, 1)
def GetUpdateSignature(self, wallet, tx_hash, sighash):
assert self.xprv
return bip32_sign(wallet, tx_hash, self.xprv, 0) + chr(sighash).encode('latin-1')
def GetSettleSignature(self, wallet, tx_hash, sighash, state):
assert self.xprv
return bip32_sign(wallet, tx_hash, self.xprv, 2 + state) + chr(sighash).encode('latin-1')
def GetPaymentSignature(self, wallet, tx_hash, sighash):
assert self.xprv
return bip32_sign(wallet, tx_hash, self.xprv, 1) + chr(sighash).encode('latin-1')
class PaymentChannel:
__slots__ = "state", "witness", "other_witness", "spending_tx", "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 TotalOfferedPayments(self):
total = 0
for key, value in self.offered_payments.items():
total += value.amount
return total
def TotalReceivedPayments(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.TotalOfferedPayments(), self.TotalReceivedPayments())
class UpdateTx(CTransaction):
__slots__ = ("state", "witness", "other_witness")
def __init__(self, node, channel_partner):
super().__init__(tx=None)
# keep a copy of initialization parameters
payment_channel = node.payment_channels[channel_partner]
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(node, 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, node, channel_partner):
keys = node.keychain[channel_partner]
# add dummy vin, digest only serializes the nSequence value
prevscript = CScript()
self.vin.append( CTxIn(outpoint = COutPoint(prevscript, 0), scriptSig = b"", nSequence=0xFFFFFFFE) )
tx_hash = SegwitVersion1SignatureHash(prevscript, self, 0, SIGHASH_ANYPREVOUT | SIGHASH_SINGLE, CHANNEL_AMOUNT)
signature = keys.GetUpdateSignature(node.wallet, tx_hash, SIGHASH_ANYPREVOUT | SIGHASH_SINGLE)
# remove dummy vin
self.vin.pop()
return signature
def Verify(self, node):
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=0xFFFFFFFE) )
for witness in witnesses:
pk = ECPubKey()
pk.set( witness.GetUpdatePk(node.watch_wallet) )
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 == False:
verified = False
# remove dummy vin
self.vin.pop()
return verified
def AddWitness(self, node, spend_tx):
# witness script to spend update tx to update tx
witness_program = get_eltoo_update_script(node,spend_tx.state, spend_tx.witness, spend_tx.other_witness)
sig1 = self.witness.update_sig
sig2 = self.other_witness.update_sig
self.wit.vtxinwit[-1].scriptWitness = CScriptWitness()
self.wit.vtxinwit[-1].scriptWitness.stack = [b'', sig1, sig2, witness_program]
def AddInputs(self, fee_funder, spend_tx):
# first vin funds the transaction fee only
utxo = fee_funder.wallet.listunspent(include_unsafe = False, query_options = {"minimumAmount": FEE_AMOUNT / COIN, "maximumCount":1})[0]
self.vin = [ CTxIn(outpoint = COutPoint(int(utxo['txid'],16), utxo['vout']), scriptSig = b"", nSequence=0xFFFFFFFE) ]
# vout[1] of spend_tx spends the channel balance output of an update tx to a new update tx
self.vin.append( CTxIn(outpoint = COutPoint(spend_tx.sha256, 1), scriptSig = b"", nSequence=0xFFFFFFFE) )
# first vout is the new change address, with same P2WKH as funding transaction
self.vout.insert(0, CTxOut(int(utxo['amount']*COIN - FEE_AMOUNT), hex_str_to_bytes(utxo['scriptPubKey'])))
class SettleTx(CTransaction):
__slots__ = ("payment_channel")
def __init__(self, node, channel_partner):
super().__init__(tx=None)
self.payment_channel = copy.deepcopy(node.payment_channels[channel_partner])
# 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(node, 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.TotalOfferedPayments() - CHANNEL_AMOUNT == 0
settled_amounts = [ self.payment_channel.settled_refund_amount, self.payment_channel.settled_payment_amount ]
signers = [ self.payment_channel.witness.GetPaymentPk(node.watch_wallet), self.payment_channel.other_witness.GetPaymentPk(node.watch_wallet) ]
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.GetPaymentPk(node.watch_wallet)
payment_pubkey = self.payment_channel.other_witness.GetPaymentPk(node.watch_wallet)
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, node, channel_partner):
# TODO: spending from a SetupTx (first UpdateTx) should not use the NOINPUT sighash
keys = node.keychain[channel_partner]
# 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.GetSettleSignature(node.wallet, tx_hash, SIGHASH_ANYPREVOUT | SIGHASH_SINGLE, self.payment_channel.state)
# remove dummy vin
self.vin.pop()
return signature
def Verify(self, node):
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.GetSettlePk(node.watch_wallet, self.payment_channel.state) )
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 AddWitness(self, node, spend_tx):
# witness script to spend update tx to settle tx
assert spend_tx.state == self.payment_channel.state
spend_tx.rehash()
witness_program = get_eltoo_update_script(node, 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[-1].scriptWitness = CScriptWitness()
self.wit.vtxinwit[-1].scriptWitness.stack = [b'', sig1, sig2, b'', b'', b'', witness_program]
def AddInputs(self, fee_funder, spend_tx):
# first vin funds the transaction fee only
utxo = fee_funder.wallet.listunspent(include_unsafe = False, query_options = {"minimumAmount": FEE_AMOUNT / COIN, "maximumCount":1})[0]
self.vin = [ CTxIn(outpoint = COutPoint(int(utxo['txid'],16), utxo['vout']), scriptSig = b"", nSequence=0xFFFFFFFE) ]
# vout[1] of spend_tx spends the channel balance output of an update tx to a settle tx
self.vin.append( CTxIn(outpoint = COutPoint(spend_tx.sha256, 1), scriptSig = b"", nSequence=CSV_DELAY) )
# first vout is the new change address, with same P2WKH as funding transaction
self.vout.insert(0, CTxOut(int(utxo['amount']*COIN - FEE_AMOUNT), hex_str_to_bytes(utxo['scriptPubKey'])))
class RedeemTx(CTransaction):
__slots__ = ("payment_channel", "secrets", "is_funder", "settled_only", "include_invalid", "block_time")
def __init__(self, node, 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.GetPaymentPk(node.watch_wallet)
script_pkh = CScript([OP_0, hash160(pubkey)])
# add channel output
self.vout = [ CTxOut(settled_amount, script_pkh) ] # channel balance
def AddWitness(self, node, channel_partner, spend_tx, settled_only=False):
keys=node.keychain[channel_partner]
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 ]
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:
pubkey = keys.GetPaymentPk(node.watch_wallet)
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 = keys.GetPaymentSignature(node.wallet, tx_hash, 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
refund_pubkey = self.payment_channel.witness.GetPaymentPk(node.watch_wallet)
payment_pubkey = self.payment_channel.other_witness.GetPaymentPk(node.watch_wallet)
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 = keys.GetPaymentSignature(node.wallet, tx_hash, 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
def AddInputs(self, 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 = 1 # skip first change input
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:
assert spend_tx.vout[input_index].nValue == settled_amounts[amount_index]
self.vin.append( CTxIn(outpoint = COutPoint(spend_tx.sha256, input_index), scriptSig = b"", nSequence=0xfffffffe) )
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=0xfffffffe) )
input_index += 1
class CloseTx(CTransaction):
__slots__ = ("payment_channel", "setup_tx")
def __init__(self, node, channel_partner, setup_tx):
super().__init__(tx=None)
payment_channel=node.payment_channels[channel_partner]
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, vout[0] of setup_tx is change, vout[1] is the channel balance
self.vin = [ CTxIn(outpoint = COutPoint(setup_tx.sha256, 1), scriptSig = b"", nSequence=0xFFFFFFFE) ]
# build witness program for settled refund output (p2wpkh)
pubkey = self.payment_channel.witness.GetPaymentPk(node.watch_wallet)
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.GetPaymentPk(node.watch_wallet)
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 IsChannelFunder(self, node, keys):
pubkey = keys.GetUpdatePk(node.watch_wallet)
if pubkey == self.payment_channel.witness.GetUpdatePk(node.watch_wallet):
return True
else:
return False
def Sign(self, node, channel_partner, setup_tx):
# spending from a SetupTx (first UpdateTx) should not use the NOINPUT sighash
keys = node.keychain[channel_partner]
witness_program = get_eltoo_update_script(node, setup_tx.state, setup_tx.witness, setup_tx.other_witness)
tx_hash = SegwitVersion1SignatureHash(witness_program, self, 0, SIGHASH_SINGLE, CHANNEL_AMOUNT)
signature = keys.GetUpdateSignature(node.wallet, tx_hash, SIGHASH_SINGLE)
if self.IsChannelFunder(node, keys):
self.payment_channel.witness.update_sig = signature
else:
self.payment_channel.other_witness.update_sig = signature
return signature
def Verify(self, node, setup_tx):
verified = True
witnesses = [ self.payment_channel.witness, self.payment_channel.other_witness ]
for witness in witnesses:
pk = ECPubKey()
pk.set( witness.GetUpdatePk(node.watch_wallet) )
sig = witness.update_sig[0:-1]
sighash = witness.update_sig[-1]
assert(sighash == (SIGHASH_SINGLE))
witness_program = get_eltoo_update_script(node, setup_tx.state, setup_tx.witness, setup_tx.other_witness)
tx_hash = SegwitVersion1SignatureHash(witness_program, self, 0, sighash, CHANNEL_AMOUNT)
v = pk.verify_ecdsa( sig, tx_hash )
verified = verified and pk.verify_ecdsa( sig, tx_hash )
return verified
def AddWitness(self, node, spend_tx):
# witness script to spend update tx to close tx
self.wit.vtxinwit = [ CTxInWitness() ]
witness_program = get_eltoo_update_script(node, spend_tx.state, spend_tx.witness, spend_tx.other_witness)
sig1 = self.payment_channel.witness.update_sig
sig2 = self.payment_channel.other_witness.update_sig
self.wit.vtxinwit[0].scriptWitness = CScriptWitness()
self.wit.vtxinwit[0].scriptWitness.stack = [b'', sig1, sig2, witness_program]
class L2Node:
__slots__ = "gid","issued_invoices", "secrets", "payment_channels", "keychain", "complete_payment_channels", "node", "wallet", "watch_wallet"
def __init__(self, gid, node, coinbase_wallet):
self.gid = gid
self.issued_invoices = []
self.secrets = {}
self.payment_channels = {}
self.keychain = {}
self.complete_payment_channels = {}
self.node = node
wallet_list = node.listwallets()
if not str(self.gid) in wallet_list:
# create a HD wallet for generating private keys
self.node.createwallet(wallet_name=str(self.gid), disable_private_keys=False)
self.wallet = self.node.get_wallet_rpc(str(self.gid))
if not str(self.gid)+"_watch" in wallet_list:
# create a HD watch wallet for generating public keys from us and our channel partners
self.node.createwallet(wallet_name=str(self.gid)+"_watch", disable_private_keys=True)
self.watch_wallet = self.node.get_wallet_rpc(str(self.gid)+"_watch")
# fund wallet from coinbase (to native p2wpkh)
addr = self.wallet.getnewaddress("", "bech32")
txid = coinbase_wallet.sendtoaddress(address=addr, amount=10, subtractfeefromamount=False)
def __hash__(self):
return hash(self.gid)
def __eq__(self, other):
return (self.gid == other.gid)
def __ne__(self, other):
# Not strictly necessary, but to avoid having both x==y and x!=y
# True at the same time
return not(self == other)
def Fund(self, tx, spend_tx):
assert spend_tx != None
assert self.wallet.getbalance() > FEE_AMOUNT / COIN
# add funding input, change output and channel input from spend_tx
tx.AddInputs(self, spend_tx)
# add witness to spend funding inputs
signed_fee = self.wallet.signrawtransactionwithwallet(hexstring=ToHex(tx),sighashtype="SINGLE")
signed_fee_tx = FromHex(CTransaction(), signed_fee['hex'])
tx.wit.vtxinwit = signed_fee_tx.wit.vtxinwit
# add witness to spend a specific update tx
tx.AddWitness(self, spend_tx)
return tx
def FundSetup(self, tx, amount):
assert self.wallet.getbalance() > (amount + FEE_AMOUNT) / COIN
# first vin funds the channel and pays the transaction
utxo = self.wallet.listunspent(include_unsafe = False, query_options = {"minimumAmount": (amount + FEE_AMOUNT) / COIN, "maximumCount":1})[0]
tx.vin = [ CTxIn(outpoint = COutPoint(int(utxo['txid'],16), utxo['vout']), scriptSig = b"", nSequence=0xFFFFFFFE) ]
# first vout is the new change address, with same P2WKH as funding transaction
tx.vout.insert(0, CTxOut(int(utxo['amount']*COIN - (amount + FEE_AMOUNT)), hex_str_to_bytes(utxo['scriptPubKey'])))
signed_fee = self.wallet.signrawtransactionwithwallet(hexstring=ToHex(tx), sighashtype="SINGLE")
signed_fee_tx = FromHex(CTransaction(), signed_fee['hex'])
tx.wit.vtxinwit = [ signed_fee_tx.wit.vtxinwit[0] ]
return tx
def IsChannelFunder(self, channel_partner):
pubkey = self.keychain[channel_partner].GetUpdatePk(self.watch_wallet)
if pubkey == self.payment_channels[channel_partner].witness.GetUpdatePk(self.watch_wallet):
return True
else:
return False
def ProposeChannel(self):
keys = Keys()
witness = Witness(keys)
return (keys, witness)
def JoinChannel(self, channel_partner, witness):
# generate local keys for proposed channel
self.keychain[channel_partner] = Keys()
other_witness = Witness(self.keychain[channel_partner])
# initialize a new payment channel
self.payment_channels[channel_partner] = PaymentChannel(witness, other_witness)
# no need to sign an Update Tx transaction, only need to sign a SettleTx that refunds the first Setup Tx
# sign settle transaction
assert self.payment_channels[channel_partner].state == 0
settle_tx = SettleTx(self, channel_partner)
self.payment_channels[channel_partner].other_witness.settle_sig = \
settle_tx.Sign(self, channel_partner)
# create the first Update Tx (aka Setup Tx)
self.payment_channels[channel_partner].spending_tx = UpdateTx(self, channel_partner)
# return witness updated with valid signatures for the refund settle transaction
return self.payment_channels[channel_partner].other_witness
def CreateChannel(self, channel_partner, keys, witness, other_witness):
# use keys created for this payment channel by ProposeChannel
self.keychain[channel_partner] = keys
# initialize a new payment channel
self.payment_channels[channel_partner] = PaymentChannel(witness, other_witness)
assert len(self.keychain) == len(self.payment_channels)
# no need to sign an Update Tx transaction, only need to sign a SettleTx that refunds the first Setup Tx
# sign settle transaction
assert self.payment_channels[channel_partner].state == 0
settle_tx = SettleTx(self, channel_partner)
signature = settle_tx.Sign(self, channel_partner)
# save signature to payment channel and settle tx
self.payment_channels[channel_partner].witness.settle_sig = signature
settle_tx.payment_channel.witness.settle_sig = signature
# check that we can create a valid refund/settle transaction to use if we need to close the channel
assert(settle_tx.Verify(self))
# create the first Update Tx (aka Setup Tx)
setup_tx = UpdateTx(self, channel_partner)
# save the most recent co-signed payment_channel state that can be used to uncooperatively close the channel
self.complete_payment_channels[channel_partner] = (copy.deepcopy(self.payment_channels[channel_partner]), copy.deepcopy(self.keychain[channel_partner]))
return setup_tx, settle_tx
def CreateInvoice(self, id, amount, expiry):
secret = random.randrange(0, RANDOM_RANGE).to_bytes(32, 'big')
self.secrets[hash160(secret)] = secret
invoice = Invoice(id=id, preimage_hash=hash160(secret), amount=amount, expiry=expiry)
return invoice
def LearnSecret(self, secret):
self.secrets[hash160(secret)] = secret
def ProposePayment(self, channel_partner, invoice, prev_update_tx):
# create updated payment channel information for the next proposed payment channel state
payment_channel = self.payment_channels[channel_partner]
payment_channel.state += 1
payment_channel.settled_refund_amount -= invoice.amount
payment_channel.offered_payments[invoice.preimage_hash] = invoice
# save updated payment channel state
self.payment_channels[channel_partner] = payment_channel
# create an update tx that spends any update tx with an earlier state
update_tx = UpdateTx(self, channel_partner)
# sign with new update key
update_sig = update_tx.Sign(self, channel_partner)
update_tx.witness.update_sig = update_sig
# create a settle tx that spends the new update tx
settle_tx = SettleTx(self, channel_partner)
# sign with new update key for this state
settle_sig = settle_tx.Sign(self, channel_partner)
settle_tx.payment_channel.witness.settle_sig = settle_sig
return (update_tx, settle_tx)
def ReceivePayment(self, channel_partner, update_tx, settle_tx):
# check that new payment channel state passes sanity checks
payment_channel = settle_tx.payment_channel
assert payment_channel.witness == update_tx.witness
assert payment_channel.other_witness == update_tx.other_witness
assert payment_channel.state == update_tx.state
assert payment_channel.state > self.payment_channels[channel_partner].state
assert payment_channel.settled_refund_amount + payment_channel.settled_payment_amount + payment_channel.TotalOfferedPayments() - CHANNEL_AMOUNT == 0
assert payment_channel.settled_payment_amount >= self.payment_channels[channel_partner].settled_payment_amount
assert payment_channel.TotalOfferedPayments() > self.payment_channels[channel_partner].TotalOfferedPayments()
# sign update tx with my key
update_sig = update_tx.Sign(self, channel_partner)
update_tx.other_witness.update_sig = update_sig
# sign settle tx with new settle key
settle_sig = settle_tx.Sign(self, channel_partner)
settle_tx.payment_channel.other_witness.settle_sig = settle_sig
# verify both channel partners signed the txs
assert update_tx.Verify(self)
assert settle_tx.Verify(self)
# accept new channl state
self.payment_channels[channel_partner] = payment_channel
# check if we know the secret
found_htlc = None
secret = None
for hashed_secret, tmp_secret in self.secrets.items():
found_htlc = payment_channel.offered_payments.get(hashed_secret, None)
if found_htlc != None:
secret = tmp_secret
break
return update_tx, settle_tx, secret
def UncooperativelyClose(self, channel_partner, settle_tx, settled_only=False, include_invalid=True, block_time=0):
# create an redeem tx that spends a commited settle tx
is_funder = self.IsChannelFunder(channel_partner)
redeem_tx = RedeemTx(node=self, payment_channel=settle_tx.payment_channel, secrets=self.secrets, is_funder=is_funder, settled_only=settled_only, include_invalid=include_invalid, block_time=block_time)
redeem_tx.AddInputs(spend_tx=settle_tx, settled_only=settled_only)
redeem_tx.AddWitness(node=self, channel_partner=channel_partner, spend_tx=settle_tx, settled_only=settled_only)
return redeem_tx
def ProposeUpdate(self, channel_partner, block_time):