forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_lightningd.py
5002 lines (4050 loc) · 213 KB
/
test_lightningd.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 concurrent import futures
from decimal import Decimal
from ephemeral_port_reserve import reserve as reserve_port
from flaky import flaky
from utils import wait_for
import copy
import json
import logging
import queue
import os
import random
import re
import shutil
import socket
import sqlite3
import stat
import string
import subprocess
import sys
import tempfile
import threading
import time
import unittest
import utils
from lightning import LightningRpc
with open('config.vars') as configfile:
config = dict([(line.rstrip().split('=', 1)) for line in configfile])
bitcoind = None
TEST_DIR = tempfile.mkdtemp(prefix='lightning-')
VALGRIND = os.getenv("VALGRIND", config['VALGRIND']) == "1"
DEVELOPER = os.getenv("DEVELOPER", config['DEVELOPER']) == "1"
TEST_DEBUG = os.getenv("TEST_DEBUG", "0") == "1"
if TEST_DEBUG:
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
logging.info("Tests running in '%s'", TEST_DIR)
def to_json(arg):
return json.loads(json.dumps(arg))
def setupBitcoind(directory):
global bitcoind
bitcoind = utils.BitcoinD(bitcoin_dir=directory, rpcport=None)
try:
bitcoind.start()
except Exception:
teardown_bitcoind()
raise
info = bitcoind.rpc.getnetworkinfo()
if info['version'] < 160000:
bitcoind.rpc.stop()
raise ValueError("bitcoind is too old. At least version 16000 (v0.16.0)"
" is needed, current version is {}".format(info['version']))
info = bitcoind.rpc.getblockchaininfo()
# Make sure we have some spendable funds
if info['blocks'] < 101:
bitcoind.generate_block(101 - info['blocks'])
elif bitcoind.rpc.getwalletinfo()['balance'] < 1:
logging.debug("Insufficient balance, generating 1 block")
bitcoind.generate_block(1)
def wait_forget_channels(node):
"""This node is closing all of its channels, check we are forgetting them
"""
node.daemon.wait_for_log(r'onchaind complete, forgetting peer')
# May have reconnected, but should merely be gossiping.
for peer in node.rpc.listpeers()['peers']:
assert peer['state'] == 'GOSSIPING'
assert node.db_query("SELECT * FROM channels") == []
def sync_blockheight(nodes):
target = bitcoind.rpc.getblockcount()
for n in nodes:
wait_for(lambda: n.rpc.getinfo()['blockheight'] == target)
def teardown_bitcoind():
global bitcoind
try:
bitcoind.rpc.stop()
except Exception:
bitcoind.proc.kill()
bitcoind.proc.wait()
class NodeFactory(object):
"""A factory to setup and start `lightningd` daemons.
"""
def __init__(self, testname, bitcoind, executor, directory=None):
self.testname = testname
self.next_id = 1
self.nodes = []
self.executor = executor
self.bitcoind = bitcoind
if directory is not None:
self.directory = directory
else:
self.directory = os.path.join(TEST_DIR, testname)
self.lock = threading.Lock()
def split_options(self, opts):
"""Split node options from cli options
Some options are used to instrument the node wrapper and some are passed
to the daemon on the command line. Split them so we know where to use
them.
"""
node_opt_keys = [
'disconnect',
'may_fail',
'may_reconnect',
'random_hsm',
'fake_bitcoin_cli'
]
node_opts = {k: v for k, v in opts.items() if k in node_opt_keys}
cli_opts = {k: v for k, v in opts.items() if k not in node_opt_keys}
return node_opts, cli_opts
def get_next_port(self):
with self.lock:
return reserve_port()
def get_nodes(self, num_nodes, opts=None):
"""Start a number of nodes in parallel, each with its own options
"""
if opts is None:
# No opts were passed in, give some dummy opts
opts = [{} for _ in range(num_nodes)]
elif isinstance(opts, dict):
# A single dict was passed in, so we use these opts for all nodes
opts = [opts] * num_nodes
assert len(opts) == num_nodes
jobs = []
for i in range(num_nodes):
node_opts, cli_opts = self.split_options(opts[i])
jobs.append(self.executor.submit(self.get_node, options=cli_opts, **node_opts))
return [j.result() for j in jobs]
def get_node(self, disconnect=None, options=None, may_fail=False, may_reconnect=False, random_hsm=False, fake_bitcoin_cli=False):
with self.lock:
node_id = self.next_id
self.next_id += 1
port = self.get_next_port()
lightning_dir = os.path.join(
self.directory, "lightning-{}/".format(node_id))
if os.path.exists(lightning_dir):
shutil.rmtree(lightning_dir)
socket_path = os.path.join(lightning_dir, "lightning-rpc").format(node_id)
daemon = utils.LightningD(
lightning_dir, self.bitcoind.bitcoin_dir,
port=port, random_hsm=random_hsm, node_id=node_id
)
# If we have a disconnect string, dump it to a file for daemon.
if disconnect:
with open(os.path.join(lightning_dir, "dev_disconnect"), "w") as f:
f.write("\n".join(disconnect))
daemon.opts["dev-disconnect"] = "dev_disconnect"
if DEVELOPER:
daemon.opts["dev-fail-on-subdaemon-fail"] = None
daemon.env["LIGHTNINGD_DEV_MEMLEAK"] = "1"
if VALGRIND:
daemon.env["LIGHTNINGD_DEV_NO_BACKTRACE"] = "1"
if not may_reconnect:
daemon.opts["dev-no-reconnect"] = None
if fake_bitcoin_cli:
cli = os.path.join(lightning_dir, "fake-bitcoin-cli")
with open(cli, "w") as text_file:
print("""#! /bin/sh
! [ -f bitcoin-cli-fail ] || exit `cat bitcoin-cli-fail`
exec bitcoin-cli "$@"
""", file=text_file)
os.chmod(cli, os.stat(cli).st_mode | stat.S_IEXEC)
daemon.opts['bitcoin-cli'] = cli
if options is not None:
daemon.opts.update(options)
rpc = LightningRpc(socket_path, self.executor)
node = utils.LightningNode(daemon, rpc, self.bitcoind, self.executor, may_fail=may_fail, may_reconnect=may_reconnect)
self.nodes.append(node)
if VALGRIND:
node.daemon.cmd_prefix = [
'valgrind',
'-q',
'--trace-children=yes',
'--trace-children-skip=*bitcoin-cli*',
'--error-exitcode=7',
'--log-file={}/valgrind-errors.%p'.format(node.daemon.lightning_dir)
]
try:
node.start()
except Exception:
node.daemon.stop()
raise
# Cache `getinfo`, we'll be using it a lot
node.info = node.rpc.getinfo()
return node
def killall(self, expected_successes):
"""Returns true if every node we expected to succeed actually succeeded"""
unexpected_fail = False
for i in range(len(self.nodes)):
leaks = None
# leak detection upsets VALGRIND by reading uninitialized mem.
# If it's dead, we'll catch it below.
if not VALGRIND:
try:
# This also puts leaks in log.
leaks = self.nodes[i].rpc.dev_memleak()['leaks']
except Exception:
pass
try:
self.nodes[i].stop()
except Exception:
if expected_successes[i]:
unexpected_fail = True
if leaks is not None and len(leaks) != 0:
raise Exception("Node {} has memory leaks: {}"
.format(self.nodes[i].daemon.lightning_dir, leaks))
return not unexpected_fail
class BaseLightningDTests(unittest.TestCase):
def setUp(self):
bitcoin_dir = os.path.join(TEST_DIR, self._testMethodName, "bitcoind")
setupBitcoind(bitcoin_dir)
# Most of the executor threads will be waiting for IO, so
# let's have a few of them
self.executor = futures.ThreadPoolExecutor(max_workers=20)
self.node_factory = NodeFactory(self._testMethodName, bitcoind, self.executor)
def getValgrindErrors(self, node):
for error_file in os.listdir(node.daemon.lightning_dir):
if not re.fullmatch("valgrind-errors.\d+", error_file):
continue
with open(os.path.join(node.daemon.lightning_dir, error_file), 'r') as f:
errors = f.read().strip()
if errors:
return errors, error_file
return None, None
def printValgrindErrors(self, node):
errors, fname = self.getValgrindErrors(node)
if errors:
print("-" * 31, "Valgrind errors", "-" * 32)
print("Valgrind error file:", fname)
print(errors)
print("-" * 80)
return 1 if errors else 0
def getCrashLog(self, node):
if node.may_fail:
return None, None
try:
crashlog = os.path.join(node.daemon.lightning_dir, 'crash.log')
with open(crashlog, 'r') as f:
return f.readlines(), crashlog
except Exception:
return None, None
def printCrashLog(self, node):
errors, fname = self.getCrashLog(node)
if errors:
print("-" * 10, "{} (last 50 lines)".format(fname), "-" * 10)
for l in errors[-50:]:
print(l, end='')
print("-" * 80)
return 1 if errors else 0
def checkReconnect(self, node):
# Without DEVELOPER, we can't suppress reconnection.
if node.may_reconnect or not DEVELOPER:
return 0
if node.daemon.is_in_log('Peer has reconnected'):
return 1
return 0
def checkBadGossipOrder(self, node):
# We can have a race where we notice a channel deleted and someone
# sends an update, and we can get unknown channel updates in errors.
if node.daemon.is_in_log('Bad gossip order from (?!error)') and not node.daemon.is_in_log('Deleting channel'):
return 1
return 0
def tearDown(self):
ok = self.node_factory.killall([not n.may_fail for n in self.node_factory.nodes])
self.executor.shutdown(wait=False)
teardown_bitcoind()
err_count = 0
# Do not check for valgrind error files if it is disabled
if VALGRIND:
for node in self.node_factory.nodes:
err_count += self.printValgrindErrors(node)
if err_count:
raise ValueError("{} nodes reported valgrind errors".format(err_count))
for node in self.node_factory.nodes:
err_count += self.printCrashLog(node)
if err_count:
raise ValueError("{} nodes had crash.log files".format(err_count))
for node in self.node_factory.nodes:
err_count += self.checkReconnect(node)
if err_count:
raise ValueError("{} nodes had unexpected reconnections".format(err_count))
for node in self.node_factory.nodes:
err_count += self.checkBadGossipOrder(node)
if err_count:
raise ValueError("{} nodes had bad gossip order".format(err_count))
if not ok:
raise Exception("At least one lightning exited with unexpected non-zero return code")
shutil.rmtree(self.node_factory.directory)
class LightningDTests(BaseLightningDTests):
def connect(self, may_reconnect=False):
l1, l2 = self.node_factory.get_nodes(2, opts={'may_reconnect': may_reconnect})
ret = l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
assert ret['id'] == l2.info['id']
l1.daemon.wait_for_log('Handing back peer .* to master')
l2.daemon.wait_for_log('Handing back peer .* to master')
return l1, l2
# Waits until l1 notices funds
def give_funds(self, l1, satoshi):
addr = l1.rpc.newaddr()['address']
bitcoind.rpc.sendtoaddress(addr, satoshi / 10**8)
numfunds = len(l1.rpc.listfunds()['outputs'])
bitcoind.generate_block(1)
wait_for(lambda: len(l1.rpc.listfunds()['outputs']) > numfunds)
# Returns the short channel-id: <blocknum>:<txnum>:<outnum>
def fund_channel(self, l1, l2, amount):
return l1.fund_channel(l2, amount)
def pay(self, lsrc, ldst, amt, label=None, async=False):
if not label:
label = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(20))
rhash = ldst.rpc.invoice(amt, label, label)['payment_hash']
assert ldst.rpc.listinvoices(label)['invoices'][0]['status'] == 'unpaid'
routestep = {
'msatoshi': amt,
'id': ldst.info['id'],
'delay': 5,
'channel': '1:1:1'
}
def wait_pay():
# Up to 10 seconds for payment to succeed.
start_time = time.time()
while ldst.rpc.listinvoices(label)['invoices'][0]['status'] != 'paid':
if time.time() > start_time + 10:
raise TimeoutError('Payment timed out')
time.sleep(0.1)
# sendpay is async now
lsrc.rpc.sendpay(to_json([routestep]), rhash)
if async:
return self.executor.submit(wait_pay)
else:
# wait for sendpay to comply
lsrc.rpc.waitsendpay(rhash)
# This waits until gossipd sees channel_update in both directions
# (or for local channels, at least a local announcement)
def wait_for_routes(self, l1, channel_ids):
bitcoind.generate_block(5)
# Could happen in any order...
l1.daemon.wait_for_logs(['Received channel_update for channel {}\\(0\\)'.format(c)
for c in channel_ids] +
['Received channel_update for channel {}\\(1\\)'.format(c)
for c in channel_ids])
def fake_bitcoind_fail(self, l1, exitcode):
# Create and rename, for atomicity.
f = os.path.join(l1.daemon.lightning_dir, "bitcoin-cli-fail.tmp")
with open(f, "w") as text_file:
print(exitcode, file=text_file)
os.rename(f, os.path.join(l1.daemon.lightning_dir, "bitcoin-cli-fail"))
def fake_bitcoind_unfail(self, l1):
os.remove(os.path.join(l1.daemon.lightning_dir, "bitcoin-cli-fail"))
@unittest.skipIf(not DEVELOPER, "needs DEVELOPER=1")
def test_shutdown(self):
# Fail, in that it will exit before cleanup.
l1 = self.node_factory.get_node(may_fail=True)
if not VALGRIND:
leaks = l1.rpc.dev_memleak()['leaks']
if len(leaks):
raise Exception("Node {} has memory leaks: {}"
.format(l1.daemon.lightning_dir, leaks))
l1.rpc.stop()
def test_autocleaninvoice(self):
l1 = self.node_factory.get_node()
start_time = time.time()
l1.rpc.autocleaninvoice(cycle_seconds=8, expired_by=2)
l1.rpc.invoice(msatoshi=12300, label='inv1', description='1', expiry=4)
l1.rpc.invoice(msatoshi=12300, label='inv2', description='2', expiry=12)
# time 0
# Both should still be there.
assert len(l1.rpc.listinvoices('inv1')['invoices']) == 1
assert len(l1.rpc.listinvoices('inv2')['invoices']) == 1
time.sleep(start_time - time.time() + 6) # total 6
# Both should still be there - auto clean cycle not started.
# inv1 should be expired
assert len(l1.rpc.listinvoices('inv1')['invoices']) == 1
assert l1.rpc.listinvoices('inv1')['invoices'][0]['status'] == 'expired'
assert len(l1.rpc.listinvoices('inv2')['invoices']) == 1
assert l1.rpc.listinvoices('inv2')['invoices'][0]['status'] != 'expired'
time.sleep(start_time - time.time() + 10) # total 10
# inv1 should have deleted, inv2 still there and unexpired.
assert len(l1.rpc.listinvoices('inv1')['invoices']) == 0
assert len(l1.rpc.listinvoices('inv2')['invoices']) == 1
assert l1.rpc.listinvoices('inv2')['invoices'][0]['status'] != 'expired'
time.sleep(start_time - time.time() + 14) # total 14
# inv2 should still be there, but expired
assert len(l1.rpc.listinvoices('inv1')['invoices']) == 0
assert len(l1.rpc.listinvoices('inv2')['invoices']) == 1
assert l1.rpc.listinvoices('inv2')['invoices'][0]['status'] == 'expired'
time.sleep(start_time - time.time() + 18) # total 18
# Everything deleted
assert len(l1.rpc.listinvoices('inv1')['invoices']) == 0
assert len(l1.rpc.listinvoices('inv2')['invoices']) == 0
def test_invoice_preimage(self):
"""Test explicit invoice 'preimage'.
"""
l1, l2 = self.connect()
self.fund_channel(l1, l2, 10**6)
# I promise the below number is randomly generated
invoice_preimage = "17b08f669513b7379728fc1abcea5eaf3448bc1eba55a68ca2cd1843409cdc04"
# Make invoice and pay it
inv = l2.rpc.invoice(msatoshi=123456, label="inv", description="?", preimage=invoice_preimage)
payment = l1.rpc.pay(inv['bolt11'])
# Check preimage was given.
payment_preimage = payment['payment_preimage']
assert invoice_preimage == payment_preimage
# Creating a new invoice with same preimage should error.
self.assertRaisesRegex(ValueError,
"preimage already used",
l2.rpc.invoice, 123456, 'inv2', '?',
None, None, invoice_preimage)
def test_names(self):
for key, alias, color in [('0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c03518', 'JUNIORBEAM', '0266e4'),
('022d223620a359a47ff7f7ac447c85c46c923da53389221a0054c11c1e3ca31d59', 'SILENTARTIST', '022d22'),
('035d2b1192dfba134e10e540875d366ebc8bc353d5aa766b80c090b39c3a5d885d', 'HOPPINGFIRE', '035d2b'),
('0382ce59ebf18be7d84677c2e35f23294b9992ceca95491fcf8a56c6cb2d9de199', 'JUNIORFELONY', '0382ce'),
('032cf15d1ad9c4a08d26eab1918f732d8ef8fdc6abb9640bf3db174372c491304e', 'SOMBERFIRE', '032cf1'),
('0265b6ab5ec860cd257865d61ef0bbf5b3339c36cbda8b26b74e7f1dca490b6518', 'LOUDPHOTO', '0265b6')]:
n = self.node_factory.get_node()
assert n.daemon.is_in_log('public key {}, alias {}.* \(color #{}\)'
.format(key, alias, color))
def test_invoice(self):
l1 = self.node_factory.get_node()
l2 = self.node_factory.get_node()
addr1 = l2.rpc.newaddr('bech32')['address']
addr2 = l2.rpc.newaddr('p2sh-segwit')['address']
before = int(time.time())
inv = l1.rpc.invoice(123000, 'label', 'description', '3700', [addr1, addr2])
after = int(time.time())
b11 = l1.rpc.decodepay(inv['bolt11'])
assert b11['currency'] == 'bcrt'
assert b11['created_at'] >= before
assert b11['created_at'] <= after
assert b11['payment_hash'] == inv['payment_hash']
assert b11['description'] == 'description'
assert b11['expiry'] == 3700
assert b11['payee'] == l1.info['id']
assert len(b11['fallbacks']) == 2
assert b11['fallbacks'][0]['addr'] == addr1
assert b11['fallbacks'][0]['type'] == 'P2WPKH'
assert b11['fallbacks'][1]['addr'] == addr2
assert b11['fallbacks'][1]['type'] == 'P2SH'
# Check pay_index is null
outputs = l1.db_query('SELECT pay_index IS NULL AS q FROM invoices WHERE label="label";')
assert len(outputs) == 1 and outputs[0]['q'] != 0
# Check any-amount invoice
inv = l1.rpc.invoice("any", 'label2', 'description2')
b11 = inv['bolt11']
# Amount usually comes after currency (bcrt in our case),
# but an any-amount invoices will have no amount
assert b11.startswith("lnbcrt1")
# By bech32 rules, the last '1' digit is the separator
# between the human-readable and data parts. We want
# to match the "lnbcrt1" above with the '1' digit as the
# separator, and not for example "lnbcrt1m1....".
assert b11.count('1') == 1
def test_invoice_weirdstring(self):
l1 = self.node_factory.get_node()
weird_label = 'label \\ " \t \n'
weird_desc = 'description \\ " \t \n'
l1.rpc.invoice(123000, weird_label, weird_desc)
# FIXME: invoice RPC should return label!
# Can find by this label.
inv = l1.rpc.listinvoices(weird_label)['invoices'][0]
assert inv['label'] == weird_label
# Can find this in list.
inv = l1.rpc.listinvoices()['invoices'][0]
assert inv['label'] == weird_label
b11 = l1.rpc.decodepay(inv['bolt11'])
assert b11['description'] == weird_desc
# Can delete by weird label.
l1.rpc.delinvoice(weird_label, "unpaid")
# We can also use numbers as labels.
weird_label = 25
weird_desc = '"'
l1.rpc.invoice(123000, weird_label, weird_desc)
# FIXME: invoice RPC should return label!
# Can find by this label.
inv = l1.rpc.listinvoices(weird_label)['invoices'][0]
assert inv['label'] == str(weird_label)
# Can find this in list.
inv = l1.rpc.listinvoices()['invoices'][0]
assert inv['label'] == str(weird_label)
b11 = l1.rpc.decodepay(inv['bolt11'])
assert b11['description'] == weird_desc
# Can delete by weird label.
l1.rpc.delinvoice(weird_label, "unpaid")
def test_invoice_expiry(self):
l1, l2 = self.connect()
chanid = self.fund_channel(l1, l2, 10**6)
# Wait for route propagation.
self.wait_for_routes(l1, [chanid])
inv = l2.rpc.invoice(msatoshi=123000, label='test_pay', description='description', expiry=1)['bolt11']
time.sleep(2)
self.assertRaises(ValueError, l1.rpc.pay, inv)
assert l2.rpc.listinvoices('test_pay')['invoices'][0]['status'] == 'expired'
assert l2.rpc.listinvoices('test_pay')['invoices'][0]['expires_at'] < time.time()
# Try deleting it.
self.assertRaisesRegex(ValueError,
'Invoice status is expired not unpaid',
l2.rpc.delinvoice,
'test_pay', 'unpaid')
self.assertRaisesRegex(ValueError,
'Invoice status is expired not paid',
l2.rpc.delinvoice,
'test_pay', 'paid')
l2.rpc.delinvoice('test_pay', 'expired')
self.assertRaisesRegex(ValueError,
'Unknown invoice',
l2.rpc.delinvoice,
'test_pay', 'expired')
# Test expiration waiting.
# The second invoice created expires first.
l2.rpc.invoice('any', 'inv1', 'description', 10)
l2.rpc.invoice('any', 'inv2', 'description', 4)
l2.rpc.invoice('any', 'inv3', 'description', 16)
creation = int(time.time())
# Check waitinvoice correctly waits
w1 = self.executor.submit(l2.rpc.waitinvoice, 'inv1')
w2 = self.executor.submit(l2.rpc.waitinvoice, 'inv2')
w3 = self.executor.submit(l2.rpc.waitinvoice, 'inv3')
time.sleep(2) # total 2
assert not w1.done()
assert not w2.done()
assert not w3.done()
time.sleep(4) # total 6
assert not w1.done()
self.assertRaises(ValueError, w2.result)
assert not w3.done()
time.sleep(6) # total 12
self.assertRaises(ValueError, w1.result)
assert not w3.done()
time.sleep(8) # total 20
self.assertRaises(ValueError, w3.result)
# Test delexpiredinvoice
l2.rpc.delexpiredinvoice(maxexpirytime=creation + 8)
# only inv2 should have been deleted
assert len(l2.rpc.listinvoices()['invoices']) == 2
assert len(l2.rpc.listinvoices('inv2')['invoices']) == 0
# Test delexpiredinvoice all
l2.rpc.delexpiredinvoice()
# all invoices are expired and should be deleted
assert len(l2.rpc.listinvoices()['invoices']) == 0
def test_connect(self):
l1, l2 = self.connect()
# These should be in gossipd.
assert l1.rpc.getpeer(l2.info['id'])['state'] == 'GOSSIPING'
assert l2.rpc.getpeer(l1.info['id'])['state'] == 'GOSSIPING'
# Both gossipds will have them as new peers once handed back.
l1.daemon.wait_for_log('hand_back_peer {}: now local again'.format(l2.info['id']))
l2.daemon.wait_for_log('hand_back_peer {}: now local again'.format(l1.info['id']))
# Reconnect should be a noop
ret = l1.rpc.connect(l2.info['id'], 'localhost', port=l2.port)
assert ret['id'] == l2.info['id']
ret = l2.rpc.connect(l1.info['id'], host='localhost', port=l1.port)
assert ret['id'] == l1.info['id']
# Should still only have one peer!
assert len(l1.rpc.listpeers()) == 1
assert len(l2.rpc.listpeers()) == 1
# Should get reasonable error if unknown addr for peer.
self.assertRaisesRegex(ValueError,
"No address known",
l1.rpc.connect, '032cf15d1ad9c4a08d26eab1918f732d8ef8fdc6abb9640bf3db174372c491304e')
# Should get reasonable error if connection refuse.
self.assertRaisesRegex(ValueError,
"Connection establishment: Connection refused",
l1.rpc.connect, '032cf15d1ad9c4a08d26eab1918f732d8ef8fdc6abb9640bf3db174372c491304e', 'localhost', 1)
# Should get reasonable error if wrong key for peer.
self.assertRaisesRegex(ValueError,
"Cryptographic handshake: ",
l1.rpc.connect, '032cf15d1ad9c4a08d26eab1918f732d8ef8fdc6abb9640bf3db174372c491304e', 'localhost', l2.port)
@unittest.skipIf(not DEVELOPER, "needs --dev-allow-localhost")
def test_connect_by_gossip(self):
"""Test connecting to an unknown peer using node gossip
"""
l1 = self.node_factory.get_node()
l2 = self.node_factory.get_node()
l3 = self.node_factory.get_node()
l2.rpc.connect(l3.info['id'], 'localhost', l3.port)
# Nodes are gossiped only if they have channels
chanid = self.fund_channel(l2, l3, 10**6)
# Let channel reach announcement depth
self.wait_for_routes(l2, [chanid])
# Make sure l3 has given node announcement to l2.
l2.daemon.wait_for_logs(['Received node_announcement for node {}'.format(l3.info['id'])])
# Let l1 learn of l3 by node gossip
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
l1.daemon.wait_for_logs(['Received node_announcement for node {}'.format(l3.info['id'])])
# Have l1 connect to l3 without explicit host and port.
l1.rpc.connect(l3.info['id'])
def test_connect_standard_addr(self):
"""Test standard node@host:port address
"""
l1 = self.node_factory.get_node()
l2 = self.node_factory.get_node()
l3 = self.node_factory.get_node()
# node@host
ret = l1.rpc.connect("{}@{}".format(l2.info['id'], 'localhost'), port=l2.port)
assert ret['id'] == l2.info['id']
# node@host:port
ret = l1.rpc.connect("{}@localhost:{}".format(l3.info['id'], l3.port))
assert ret['id'] == l3.info['id']
# node@[ipv6]:port --- not supported by our CI
# ret = l1.rpc.connect("{}@[::1]:{}".format(l3.info['id'], l3.port))
# assert ret['id'] == l3.info['id']
def test_reconnect_channel_peers(self):
l1 = self.node_factory.get_node(may_reconnect=True)
l2 = self.node_factory.get_node(may_reconnect=True)
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
self.fund_channel(l1, l2, 10**6)
l2.restart()
# Should reconnect.
wait_for(lambda: l1.rpc.listpeers(l2.info['id'])['peers'][0]['connected'])
wait_for(lambda: l2.rpc.listpeers(l1.info['id'])['peers'][0]['connected'])
# Connect command should succeed.
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
# Stop l2 and wait for l1 to notice.
l2.stop()
wait_for(lambda: not l1.rpc.listpeers(l2.info['id'])['peers'][0]['connected'])
# Now should fail.
self.assertRaisesRegex(ValueError,
"Connection refused",
l1.rpc.connect, l2.info['id'], 'localhost', l2.port)
# Wait for exponential backoff to give us a 2 second window.
l1.daemon.wait_for_log('...will try again in 2 seconds')
# It should now succeed when it restarts.
l2.start()
# Multiples should be fine!
fut1 = self.executor.submit(l1.rpc.connect, l2.info['id'], 'localhost', l2.port)
fut2 = self.executor.submit(l1.rpc.connect, l2.info['id'], 'localhost', l2.port)
fut3 = self.executor.submit(l1.rpc.connect, l2.info['id'], 'localhost', l2.port)
fut1.result(10)
fut2.result(10)
fut3.result(10)
def test_balance(self):
l1, l2 = self.connect()
self.fund_channel(l1, l2, 10**6)
p1 = l1.rpc.getpeer(peer_id=l2.info['id'], level='info')['channels'][0]
p2 = l2.rpc.getpeer(l1.info['id'], 'info')['channels'][0]
assert p1['msatoshi_to_us'] == 10**6 * 1000
assert p1['msatoshi_total'] == 10**6 * 1000
assert p2['msatoshi_to_us'] == 0
assert p2['msatoshi_total'] == 10**6 * 1000
def test_decodepay(self):
l1 = self.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.decodepay('lnbc1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpl2pkx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6twvus8g6rfwvs8qun0dfjkxaq8rkx3yf5tcsyz3d73gafnh3cax9rn449d9p5uxz9ezhhypd0elx87sjle52x86fux2ypatgddc6k63n7erqz25le42c4u4ecky03ylcqca784w')
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.decodepay('lnbc2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpuaztrnwngzn3kdzw5hydlzf03qdgm2hdq27cqv3agm2awhz5se903vruatfhq77w3ls4evs3ch9zw97j25emudupq63nyw24cg27h2rspfj9srp')
assert b11['currency'] == 'bc'
assert b11['msatoshi'] == 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.decodepay('lnbc20m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqscc6gd6ql3jrc5yzme8v4ntcewwz5cnw92tz0pc8qcuufvq7khhr8wpald05e92xw006sq94mg8v2ndf4sefvf9sygkshp5zfem29trqq2yxxz7', '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')
assert b11['currency'] == 'bc'
assert b11['msatoshi'] == 20 * 10**11 // 1000
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.decodepay('lntb20m1pvjluezhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqfpp3x9et2e20v6pu37c5d9vax37wxq72un98kmzzhznpurw9sgl2v0nklu2g4d0keph5t7tj9tcqd8rexnd07ux4uv2cjvcqwaxgj7v4uwn5wmypjd5n69z2xm3xgksg28nwht7f6zspwp3f9t', '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')
assert b11['currency'] == 'tb'
assert b11['msatoshi'] == 20 * 10**11 // 1000
assert b11['created_at'] == 1496314658
assert b11['payment_hash'] == '0001020304050607080900010203040506070809000102030405060708090102'
assert b11['expiry'] == 3600
assert b11['payee'] == '03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad'
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.decodepay('lnbc20m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqsfpp3qjmp7lwpagxun9pygexvgpjdc4jdj85fr9yq20q82gphp2nflc7jtzrcazrra7wwgzxqc8u7754cdlpfrmccae92qgzqvzq2ps8pqqqqqqpqqqqq9qqqvpeuqafqxu92d8lr6fvg0r5gv0heeeqgcrqlnm6jhphu9y00rrhy4grqszsvpcgpy9qqqqqqgqqqqq7qqzqj9n4evl6mr5aj9f58zp6fyjzup6ywn3x6sk8akg5v4tgn2q8g4fhx05wf6juaxu9760yp46454gpg5mtzgerlzezqcqvjnhjh8z3g2qqdhhwkj', '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')
assert b11['currency'] == 'bc'
assert b11['msatoshi'] == 20 * 10**11 // 1000
assert b11['created_at'] == 1496314658
assert b11['payment_hash'] == '0001020304050607080900010203040506070809000102030405060708090102'
assert b11['expiry'] == 3600
assert b11['payee'] == '03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad'
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'] == '66051:263430:1800'
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'] == '197637:395016:2314'
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.decodepay('lnbc20m1pvjluezhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqfppj3a24vwu6r8ejrss3axul8rxldph2q7z9kmrgvr7xlaqm47apw3d48zm203kzcq357a4ls9al2ea73r8jcceyjtya6fu5wzzpe50zrge6ulk4nvjcpxlekvmxl6qcs9j3tz0469gq5g658y', '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')
assert b11['currency'] == 'bc'
assert b11['msatoshi'] == 20 * 10**11 // 1000
assert b11['created_at'] == 1496314658
assert b11['payment_hash'] == '0001020304050607080900010203040506070809000102030405060708090102'
assert b11['expiry'] == 3600
assert b11['payee'] == '03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad'
assert b11['fallbacks'][0]['type'] == 'P2SH'
assert b11['fallbacks'][0]['addr'] == '3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX'
# > ### On mainnet, with fallback (P2WPKH) address bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4
# > lnbc20m1pvjluezhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqfppqw508d6qejxtdg4y5r3zarvary0c5xw7kepvrhrm9s57hejg0p662ur5j5cr03890fa7k2pypgttmh4897d3raaq85a293e9jpuqwl0rnfuwzam7yr8e690nd2ypcq9hlkdwdvycqa0qza8
#
# * `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)
# * `q`: 0, so witness version 0.
# * `qw508d6qejxtdg4y5r3zarvary0c5xw7k`: 160 bits = P2WPKH.
# * `h`: tagged field: hash of description...
# * `gw6tk8z0p0qdy9ulggx65lvfsg3nxxhqjxuf2fvmkhl9f4jc74gy44d5ua9us509prqz3e7vjxrftn3jnk7nrglvahxf7arye5llphgq`: signature
# * `qdtpa4`: Bech32 checksum
b11 = l1.rpc.decodepay('lnbc20m1pvjluezhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqfppqw508d6qejxtdg4y5r3zarvary0c5xw7kepvrhrm9s57hejg0p662ur5j5cr03890fa7k2pypgttmh4897d3raaq85a293e9jpuqwl0rnfuwzam7yr8e690nd2ypcq9hlkdwdvycqa0qza8', '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')
assert b11['currency'] == 'bc'
assert b11['msatoshi'] == 20 * 10**11 // 1000
assert b11['created_at'] == 1496314658
assert b11['payment_hash'] == '0001020304050607080900010203040506070809000102030405060708090102'
assert b11['expiry'] == 3600
assert b11['payee'] == '03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad'
assert b11['fallbacks'][0]['type'] == 'P2WPKH'
assert b11['fallbacks'][0]['addr'] == 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4'
# > ### On mainnet, with fallback (P2WSH) address bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3
# > lnbc20m1pvjluezhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqfp4qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q28j0v3rwgy9pvjnd48ee2pl8xrpxysd5g44td63g6xcjcu003j3qe8878hluqlvl3km8rm92f5stamd3jw763n3hck0ct7p8wwj463cql26ava
#
# * `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.
# * `p4`: `data_length` (`p` = 1, `4` = 21. 1 * 32 + 21 == 53)
# * `q`: 0, so witness version 0.
# * `rp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q`: 260 bits = P2WSH.
# * `h`: tagged field: hash of description...
# * `5yps56lmsvgcrf476flet6js02m93kgasews8q3jhtp7d6cqckmh70650maq4u65tk53ypszy77v9ng9h2z3q3eqhtc3ewgmmv2grasp`: signature
# * `akvd7y`: Bech32 checksum
b11 = l1.rpc.decodepay('lnbc20m1pvjluezhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqfp4qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q28j0v3rwgy9pvjnd48ee2pl8xrpxysd5g44td63g6xcjcu003j3qe8878hluqlvl3km8rm92f5stamd3jw763n3hck0ct7p8wwj463cql26ava', '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')
assert b11['currency'] == 'bc'
assert b11['msatoshi'] == 20 * 10**11 // 1000
assert b11['created_at'] == 1496314658
assert b11['payment_hash'] == '0001020304050607080900010203040506070809000102030405060708090102'
assert b11['expiry'] == 3600
assert b11['payee'] == '03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad'
assert b11['fallbacks'][0]['type'] == 'P2WSH'
assert b11['fallbacks'][0]['addr'] == 'bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3'