forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_gossip.py
2225 lines (1807 loc) · 101 KB
/
test_gossip.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 collections import Counter
from ephemeral_port_reserve import reserve
from fixtures import * # noqa: F401,F403
from fixtures import TEST_NETWORK
from pyln.client import RpcError, Millisatoshi
from utils import (
DEVELOPER, wait_for, TIMEOUT, only_one, sync_blockheight,
expected_node_features,
mine_funding_to_announce, default_ln_port
)
import json
import logging
import math
import os
import pytest
import struct
import subprocess
import time
import unittest
import socket
with open('config.vars') as configfile:
config = dict([(line.rstrip().split('=', 1)) for line in configfile])
@pytest.mark.developer("needs --dev-fast-gossip-prune")
def test_gossip_pruning(node_factory, bitcoind):
""" Create channel and see it being updated in time before pruning
"""
l1, l2, l3 = node_factory.get_nodes(3, opts={'dev-fast-gossip-prune': None,
'allow_bad_gossip': True})
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
l2.rpc.connect(l3.info['id'], 'localhost', l3.port)
scid1, _ = l1.fundchannel(l2, 10**6)
scid2, _ = l2.fundchannel(l3, 10**6)
mine_funding_to_announce(bitcoind, [l1, l2, l3])
# Channels should be activated locally
wait_for(lambda: [c['active'] for c in l1.rpc.listchannels()['channels']] == [True] * 4)
wait_for(lambda: [c['active'] for c in l2.rpc.listchannels()['channels']] == [True] * 4)
wait_for(lambda: [c['active'] for c in l3.rpc.listchannels()['channels']] == [True] * 4)
# Also check that it sends a redundant node_announcement.
ts1 = only_one(l2.rpc.listnodes(l1.info['id'])['nodes'])['last_timestamp']
wait_for(lambda: only_one(l2.rpc.listnodes(l1.info['id'])['nodes'])['last_timestamp'] != ts1)
assert only_one(l2.rpc.listnodes(l1.info['id'])['nodes'])['last_timestamp'] >= ts1 + 24
# All of them should send a keepalive message (after 30 seconds)
l1.daemon.wait_for_logs([
'Sending keepalive channel_update for {}'.format(scid1),
], timeout=50)
l2.daemon.wait_for_logs([
'Sending keepalive channel_update for {}'.format(scid1),
'Sending keepalive channel_update for {}'.format(scid2),
])
l3.daemon.wait_for_logs([
'Sending keepalive channel_update for {}'.format(scid2),
])
# Now kill l2, so that l1 and l3 will prune from their view after 60 seconds
l2.stop()
# We check every 60/4 seconds, and takes 60 seconds since last update.
l1.daemon.wait_for_log("Pruning channel {} from network view".format(scid2),
timeout=80)
l3.daemon.wait_for_log("Pruning channel {} from network view".format(scid1))
assert scid2 not in [c['short_channel_id'] for c in l1.rpc.listchannels()['channels']]
assert scid1 not in [c['short_channel_id'] for c in l3.rpc.listchannels()['channels']]
assert l3.info['id'] not in [n['nodeid'] for n in l1.rpc.listnodes()['nodes']]
assert l1.info['id'] not in [n['nodeid'] for n in l3.rpc.listnodes()['nodes']]
@pytest.mark.developer("needs --dev-fast-gossip, --dev-no-reconnect")
def test_gossip_disable_channels(node_factory, bitcoind):
"""Simple test to check that channels get disabled correctly on disconnect and
reenabled upon reconnecting
"""
opts = {'dev-no-reconnect': None, 'may_reconnect': True}
l1, l2 = node_factory.get_nodes(2, opts=opts)
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
scid, _ = l1.fundchannel(l2, 10**6)
bitcoind.generate_block(5)
def count_active(node):
chans = node.rpc.listchannels()['channels']
active = [c for c in chans if c['active']]
return len(active)
l1.wait_channel_active(scid)
l2.wait_channel_active(scid)
assert(count_active(l1) == 2)
assert(count_active(l2) == 2)
l2.restart()
wait_for(lambda: count_active(l1) == 0)
assert(count_active(l2) == 0)
# Now reconnect, they should re-enable the channels
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
wait_for(lambda: count_active(l1) == 2)
wait_for(lambda: count_active(l2) == 2)
@pytest.mark.developer("needs --dev-allow-localhost")
def test_announce_address(node_factory, bitcoind):
"""Make sure our announcements are well formed."""
# We do not allow announcement of duplicates.
opts = {'announce-addr-dns': True,
'announce-addr':
['4acth47i6kxnvkewtm6q7ib2s3ufpo5sqbsnzjpbi7utijcltosqemad.onion',
'1.2.3.4:1234',
'example.com:1236',
'::'],
'log-level': 'io',
'dev-allow-localhost': None}
l1, l2 = node_factory.get_nodes(2, opts=[opts, {}])
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
scid, _ = l1.fundchannel(l2, 10**6)
bitcoind.generate_block(5)
l1.wait_channel_active(scid)
l2.wait_channel_active(scid)
# We should see it send node announce with all addresses (257 = 0x0101)
# Note: local ephemeral port is masked out.
# Note: Since we `disable-dns` it should not announce a resolved IPv4
# or IPv6 address for example.com
#
# Also expect the address descriptor types to be sorted!
# BOLT #7:
# - MUST place address descriptors in ascending order.
l1.daemon.wait_for_log(r"\[OUT\] 0101.*0056"
"010102030404d2" # IPv4 01 1.2.3.4:1234
"017f000001...." # IPv4 01 127.0.0.1:wxyz
"0200000000000000000000000000000000...." # IPv6 02 :::<any_port>
"04e00533f3e8f2aedaa8969b3d0fa03a96e857bbb28064dca5e147e934244b9ba5023003...." # TORv3 04
"050b6578616d706c652e636f6d04d4") # DNS 05 len example.com:1236
# Check other node can parse these (make sure it has digested msg)
wait_for(lambda: 'addresses' in l2.rpc.listnodes(l1.info['id'])['nodes'][0])
addresses = l2.rpc.listnodes(l1.info['id'])['nodes'][0]['addresses']
addresses_dns = [address for address in addresses if address['type'] == 'dns']
assert len(addresses) == 5
assert len(addresses_dns) == 1
assert addresses_dns[0]['address'] == 'example.com'
assert addresses_dns[0]['port'] == 1236
def test_announce_dns_suppressed(node_factory, bitcoind):
"""By default announce DNS names as IPs"""
opts = {'announce-addr': 'example.com:1236',
'start': False}
l1, l2 = node_factory.get_nodes(2, opts=[opts, {}])
# Remove unwanted disable-dns option!
del l1.daemon.opts['disable-dns']
l1.start()
# Need a channel so l1 will announce itself.
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
scid, _ = l1.fundchannel(l2, 10**6)
bitcoind.generate_block(5)
# Wait for l2 to see l1, with addresses.
wait_for(lambda: l2.rpc.listnodes(l1.info['id'])['nodes'] != [])
wait_for(lambda: 'addresses' in only_one(l2.rpc.listnodes(l1.info['id'])['nodes']))
addresses = only_one(l2.rpc.listnodes(l1.info['id'])['nodes'])['addresses']
assert len(addresses) == 1
assert addresses[0]['type'] == 'ipv4'
assert addresses[0]['address'] != 'example.com'
assert addresses[0]['port'] == 1236
@pytest.mark.developer("gossip without DEVELOPER=1 is slow")
def test_announce_and_connect_via_dns(node_factory, bitcoind):
""" Test that DNS annoucements propagate and can be used when connecting.
- First node announces only a FQDN like 'localhost.localdomain'.
- Second node gets a channel with first node.
- Third node just connects to second node.
- Fourth node with DNS disabled also connects to second node.
- Wait for gossip so third and fourth node sees first node.
- Third node must be able to 'resolve' 'localhost.localdomain'
and connect to first node.
- Fourth node must not be able to connect because he has disabled DNS.
Notes:
- --disable-dns is needed so the first node does not announce 127.0.0.1 itself.
- 'dev-allow-localhost' must not be set, so it does not resolve localhost anyway.
"""
opts1 = {'disable-dns': None,
'announce-addr-dns': True,
'announce-addr': ['localhost.localdomain:12345'], # announce dns
'bind-addr': ['127.0.0.1:12345', '[::1]:12345']} # and bind local IPs
opts3 = {'may_reconnect': True}
opts4 = {'disable-dns': None}
l1, l2, l3, l4 = node_factory.get_nodes(4, opts=[opts1, {}, opts3, opts4])
# In order to enable DNS on a pyln testnode we need to delete the
# 'disable-dns' opt (which is added by pyln test utils) and restart it.
del l3.daemon.opts['disable-dns']
l3.restart()
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
l3.rpc.connect(l2.info['id'], 'localhost', l2.port)
l4.rpc.connect(l2.info['id'], 'localhost', l2.port)
scid, _ = l1.fundchannel(l2, 10**6)
mine_funding_to_announce(bitcoind, [l1, l2, l3])
# wait until l3 and l4 see l1 via gossip with announced addresses
wait_for(lambda: len(l3.rpc.listnodes(l1.info['id'])['nodes']) == 1)
wait_for(lambda: len(l4.rpc.listnodes(l1.info['id'])['nodes']) == 1)
wait_for(lambda: 'addresses' in l3.rpc.listnodes(l1.info['id'])['nodes'][0])
wait_for(lambda: 'addresses' in l4.rpc.listnodes(l1.info['id'])['nodes'][0])
addresses = l3.rpc.listnodes(l1.info['id'])['nodes'][0]['addresses']
assert(len(addresses) == 1) # no other addresses must be announced for this
assert(addresses[0]['type'] == 'dns')
assert(addresses[0]['address'] == 'localhost.localdomain')
assert(addresses[0]['port'] == 12345)
# now l3 must be able to use DNS to resolve and connect to l1
result = l3.rpc.connect(l1.info['id'])
assert result['id'] == l1.info['id']
assert result['direction'] == 'out'
assert result['address']['port'] == 12345
if result['address']['type'] == 'ipv4':
assert result['address']['address'] == '127.0.0.1'
elif result['address']['type'] == 'ipv6':
assert result['address']['address'] == '::1'
else:
assert False
# l4 however must not be able to connect because he used '--disable-dns'
# This raises RpcError code 401, currently with an empty error message.
with pytest.raises(RpcError, match=r"401.*dns disabled"):
l4.rpc.connect(l1.info['id'])
def test_only_announce_one_dns(node_factory, bitcoind):
# and test that we can't announce more than one DNS address
l1 = node_factory.get_node(expect_fail=True, start=False,
options={'announce-addr-dns': True,
'announce-addr': ['localhost.localdomain:12345', 'example.com:12345']})
l1.daemon.start(wait_for_initialized=False, stderr_redir=True)
wait_for(lambda: l1.daemon.is_in_stderr("Only one DNS can be announced"))
def test_announce_dns_without_port(node_factory, bitcoind):
""" Checks that the port of a DNS announcement is set to the corresponding
network port. In this case regtest 19846
"""
opts = {'announce-addr-dns': True, 'announce-addr': ['example.com']}
l1 = node_factory.get_node(options=opts)
# 'address': [{'type': 'dns', 'address': 'example.com', 'port': 0}]
info = l1.rpc.getinfo()
assert info['address'][0]['type'] == 'dns'
assert info['address'][0]['address'] == 'example.com'
if TEST_NETWORK == 'regtest':
default_port = 19846
else:
assert TEST_NETWORK == 'liquid-regtest'
default_port = 20735
assert info['address'][0]['port'] == default_port
@pytest.mark.developer("needs DEVELOPER=1")
def test_gossip_timestamp_filter(node_factory, bitcoind, chainparams):
# Updates get backdated 5 seconds with --dev-fast-gossip.
backdate = 5
l1, l2, l3, l4 = node_factory.line_graph(4, fundchannel=False, opts={'log-level': 'io'})
genesis_blockhash = chainparams['chain_hash']
before_anything = int(time.time())
# Make a public channel.
chan12, _ = l1.fundchannel(l2, 10**5)
mine_funding_to_announce(bitcoind, [l1, l2, l3, l4])
l3.wait_for_channel_updates([chan12])
after_12 = int(time.time())
# Make another one, different timestamp.
time.sleep(10)
before_23 = int(time.time())
chan23, _ = l2.fundchannel(l3, 10**5)
bitcoind.generate_block(5)
l1.wait_for_channel_updates([chan23])
after_23 = int(time.time()) + 1
# Make sure l4 has received all the gossip.
wait_for(lambda: ['alias' in node for node in l4.rpc.listnodes()['nodes']] == [True, True, True])
msgs = l4.query_gossip('gossip_timestamp_filter',
genesis_blockhash,
'0', '0xFFFFFFFF',
filters=['0109', '0107', '0012'])
# 0x0100 = channel_announcement
# 0x0102 = channel_update
# 0x0101 = node_announcement
# The order of node_announcements relative to others is undefined.
types = Counter([m[0:4] for m in msgs])
assert types == Counter(['0100'] * 2 + ['0102'] * 4 + ['0101'] * 3)
# Now timestamp which doesn't overlap (gives nothing).
msgs = l4.query_gossip('gossip_timestamp_filter',
genesis_blockhash,
'0', before_anything - backdate,
filters=['0109', '0107', '0012'])
assert msgs == []
# Now choose range which will only give first update.
msgs = l4.query_gossip('gossip_timestamp_filter',
genesis_blockhash,
before_anything - backdate,
after_12 - before_anything + 1,
filters=['0109', '0107', '0012'])
# 0x0100 = channel_announcement
# 0x0102 = channel_update
# (Node announcement may have any timestamp)
types = Counter([m[0:4] for m in msgs])
assert types['0100'] == 1
assert types['0102'] == 2
# Now choose range which will only give second update.
msgs = l4.query_gossip('gossip_timestamp_filter',
genesis_blockhash,
before_23 - backdate,
after_23 - before_23 + 1,
filters=['0109', '0107', '0012'])
# 0x0100 = channel_announcement
# 0x0102 = channel_update
# (Node announcement may have any timestamp)
types = Counter([m[0:4] for m in msgs])
assert types['0100'] == 1
assert types['0102'] == 2
@pytest.mark.developer("needs --dev-allow-localhost")
def test_connect_by_gossip(node_factory, bitcoind):
"""Test connecting to an unknown peer using node gossip
"""
# l1 announces a bogus addresses.
l1, l2, l3 = node_factory.get_nodes(3,
opts=[{'announce-addr':
['127.0.0.1:2',
'[::]:2',
'vww6ybal4bd7szmgncyruucpgfkqahzddi37ktceo3ah7ngmcopnpyyd.onion'],
'dev-allow-localhost': None},
{},
{'dev-allow-localhost': None,
'log-level': 'io'}])
l2.rpc.connect(l3.info['id'], 'localhost', l3.port)
# Nodes are gossiped only if they have channels
chanid, _ = l2.fundchannel(l3, 10**6)
mine_funding_to_announce(bitcoind, [l1, l2, l3])
# Let channel reach announcement depth
l2.wait_channel_active(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.
ret = l1.rpc.connect(l3.info['id'])
assert ret['address'] == {'type': 'ipv4', 'address': '127.0.0.1', 'port': l3.port}
# Now give it *wrong* port (after we make sure l2 isn't listening), it should fall back.
l1.rpc.disconnect(l3.info['id'])
l2.stop()
ret = l1.rpc.connect(l3.info['id'], 'localhost', l2.port)
assert ret['address'] == {'type': 'ipv4', 'address': '127.0.0.1', 'port': l3.port}
@pytest.mark.developer("DEVELOPER=1 needed to speed up gossip propagation, would be too long otherwise")
def test_gossip_jsonrpc(node_factory):
l1, l2 = node_factory.line_graph(2, fundchannel=True, wait_for_announce=False)
# Shouldn't send announce signatures until 6 deep.
assert not l1.daemon.is_in_log('peer_out WIRE_ANNOUNCEMENT_SIGNATURES')
# Channels should be activated locally
wait_for(lambda: len(l1.rpc.listchannels()['channels']) == 2)
wait_for(lambda: len(l2.rpc.listchannels()['channels']) == 2)
# Make sure we can route through the channel, will raise on failure
l1.rpc.getroute(l2.info['id'], 100, 1)
# Outgoing should be active, but not public.
channels1 = l1.rpc.listchannels()['channels']
channels2 = l2.rpc.listchannels()['channels']
assert [c['active'] for c in channels1] == [True, True]
assert [c['active'] for c in channels2] == [True, True]
# The incoming direction will be considered public, hence check for out
# outgoing only
assert len([c for c in channels1 if not c['public']]) == 2
assert len([c for c in channels2 if not c['public']]) == 2
# Test listchannels-by-source
channels1 = l1.rpc.listchannels(source=l1.info['id'])['channels']
channels2 = l2.rpc.listchannels(source=l1.info['id'])['channels']
assert only_one(channels1)['source'] == l1.info['id']
assert only_one(channels1)['destination'] == l2.info['id']
assert channels1 == channels2
# Test listchannels-by-destination
channels1 = l1.rpc.listchannels(destination=l1.info['id'])['channels']
channels2 = l2.rpc.listchannels(destination=l1.info['id'])['channels']
assert only_one(channels1)['destination'] == l1.info['id']
assert only_one(channels1)['source'] == l2.info['id']
assert channels1 == channels2
# Test only one of short_channel_id, source or destination can be supplied
with pytest.raises(RpcError, match=r"Can only specify one of.*"):
l1.rpc.listchannels(source=l1.info['id'], destination=l2.info['id'])
with pytest.raises(RpcError, match=r"Can only specify one of.*"):
l1.rpc.listchannels(short_channel_id="1x1x1", source=l2.info['id'])
# Now proceed to funding-depth and do a full gossip round
l1.bitcoin.generate_block(5)
# Could happen in either order.
l1.daemon.wait_for_logs(['peer_out WIRE_ANNOUNCEMENT_SIGNATURES',
'peer_in WIRE_ANNOUNCEMENT_SIGNATURES'])
# Just wait for the update to kick off and then check the effect
needle = "Received node_announcement for node"
l1.daemon.wait_for_log(needle)
l2.daemon.wait_for_log(needle)
# Need to increase timeout, intervals cannot be shortened with DEVELOPER=0
wait_for(lambda: len(l1.getactivechannels()) == 2, timeout=60)
wait_for(lambda: len(l2.getactivechannels()) == 2, timeout=60)
nodes = l1.rpc.listnodes()['nodes']
assert set([n['nodeid'] for n in nodes]) == set([l1.info['id'], l2.info['id']])
# Test listnodes with an arg, while we're here.
n1 = l1.rpc.listnodes(l1.info['id'])['nodes'][0]
n2 = l1.rpc.listnodes(l2.info['id'])['nodes'][0]
assert n1['nodeid'] == l1.info['id']
assert n2['nodeid'] == l2.info['id']
# Might not have seen other node-announce yet.
assert n1['alias'].startswith('JUNIORBEAM')
assert n1['color'] == '0266e4'
if 'alias' not in n2:
assert 'color' not in n2
assert 'addresses' not in n2
else:
assert n2['alias'].startswith('SILENTARTIST')
assert n2['color'] == '022d22'
assert [c['active'] for c in l1.rpc.listchannels()['channels']] == [True, True]
assert [c['public'] for c in l1.rpc.listchannels()['channels']] == [True, True]
assert [c['active'] for c in l2.rpc.listchannels()['channels']] == [True, True]
assert [c['public'] for c in l2.rpc.listchannels()['channels']] == [True, True]
@pytest.mark.developer("Too slow without --dev-fast-gossip")
def test_gossip_badsig(node_factory, bitcoind):
"""Make sure node announcement signatures are ok.
This is a smoke test to see if signatures fail. This used to be the case
occasionally before PR #276 was merged: we'd be waiting for the HSM to reply
with a signature and would then regenerate the message, which might roll the
timestamp, invalidating the signature.
"""
l1, l2, l3 = node_factory.get_nodes(3)
# l2 connects to both, so l1 can't reconnect and thus l2 drops to chain
l2.rpc.connect(l1.info['id'], 'localhost', l1.port)
l2.rpc.connect(l3.info['id'], 'localhost', l3.port)
l2.fundchannel(l1, 10**6)
l2.fundchannel(l3, 10**6)
# Wait for route propagation.
mine_funding_to_announce(bitcoind, [l1, l2, l3])
l1.daemon.wait_for_log('Received node_announcement for node {}'
.format(l3.info['id']))
assert not l1.daemon.is_in_log('signature verification failed')
assert not l2.daemon.is_in_log('signature verification failed')
assert not l3.daemon.is_in_log('signature verification failed')
def test_gossip_weirdalias(node_factory, bitcoind):
weird_name = '\t \n \" \n \r \n \\'
normal_name = 'Normal name'
opts = [
{'alias': weird_name},
{'alias': normal_name}
]
l1, l2 = node_factory.get_nodes(2, opts=opts)
weird_name_json = json.encoder.JSONEncoder().encode(weird_name)[1:-1]
aliasline = l1.daemon.is_in_log('Server started with public key .* alias')
assert weird_name_json in str(aliasline)
assert l2.daemon.is_in_log('Server started with public key .* alias {}'
.format(normal_name))
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
l2.daemon.wait_for_log('Handed peer, entering loop')
l2.fundchannel(l1, 10**6)
bitcoind.generate_block(6)
# They should gossip together.
l1.daemon.wait_for_log('Received node_announcement for node {}'
.format(l2.info['id']))
l2.daemon.wait_for_log('Received node_announcement for node {}'
.format(l1.info['id']))
node = l1.rpc.listnodes(l1.info['id'])['nodes'][0]
assert node['alias'] == weird_name
node = l2.rpc.listnodes(l1.info['id'])['nodes'][0]
assert node['alias'] == weird_name
@pytest.mark.developer("needs DEVELOPER=1 for --dev-no-reconnect")
def test_gossip_persistence(node_factory, bitcoind):
"""Gossip for a while, restart and it should remember.
Also tests for funding outpoint spends, and they should be persisted
too.
"""
opts = {'dev-no-reconnect': None, 'may_reconnect': True}
l1, l2, l3, l4 = node_factory.get_nodes(4, opts=opts)
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
l2.rpc.connect(l3.info['id'], 'localhost', l3.port)
l3.rpc.connect(l4.info['id'], 'localhost', l4.port)
scid12, _ = l1.fundchannel(l2, 10**6)
scid23, _ = l2.fundchannel(l3, 10**6)
# Make channels public, except for l3 -> l4, which is kept local-only
mine_funding_to_announce(bitcoind, [l1, l2, l3, l4])
scid34, _ = l3.fundchannel(l4, 10**6, announce_channel=False)
bitcoind.generate_block(1)
def active(node):
chans = node.rpc.listchannels()['channels']
return sorted([c['short_channel_id'] for c in chans if c['active']])
def non_public(node):
chans = node.rpc.listchannels()['channels']
return sorted([c['short_channel_id'] for c in chans if not c['public']])
# Channels should be activated
wait_for(lambda: active(l1) == [scid12, scid12, scid23, scid23])
wait_for(lambda: active(l2) == [scid12, scid12, scid23, scid23])
# This one sees its private channel
wait_for(lambda: active(l3) == [scid12, scid12, scid23, scid23, scid34, scid34])
# l1 restarts and doesn't connect, but loads from persisted store, all
# local channels should be disabled, leaving only the two l2 <-> l3
# directions
l1.restart()
wait_for(lambda: active(l1) == [scid23, scid23])
# Now reconnect, they should re-enable the two l1 <-> l2 directions
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
wait_for(lambda: active(l1) == [scid12, scid12, scid23, scid23])
# Now spend the funding tx, generate a block and see others deleting the
# channel from their network view
l1.rpc.dev_fail(l2.info['id'])
# We need to wait for the unilateral close to hit the mempool,
# and 12 blocks for nodes to actually forget it.
bitcoind.generate_block(13, wait_for_mempool=1)
wait_for(lambda: active(l1) == [scid23, scid23])
wait_for(lambda: active(l2) == [scid23, scid23])
wait_for(lambda: active(l3) == [scid23, scid23, scid34, scid34])
# The channel l3 -> l4 should be known only to them
assert non_public(l1) == []
assert non_public(l2) == []
wait_for(lambda: non_public(l3) == [scid34, scid34])
wait_for(lambda: non_public(l4) == [scid34, scid34])
# Finally, it should also remember the deletion after a restart
l3.restart()
l4.restart()
l2.rpc.connect(l3.info['id'], 'localhost', l3.port)
l3.rpc.connect(l4.info['id'], 'localhost', l4.port)
wait_for(lambda: active(l3) == [scid23, scid23, scid34, scid34])
# Both l3 and l4 should remember their local-only channel
wait_for(lambda: non_public(l3) == [scid34, scid34])
wait_for(lambda: non_public(l4) == [scid34, scid34])
@pytest.mark.developer("needs DEVELOPER=1")
def test_routing_gossip_reconnect(node_factory):
# Connect two peers, reconnect and then see if we resume the
# gossip.
disconnects = ['-WIRE_CHANNEL_ANNOUNCEMENT']
l1, l2, l3 = node_factory.get_nodes(3,
opts=[{'disconnect': disconnects,
'may_reconnect': True},
{'may_reconnect': True},
{}])
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
l1.openchannel(l2, 25000)
# Now open new channels and everybody should sync
l2.rpc.connect(l3.info['id'], 'localhost', l3.port)
l2.openchannel(l3, 25000)
# Settle the gossip
for n in [l1, l2, l3]:
wait_for(lambda: len(n.rpc.listchannels()['channels']) == 4)
@pytest.mark.developer("needs fast gossip, dev-no-reconnect")
def test_gossip_no_empty_announcements(node_factory, bitcoind, chainparams):
# Need full IO logging so we can see gossip
# l2 sends CHANNEL_ANNOUNCEMENT to l1, but not CHANNEL_UDPATE.
l1, l2, l3, l4 = node_factory.line_graph(4, opts=[{'log-level': 'io',
'dev-no-reconnect': None},
{'log-level': 'io',
'disconnect': ['+WIRE_CHANNEL_ANNOUNCEMENT'],
'may_reconnect': True},
{'may_reconnect': True},
{'may_reconnect': True}],
fundchannel=False)
l3.fundchannel(l4, 10**5)
mine_funding_to_announce(bitcoind, [l1, l2, l3, l4])
# l2 sends CHANNEL_ANNOUNCEMENT to l1, then disconnects/
l2.daemon.wait_for_log('dev_disconnect')
l1.daemon.wait_for_log(r'\[IN\] 0100')
wait_for(lambda: l1.rpc.listchannels()['channels'] == [])
# l1 won't relay it (make sure it has time to digest though)
time.sleep(2)
encoded = subprocess.run(['devtools/mkencoded', '--scids', '00'],
check=True,
timeout=TIMEOUT,
stdout=subprocess.PIPE).stdout.strip().decode()
assert l1.query_gossip('query_channel_range',
chainparams['chain_hash'],
0, 1000000,
filters=['0109', '0107', '0012']) == ['0108'
# blockhash
+ chainparams['chain_hash']
# first_blocknum, number_of_blocks, complete
+ format(0, '08x') + format(1000000, '08x') + '01'
# encoded_short_ids
+ format(len(encoded) // 2, '04x')
+ encoded]
# If we reconnect, gossip will now flow.
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
wait_for(lambda: len(l1.rpc.listchannels()['channels']) == 2)
@pytest.mark.developer("Too slow without --dev-fast-gossip")
def test_routing_gossip(node_factory, bitcoind):
nodes = node_factory.get_nodes(5)
for i in range(len(nodes) - 1):
src, dst = nodes[i], nodes[i + 1]
src.rpc.connect(dst.info['id'], 'localhost', dst.port)
src.openchannel(dst, 25000, confirm=False, wait_for_announce=False)
# openchannel calls fundwallet which mines a block; so first channel
# is 4 deep, last is unconfirmed.
# Allow announce messages.
mine_funding_to_announce(bitcoind, nodes, num_blocks=6, wait_for_mempool=1)
# Deep check that all channels are in there
comb = []
for i in range(len(nodes) - 1):
comb.append((nodes[i].info['id'], nodes[i + 1].info['id']))
comb.append((nodes[i + 1].info['id'], nodes[i].info['id']))
def check_gossip(n):
seen = []
channels = n.rpc.listchannels()['channels']
for c in channels:
seen.append((c['source'], c['destination']))
missing = set(comb) - set(seen)
logging.debug("Node {id} is missing channels {chans}".format(
id=n.info['id'],
chans=missing)
)
return len(missing) == 0
for n in nodes:
wait_for(lambda: check_gossip(n))
@pytest.mark.developer("needs dev-set-max-scids-encode-size")
def test_gossip_query_channel_range(node_factory, bitcoind, chainparams):
l1, l2, l3, l4 = node_factory.line_graph(4, fundchannel=False)
genesis_blockhash = chainparams['chain_hash']
# Make public channels on consecutive blocks
l1.fundwallet(10**6)
l2.fundwallet(10**6)
num_tx = len(bitcoind.rpc.getrawmempool())
# We want these one block apart.
l1.rpc.fundchannel(l2.info['id'], 10**5)['tx']
bitcoind.generate_block(wait_for_mempool=num_tx + 1)
sync_blockheight(bitcoind, [l1, l2, l3, l4])
l2.rpc.fundchannel(l3.info['id'], 10**5)['tx']
# Get them both to gossip depth.
mine_funding_to_announce(bitcoind, [l1, l2, l3, l4],
num_blocks=6,
wait_for_mempool=1)
# Make sure l4 has received all the gossip.
l4.daemon.wait_for_logs(['Received node_announcement for node ' + n.info['id'] for n in (l1, l2, l3)])
scid12 = only_one(l1.rpc.listpeers(l2.info['id'])['peers'])['channels'][0]['short_channel_id']
scid23 = only_one(l3.rpc.listpeers(l2.info['id'])['peers'])['channels'][0]['short_channel_id']
block12 = int(scid12.split('x')[0])
block23 = int(scid23.split('x')[0])
assert block23 == block12 + 1
# Asks l4 for all channels, gets both.
msgs = l4.query_gossip('query_channel_range',
chainparams['chain_hash'],
0, 1000000,
filters=['0109', '0107', '0012'])
encoded = subprocess.run(['devtools/mkencoded', '--scids', '00', scid12, scid23],
check=True,
timeout=TIMEOUT,
stdout=subprocess.PIPE).stdout.strip().decode()
# reply_channel_range == 264
assert msgs == ['0108'
# blockhash
+ genesis_blockhash
# first_blocknum, number_of_blocks, complete
+ format(0, '08x') + format(1000000, '08x') + '01'
# encoded_short_ids
+ format(len(encoded) // 2, '04x')
+ encoded]
# Does not include scid12
msgs = l4.query_gossip('query_channel_range',
genesis_blockhash,
0, block12,
filters=['0109', '0107', '0012'])
# reply_channel_range == 264
assert msgs == ['0108'
# blockhash
+ genesis_blockhash
# first_blocknum, number_of_blocks, complete
+ format(0, '08x') + format(block12, '08x') + '01'
# encoded_short_ids
'000100']
# Does include scid12
msgs = l4.query_gossip('query_channel_range',
genesis_blockhash,
0, block12 + 1,
filters=['0109', '0107', '0012'])
encoded = subprocess.run(['devtools/mkencoded', '--scids', '00', scid12],
check=True,
timeout=TIMEOUT,
stdout=subprocess.PIPE).stdout.strip().decode()
# reply_channel_range == 264
assert msgs == ['0108'
# blockhash
+ genesis_blockhash
# first_blocknum, number_of_blocks, complete
+ format(0, '08x') + format(block12 + 1, '08x') + '01'
# encoded_short_ids
+ format(len(encoded) // 2, '04x')
+ encoded]
# Doesn't include scid23
msgs = l4.query_gossip('query_channel_range',
genesis_blockhash,
0, block23,
filters=['0109', '0107', '0012'])
encoded = subprocess.run(['devtools/mkencoded', '--scids', '00', scid12],
check=True,
timeout=TIMEOUT,
stdout=subprocess.PIPE).stdout.strip().decode()
# reply_channel_range == 264
assert msgs == ['0108'
# blockhash
+ genesis_blockhash
# first_blocknum, number_of_blocks, complete
+ format(0, '08x') + format(block23, '08x') + '01'
# encoded_short_ids
+ format(len(encoded) // 2, '04x')
+ encoded]
# Does include scid23
msgs = l4.query_gossip('query_channel_range',
genesis_blockhash,
block12, block23 - block12 + 1,
filters=['0109', '0107', '0012'])
encoded = subprocess.run(['devtools/mkencoded', '--scids', '00', scid12, scid23],
check=True,
timeout=TIMEOUT,
stdout=subprocess.PIPE).stdout.strip().decode()
# reply_channel_range == 264
assert msgs == ['0108'
# blockhash
+ genesis_blockhash
# first_blocknum, number_of_blocks, complete
+ format(block12, '08x') + format(block23 - block12 + 1, '08x') + '01'
# encoded_short_ids
+ format(len(encoded) // 2, '04x')
+ encoded]
# Only includes scid23
msgs = l4.query_gossip('query_channel_range',
genesis_blockhash,
block23, 1,
filters=['0109', '0107', '0012'])
encoded = subprocess.run(['devtools/mkencoded', '--scids', '00', scid23],
check=True,
timeout=TIMEOUT,
stdout=subprocess.PIPE).stdout.strip().decode()
# reply_channel_range == 264
assert msgs == ['0108'
# blockhash
+ genesis_blockhash
# first_blocknum, number_of_blocks, complete
+ format(block23, '08x') + format(1, '08x') + '01'
# encoded_short_ids
+ format(len(encoded) // 2, '04x')
+ encoded]
# Past both
msgs = l4.query_gossip('query_channel_range',
genesis_blockhash,
block23 + 1, 1000000,
filters=['0109', '0107', '0012'])
# reply_channel_range == 264
assert msgs == ['0108'
# blockhash
+ genesis_blockhash
# first_blocknum, number_of_blocks, complete
+ format(block23 + 1, '08x') + format(1000000, '08x') + '01'
# encoded_short_ids
+ '000100']
# Make l4 split reply into two (technically async)
l4.rpc.dev_set_max_scids_encode_size(max=9)
l4.daemon.wait_for_log('Set max_scids_encode_bytes to 9')
msgs = l4.query_gossip('query_channel_range',
genesis_blockhash,
0, 1000000,
filters=['0109', '0107', '0012'])
# It should definitely have split
l4.daemon.wait_for_log('reply_channel_range: splitting 0-1 of 2')
start = 0
scids = '00'
for m in msgs:
assert m.startswith('0108' + genesis_blockhash)
this_start = int(m[4 + 64:4 + 64 + 8], base=16)
num = int(m[4 + 64 + 8:4 + 64 + 8 + 8], base=16)
# Pull off end of packet, assume it's uncompressed, and no TLVs!
scids += m[4 + 64 + 8 + 8 + 2 + 4 + 2:]
assert this_start == start
start += num
encoded = subprocess.run(['devtools/mkencoded', '--scids', '00', scid12, scid23],
check=True,
timeout=TIMEOUT,
stdout=subprocess.PIPE).stdout.strip().decode()
assert scids == encoded
# Test overflow case doesn't split forever; should still only get 2 for this
msgs = l4.query_gossip('query_channel_range',
genesis_blockhash,
1, 429496000,
filters=['0109', '0107', '0012'])
assert len(msgs) == 2
# Long test involving 4 lightningd instances.
@pytest.mark.developer("needs DEVELOPER=1")
def test_report_routing_failure(node_factory, bitcoind):
"""Test routing failure and retrying of routing.
"""
# The setup is as follows:
# l3-->l4
# ^ / |
# | / |
# | L v
# l2<--l1
#
# l1 wants to pay to l4.
# The shortest route is l1-l4, but l1 cannot
# afford to pay to l1 because l4 has all the
# funds.
# This is a local failure.
# The next shortest route is l1-l2-l4, but
# l2 cannot afford to pay l4 for same reason.
# This is a remote failure.
# Finally the only possible path is
# l1-l2-l3-l4.
# Setup
# Construct lightningd
l1, l2, l3, l4 = node_factory.get_nodes(4)
# Wire them up
# The ordering below matters!
# Particularly, l1 is payer and we will
# wait for l1 to receive gossip for the
# channel being made.
channels = []
for src, dst in [(l1, l2), (l2, l3), (l3, l4), (l4, l1), (l4, l2)]:
src.rpc.connect(dst.info['id'], 'localhost', dst.port)
print("src={}, dst={}".format(src.daemon.lightning_dir,
dst.daemon.lightning_dir))
c, _ = src.fundchannel(dst, 10**6)
channels.append(c)
mine_funding_to_announce(bitcoind, [l1, l2, l3, l4])
for c in channels:
l1.wait_channel_active(c)
# Test
inv = l4.rpc.invoice(1234567, 'inv', 'for testing')['bolt11']
l1.rpc.pay(inv)
@pytest.mark.developer("needs fast gossip")
def test_query_short_channel_id(node_factory, bitcoind, chainparams):
l1, l2, l3, l4 = node_factory.get_nodes(4)
l1.rpc.connect(l2.info['id'], 'localhost', l2.port)
l2.rpc.connect(l3.info['id'], 'localhost', l3.port)
chain_hash = chainparams['chain_hash']
# Empty result tests.
encoded = subprocess.run(['devtools/mkencoded', '--scids', '00', '1x1x1', '2x2x2'],
check=True,
timeout=TIMEOUT,
stdout=subprocess.PIPE).stdout.strip().decode()
msgs = l1.query_gossip('query_short_channel_ids',
chain_hash,
encoded,
filters=['0109', '0107', '0012'])
# Should just get the WIRE_REPLY_SHORT_CHANNEL_IDS_END = 262
# (with chainhash and completeflag = 1)
assert len(msgs) == 1
assert msgs[0] == '0106{}01'.format(chain_hash)
# Make channels public.
scid12, _ = l1.fundchannel(l2, 10**5)
scid23, _ = l2.fundchannel(l3, 10**5)
mine_funding_to_announce(bitcoind, [l1, l2, l3])
# Attach node which won't spam us (since it's not their channel).
l4.rpc.connect(l1.info['id'], 'localhost', l1.port)
l4.rpc.connect(l2.info['id'], 'localhost', l2.port)
l4.rpc.connect(l3.info['id'], 'localhost', l3.port)
# Make sure it sees all channels, then node announcements.
wait_for(lambda: len(l4.rpc.listchannels()['channels']) == 4)
wait_for(lambda: all('alias' in n for n in l4.rpc.listnodes()['nodes']))
# This query should get channel announcements, channel updates, and node announcements.
encoded = subprocess.run(['devtools/mkencoded', '--scids', '00', scid23],
check=True,
timeout=TIMEOUT,
stdout=subprocess.PIPE).stdout.strip().decode()
msgs = l4.query_gossip('query_short_channel_ids',
chain_hash,