forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_pay.py
6704 lines (5434 loc) · 286 KB
/
test_pay.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 fixtures import * # noqa: F401,F403
from fixtures import TEST_NETWORK
from hashlib import sha256
from pathlib import Path
from pyln.client import RpcError, Millisatoshi
from pyln.proto.onion import TlvPayload
from pyln.testing.utils import EXPERIMENTAL_DUAL_FUND, FUNDAMOUNT, scid_to_int
from utils import (
wait_for, only_one, sync_blockheight, TIMEOUT,
mine_funding_to_announce, first_scid, serialize_payload_tlv, serialize_payload_final_tlv,
tu64_encode
)
import copy
import os
import pytest
import random
import re
import string
import subprocess
import time
import unittest
@pytest.mark.openchannel('v1')
@pytest.mark.openchannel('v2')
def test_pay(node_factory):
l1, l2 = node_factory.line_graph(2)
inv = l2.rpc.invoice(123000, 'test_pay', 'description')['bolt11']
before = int(time.time())
details = l1.dev_pay(inv, dev_use_shadow=False)
after = time.time()
preimage = details['payment_preimage']
assert details['status'] == 'complete'
assert details['amount_msat'] == Millisatoshi(123000)
assert details['destination'] == l2.info['id']
assert details['created_at'] >= before
assert details['created_at'] <= after
invoices = l2.rpc.listinvoices('test_pay')['invoices']
assert len(invoices) == 1
invoice = invoices[0]
assert invoice['status'] == 'paid' and invoice['paid_at'] >= before and invoice['paid_at'] <= after
# Repeat payments are NOPs (if valid): we can hand null.
l1.dev_pay(inv, dev_use_shadow=False)
# This won't work: can't provide an amount (even if correct!)
with pytest.raises(RpcError):
l1.rpc.pay(inv, 123000)
with pytest.raises(RpcError):
l1.rpc.pay(inv, 122000)
# Check pay_index is not null
outputs = l2.db_query('SELECT pay_index IS NOT NULL AS q FROM invoices WHERE label="label";')
assert len(outputs) == 1 and outputs[0]['q'] != 0
# Check payment of any-amount invoice.
for i in range(5):
label = "any{}".format(i)
inv2 = l2.rpc.invoice("any", label, 'description')['bolt11']
# Must provide an amount!
with pytest.raises(RpcError):
l1.rpc.pay(inv2)
l1.dev_pay(inv2, random.randint(1000, 999999), dev_use_shadow=False)
# Should see 6 completed payments
assert len(l1.rpc.listsendpays()['payments']) == 6
# Test listsendpays indexed by bolt11.
payments = l1.rpc.listsendpays(inv)['payments']
assert len(payments) == 1 and payments[0]['payment_preimage'] == preimage
# Make sure they're completely settled, so accounting correct.
wait_for(lambda: only_one(l1.rpc.listpeerchannels()['channels'])['htlcs'] == [])
# Check channels apy summary view of channel activity
apys_1 = l1.rpc.bkpr_channelsapy()['channels_apy']
apys_2 = l2.rpc.bkpr_channelsapy()['channels_apy']
assert apys_1[0]['channel_start_balance_msat'] == apys_2[0]['channel_start_balance_msat']
assert apys_1[0]['channel_start_balance_msat'] == apys_1[0]['our_start_balance_msat']
assert apys_2[0]['our_start_balance_msat'] == Millisatoshi(0)
assert apys_1[0]['routed_out_msat'] == apys_2[0]['routed_in_msat']
assert apys_1[0]['routed_in_msat'] == apys_2[0]['routed_out_msat']
def test_pay_amounts(node_factory):
l1, l2 = node_factory.line_graph(2)
inv = l2.rpc.invoice(Millisatoshi("123sat"), 'test_pay_amounts', 'description')['bolt11']
invoice = only_one(l2.rpc.listinvoices('test_pay_amounts')['invoices'])
assert invoice['amount_msat'] == Millisatoshi(123000)
l1.dev_pay(inv, dev_use_shadow=False)
invoice = only_one(l2.rpc.listinvoices('test_pay_amounts')['invoices'])
assert invoice['amount_received_msat'] >= Millisatoshi(123000)
def test_pay_limits(node_factory):
"""Test that we enforce fee max percentage and max delay"""
l1, l2, l3 = node_factory.line_graph(3, wait_for_announce=True)
# FIXME: pylightning should define these!
PAY_STOPPED_RETRYING = 210
inv = l3.rpc.invoice("any", "any", 'description')
# Fee too high.
err = r'Fee exceeds our fee budget: [1-9]msat > 0msat, discarding route'
with pytest.raises(RpcError, match=err) as err:
l1.rpc.call('pay', {'bolt11': inv['bolt11'], 'amount_msat': 100000, 'maxfeepercent': 0.0001, 'exemptfee': 0})
assert err.value.error['code'] == PAY_STOPPED_RETRYING
# It should have retried two more times (one without routehint and one with routehint)
status = l1.rpc.call('paystatus', {'bolt11': inv['bolt11']})['pay'][0]['attempts']
# We have an internal test to see if we can reach the destination directly
# without a routehint, that will enable a NULL-routehint. We will then try
# with the provided routehint, and the NULL routehint, resulting in 2
# attempts.
assert(len(status) == 2)
assert(status[0]['failure']['code'] == 205)
failmsg = r'CLTV delay exceeds our CLTV budget'
# Delay too high.
with pytest.raises(RpcError, match=failmsg) as err:
l1.rpc.call('pay', {'bolt11': inv['bolt11'], 'amount_msat': 100000, 'maxdelay': 0})
assert err.value.error['code'] == PAY_STOPPED_RETRYING
# Should also have retried two more times.
status = l1.rpc.call('paystatus', {'bolt11': inv['bolt11']})['pay'][1]['attempts']
assert(len(status) == 2)
assert(status[0]['failure']['code'] == 205)
# This fails!
err = r'Fee exceeds our fee budget: 2msat > 1msat, discarding route'
with pytest.raises(RpcError, match=err) as err:
l1.rpc.pay(bolt11=inv['bolt11'], amount_msat=100000, maxfee=1)
# This works, because fee is less than exemptfee.
l1.dev_pay(inv['bolt11'], amount_msat=100000, maxfeepercent=0.0001,
exemptfee=2000, dev_use_shadow=False)
status = l1.rpc.call('paystatus', {'bolt11': inv['bolt11']})['pay'][3]['attempts']
assert len(status) == 1
assert status[0]['strategy'] == "Initial attempt"
def test_pay_exclude_node(node_factory, bitcoind):
"""Test excluding the node if there's the NODE-level error in the failure_code
"""
# FIXME: Remove our reliance on HTLCs failing on startup and the need for
# this plugin
opts = [
{'disable-mpp': None},
{'plugin': os.path.join(os.getcwd(), 'tests/plugins/fail_htlcs.py')},
{},
{'fee-base': 100, 'fee-per-satoshi': 1000},
{}
]
l1, l2, l3, l4, l5 = node_factory.get_nodes(5, opts=opts)
node_factory.join_nodes([l1, l2, l3], wait_for_announce=True)
amount = 10**8
inv = l3.rpc.invoice(amount, "test1", 'description')['bolt11']
with pytest.raises(RpcError):
l1.rpc.pay(inv)
# It should have retried (once without routehint, too)
status = l1.rpc.call('paystatus', {'bolt11': inv})['pay'][0]['attempts']
# Excludes channel, then ignores routehint which includes that, then
# it excludes other channel.
assert len(status) == 2
assert status[0]['strategy'] == "Initial attempt"
assert status[0]['failure']['data']['failcodename'] == 'WIRE_TEMPORARY_NODE_FAILURE'
assert 'failure' in status[1]
# Get a fresh invoice, but do it before other routes exist, so routehint
# will be via l2.
inv = l3.rpc.invoice(amount, "test2", 'description')['bolt11']
assert only_one(l1.rpc.decode(inv)['routes'])[0]['pubkey'] == l2.info['id']
# l1->l4->l5->l3 is the longer route. This makes sure this route won't be
# tried for the first pay attempt. Just to be sure we also raise the fees
# that l4 leverages.
l1.rpc.connect(l4.info['id'], 'localhost', l4.port)
l4.rpc.connect(l5.info['id'], 'localhost', l5.port)
l5.rpc.connect(l3.info['id'], 'localhost', l3.port)
scid14, _ = l1.fundchannel(l4, 10**6, wait_for_active=False)
scid45, _ = l4.fundchannel(l5, 10**6, wait_for_active=False)
scid53, _ = l5.fundchannel(l3, 10**6, wait_for_active=False)
mine_funding_to_announce(bitcoind, [l1, l2, l3, l4, l5])
l1.daemon.wait_for_logs([r'update for channel {}/0 now ACTIVE'
.format(scid14),
r'update for channel {}/1 now ACTIVE'
.format(scid14),
r'update for channel {}/0 now ACTIVE'
.format(scid45),
r'update for channel {}/1 now ACTIVE'
.format(scid45),
r'update for channel {}/0 now ACTIVE'
.format(scid53),
r'update for channel {}/1 now ACTIVE'
.format(scid53)])
# This `pay` will work
l1.rpc.pay(inv)
# It should have retried (once without routehint, too)
status = l1.rpc.call('paystatus', {'bolt11': inv})['pay'][0]['attempts']
# Excludes channel, then ignores routehint which includes that, then
# it excludes other channel.
assert len(status) == 2
assert status[0]['strategy'] == "Initial attempt"
assert status[0]['failure']['data']['failcodename'] == 'WIRE_TEMPORARY_NODE_FAILURE'
assert 'success' in status[1]
def test_pay0(node_factory):
"""Test paying 0 amount
"""
l1, l2 = node_factory.line_graph(2)
chanid = l1.get_channel_scid(l2)
# Get any-amount invoice
inv = l2.rpc.invoice("any", "any", 'description')
rhash = inv['payment_hash']
routestep = {
'amount_msat': 0,
'id': l2.info['id'],
'delay': 10,
'channel': chanid
}
# Amount must be nonzero!
l1.rpc.sendpay([routestep], rhash, payment_secret=inv['payment_secret'])
with pytest.raises(RpcError, match=r'WIRE_AMOUNT_BELOW_MINIMUM'):
l1.rpc.waitsendpay(rhash)
def test_pay_disconnect(node_factory, bitcoind):
"""If the remote node has disconnected, we fail payment, but can try again when it reconnects"""
l1, l2 = node_factory.line_graph(2, opts={'dev-max-fee-multiplier': 5,
'may_reconnect': True,
'allow_warning': True})
# Dummy payment to kick off update_fee messages
l1.pay(l2, 1000)
inv = l2.rpc.invoice(123000, 'test_pay_disconnect', 'description')
rhash = inv['payment_hash']
# Can't use `pay` since that'd notice that we can't route, due to disabling channel_update
route = l1.rpc.getroute(l2.info['id'], 123000, 1)["route"]
l2.stop()
# Make sure channeld has exited!
wait_for(lambda: 'owner' not in only_one(l1.rpc.listpeerchannels(l2.info['id'])['channels']))
# Can't pay while its offline.
with pytest.raises(RpcError, match=r'failed: WIRE_TEMPORARY_CHANNEL_FAILURE \(First peer not ready\)'):
l1.rpc.sendpay(route, rhash, payment_secret=inv['payment_secret'])
l2.start()
l1.daemon.wait_for_log('peer_out WIRE_CHANNEL_REESTABLISH')
# Make l2 upset by asking for crazy fee.
l1.set_feerates((10**6, 10**6, 10**6, 10**6), False)
# Wait for l1 notice
if 'anchors/even' in only_one(l1.rpc.listpeerchannels()['channels'])['channel_type']['names']:
l1.daemon.wait_for_log(r'WARNING .*: update_fee \d+ outside range 253-75000')
else:
l1.daemon.wait_for_log(r'WARNING .*: update_fee \d+ outside range 1875-75000')
# They hang up on us
l1.daemon.wait_for_log(r'Peer transient failure in CHANNELD_NORMAL')
# Make l2 fail hard.
l2.rpc.close(l1.info['id'], unilateraltimeout=1)
l2.daemon.wait_for_log('sendrawtx exit')
bitcoind.generate_block(1, wait_for_mempool=1)
sync_blockheight(bitcoind, [l1, l2])
# Should fail due to permenant channel fail
with pytest.raises(RpcError, match=r'WIRE_UNKNOWN_NEXT_PEER'):
l1.rpc.sendpay(route, rhash, payment_secret=inv['payment_secret'])
assert not l1.daemon.is_in_log('Payment is still in progress')
# After it sees block, someone should close channel.
l1.daemon.wait_for_log('ONCHAIN')
def test_pay_get_error_with_update(node_factory):
"""We should process an update inside a temporary_channel_failure"""
l1, l2, l3 = node_factory.line_graph(3, opts={'log-level': 'io'}, fundchannel=True, wait_for_announce=True)
chanid2 = l2.get_channel_scid(l3)
inv = l3.rpc.invoice(123000, 'test_pay_get_error_with_update', 'description')
# Make sure l2 doesn't tell l1 directly that channel is disabled.
l2.rpc.dev_suppress_gossip()
l3.stop()
# Make sure that l2 has seen disconnect, considers channel disabled.
wait_for(lambda: only_one(l2.rpc.listpeerchannels(l3.info['id'])['channels'])['peer_connected'] is False)
assert(l1.is_channel_active(chanid2))
# Make sure it's not doing startup any more (where it doesn't disable channels!)
l1.daemon.wait_for_log("channel_gossip: no longer in startup mode", timeout=70)
with pytest.raises(RpcError, match=r'WIRE_TEMPORARY_CHANNEL_FAILURE'):
l1.rpc.pay(inv['bolt11'])
# Make sure we get an onionreply, without the type prefix of the nested
# channel_update, and it should patch it to include a type prefix. The
# prefix 0x0102 should be in the channel_update, but not in the
# onionreply (negation of 0x0102 in the RE)
l1.daemon.wait_for_log(r'Extracted channel_update 0102.*from onionreply 1007008a[0-9a-fA-F]{276}$')
# And now monitor for l1 to apply the channel_update we just extracted
wait_for(lambda: not l1.is_channel_active(chanid2))
def test_pay_error_update_fees(node_factory):
"""We should process an update inside a temporary_channel_failure"""
l1, l2, l3 = node_factory.line_graph(3, fundchannel=True, wait_for_announce=True)
# Don't include any routehints in first invoice.
inv1 = l3.dev_invoice(amount_msat=123000,
label='test_pay_error_update_fees',
description='description',
dev_routes=[])
inv2 = l3.rpc.invoice(123000, 'test_pay_error_update_fees2', 'desc') # noqa: F841
# Make sure l2 doesn't tell l1 directly that channel fee is changed.
l2.rpc.dev_suppress_gossip()
l2.rpc.setchannel(l3.info['id'], 1337, 137, enforcedelay=0)
# Should bounce off and retry...
l1.rpc.pay(inv1['bolt11'])
attempts = only_one(l1.rpc.paystatus(inv1['bolt11'])['pay'])['attempts']
assert len(attempts) == 2
# WIRE_FEE_INSUFFICIENT = UPDATE|12
assert attempts[0]['failure']['data']['failcode'] == 4108
# FIXME: We *DO NOT* handle misleading routehints!
# # Should ignore old routehint and do the same...
# l1.rpc.pay(inv2['bolt11'])
# attempts = only_one(l1.rpc.paystatus(inv2['bolt11'])['pay'])['attempts']
# assert len(attempts) == 2
# # WIRE_FEE_INSUFFICIENT = UPDATE|12
# assert attempts[0]['failure']['data']['failcode'] == 4108
def test_pay_optional_args(node_factory):
l1, l2 = node_factory.line_graph(2)
inv1 = l2.rpc.invoice(123000, 'test_pay', 'desc')['bolt11']
l1.dev_pay(inv1, label='desc', dev_use_shadow=False)
payment1 = l1.rpc.listsendpays(inv1)['payments']
assert len(payment1) and payment1[0]['amount_sent_msat'] == 123000
assert payment1[0]['label'] == 'desc'
inv2 = l2.rpc.invoice(321000, 'test_pay2', 'description')['bolt11']
l1.dev_pay(inv2, riskfactor=5.0, dev_use_shadow=False)
payment2 = l1.rpc.listsendpays(inv2)['payments']
assert(len(payment2) == 1)
# The pay plugin uses `sendonion` since 0.9.0 and `lightningd` doesn't
# learn about the amount we intended to send (that's why we annotate the
# root of a payment tree with the bolt11 invoice).
anyinv = l2.rpc.invoice('any', 'any_pay', 'desc')['bolt11']
l1.dev_pay(anyinv, label='desc', amount_msat=500, dev_use_shadow=False)
payment3 = l1.rpc.listsendpays(anyinv)['payments']
assert len(payment3) == 1
assert payment3[0]['label'] == 'desc'
# Should see 3 completed transactions
assert len(l1.rpc.listsendpays()['payments']) == 3
@pytest.mark.openchannel('v1')
@pytest.mark.openchannel('v2')
def test_payment_success_persistence(node_factory, bitcoind, executor):
# Start two nodes and open a channel.. die during payment.
# Feerates identical so we don't get gratuitous commit to update them
disconnect = ['+WIRE_COMMITMENT_SIGNED']
if EXPERIMENTAL_DUAL_FUND:
# We have to add an extra 'wire-commitment-signed' because
# dual funding uses this for channel establishment also
disconnect = ['=WIRE_COMMITMENT_SIGNED'] + disconnect
l1 = node_factory.get_node(disconnect=disconnect,
options={'dev-no-reconnect': None},
may_reconnect=True,
feerates=(7500, 7500, 7500, 7500))
l2 = node_factory.get_node(may_reconnect=True)
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
chanid, _ = l1.fundchannel(l2, 100000)
inv1 = l2.rpc.invoice(1000, 'inv1', 'inv1')
# Fire off a pay request, it'll get interrupted by a restart
executor.submit(l1.dev_pay, inv1['bolt11'], dev_use_shadow=False)
l1.daemon.wait_for_log(r'dev_disconnect: \+WIRE_COMMITMENT_SIGNED')
print("Killing l1 in mid HTLC")
l1.daemon.kill()
# Restart l1, without disconnect stuff.
del l1.daemon.opts['dev-no-reconnect']
l1.daemon.disconnect = None
# Should reconnect, and sort the payment out.
l1.start()
wait_for(lambda: l1.rpc.listsendpays()['payments'][0]['status'] != 'pending')
payments = l1.rpc.listsendpays()['payments']
invoices = l2.rpc.listinvoices('inv1')['invoices']
assert len(payments) == 1 and payments[0]['status'] == 'complete'
assert len(invoices) == 1 and invoices[0]['status'] == 'paid'
l1.wait_local_channel_active(chanid)
# A duplicate should succeed immediately (nop) and return correct preimage.
preimage = l1.dev_pay(
inv1['bolt11'],
dev_use_shadow=False
)['payment_preimage']
assert l1.rpc.dev_rhash(preimage)['rhash'] == inv1['payment_hash']
@pytest.mark.openchannel('v1')
@pytest.mark.openchannel('v2')
def test_payment_failed_persistence(node_factory, executor):
# Start two nodes and open a channel.. die during payment.
# Feerates identical so we don't get gratuitous commit to update them
disconnect = ['+WIRE_COMMITMENT_SIGNED']
if EXPERIMENTAL_DUAL_FUND:
# We have to add an extra 'wire-commitment-signed' because
# dual funding uses this for channel establishment also
disconnect = ['=WIRE_COMMITMENT_SIGNED'] + disconnect
l1 = node_factory.get_node(disconnect=disconnect,
options={'dev-no-reconnect': None},
may_reconnect=True,
feerates=(7500, 7500, 7500, 7500))
l2 = node_factory.get_node(may_reconnect=True)
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
l1.fundchannel(l2, 100000)
# Expires almost immediately, so it will fail.
inv1 = l2.rpc.invoice(1000, 'inv1', 'inv1', 5)
# Fire off a pay request, it'll get interrupted by a restart
executor.submit(l1.rpc.pay, inv1['bolt11'])
l1.daemon.wait_for_log(r'dev_disconnect: \+WIRE_COMMITMENT_SIGNED')
print("Killing l1 in mid HTLC")
l1.daemon.kill()
# Restart l1, without disconnect stuff.
del l1.daemon.opts['dev-no-reconnect']
l1.daemon.disconnect = None
# Make sure invoice has expired.
time.sleep(5 + 1)
# Should reconnect, and fail the payment
l1.start()
wait_for(lambda: l1.rpc.listsendpays()['payments'][0]['status'] != 'pending')
payments = l1.rpc.listsendpays()['payments']
invoices = l2.rpc.listinvoices('inv1')['invoices']
assert len(invoices) == 1 and invoices[0]['status'] == 'expired'
assert len(payments) == 1 and payments[0]['status'] == 'failed'
# Another attempt should also fail.
with pytest.raises(RpcError):
l1.rpc.pay(inv1['bolt11'])
def test_payment_duplicate_uncommitted(node_factory, executor):
# We want to test two payments at the same time, before we send commit
l1 = node_factory.get_node(options={'dev-disable-commit-after': 0})
l2 = node_factory.get_node()
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
l1.fundchannel(l2, 100000)
inv1 = l2.rpc.invoice(1000, 'inv1', 'inv1')
# Start first payment, but not yet in db.
fut = executor.submit(l1.rpc.pay, inv1['bolt11'])
# Make sure that's started...
l1.daemon.wait_for_log('peer_out WIRE_UPDATE_ADD_HTLC')
# We should see it in listsendpays
payments = l1.rpc.listsendpays()['payments']
assert len(payments) == 1
assert payments[0]['status'] == 'pending' and payments[0]['payment_hash'] == inv1['payment_hash']
# Second one will succeed eventually.
fut2 = executor.submit(l1.rpc.pay, inv1['bolt11'])
# Now, let it commit.
l1.rpc.dev_reenable_commit(l2.info['id'])
# These should succeed.
fut.result(TIMEOUT)
fut2.result(TIMEOUT)
def test_pay_maxfee_shadow(node_factory):
"""Test that we respect maxfeepercent for shadow routing."""
l1, l2, l3 = node_factory.line_graph(3, fundchannel=True,
wait_for_announce=True)
# We use this to search for shadow routes
wait_for(
lambda: len(l1.rpc.listchannels(source=l2.info["id"])["channels"]) > 1
)
# shadow routes are random, so run multiple times.
for i in range(5):
# A tiny amount, we must not add the base_fee between l2 and l3
amount = 2
bolt11 = l2.rpc.invoice(amount, "tiny.{}".format(i), "tiny")["bolt11"]
pay_status = l1.rpc.pay(bolt11)
assert pay_status["amount_msat"] == Millisatoshi(amount)
# shadow routes are random, so run multiple times.
for i in range(5):
# A bigger amount, shadow routing could have been used but we set a low
# maxfeepercent.
amount = 20000
bolt11 = l2.rpc.invoice(amount, "big.{}".format(i), "bigger")["bolt11"]
pay_status = l1.rpc.pay(bolt11, maxfeepercent=0.001)
assert pay_status["amount_msat"] == Millisatoshi(amount)
def test_sendpay(node_factory):
l1, l2 = node_factory.line_graph(2, fundamount=10**6)
amt = 200000000
inv = l2.rpc.invoice(amt, 'testpayment2', 'desc')
rhash = inv['payment_hash']
def invoice_unpaid(dst, label):
invoices = dst.rpc.listinvoices(label)['invoices']
return len(invoices) == 1 and invoices[0]['status'] == 'unpaid'
routestep = {
'amount_msat': amt,
'id': l2.info['id'],
'delay': 5,
'channel': first_scid(l1, l2)
}
# Insufficient funds.
with pytest.raises(RpcError):
rs = copy.deepcopy(routestep)
rs['amount_msat'] = rs['amount_msat'] - 1
l1.rpc.sendpay([rs], rhash, payment_secret=inv['payment_secret'])
l1.rpc.waitsendpay(rhash)
assert invoice_unpaid(l2, 'testpayment2')
# Gross overpayment (more than factor of 2)
with pytest.raises(RpcError):
rs = copy.deepcopy(routestep)
rs['amount_msat'] = rs['amount_msat'] * 2 + 1
l1.rpc.sendpay([rs], rhash, payment_secret=inv['payment_secret'])
l1.rpc.waitsendpay(rhash)
assert invoice_unpaid(l2, 'testpayment2')
# Insufficient delay.
with pytest.raises(RpcError):
rs = copy.deepcopy(routestep)
rs['delay'] = rs['delay'] - 2
l1.rpc.sendpay([rs], rhash, payment_secret=inv['payment_secret'])
l1.rpc.waitsendpay(rhash)
assert invoice_unpaid(l2, 'testpayment2')
# Bad ID.
l1.rpc.check_request_schemas = False
with pytest.raises(RpcError):
rs = copy.deepcopy(routestep)
rs['id'] = '00000000000000000000000000000000'
l1.rpc.sendpay([rs], rhash, payment_secret=inv['payment_secret'])
assert invoice_unpaid(l2, 'testpayment2')
l1.rpc.check_request_schemas = True
# Bad payment_secret
l1.rpc.sendpay([routestep], rhash, payment_secret="00" * 32)
with pytest.raises(RpcError):
l1.rpc.waitsendpay(rhash)
assert invoice_unpaid(l2, 'testpayment2')
# Missing payment_secret
l1.rpc.sendpay([routestep], rhash)
with pytest.raises(RpcError):
l1.rpc.waitsendpay(rhash)
assert invoice_unpaid(l2, 'testpayment2')
# FIXME: test paying via another node, should fail to pay twice.
c1 = only_one(l1.rpc.listpeerchannels(l2.info['id'])['channels'])
c2 = only_one(l2.rpc.listpeerchannels(l1.info['id'])['channels'])
assert c1['to_us_msat'] == 10**6 * 1000
assert c1['total_msat'] == 10**6 * 1000
assert c2['to_us_msat'] == 0
assert c2['total_msat'] == 10**6 * 1000
# This works.
before = int(time.time())
details = l1.rpc.sendpay([routestep], rhash, payment_secret=inv['payment_secret'])
after = int(time.time())
preimage = l1.rpc.waitsendpay(rhash)['payment_preimage']
# Check details
assert details['payment_hash'] == rhash
assert details['destination'] == l2.info['id']
assert details['amount_msat'] == amt
assert details['created_at'] >= before
assert details['created_at'] <= after
# Check receiver
assert only_one(l2.rpc.listinvoices('testpayment2')['invoices'])['status'] == 'paid'
assert only_one(l2.rpc.listinvoices('testpayment2')['invoices'])['pay_index'] == 1
assert only_one(l2.rpc.listinvoices('testpayment2')['invoices'])['amount_received_msat'] == rs['amount_msat']
assert only_one(l2.rpc.listinvoices('testpayment2')['invoices'])['payment_preimage'] == preimage
# Balances should reflect it.
def check_balances():
c1 = only_one(l1.rpc.listpeerchannels(l2.info['id'])['channels'])
c2 = only_one(l2.rpc.listpeerchannels(l1.info['id'])['channels'])
return (
c1['to_us_msat'] == 10**6 * 1000 - amt
and c1['total_msat'] == 10**6 * 1000
and c2['to_us_msat'] == amt
and c2['total_msat'] == 10**6 * 1000
)
wait_for(check_balances)
# Repeat will "succeed", but won't actually send anything (duplicate)
assert not l1.daemon.is_in_log('Payment: .* COMPLETE')
details = l1.rpc.sendpay([routestep], rhash, payment_secret=inv['payment_secret'])
assert details['status'] == "complete"
preimage2 = details['payment_preimage']
assert preimage == preimage2
l1.daemon.wait_for_log('Payment: .* COMPLETE')
assert only_one(l2.rpc.listinvoices('testpayment2')['invoices'])['status'] == 'paid'
assert only_one(l2.rpc.listinvoices('testpayment2')['invoices'])['amount_received_msat'] == rs['amount_msat']
# Overpaying by "only" a factor of 2 succeeds.
inv = l2.rpc.invoice(amt, 'testpayment3', 'desc')
rhash = inv['payment_hash']
assert only_one(l2.rpc.listinvoices('testpayment3')['invoices'])['status'] == 'unpaid'
routestep = {'amount_msat': amt * 2, 'id': l2.info['id'], 'delay': 5, 'channel': first_scid(l1, l2)}
l1.rpc.sendpay([routestep], rhash, payment_secret=inv['payment_secret'])
preimage3 = l1.rpc.waitsendpay(rhash)['payment_preimage']
assert only_one(l2.rpc.listinvoices('testpayment3')['invoices'])['status'] == 'paid'
assert only_one(l2.rpc.listinvoices('testpayment3')['invoices'])['amount_received_msat'] == amt * 2
# Test listsendpays
payments = l1.rpc.listsendpays()['payments']
assert len(payments) == 7 # Failed attempts also create entries, but with a different groupid
invoice2 = only_one(l2.rpc.listinvoices('testpayment2')['invoices'])
payments = l1.rpc.listsendpays(payment_hash=invoice2['payment_hash'])['payments']
assert len(payments) == 6 # Failed attempts also create entries, but with a different groupid
assert payments[-1]['status'] == 'complete'
assert payments[-1]['payment_preimage'] == preimage2
invoice3 = only_one(l2.rpc.listinvoices('testpayment3')['invoices'])
payments = l1.rpc.listsendpays(payment_hash=invoice3['payment_hash'])['payments']
assert len(payments) == 1
assert payments[-1]['status'] == 'complete'
assert payments[-1]['payment_preimage'] == preimage3
def test_repay(node_factory):
l1, l2 = node_factory.line_graph(2, fundamount=10**6)
amt = 200000000
inv = l2.rpc.invoice(amt, 'testpayment2', 'desc')
routestep = {
'amount_msat': amt,
'id': l2.info['id'],
'delay': 5,
'channel': first_scid(l1, l2)
}
l1.rpc.sendpay([routestep], inv['payment_hash'], payment_secret=inv['payment_secret'])
l1.daemon.wait_for_log("Sending 200000000msat over 1 hops to deliver 200000000msat")
l1.rpc.waitsendpay(inv['payment_hash'])['payment_preimage']
# Re-attempt is instant
assert l1.rpc.sendpay([routestep], inv['payment_hash'], payment_secret=inv['payment_secret'])['status'] == 'complete'
# Don't re-log that we are sending!
assert l1.daemon.is_in_log("Sending 200000000msat over 1 hops to deliver 200000000msat", start=l1.daemon.logsearch_start) is None
def test_wait_sendpay(node_factory, executor):
l1, l2 = node_factory.line_graph(2, fundamount=10**6)
assert l1.rpc.wait(subsystem='sendpays', indexname='created', nextvalue=0) == {'subsystem': 'sendpays', 'created': 0}
wait_created = executor.submit(l1.rpc.call, 'wait', {'subsystem': 'sendpays', 'indexname': 'created', 'nextvalue': 1})
wait_updated = executor.submit(l1.rpc.call, 'wait', {'subsystem': 'sendpays', 'indexname': 'updated', 'nextvalue': 1})
time.sleep(1)
amt = 200000000
inv = l2.rpc.invoice(amt, 'testpayment2', 'desc')
routestep = {
'amount_msat': amt,
'id': l2.info['id'],
'delay': 5,
'channel': first_scid(l1, l2)
}
l1.rpc.sendpay([routestep], inv['payment_hash'], payment_secret=inv['payment_secret'])
assert wait_created.result(TIMEOUT) == {'subsystem': 'sendpays',
'created': 1,
'details': {'groupid': 1,
'partid': 0,
'payment_hash': inv['payment_hash'],
'status': 'pending'}}
assert wait_updated.result(TIMEOUT) == {'subsystem': 'sendpays',
'updated': 1,
'details': {'groupid': 1,
'partid': 0,
'payment_hash': inv['payment_hash'],
'status': 'complete'}}
l1.rpc.waitsendpay(inv['payment_hash'])['payment_preimage']
@unittest.skipIf(TEST_NETWORK != 'regtest', "The reserve computation is bitcoin specific")
@pytest.mark.parametrize("anchors", [False, True])
def test_sendpay_cant_afford(node_factory, anchors):
# Set feerates the same so we don't have to wait for update.
opts = {'feerates': (15000, 15000, 15000, 15000),
'commit-feerate-offset': 0}
if anchors is False:
opts['dev-force-features'] = "-23"
l1, l2 = node_factory.line_graph(2, fundamount=10**6, opts=opts)
# Can't pay more than channel capacity.
with pytest.raises(RpcError):
l1.pay(l2, 10**9 + 1)
# Reserve is 1%.
reserve = 10**7
# This is how we recalc constants (v. v. slow!)
# minimum = 1
# maximum = 10**9
# while maximum - minimum > 1:
# l1, l2 = node_factory.line_graph(2, fundamount=10**6, opts=opts)
# try:
# l1.pay(l2, (minimum + maximum) // 2)
# print("XXX Pay {} WORKED!".format((minimum + maximum) // 2))
# minimum = (minimum + maximum) // 2
# except RpcError:
# print("XXX Pay {} FAILED!".format((minimum + maximum) // 2))
# maximum = (minimum + maximum) // 2
# print("{} - {}".format(minimum, maximum))
# assert False, "Max we can pay == {}".format(minimum)
# # Currently this gives: 962713000 for non-anchors, 951833000 for anchors
# # Add reserve to this result to derive `available`
# This is the fee, which needs to be taken into account for l1.
if anchors:
available = 951833000 + reserve
else:
available = 962713000 + reserve
# Can't pay past reserve.
with pytest.raises(RpcError):
l1.pay(l2, available)
with pytest.raises(RpcError):
l1.pay(l2, available - reserve + 1)
# Can pay up to reserve (1%)
l1.pay(l2, available - reserve)
# And now it can't pay back, due to its own reserve.
with pytest.raises(RpcError):
l2.pay(l1, available - reserve)
# But this should work.
l2.pay(l1, available - reserve * 2)
def test_decode(node_factory):
l1 = node_factory.get_node()
# BOLT #11:
# > ### Please make a donation of any amount using payment_hash 0001020304050607080900010203040506070809000102030405060708090102 to me @03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad
# > lnbc1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpl2pkx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6twvus8g6rfwvs8qun0dfjkxaq8rkx3yf5tcsyz3d73gafnh3cax9rn449d9p5uxz9ezhhypd0elx87sjle52x86fux2ypatgddc6k63n7erqz25le42c4u4ecky03ylcqca784w
#
# Breakdown:
#
# * `lnbc`: prefix, lightning on bitcoin mainnet
# * `1`: Bech32 separator
# * `pvjluez`: timestamp (1496314658)
# * `p`: payment hash
# * `p5`: `data_length` (`p` = 1, `5` = 20. 1 * 32 + 20 == 52)
# * `qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypq`: payment hash 0001020304050607080900010203040506070809000102030405060708090102
# * `d`: short description
# * `pl`: `data_length` (`p` = 1, `l` = 31. 1 * 32 + 31 == 63)
# * `2pkx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6twvus8g6rfwvs8qun0dfjkxaq`: 'Please consider supporting this project'
# * `32vjcgqxyuj7nqphl3xmmhls2rkl3t97uan4j0xa87gj5779czc8p0z58zf5wpt9ggem6adl64cvawcxlef9djqwp2jzzfvs272504sp`: signature
# * `0lkg3c`: Bech32 checksum
b11 = l1.rpc.decode(
'lnbc1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqd'
'pl2pkx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6twvus8g6rfwvs8qun0dfjkxaq8rk'
'x3yf5tcsyz3d73gafnh3cax9rn449d9p5uxz9ezhhypd0elx87sjle52x86fux2ypatg'
'ddc6k63n7erqz25le42c4u4ecky03ylcqca784w'
)
assert b11['currency'] == 'bc'
assert b11['created_at'] == 1496314658
assert b11['payment_hash'] == '0001020304050607080900010203040506070809000102030405060708090102'
assert b11['description'] == 'Please consider supporting this project'
assert b11['expiry'] == 3600
assert b11['payee'] == '03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad'
# BOLT #11:
# > ### Please send $3 for a cup of coffee to the same peer, within 1 minute
# > lnbc2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpuaztrnwngzn3kdzw5hydlzf03qdgm2hdq27cqv3agm2awhz5se903vruatfhq77w3ls4evs3ch9zw97j25emudupq63nyw24cg27h2rspfj9srp
#
# Breakdown:
#
# * `lnbc`: prefix, lightning on bitcoin mainnet
# * `2500u`: amount (2500 micro-bitcoin)
# * `1`: Bech32 separator
# * `pvjluez`: timestamp (1496314658)
# * `p`: payment hash...
# * `d`: short description
# * `q5`: `data_length` (`q` = 0, `5` = 20. 0 * 32 + 20 == 20)
# * `xysxxatsyp3k7enxv4js`: '1 cup coffee'
# * `x`: expiry time
# * `qz`: `data_length` (`q` = 0, `z` = 2. 0 * 32 + 2 == 2)
# * `pu`: 60 seconds (`p` = 1, `u` = 28. 1 * 32 + 28 == 60)
# * `azh8qt5w7qeewkmxtv55khqxvdfs9zzradsvj7rcej9knpzdwjykcq8gv4v2dl705pjadhpsc967zhzdpuwn5qzjm0s4hqm2u0vuhhqq`: signature
# * `7vc09u`: Bech32 checksum
b11 = l1.rpc.decode(
'lnbc2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqf'
'qypqdq5xysxxatsyp3k7enxv4jsxqzpuaztrnwngzn3kdzw5hydlzf03qdgm2hdq27cq'
'v3agm2awhz5se903vruatfhq77w3ls4evs3ch9zw97j25emudupq63nyw24cg27h2rsp'
'fj9srp'
)
assert b11['currency'] == 'bc'
assert b11['amount_msat'] == Millisatoshi(2500 * 10**11 // 1000000)
assert b11['created_at'] == 1496314658
assert b11['payment_hash'] == '0001020304050607080900010203040506070809000102030405060708090102'
assert b11['description'] == '1 cup coffee'
assert b11['expiry'] == 60
assert b11['payee'] == '03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad'
# BOLT #11:
# > ### Now send $24 for an entire list of things (hashed)
# > lnbc20m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqscc6gd6ql3jrc5yzme8v4ntcewwz5cnw92tz0pc8qcuufvq7khhr8wpald05e92xw006sq94mg8v2ndf4sefvf9sygkshp5zfem29trqq2yxxz7
#
# Breakdown:
#
# * `lnbc`: prefix, lightning on bitcoin mainnet
# * `20m`: amount (20 milli-bitcoin)
# * `1`: Bech32 separator
# * `pvjluez`: timestamp (1496314658)
# * `p`: payment hash...
# * `h`: tagged field: hash of description
# * `p5`: `data_length` (`p` = 1, `5` = 20. 1 * 32 + 20 == 52)
# * `8yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqs`: SHA256 of 'One piece of chocolate cake, one icecream cone, one pickle, one slice of swiss cheese, one slice of salami, one lollypop, one piece of cherry pie, one sausage, one cupcake, and one slice of watermelon'
# * `vjfls3ljx9e93jkw0kw40yxn4pevgzflf83qh2852esjddv4xk4z70nehrdcxa4fk0t6hlcc6vrxywke6njenk7yzkzw0quqcwxphkcp`: signature
# * `vam37w`: Bech32 checksum
b11 = l1.rpc.decode(
'lnbc20m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqy'
'pqhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqscc6gd6ql3jr'
'c5yzme8v4ntcewwz5cnw92tz0pc8qcuufvq7khhr8wpald05e92xw006sq94mg8v2ndf'
'4sefvf9sygkshp5zfem29trqq2yxxz7'
)
assert b11['currency'] == 'bc'
assert b11['amount_msat'] == Millisatoshi(str(20 * 10**11 // 1000) + 'msat')
assert b11['created_at'] == 1496314658
assert b11['payment_hash'] == '0001020304050607080900010203040506070809000102030405060708090102'
assert b11['expiry'] == 3600
assert b11['payee'] == '03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad'
# > ### The same, on testnet, with a fallback address mk2QpYatsKicvFVuTAQLBryyccRXMUaGHP
# > lntb20m1pvjluezhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqfpp3x9et2e20v6pu37c5d9vax37wxq72un98kmzzhznpurw9sgl2v0nklu2g4d0keph5t7tj9tcqd8rexnd07ux4uv2cjvcqwaxgj7v4uwn5wmypjd5n69z2xm3xgksg28nwht7f6zspwp3f9t
#
# Breakdown:
#
# * `lntb`: prefix, lightning on bitcoin testnet
# * `20m`: amount (20 milli-bitcoin)
# * `1`: Bech32 separator
# * `pvjluez`: timestamp (1496314658)
# * `p`: payment hash...
# * `f`: tagged field: fallback address
# * `pp`: `data_length` (`p` = 1. 1 * 32 + 1 == 33)
# * `3x9et2e20v6pu37c5d9vax37wxq72un98`: `3` = 17, so P2PKH address
# * `h`: tagged field: hash of description...
# * `qh84fmvn2klvglsjxfy0vq2mz6t9kjfzlxfwgljj35w2kwa60qv49k7jlsgx43yhs9nuutllkhhnt090mmenuhp8ue33pv4klmrzlcqp`: signature
# * `us2s2r`: Bech32 checksum
b11 = l1.rpc.decode(
'lntb20m1pvjluezhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqfpp3x9et2e20v6pu37c5d9vax37wxq72un98kmzzhznpurw9sgl2v0nklu2g4d0keph5t7tj9tcqd8rexnd07ux4uv2cjvcqwaxgj7v4uwn5wmypjd5n69z2xm3xgksg28nwht7f6zspwp3f9t'
)
assert b11['currency'] == 'tb'
assert b11['amount_msat'] == Millisatoshi(20 * 10**11 // 1000)
assert b11['created_at'] == 1496314658
assert b11['payment_hash'] == '0001020304050607080900010203040506070809000102030405060708090102'
assert b11['expiry'] == 3600
assert b11['payee'] == '03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad'
assert len(b11['fallbacks']) == 1
assert b11['fallbacks'][0]['type'] == 'P2PKH'
assert b11['fallbacks'][0]['addr'] == 'mk2QpYatsKicvFVuTAQLBryyccRXMUaGHP'
# > ### On mainnet, with fallback address 1RustyRX2oai4EYYDpQGWvEL62BBGqN9T with extra routing info to go via nodes 029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255 then 039e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255
# > lnbc20m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqsfpp3qjmp7lwpagxun9pygexvgpjdc4jdj85fr9yq20q82gphp2nflc7jtzrcazrra7wwgzxqc8u7754cdlpfrmccae92qgzqvzq2ps8pqqqqqqpqqqqq9qqqvpeuqafqxu92d8lr6fvg0r5gv0heeeqgcrqlnm6jhphu9y00rrhy4grqszsvpcgpy9qqqqqqgqqqqq7qqzqj9n4evl6mr5aj9f58zp6fyjzup6ywn3x6sk8akg5v4tgn2q8g4fhx05wf6juaxu9760yp46454gpg5mtzgerlzezqcqvjnhjh8z3g2qqdhhwkj
#
# Breakdown:
#
# * `lnbc`: prefix, lightning on bitcoin mainnet
# * `20m`: amount (20 milli-bitcoin)
# * `1`: Bech32 separator
# * `pvjluez`: timestamp (1496314658)
# * `p`: payment hash...
# * `h`: tagged field: hash of description...
# * `f`: tagged field: fallback address
# * `pp`: `data_length` (`p` = 1. 1 * 32 + 1 == 33)
# * `3` = 17, so P2PKH address
# * `qjmp7lwpagxun9pygexvgpjdc4jdj85f`: 160 bit P2PKH address
# * `r`: tagged field: route information
# * `9y`: `data_length` (`9` = 5, `y` = 4. 5 * 32 + 4 = 164)
# `q20q82gphp2nflc7jtzrcazrra7wwgzxqc8u7754cdlpfrmccae92qgzqvzq2ps8pqqqqqqqqqqqq9qqqvpeuqafqxu92d8lr6fvg0r5gv0heeeqgcrqlnm6jhphu9y00rrhy4grqszsvpcgpy9qqqqqqqqqqqq7qqzq`: pubkey `029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255`, `short_channel_id` 0102030405060708, `fee_base_msat` 1 millisatoshi, `fee_proportional_millionths` 20, `cltv_expiry_delta` 3. pubkey `039e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255`, `short_channel_id` 030405060708090a, `fee_base_msat` 2 millisatoshi, `fee_proportional_millionths` 30, `cltv_expiry_delta` 4.
# * `j9n4evl6mr5aj9f58zp6fyjzup6ywn3x6sk8akg5v4tgn2q8g4fhx05wf6juaxu9760yp46454gpg5mtzgerlzezqcqvjnhjh8z3g2qq`: signature
# * `dhhwkj`: Bech32 checksum
b11 = l1.rpc.decode('lnbc20m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqsfpp3qjmp7lwpagxun9pygexvgpjdc4jdj85fr9yq20q82gphp2nflc7jtzrcazrra7wwgzxqc8u7754cdlpfrmccae92qgzqvzq2ps8pqqqqqqpqqqqq9qqqvpeuqafqxu92d8lr6fvg0r5gv0heeeqgcrqlnm6jhphu9y00rrhy4grqszsvpcgpy9qqqqqqgqqqqq7qqzqj9n4evl6mr5aj9f58zp6fyjzup6ywn3x6sk8akg5v4tgn2q8g4fhx05wf6juaxu9760yp46454gpg5mtzgerlzezqcqvjnhjh8z3g2qqdhhwkj')
assert b11['currency'] == 'bc'
assert b11['amount_msat'] == Millisatoshi(20 * 10**11 // 1000)
assert b11['created_at'] == 1496314658
assert b11['payment_hash'] == '0001020304050607080900010203040506070809000102030405060708090102'
assert b11['expiry'] == 3600
assert b11['payee'] == '03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad'
assert len(b11['fallbacks']) == 1
assert b11['fallbacks'][0]['type'] == 'P2PKH'
assert b11['fallbacks'][0]['addr'] == '1RustyRX2oai4EYYDpQGWvEL62BBGqN9T'
assert len(b11['routes']) == 1
assert len(b11['routes'][0]) == 2
assert b11['routes'][0][0]['pubkey'] == '029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255'
# 0x010203:0x040506:0x0708
assert b11['routes'][0][0]['short_channel_id'] == '66051x263430x1800'
assert b11['routes'][0][0]['fee_base_msat'] == 1
assert b11['routes'][0][0]['fee_proportional_millionths'] == 20
assert b11['routes'][0][0]['cltv_expiry_delta'] == 3
assert b11['routes'][0][1]['pubkey'] == '039e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255'
# 0x030405:0x060708:0x090a
assert b11['routes'][0][1]['short_channel_id'] == '197637x395016x2314'
assert b11['routes'][0][1]['fee_base_msat'] == 2
assert b11['routes'][0][1]['fee_proportional_millionths'] == 30
assert b11['routes'][0][1]['cltv_expiry_delta'] == 4
# > ### On mainnet, with fallback (P2SH) address 3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX
# > lnbc20m1pvjluezhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqfppj3a24vwu6r8ejrss3axul8rxldph2q7z9kmrgvr7xlaqm47apw3d48zm203kzcq357a4ls9al2ea73r8jcceyjtya6fu5wzzpe50zrge6ulk4nvjcpxlekvmxl6qcs9j3tz0469gq5g658y
#
# Breakdown:
#
# * `lnbc`: prefix, lightning on bitcoin mainnet
# * `20m`: amount (20 milli-bitcoin)
# * `1`: Bech32 separator
# * `pvjluez`: timestamp (1496314658)
# * `p`: payment hash...
# * `f`: tagged field: fallback address.
# * `pp`: `data_length` (`p` = 1. 1 * 32 + 1 == 33)
# * `j3a24vwu6r8ejrss3axul8rxldph2q7z9`: `j` = 18, so P2SH address
# * `h`: tagged field: hash of description...
# * `2jhz8j78lv2jynuzmz6g8ve53he7pheeype33zlja5azae957585uu7x59w0f2l3rugyva6zpu394y4rh093j6wxze0ldsvk757a9msq`: signature
# * `mf9swh`: Bech32 checksum
b11 = l1.rpc.decode('lnbc20m1pvjluezhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqfppj3a24vwu6r8ejrss3axul8rxldph2q7z9kmrgvr7xlaqm47apw3d48zm203kzcq357a4ls9al2ea73r8jcceyjtya6fu5wzzpe50zrge6ulk4nvjcpxlekvmxl6qcs9j3tz0469gq5g658y')
assert b11['currency'] == 'bc'
assert b11['amount_msat'] == Millisatoshi(20 * 10**11 // 1000)