forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_wallet.py
1670 lines (1360 loc) · 69.1 KB
/
test_wallet.py
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
from bitcoin.rpc import JSONRPCError
from decimal import Decimal
from fixtures import * # noqa: F401,F403
from fixtures import TEST_NETWORK
from pyln.client import RpcError, Millisatoshi
from shutil import copyfile
from utils import (
only_one, wait_for, sync_blockheight,
VALGRIND, check_coin_moves, TailableProc, scriptpubkey_addr,
check_utxos_channel
)
import os
import pytest
import subprocess
import sys
import time
import unittest
WAIT_TIMEOUT = 60 # Wait timeout for processes
# Errors codes
HSM_GENERIC_ERROR = 20
HSM_ERROR_IS_ENCRYPT = 21
HSM_BAD_PASSWORD = 22
@unittest.skipIf(TEST_NETWORK != 'regtest', "Test relies on a number of example addresses valid only in regtest")
def test_withdraw(node_factory, bitcoind):
amount = 1000000
# Don't get any funds from previous runs.
l1 = node_factory.get_node(random_hsm=True, options={'log-level': 'io'})
l2 = node_factory.get_node(random_hsm=True)
addr = l1.rpc.newaddr()['bech32']
# Add some funds to withdraw later
for i in range(10):
l1.bitcoin.rpc.sendtoaddress(addr, amount / 10**8 + 0.01)
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10)
# Reach around into the db to check that outputs were added
assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] == 10
waddr = l1.bitcoin.rpc.getnewaddress()
# Now attempt to withdraw some (making sure we collect multiple inputs)
# These violate schemas!
l1.rpc.check_request_schemas = False
with pytest.raises(RpcError):
l1.rpc.withdraw('not an address', amount)
with pytest.raises(RpcError):
l1.rpc.withdraw(waddr, 'not an amount')
with pytest.raises(RpcError):
l1.rpc.withdraw(waddr, -amount)
with pytest.raises(RpcError, match=r'Could not afford'):
l1.rpc.withdraw(waddr, amount * 100)
l1.rpc.check_request_schemas = True
out = l1.rpc.withdraw(waddr, 2 * amount)
# Side note: sendrawtransaction will trace back to withdrawl
myname = os.path.splitext(os.path.basename(sys.argv[0]))[0]
l1.daemon.wait_for_log(r': "{}:withdraw#[0-9]*/cln:withdraw#[0-9]*/txprepare:sendpsbt#[0-9]*/cln:sendrawtransaction#[0-9]*"\[OUT\]'.format(myname))
# Make sure bitcoind received the withdrawal
unspent = l1.bitcoin.rpc.listunspent(0)
withdrawal = [u for u in unspent if u['txid'] == out['txid']]
assert(withdrawal[0]['amount'] == Decimal('0.02'))
l1.bitcoin.generate_block(1)
sync_blockheight(l1.bitcoin, [l1])
# Check that there are no unconfirmed outputs (change should be confirmed)
for o in l1.rpc.listfunds()['outputs']:
assert o['status'] == 'confirmed'
# Now make sure two of them were marked as spent
assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 2
# Now send some money to l2.
# lightningd uses P2SH-P2WPKH
waddr = l2.rpc.newaddr('bech32')['bech32']
l1.rpc.withdraw(waddr, 2 * amount)
# Now make sure an additional two of them were marked as reserved
assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 2
assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=1')[0]['c'] == 2
# They're turned into spent once the node sees them mined.
bitcoind.generate_block(1)
sync_blockheight(l1.bitcoin, [l1, l2])
# Make sure l2 received the withdrawal.
assert len(l2.rpc.listfunds()['outputs']) == 1
outputs = l2.db_query('SELECT value FROM outputs WHERE status=0;')
assert only_one(outputs)['value'] == 2 * amount
# Now make sure an additional two of them were marked as spent
assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 4
assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=1')[0]['c'] == 0
# Simple test for withdrawal to P2WPKH
# Address from: https://bc-2.jp/tools/bech32demo/index.html
waddr = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080'
with pytest.raises(RpcError):
l1.rpc.withdraw('xx1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx', 2 * amount)
with pytest.raises(RpcError):
l1.rpc.withdraw('tb1pw508d6qejxtdg4y5r3zarvary0c5xw7kdl9fad', 2 * amount)
with pytest.raises(RpcError):
l1.rpc.withdraw('tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxxxxxx', 2 * amount)
l1.rpc.withdraw(waddr, 2 * amount)
bitcoind.generate_block(1)
sync_blockheight(l1.bitcoin, [l1])
# Now make sure additional two of them were marked as spent
assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 6
# Simple test for withdrawal to P2WSH
# Address from: https://bc-2.jp/tools/bech32demo/index.html
waddr = 'bcrt1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qzf4jry'
with pytest.raises(RpcError):
l1.rpc.withdraw('xx1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7', 2 * amount)
with pytest.raises(RpcError):
l1.rpc.withdraw('tb1prp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qsm03tq', 2 * amount)
with pytest.raises(RpcError):
l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qxxxxxx', 2 * amount)
l1.rpc.withdraw(waddr, 2 * amount)
bitcoind.generate_block(1)
sync_blockheight(l1.bitcoin, [l1])
# Now make sure additional two of them were marked as spent
assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 8
# failure testing for invalid SegWit addresses, from BIP173
# HRP character out of range
with pytest.raises(RpcError):
l1.rpc.withdraw(' 1nwldj5', 2 * amount)
# overall max length exceeded
with pytest.raises(RpcError):
l1.rpc.withdraw('an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx', 2 * amount)
# No separator character
with pytest.raises(RpcError):
l1.rpc.withdraw('pzry9x0s0muk', 2 * amount)
# Empty HRP
with pytest.raises(RpcError):
l1.rpc.withdraw('1pzry9x0s0muk', 2 * amount)
# Invalid witness version
with pytest.raises(RpcError):
l1.rpc.withdraw('BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2', 2 * amount)
# Invalid program length for witness version 0 (per BIP141)
with pytest.raises(RpcError):
l1.rpc.withdraw('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 2 * amount)
# Mixed case
with pytest.raises(RpcError):
l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7', 2 * amount)
# Non-zero padding in 8-to-5 conversion
with pytest.raises(RpcError):
l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv', 2 * amount)
# Should have 6 outputs available.
assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] == 6
# Test withdrawal to self.
l1.rpc.withdraw(l1.rpc.newaddr('bech32')['bech32'], 'all', minconf=0)
bitcoind.generate_block(1)
assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] == 1
l1.rpc.withdraw(waddr, 'all', minconf=0)
assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] == 0
# This should fail, can't even afford fee.
with pytest.raises(RpcError, match=r'Could not afford'):
l1.rpc.withdraw(waddr, 'all')
# Add some funds to withdraw
for i in range(12):
l1.bitcoin.rpc.sendtoaddress(addr, amount / 10**8 + 0.01)
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 12)
# Try passing in a utxo set
utxos = [utxo["txid"] + ":" + str(utxo["output"]) for utxo in l1.rpc.listfunds()["outputs"]][:4]
withdrawal = l1.rpc.withdraw(waddr, 2 * amount, utxos=utxos)
decode = bitcoind.rpc.decoderawtransaction(withdrawal['tx'])
assert decode['txid'] == withdrawal['txid']
# Check that correct utxos are included
assert len(decode['vin']) == 4
vins = ["{}:{}".format(v['txid'], v['vout']) for v in decode['vin']]
for utxo in utxos:
assert utxo in vins
# Try passing unconfirmed utxos
unconfirmed_utxos = [l1.rpc.withdraw(l1.rpc.newaddr()["bech32"], 10**5)
for _ in range(5)]
uutxos = [u["txid"] + ":0" for u in unconfirmed_utxos]
l1.rpc.withdraw(waddr, "all", minconf=0, utxos=uutxos)
# Try passing minimum feerates (for relay)
l1.rpc.withdraw(l1.rpc.newaddr()["bech32"], 10**5, feerate="253perkw")
l1.rpc.withdraw(l1.rpc.newaddr()["bech32"], 10**5, feerate="1000perkb")
def test_minconf_withdraw(node_factory, bitcoind):
"""Issue 2518: ensure that ridiculous confirmation levels don't overflow
The number of confirmations is used to compute a maximum height that is to
be accepted. If the current height is smaller than the number of
confirmations we wrap around and just select everything. The fix is to
clamp the maxheight parameter to a positive small number.
"""
amount = 1000000
# Don't get any funds from previous runs.
l1 = node_factory.get_node(random_hsm=True)
addr = l1.rpc.newaddr()['bech32']
# Add some funds to withdraw later
for i in range(10):
l1.bitcoin.rpc.sendtoaddress(addr, amount / 10**8 + 0.01)
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10)
# This violates the request schema!
l1.rpc.check_request_schemas = False
with pytest.raises(RpcError):
l1.rpc.withdraw(destination=addr, satoshi=10000, feerate='normal', minconf=9999999)
def test_addfunds_from_block(node_factory, bitcoind):
"""Send funds to the daemon without telling it explicitly
"""
# Previous runs with same bitcoind can leave funds!
coin_plugin = os.path.join(os.getcwd(), 'tests/plugins/coin_movements.py')
l1 = node_factory.get_node(random_hsm=True, options={'plugin': coin_plugin})
addr = l1.rpc.newaddr()['bech32']
bitcoind.rpc.sendtoaddress(addr, 0.1)
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1)
outputs = l1.db_query('SELECT value FROM outputs WHERE status=0;')
assert only_one(outputs)['value'] == 10000000
# The address we detect must match what was paid to.
output = only_one(l1.rpc.listfunds()['outputs'])
assert output['address'] == addr
# Send all our money to a P2WPKH address this time.
addr = l1.rpc.newaddr("bech32")['bech32']
l1.rpc.withdraw(addr, "all")
bitcoind.generate_block(1)
sync_blockheight(bitcoind, [l1])
# The address we detect must match what was paid to.
output = only_one(l1.rpc.listfunds()['outputs'])
assert output['address'] == addr
# We don't print a 'external deposit' event
# for funds that come back to our own wallet
expected_utxos = {
'0': [('wallet', ['deposit'], ['withdrawal'], 'A')],
'A': [('wallet', ['deposit'], None, None)],
}
check_utxos_channel(l1, [], expected_utxos)
def test_txprepare_multi(node_factory, bitcoind):
amount = 10000000
l1 = node_factory.get_node(random_hsm=True)
bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8)
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1)
outputs = []
for i in range(9):
outputs.append({l1.rpc.newaddr()['bech32']: Millisatoshi(amount * 100)})
prep = l1.rpc.txprepare(outputs=outputs)
l1.rpc.txdiscard(prep['txid'])
def test_txprepare(node_factory, bitcoind, chainparams):
amount = 1000000
l1 = node_factory.get_node(random_hsm=True)
addr = chainparams['example_addr']
# Add some funds to withdraw later
for i in range(10):
bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'],
amount / 10**8)
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10)
prep = l1.rpc.txprepare(outputs=[{addr: Millisatoshi(amount * 3 * 1000)}])
decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx'])
assert decode['txid'] == prep['txid']
# 4 inputs, 2 outputs (3 if we have a fee output).
assert len(decode['vin']) == 4
assert len(decode['vout']) == 2 if not chainparams['feeoutput'] else 3
# One output will be correct.
outnum = [i for i, o in enumerate(decode['vout']) if o['value'] == Decimal(amount * 3) / 10**8][0]
for i, o in enumerate(decode['vout']):
if i == outnum:
assert o['scriptPubKey']['type'] == 'witness_v0_keyhash'
assert scriptpubkey_addr(o['scriptPubKey']) == addr
else:
if chainparams['elements']:
o['scriptPubKey']['type'] in ['witness_v0_keyhash', 'fee']
else:
assert o['scriptPubKey']['type'] in ['witness_v1_taproot', 'fee']
# Now prepare one with no change.
prep2 = l1.rpc.txprepare([{addr: 'all'}])
decode = bitcoind.rpc.decoderawtransaction(prep2['unsigned_tx'])
assert decode['txid'] == prep2['txid']
# 6 inputs, 1 outputs.
assert len(decode['vin']) == 6
assert len(decode['vout']) == 1 if not chainparams['feeoutput'] else 2
# Some fees will be paid.
assert decode['vout'][0]['value'] < Decimal(amount * 6) / 10**8
assert decode['vout'][0]['value'] > Decimal(amount * 6) / 10**8 - Decimal(0.0002)
assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash'
assert scriptpubkey_addr(decode['vout'][0]['scriptPubKey']) == addr
# If I cancel the first one, I can get those first 4 outputs.
discard = l1.rpc.txdiscard(prep['txid'])
assert discard['txid'] == prep['txid']
assert discard['unsigned_tx'] == prep['unsigned_tx']
prep3 = l1.rpc.txprepare([{addr: 'all'}])
decode = bitcoind.rpc.decoderawtransaction(prep3['unsigned_tx'])
assert decode['txid'] == prep3['txid']
# 4 inputs, 1 outputs.
assert len(decode['vin']) == 4
assert len(decode['vout']) == 1 if not chainparams['feeoutput'] else 2
# Some fees will be taken
assert decode['vout'][0]['value'] < Decimal(amount * 4) / 10**8
assert decode['vout'][0]['value'] > Decimal(amount * 4) / 10**8 - Decimal(0.0002)
assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash'
assert scriptpubkey_addr(decode['vout'][0]['scriptPubKey']) == addr
# Cannot discard twice.
with pytest.raises(RpcError, match=r'not an unreleased txid'):
l1.rpc.txdiscard(prep['txid'])
# Discard everything, we should now spend all inputs.
l1.rpc.txdiscard(prep2['txid'])
l1.rpc.txdiscard(prep3['txid'])
prep4 = l1.rpc.txprepare([{addr: 'all'}])
decode = bitcoind.rpc.decoderawtransaction(prep4['unsigned_tx'])
assert decode['txid'] == prep4['txid']
# 10 inputs, 1 outputs.
assert len(decode['vin']) == 10
assert len(decode['vout']) == 1 if not chainparams['feeoutput'] else 2
# Some fees will be taken
assert decode['vout'][0]['value'] < Decimal(amount * 10) / 10**8
assert decode['vout'][0]['value'] > Decimal(amount * 10) / 10**8 - Decimal(0.0003)
assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash'
assert scriptpubkey_addr(decode['vout'][0]['scriptPubKey']) == addr
l1.rpc.txdiscard(prep4['txid'])
# Try passing in a utxo set
utxos = [utxo["txid"] + ":" + str(utxo["output"])
for utxo in l1.rpc.listfunds()["outputs"]][:4]
prep5 = l1.rpc.txprepare([{addr:
Millisatoshi(amount * 3.5 * 1000)}], utxos=utxos)
# Try passing unconfirmed utxos
unconfirmed_utxo = l1.rpc.withdraw(l1.rpc.newaddr()["bech32"], 10**5)
uutxos = [unconfirmed_utxo["txid"] + ":0"]
with pytest.raises(RpcError, match=r"Could not afford"):
l1.rpc.txprepare([{addr: Millisatoshi(amount * 3.5 * 1000)}],
utxos=uutxos)
decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx'])
assert decode['txid'] == prep5['txid']
# Check that correct utxos are included
assert len(decode['vin']) == 4
vins = ["{}:{}".format(v['txid'], v['vout']) for v in decode['vin']]
for utxo in utxos:
assert utxo in vins
# We should have a change output, so this is exact
assert len(decode['vout']) == 3 if chainparams['feeoutput'] else 2
# Change output pos is random.
for vout in decode['vout']:
if vout['scriptPubKey']['type'] == 'fee':
continue
if scriptpubkey_addr(vout['scriptPubKey']) == addr:
changeout = vout
assert changeout['value'] == Decimal(amount * 3.5) / 10**8
assert changeout['scriptPubKey']['type'] == 'witness_v0_keyhash'
assert scriptpubkey_addr(changeout['scriptPubKey']) == addr
# Discard prep4 and get all funds again
l1.rpc.txdiscard(prep5['txid'])
# You can have one which is all, but not two.
prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 1000)},
{addr: 'all'}])
l1.rpc.txdiscard(prep5['txid'])
with pytest.raises(RpcError, match=r"'all'"):
prep5 = l1.rpc.txprepare([{addr: 'all'}, {addr: 'all'}])
prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 500 + 100000)},
{addr: Millisatoshi(amount * 3 * 500 - 100000)}])
decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx'])
assert decode['txid'] == prep5['txid']
# 4 inputs, 3 outputs(include change).
assert len(decode['vin']) == 4
assert len(decode['vout']) == 4 if chainparams['feeoutput'] else 3
# One output will be correct.
for i in range(3 + chainparams['feeoutput']):
if decode['vout'][i - 1]['value'] == Decimal('0.01500100'):
outnum1 = i - 1
elif decode['vout'][i - 1]['value'] == Decimal('0.01499900'):
outnum2 = i - 1
else:
changenum = i - 1
assert decode['vout'][outnum1]['scriptPubKey']['type'] == 'witness_v0_keyhash'
assert scriptpubkey_addr(decode['vout'][outnum1]['scriptPubKey']) == addr
assert decode['vout'][outnum2]['scriptPubKey']['type'] == 'witness_v0_keyhash'
assert scriptpubkey_addr(decode['vout'][outnum2]['scriptPubKey']) == addr
if chainparams['elements']:
assert decode['vout'][changenum]['scriptPubKey']['type'] == 'witness_v0_keyhash'
else:
assert decode['vout'][changenum]['scriptPubKey']['type'] == 'witness_v1_taproot'
def test_reserveinputs(node_factory, bitcoind, chainparams):
amount = 1000000
total_outs = 12
l1 = node_factory.get_node(feerates=(7500, 7500, 7500, 7500))
outputs = []
# Add a medley of funds to withdraw
for i in range(total_outs):
txid = bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'],
amount / 10**8)
outputs.append((txid, bitcoind.rpc.gettransaction(txid)['details'][0]['vout']))
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == total_outs)
assert not any(o['reserved'] for o in l1.rpc.listfunds()['outputs'])
# Try reserving one at a time.
for out in outputs:
psbt = bitcoind.rpc.createpsbt([{'txid': out[0], 'vout': out[1]}], [])
l1.rpc.reserveinputs(psbt)
assert all(o['reserved'] for o in l1.rpc.listfunds()['outputs'])
reserveheight = bitcoind.rpc.getblockchaininfo()['blocks'] + 72
assert all(o['reserved_to_block'] == reserveheight for o in l1.rpc.listfunds()['outputs'])
# Unreserve as a batch.
psbt = bitcoind.rpc.createpsbt([{'txid': out[0], 'vout': out[1]} for out in outputs], [])
l1.rpc.unreserveinputs(psbt)
assert not any(o['reserved'] for o in l1.rpc.listfunds()['outputs'])
assert not any('reserved_to_block' in o for o in l1.rpc.listfunds()['outputs'])
# Reserve twice fails unless exclusive.
l1.rpc.reserveinputs(psbt)
with pytest.raises(RpcError, match=r"already reserved"):
l1.rpc.reserveinputs(psbt)
l1.rpc.reserveinputs(psbt, False)
assert all(o['reserved_to_block'] == reserveheight + 72 for o in l1.rpc.listfunds()['outputs'])
l1.rpc.unreserveinputs(psbt)
assert all(o['reserved'] for o in l1.rpc.listfunds()['outputs'])
assert all(o['reserved_to_block'] == reserveheight for o in l1.rpc.listfunds()['outputs'])
# Stays reserved across restarts.
l1.restart()
assert all(o['reserved'] for o in l1.rpc.listfunds()['outputs'])
assert all(o['reserved_to_block'] == reserveheight for o in l1.rpc.listfunds()['outputs'])
# Final unreserve works.
l1.rpc.unreserveinputs(psbt)
assert not any(o['reserved'] for o in l1.rpc.listfunds()['outputs'])
assert not any('reserved_to_block' in o for o in l1.rpc.listfunds()['outputs'])
def test_fundpsbt(node_factory, bitcoind, chainparams):
amount = 1000000
total_outs = 4
l1 = node_factory.get_node()
# CLN returns PSBTv0 and PSETv2, for now
is_psbt_v2 = chainparams['elements']
outputs = []
# Add a medley of funds to withdraw later
for i in range(total_outs):
txid = bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'],
amount / 10**8)
outputs.append((txid, bitcoind.rpc.gettransaction(txid)['details'][0]['vout']))
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == total_outs)
feerate = '7500perkw'
# Should get one input, plus some excess
funding = l1.rpc.fundpsbt(amount // 2, feerate, 0, reserve=0)
psbt = bitcoind.rpc.decodepsbt(funding['psbt'])
# We can fuzz this up to 99 blocks back.
assert funding['excess_msat'] > Millisatoshi(0)
assert funding['excess_msat'] < Millisatoshi(amount // 2 * 1000)
assert funding['feerate_per_kw'] == 7500
assert 'estimated_final_weight' in funding
assert 'reservations' not in funding
if is_psbt_v2:
assert psbt['fallback_locktime'] > bitcoind.rpc.getblockcount() - 100
assert psbt['fallback_locktime'] <= bitcoind.rpc.getblockcount()
assert psbt['input_count'] == 1
else:
assert psbt['tx']['locktime'] > bitcoind.rpc.getblockcount() - 100
assert psbt['tx']['locktime'] <= bitcoind.rpc.getblockcount()
assert len(psbt['tx']['vin']) == 1
# This should add 99 to the weight, but otherwise be identical (might choose different inputs though!) except for locktime.
funding2 = l1.rpc.fundpsbt(amount // 2, feerate, 99, reserve=0, locktime=bitcoind.rpc.getblockcount() + 1)
psbt2 = bitcoind.rpc.decodepsbt(funding2['psbt'])
if is_psbt_v2:
assert psbt2['fallback_locktime'] == bitcoind.rpc.getblockcount() + 1
assert psbt2['input_count'] == 1
else:
assert psbt2['tx']['locktime'] == bitcoind.rpc.getblockcount() + 1
assert len(psbt2['tx']['vin']) == 1
assert funding2['excess_msat'] < funding['excess_msat']
assert funding2['feerate_per_kw'] == 7500
# Naively you'd expect this to be +99, but it might have selected a non-p2sh output...
assert funding2['estimated_final_weight'] > funding['estimated_final_weight']
# Cannot afford this one (too much)
with pytest.raises(RpcError, match=r"not afford"):
l1.rpc.fundpsbt(amount * total_outs, feerate, 0)
# Nor this (depth insufficient)
with pytest.raises(RpcError, match=r"not afford"):
l1.rpc.fundpsbt(amount // 2, feerate, 0, minconf=2)
funding3 = l1.rpc.fundpsbt(amount // 2, feerate, 0, reserve=0, excess_as_change=True)
assert funding3['excess_msat'] == Millisatoshi(0)
# Should have the excess msat as the output value (minus fee for change)
psbt = bitcoind.rpc.decodepsbt(funding3['psbt'])
if is_psbt_v2:
change = Millisatoshi("{}btc".format(psbt["outputs"][funding3['change_outnum']]["amount"]))
else:
change = Millisatoshi("{}btc".format(psbt['tx']['vout'][funding3['change_outnum']]['value']))
# The weight should be greater (now includes change output)
change_weight = funding3['estimated_final_weight'] - funding['estimated_final_weight']
assert change_weight > 0
# Check that the amount is ok (equal to excess minus change fee)
change_fee = Millisatoshi(7500 * change_weight)
assert funding['excess_msat'] == change + change_fee
# Should get two inputs.
psbt = bitcoind.rpc.decodepsbt(l1.rpc.fundpsbt(amount, feerate, 0, reserve=0)['psbt'])
if is_psbt_v2:
assert psbt['input_count'] == 2
else:
assert len(psbt['tx']['vin']) == 2
# Should not use reserved outputs.
psbt = bitcoind.rpc.createpsbt([{'txid': out[0], 'vout': out[1]} for out in outputs], [])
l1.rpc.reserveinputs(psbt)
with pytest.raises(RpcError, match=r"not afford"):
l1.rpc.fundpsbt(amount // 2, feerate, 0)
# Will use first one if unreserved.
l1.rpc.unreserveinputs(bitcoind.rpc.createpsbt([{'txid': outputs[0][0], 'vout': outputs[0][1]}], []))
psbt = l1.rpc.fundpsbt(amount // 2, feerate, 0)['psbt']
# Should have passed to reserveinputs.
with pytest.raises(RpcError, match=r"already reserved"):
l1.rpc.reserveinputs(psbt)
# And now we can't afford any more.
with pytest.raises(RpcError, match=r"not afford"):
l1.rpc.fundpsbt(amount // 2, feerate, 0)
def test_utxopsbt(node_factory, bitcoind, chainparams):
amount = 1000000
l1 = node_factory.get_node()
# CLN returns PSBTv0 and PSETv2, for now
is_psbt_v2 = chainparams['elements']
outputs = []
# Add a funds to withdraw later
for _ in range(2):
txid = bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'],
amount / 10**8)
outputs.append((txid, bitcoind.rpc.gettransaction(txid)['details'][0]['vout']))
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == len(outputs))
fee_val = 7500
feerate = '{}perkw'.format(fee_val)
# Explicitly spend the first output above.
funding = l1.rpc.utxopsbt(amount // 2, feerate, 0,
['{}:{}'.format(outputs[0][0], outputs[0][1])],
reserve=0)
psbt = bitcoind.rpc.decodepsbt(funding['psbt'])
# We can fuzz this up to 99 blocks back.
assert funding['excess_msat'] > Millisatoshi(0)
assert funding['excess_msat'] < Millisatoshi(amount // 2 * 1000)
assert funding['feerate_per_kw'] == 7500
assert 'estimated_final_weight' in funding
assert 'reservations' not in funding
if is_psbt_v2:
assert psbt['fallback_locktime'] > bitcoind.rpc.getblockcount() - 100
assert psbt['fallback_locktime'] <= bitcoind.rpc.getblockcount()
assert psbt['input_count'] == 1
else:
assert psbt['tx']['locktime'] > bitcoind.rpc.getblockcount() - 100
assert psbt['tx']['locktime'] <= bitcoind.rpc.getblockcount()
assert len(psbt['tx']['vin']) == 1
# This should add 99 to the weight, but otherwise be identical except for locktime.
start_weight = 99
funding2 = l1.rpc.utxopsbt(amount // 2, feerate, start_weight,
['{}:{}'.format(outputs[0][0], outputs[0][1])],
reserve=0, locktime=bitcoind.rpc.getblockcount() + 1)
psbt2 = bitcoind.rpc.decodepsbt(funding2['psbt'])
if is_psbt_v2:
assert psbt2['fallback_locktime'] == bitcoind.rpc.getblockcount() + 1
assert psbt2['inputs'] == psbt['inputs']
else:
assert psbt2['tx']['locktime'] == bitcoind.rpc.getblockcount() + 1
assert psbt2['tx']['vin'] == psbt['tx']['vin']
if chainparams['elements']:
assert is_psbt_v2
# elements includes the fee as an output
addl_fee = Millisatoshi((fee_val * start_weight + 999) // 1000 * 1000)
assert psbt2['outputs'][0]['amount'] == psbt['outputs'][0]['amount'] + addl_fee.to_btc()
else:
assert psbt2['tx']['vout'] == psbt['tx']['vout']
assert funding2['excess_msat'] < funding['excess_msat']
assert funding2['feerate_per_kw'] == 7500
assert funding2['estimated_final_weight'] == funding['estimated_final_weight'] + 99
assert 'reservations' not in funding2
# Cannot afford this one (too much)
with pytest.raises(RpcError, match=r"not afford"):
l1.rpc.utxopsbt(amount, feerate, 0,
['{}:{}'.format(outputs[0][0], outputs[0][1])])
# Nor this (even with both)
with pytest.raises(RpcError, match=r"not afford"):
l1.rpc.utxopsbt(amount * 2, feerate, 0,
['{}:{}'.format(outputs[0][0], outputs[0][1]),
'{}:{}'.format(outputs[1][0], outputs[1][1])])
funding3 = l1.rpc.utxopsbt(amount // 2, feerate, 0,
['{}:{}'.format(outputs[0][0], outputs[0][1])],
reserve=0,
excess_as_change=True)
assert funding3['excess_msat'] == Millisatoshi(0)
# Should have the excess msat as the output value (minus fee for change)
psbt = bitcoind.rpc.decodepsbt(funding3['psbt'])
if is_psbt_v2:
change = Millisatoshi("{}btc".format(psbt['outputs'][funding3['change_outnum']]['amount']))
else:
change = Millisatoshi("{}btc".format(psbt['tx']['vout'][funding3['change_outnum']]['value']))
# The weight should be greater (now includes change output)
change_weight = funding3['estimated_final_weight'] - funding['estimated_final_weight']
assert change_weight > 0
# Check that the amount is ok (equal to excess minus change fee)
change_fee = Millisatoshi(fee_val * change_weight // 1000 * 1000)
assert funding['excess_msat'] == change + change_fee
# Do it again, but without enough for change!
funding4 = l1.rpc.utxopsbt(amount - 3500,
feerate, 0,
['{}:{}'.format(outputs[0][0], outputs[0][1])],
reserve=0,
excess_as_change=True)
assert 'change_outnum' not in funding4
# Should get two inputs (and reserve!)
funding = l1.rpc.utxopsbt(amount, feerate, 0,
['{}:{}'.format(outputs[0][0], outputs[0][1]),
'{}:{}'.format(outputs[1][0], outputs[1][1])])
psbt = bitcoind.rpc.decodepsbt(funding['psbt'])
if is_psbt_v2:
assert psbt['input_count'] == 2
else:
assert len(psbt['tx']['vin']) == 2
assert len(funding['reservations']) == 2
assert funding['reservations'][0]['txid'] == outputs[0][0]
assert funding['reservations'][0]['vout'] == outputs[0][1]
assert funding['reservations'][0]['was_reserved'] is False
assert funding['reservations'][0]['reserved'] is True
assert funding['reservations'][1]['txid'] == outputs[1][0]
assert funding['reservations'][1]['vout'] == outputs[1][1]
assert funding['reservations'][1]['was_reserved'] is False
assert funding['reservations'][1]['reserved'] is True
# Should refuse to use reserved outputs.
with pytest.raises(RpcError, match=r"already reserved"):
l1.rpc.utxopsbt(amount, feerate, 0,
['{}:{}'.format(outputs[0][0], outputs[0][1]),
'{}:{}'.format(outputs[1][0], outputs[1][1])])
# Unless we tell it that's ok.
l1.rpc.utxopsbt(amount, feerate, 0,
['{}:{}'.format(outputs[0][0], outputs[0][1]),
'{}:{}'.format(outputs[1][0], outputs[1][1])],
reservedok=True)
def test_sign_external_psbt(node_factory, bitcoind, chainparams):
"""
A PSBT w/ one of our inputs should be signable (we can fill
in the required UTXO data).
"""
l1 = node_factory.get_node(feerates=(7500, 7500, 7500, 7500))
amount = 1000000
total_outs = 4
# Add a medley of funds to withdraw later
for i in range(total_outs):
bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'],
amount / 10**8)
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == total_outs)
# Build a PSBT using all our inputs, externally
inputs = []
for inp in l1.rpc.listfunds()['outputs']:
inputs.append({'txid': inp['txid'], 'vout': inp['output']})
addr = l1.rpc.newaddr()['bech32']
psbt = bitcoind.rpc.createpsbt(inputs, [{addr: (amount * 3) / 10**8}])
l1.rpc.reserveinputs(psbt)
l1.rpc.signpsbt(psbt)
def test_psbt_version(node_factory, bitcoind, chainparams):
sats_amount = 10**8
# CLN returns PSBTv0 and PSETv2, for now
is_elements = chainparams['elements']
l1 = node_factory.get_node()
bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'],
sats_amount / 100000000)
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1)
funding = l1.rpc.fundpsbt(satoshi=int(sats_amount / 2),
feerate=7500,
startweight=42)['psbt']
# Short elements test
if is_elements:
# Only v2 is allowed, and is a no-op
for i in [0, 1, 3, 4, 5]:
with pytest.raises(RpcError, match=r"Could not set PSBT version"):
l1.rpc.setpsbtversion(funding, i)
assert funding == l1.rpc.setpsbtversion(funding, 2)['psbt']
# And elementsd can understand it
bitcoind.rpc.decodepsbt(funding)
return
# Non-elements test
v2_funding = l1.rpc.setpsbtversion(funding, 2)['psbt']
# Bitcoind cannot understand PSBTv2 yet
with pytest.raises(JSONRPCError, match=r"TX decode failed Unsupported version number"):
bitcoind.rpc.decodepsbt(v2_funding)
# But it round-trips fine enough
v0_funding = l1.rpc.setpsbtversion(v2_funding, 0)['psbt']
# CLN returns v0 for now
assert funding == v0_funding
# And we reject non-0/2 args
for i in [1, 3, 4, 5]:
with pytest.raises(RpcError, match=r"Could not set PSBT version"):
l1.rpc.setpsbtversion(v2_funding, i)
@unittest.skipIf(TEST_NETWORK == 'liquid-regtest', 'Core/Elements need joinpsbt support for v2')
def test_sign_and_send_psbt(node_factory, bitcoind, chainparams):
"""
Tests for the sign + send psbt RPCs
"""
# CLN returns PSBTv0 and PSETv2, for now
is_psbt_v2 = chainparams['elements']
# Once support for v2 joinpsbt is added, below test should work verbatim
assert not is_psbt_v2
amount = 1000000
total_outs = 12
coin_mvt_plugin = os.path.join(os.getcwd(), 'tests/plugins/coin_movements.py')
l1 = node_factory.get_node(options={'plugin': coin_mvt_plugin},
feerates=(7500, 7500, 7500, 7500))
l2 = node_factory.get_node()
addr = chainparams['example_addr']
out_total = Millisatoshi(amount * 3 * 1000)
# Add a medley of funds to withdraw later
for i in range(total_outs):
bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'],
amount / 10**8)
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == total_outs)
# Make a PSBT out of our inputs
funding = l1.rpc.fundpsbt(satoshi=out_total,
feerate=7500,
startweight=42)
assert len([x for x in l1.rpc.listfunds()['outputs'] if x['reserved']]) == 4
psbt = bitcoind.rpc.decodepsbt(funding['psbt'])
if is_psbt_v2:
saved_input = psbt['inputs'][0]
else:
saved_input = psbt['tx']['vin'][0]
# Go ahead and unreserve the UTXOs, we'll use a smaller
# set of them to create a second PSBT that we'll attempt to sign
# and broadcast (to disastrous results)
l1.rpc.unreserveinputs(funding['psbt'])
# Re-reserve one of the utxos we just unreserved
if is_psbt_v2:
psbt = bitcoind.rpc.createpsbt([{'txid': saved_input['previous_txid'],
'vout': saved_input['previous_vout']}], [])
else:
psbt = bitcoind.rpc.createpsbt([{'txid': saved_input['txid'],
'vout': saved_input['vout']}], [])
l1.rpc.reserveinputs(psbt)
# We require the utxos be reserved before signing them
with pytest.raises(RpcError, match=r"Aborting PSBT signing. UTXO .* is not reserved"):
l1.rpc.signpsbt(funding['psbt'])['signed_psbt']
# Now we unreserve the singleton, so we can reserve it again
l1.rpc.unreserveinputs(psbt)
# Now add an output. Note, we add the 'excess msat' to the output so
# that our feerate is 'correct'. This is of particular importance to elementsd,
# who requires that every satoshi be accounted for in a tx.
out_1_ms = Millisatoshi(funding['excess_msat'])
output_psbt = bitcoind.rpc.createpsbt([],
[{addr: float((out_total + out_1_ms).to_btc())}])
fullpsbt = bitcoind.rpc.joinpsbts([funding['psbt'], output_psbt])
# We re-reserve the first set...
l1.rpc.reserveinputs(fullpsbt)
# Sign + send the PSBT we've created
signed_psbt = l1.rpc.signpsbt(fullpsbt)['signed_psbt']
broadcast_tx = l1.rpc.sendpsbt(signed_psbt)
# Check that it was broadcast successfully
l1.daemon.wait_for_log(r'sendrawtx exit 0 .* sendrawtransaction {}'.format(broadcast_tx['tx']))
bitcoind.generate_block(1)
# We didn't add a change output.
expected_outs = total_outs - 4
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == expected_outs)
# Let's try *sending* a PSBT that can't be finalized (it's unsigned)
with pytest.raises(RpcError, match=r"PSBT not finalizeable"):
l1.rpc.sendpsbt(fullpsbt)
# Now we try signing a PSBT with an output that's already been spent
with pytest.raises(RpcError, match=r"Aborting PSBT signing. UTXO .* is not reserved"):
l1.rpc.signpsbt(fullpsbt)
# Queue up another node, to make some PSBTs for us
for i in range(total_outs):
bitcoind.rpc.sendtoaddress(l2.rpc.newaddr()['bech32'],
amount / 10**8)
# Create a PSBT using L2
bitcoind.generate_block(1)
wait_for(lambda: len(l2.rpc.listfunds()['outputs']) == total_outs)
l2_funding = l2.rpc.fundpsbt(satoshi=out_total,
feerate=7500,
startweight=42)
# Try to get L1 to sign it
with pytest.raises(RpcError, match=r"No wallet inputs to sign"):
l1.rpc.signpsbt(l2_funding['psbt'])
# With signonly it will fail if it can't sign it.
with pytest.raises(RpcError, match=r"is unknown"):
l1.rpc.signpsbt(l2_funding['psbt'], signonly=[0])
# Add some of our own PSBT inputs to it
l1_funding = l1.rpc.fundpsbt(satoshi=out_total,
feerate=7500,
startweight=42)
if is_psbt_v2:
l1_num_inputs = bitcoind.rpc.decodepsbt(l1_funding['psbt'])["input_count"]
l2_num_inputs = bitcoind.rpc.decodepsbt(l2_funding['psbt'])["input_count"]
else:
l1_num_inputs = len(bitcoind.rpc.decodepsbt(l1_funding['psbt'])['tx']['vin'])
l2_num_inputs = len(bitcoind.rpc.decodepsbt(l2_funding['psbt'])['tx']['vin'])
# Join and add an output (reorders!)
out_2_ms = Millisatoshi(l1_funding['excess_msat'])
out_amt = out_2_ms + Millisatoshi(l2_funding['excess_msat']) + out_total + out_total
output_psbt = bitcoind.rpc.createpsbt([],
[{addr: float(out_amt.to_btc())}])
joint_psbt = bitcoind.rpc.joinpsbts([l1_funding['psbt'], l2_funding['psbt'],
output_psbt])
# Ask it to sign inputs it doesn't know, it will fail.
with pytest.raises(RpcError, match=r"is unknown"):
l1.rpc.signpsbt(joint_psbt,
signonly=list(range(l1_num_inputs + 1)))
# Similarly, it can't sign inputs it doesn't know.
sign_success = []
for i in range(l1_num_inputs + l2_num_inputs):
try:
l1.rpc.signpsbt(joint_psbt, signonly=[i])
except RpcError:
continue
sign_success.append(i)
assert len(sign_success) == l1_num_inputs
# But it can sign all the valid ones at once.
half_signed_psbt = l1.rpc.signpsbt(joint_psbt, signonly=sign_success)['signed_psbt']
for s in sign_success:
assert bitcoind.rpc.decodepsbt(half_signed_psbt)['inputs'][s]['partial_signatures'] is not None
totally_signed = l2.rpc.signpsbt(half_signed_psbt)['signed_psbt']
broadcast_tx = l1.rpc.sendpsbt(totally_signed)
l1.daemon.wait_for_log(r'sendrawtx exit 0 .* sendrawtransaction {}'.format(broadcast_tx['tx']))
# Send a PSBT that's not ours
l2_funding = l2.rpc.fundpsbt(satoshi=out_total,
feerate=7500,
startweight=42)
out_amt = Millisatoshi(l2_funding['excess_msat'])
output_psbt = bitcoind.rpc.createpsbt([],
[{addr: float((out_total + out_amt).to_btc())}])
psbt = bitcoind.rpc.joinpsbts([l2_funding['psbt'], output_psbt])
l2_signed_psbt = l2.rpc.signpsbt(psbt)['signed_psbt']
l1.rpc.sendpsbt(l2_signed_psbt)
# Re-try sending the same tx?
bitcoind.generate_block(1)
sync_blockheight(bitcoind, [l1])
# Expect an error here
with pytest.raises(JSONRPCError, match=r"Transaction already in block chain"):
bitcoind.rpc.sendrawtransaction(broadcast_tx['tx'])
# Try an empty PSBT
with pytest.raises(RpcError, match=r"psbt: Expected a PSBT: invalid token"):
l1.rpc.signpsbt('')
with pytest.raises(RpcError, match=r"psbt: Expected a PSBT: invalid token"):
l1.rpc.sendpsbt('')