-
Notifications
You must be signed in to change notification settings - Fork 989
Expand file tree
/
Copy pathtest_askrene.py
More file actions
2717 lines (2400 loc) · 113 KB
/
test_askrene.py
File metadata and controls
2717 lines (2400 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from fixtures import * # noqa: F401,F403
from hashlib import sha256
from pyln.client import RpcError
from pyln.testing.utils import SLOW_MACHINE
from utils import (
only_one, first_scid, first_scidd, GenChannel, generate_gossip_store,
sync_blockheight, wait_for, TEST_NETWORK, TIMEOUT, mine_funding_to_announce
)
import os
import pytest
import random
import subprocess
import time
import tempfile
import unittest
from concurrent import futures as concurrent_futures
def direction(src, dst):
"""BOLT 7 direction: 0 means from lesser encoded id"""
if src < dst:
return 0
return 1
def scid_dir(nodemap, node1_idx, node2_idx, chan_idx):
"""Get short_channel_id_dir for a channel in generate_gossip_store format"""
dir_val = direction(nodemap[node1_idx], nodemap[node2_idx])
return f"{node1_idx}x{node2_idx}x{chan_idx}/{dir_val}"
def test_reserve(node_factory):
"""Test reserving channels"""
l1, l2, l3 = node_factory.line_graph(3, wait_for_announce=True)
assert l1.rpc.askrene_listreservations() == {'reservations': []}
scid12 = first_scid(l1, l2)
scid23 = first_scid(l2, l3)
scid12dir = f"{scid12}/{direction(l1.info['id'], l2.info['id'])}"
scid23dir = f"{scid23}/{direction(l2.info['id'], l3.info['id'])}"
initial_prob = l1.rpc.getroutes(source=l1.info['id'],
destination=l3.info['id'],
amount_msat=1000000,
layers=[],
maxfee_msat=100000,
final_cltv=0)['probability_ppm']
# Reserve 1000 sats on path. This should reduce probability!
l1.rpc.askrene_reserve(path=[{'short_channel_id_dir': scid12dir,
'amount_msat': 1000_000},
{'short_channel_id_dir': scid23dir,
'amount_msat': 1000_001}])
listres = l1.rpc.askrene_listreservations()['reservations']
if listres[0]['short_channel_id_dir'] == scid12dir:
assert listres[0]['amount_msat'] == 1000_000
assert listres[1]['short_channel_id_dir'] == scid23dir
assert listres[1]['amount_msat'] == 1000_001
else:
assert listres[0]['short_channel_id_dir'] == scid23dir
assert listres[0]['amount_msat'] == 1000_001
assert listres[1]['short_channel_id_dir'] == scid12dir
assert listres[1]['amount_msat'] == 1000_000
assert len(listres) == 2
assert l1.rpc.getroutes(source=l1.info['id'],
destination=l3.info['id'],
amount_msat=1000000,
layers=[],
maxfee_msat=100000,
final_cltv=0)['probability_ppm'] < initial_prob
# Now reserve so much there's nothing left.
l1.rpc.askrene_reserve(path=[{'short_channel_id_dir': scid12dir,
'amount_msat': 1000_000_000_000},
{'short_channel_id_dir': scid23dir,
'amount_msat': 1000_000_000_000}])
# Keep it consistent: the below will mention a time if >= 1 seconds old,
# which might happen without the sleep on slow machines.
time.sleep(2)
# Reservations can be in either order.
with pytest.raises(RpcError, match=rf'We could not find a usable set of paths. The shortest path is {scid12}->{scid23}, but {scid12dir} already reserved 10000000*msat by command ".*" \([0-9]* seconds ago\), 10000000*msat by command ".*" \([0-9]* seconds ago\)'):
l1.rpc.getroutes(source=l1.info['id'],
destination=l3.info['id'],
amount_msat=1000000,
layers=[],
maxfee_msat=100000,
final_cltv=0)['probability_ppm']
# Can't remove wrong amounts: that's user error
with pytest.raises(RpcError, match="Unknown reservation"):
l1.rpc.askrene_unreserve(path=[{'short_channel_id_dir': scid12dir,
'amount_msat': 1000_001},
{'short_channel_id_dir': scid23dir,
'amount_msat': 1000_000}])
# Remove, it's all ok.
l1.rpc.askrene_unreserve(path=[{'short_channel_id_dir': scid12dir,
'amount_msat': 1000_000},
{'short_channel_id_dir': scid23dir,
'amount_msat': 1000_001}])
l1.rpc.askrene_unreserve(path=[{'short_channel_id_dir': scid12dir,
'amount_msat': 1000_000_000_000},
{'short_channel_id_dir': scid23dir,
'amount_msat': 1000_000_000_000}])
assert l1.rpc.askrene_listreservations() == {'reservations': []}
assert l1.rpc.getroutes(source=l1.info['id'],
destination=l3.info['id'],
amount_msat=1000000,
layers=[],
maxfee_msat=100000,
final_cltv=0)['probability_ppm'] == initial_prob
# Reserving in reverse makes no difference!
scid12rev = f"{first_scid(l1, l2)}/{direction(l2.info['id'], l1.info['id'])}"
scid23rev = f"{first_scid(l2, l3)}/{direction(l3.info['id'], l2.info['id'])}"
l1.rpc.askrene_reserve(path=[{'short_channel_id_dir': scid12rev,
'amount_msat': 1000_000_000_000},
{'short_channel_id_dir': scid23rev,
'amount_msat': 1000_000_000_000}])
assert l1.rpc.getroutes(source=l1.info['id'],
destination=l3.info['id'],
amount_msat=1000000,
layers=[],
maxfee_msat=100000,
final_cltv=0)['probability_ppm'] == initial_prob
def test_layers(node_factory):
"""Test manipulating information in layers"""
# remove xpay, since it creates a layer!
l1, l2, l3 = node_factory.line_graph(3, wait_for_announce=True,
opts={'disable-plugin': 'cln-xpay'})
assert l2.rpc.askrene_listlayers() == {'layers': []}
with pytest.raises(RpcError, match="Unknown layer"):
l2.rpc.askrene_listlayers('test_layers')
expect = {'layer': 'test_layers',
'persistent': False,
'disabled_nodes': [],
'created_channels': [],
'channel_updates': [],
'constraints': [],
'biases': [],
'node_biases': []}
l2.rpc.askrene_create_layer('test_layers')
l2.rpc.askrene_disable_node('test_layers', l1.info['id'])
expect['disabled_nodes'].append(l1.info['id'])
assert l2.rpc.askrene_listlayers('test_layers') == {'layers': [expect]}
assert l2.rpc.askrene_listlayers() == {'layers': [expect]}
with pytest.raises(RpcError, match="Unknown layer"):
l2.rpc.askrene_listlayers('test_layers2')
l2.rpc.askrene_update_channel('test_layers', "0x0x1/0", False)
expect['channel_updates'].append({'short_channel_id_dir': "0x0x1/0",
'enabled': False})
assert l2.rpc.askrene_listlayers('test_layers') == {'layers': [expect]}
with pytest.raises(RpcError, match="Layer already exists"):
l2.rpc.askrene_create_layer('test_layers')
# Tell it l3 connects to l1!
l2.rpc.askrene_create_channel('test_layers',
l3.info['id'],
l1.info['id'],
'0x0x1',
'1000000sat')
# src/dst gets turned into BOLT 7 order
expect['created_channels'].append({'source': l1.info['id'],
'destination': l3.info['id'],
'short_channel_id': '0x0x1',
'capacity_msat': 1000000000})
assert l2.rpc.askrene_listlayers('test_layers') == {'layers': [expect]}
# And give details.
l2.rpc.askrene_update_channel(layer='test_layers',
short_channel_id_dir='0x0x1/0',
htlc_minimum_msat=100,
htlc_maximum_msat=900000000,
fee_base_msat=1,
fee_proportional_millionths=2,
cltv_expiry_delta=18)
# This is *still* disabled, since we disabled it above!
expect['channel_updates'] = [{'short_channel_id_dir': '0x0x1/0',
'enabled': False,
'htlc_minimum_msat': 100,
'htlc_maximum_msat': 900000000,
'fee_base_msat': 1,
'fee_proportional_millionths': 2,
'cltv_expiry_delta': 18}]
assert l2.rpc.askrene_listlayers('test_layers') == {'layers': [expect]}
# Now enable (and change another value for good measure!
l2.rpc.askrene_update_channel(layer='test_layers',
short_channel_id_dir='0x0x1/0',
enabled=True,
cltv_expiry_delta=19)
expect['channel_updates'] = [{'short_channel_id_dir': '0x0x1/0',
'enabled': True,
'htlc_minimum_msat': 100,
'htlc_maximum_msat': 900000000,
'fee_base_msat': 1,
'fee_proportional_millionths': 2,
'cltv_expiry_delta': 19}]
assert l2.rpc.askrene_listlayers('test_layers') == {'layers': [expect]}
# We can tell it about made up channels...
first_timestamp = int(time.time())
l2.rpc.askrene_inform_channel('test_layers',
'0x0x1/1',
100000,
'unconstrained')
last_timestamp = int(time.time()) + 1
expect['constraints'].append({'short_channel_id_dir': '0x0x1/1',
'minimum_msat': 100000})
# Check timestamp first.
listlayers = l2.rpc.askrene_listlayers('test_layers')
ts1 = only_one(only_one(listlayers['layers'])['constraints'])['timestamp']
assert first_timestamp <= ts1 <= last_timestamp
expect['constraints'][0]['timestamp'] = ts1
assert listlayers == {'layers': [expect]}
# Make sure timestamps differ!
time.sleep(2)
# We can tell it about existing channels...
scid12 = first_scid(l1, l2)
first_timestamp = int(time.time())
scid12dir = f"{scid12}/{direction(l2.info['id'], l1.info['id'])}"
l2.rpc.askrene_inform_channel(layer='test_layers',
short_channel_id_dir=scid12dir,
amount_msat=12341235,
inform='constrained')
last_timestamp = int(time.time()) + 1
expect['constraints'].append({'short_channel_id_dir': scid12dir,
'timestamp': first_timestamp,
'maximum_msat': 12341234})
# Check timestamp first.
listlayers = l2.rpc.askrene_listlayers('test_layers')
ts2 = only_one([c['timestamp'] for c in only_one(listlayers['layers'])['constraints'] if c['short_channel_id_dir'] == scid12dir])
assert first_timestamp <= ts2 <= last_timestamp
expect['constraints'][1]['timestamp'] = ts2
# Could be either order!
actual = expect.copy()
if only_one(listlayers['layers'])['constraints'][0]['short_channel_id_dir'] == scid12dir:
actual['constraints'] = [expect['constraints'][1], expect['constraints'][0]]
assert listlayers == {'layers': [actual]}
# Now test aging: ts1 does nothing.
assert l2.rpc.askrene_age('test_layers', ts1) == {'layer': 'test_layers', 'num_removed': 0}
listlayers = l2.rpc.askrene_listlayers('test_layers')
assert listlayers == {'layers': [actual]}
# ts1+1 removes first inform
assert l2.rpc.askrene_age('test_layers', ts1 + 1) == {'layer': 'test_layers', 'num_removed': 1}
del expect['constraints'][0]
listlayers = l2.rpc.askrene_listlayers('test_layers')
assert listlayers == {'layers': [expect]}
# ts2+1 removes other.
assert l2.rpc.askrene_age('test_layers', ts2 + 1) == {'layer': 'test_layers', 'num_removed': 1}
del expect['constraints'][0]
listlayers = l2.rpc.askrene_listlayers('test_layers')
assert listlayers == {'layers': [expect]}
with pytest.raises(RpcError, match="Unknown layer"):
l2.rpc.askrene_remove_layer('test_layers_unknown')
# Add biases.
r = l2.rpc.askrene_bias_channel('test_layers', '1x1x1/1', 1)
expect['biases'] = [{'short_channel_id_dir': '1x1x1/1', 'bias': 1,
'timestamp': r['biases'][0]['timestamp']}]
listlayers = l2.rpc.askrene_listlayers('test_layers')
assert listlayers == {'layers': [expect]}
# Works with description.
r = l2.rpc.askrene_bias_channel('test_layers', '1x1x1/1', -5, "bigger bias")
expect['biases'] = [{'short_channel_id_dir': '1x1x1/1', 'bias': -5,
'description': "bigger bias",
'timestamp': r['biases'][0]['timestamp']}]
listlayers = l2.rpc.askrene_listlayers('test_layers')
assert listlayers == {'layers': [expect]}
with pytest.raises(RpcError, match="bias: should be a number between -100 and 100"):
l2.rpc.askrene_bias_channel('test_layers', '1x1x1/1', -101)
with pytest.raises(RpcError, match="bias: should be a number between -100 and 100"):
l2.rpc.askrene_bias_channel('test_layers', '1x1x1/1', 101, "bigger bias")
# We can make them relative.
r = l2.rpc.askrene_bias_channel('test_layers', '1x1x1/1', 1, 'adding bias', True)
expect['biases'] = [{'short_channel_id_dir': '1x1x1/1', 'bias': -4,
'description': "adding bias",
'timestamp': r['biases'][0]['timestamp']}]
listlayers = l2.rpc.askrene_listlayers('test_layers')
assert listlayers == {'layers': [expect]}
r = l2.rpc.askrene_bias_channel(layer='test_layers', short_channel_id_dir='1x1x1/1', bias=-1, relative=True)
expect['biases'] = [{'short_channel_id_dir': '1x1x1/1', 'bias': -5,
'timestamp': r['biases'][0]['timestamp']}]
listlayers = l2.rpc.askrene_listlayers('test_layers')
assert listlayers == {'layers': [expect]}
# They truncate on +/- 100 though:
r = l2.rpc.askrene_bias_channel('test_layers', '1x1x1/1', -99, None, True)
expect['biases'] = [{'short_channel_id_dir': '1x1x1/1', 'bias': -100,
'timestamp': r['biases'][0]['timestamp']}]
listlayers = l2.rpc.askrene_listlayers('test_layers')
assert listlayers == {'layers': [expect]}
# We can remove them.
l2.rpc.askrene_bias_channel('test_layers', '1x1x1/1', 0)
expect['biases'] = []
listlayers = l2.rpc.askrene_listlayers('test_layers')
assert listlayers == {'layers': [expect]}
assert l2.rpc.askrene_remove_layer('test_layers') == {}
assert l2.rpc.askrene_listlayers() == {'layers': []}
# This layer is not persistent.
l2.rpc.askrene_create_layer('test_layers')
l2.restart()
assert l2.rpc.askrene_listlayers() == {'layers': []}
def test_node_bias_rpc(node_factory):
"""Test manipulating node bias in layers."""
# remove xpay, since it creates a layer!
l1, l2 = node_factory.line_graph(
2, wait_for_announce=True, opts={"disable-plugin": "cln-xpay"}
)
# Simply test the presence of 'node_biases'
expect = {
"layer": "test_layers",
"persistent": False,
"disabled_nodes": [],
"created_channels": [],
"channel_updates": [],
"constraints": [],
"biases": [],
"node_biases": [],
}
l1.rpc.askrene_create_layer("test_layers")
assert l1.rpc.askrene_listlayers("test_layers") == {"layers": [expect]}
# Adding a node bias in the out direction
r = l1.rpc.askrene_bias_node(
layer="test_layers",
node=l2.info["id"],
direction="out",
bias=3,
relative=False,
)
# Adding a node bias in the in direction
r = l1.rpc.askrene_bias_node(
layer="test_layers",
node=l2.info["id"],
direction="in",
bias=-3,
relative=False,
)
expect["node_biases"] = [
{
"node": l2.info["id"],
"in_bias": -3,
"out_bias": 3,
"timestamp": r["node_biases"][0]["timestamp"],
}
]
listlayers = l1.rpc.askrene_listlayers("test_layers")
assert listlayers == {"layers": [expect]}
# Testing relative bias and descriptions
r = l1.rpc.askrene_bias_node(
layer="test_layers",
node=l2.info["id"],
direction="in",
bias=-3,
relative=True,
description="testing node bias",
)
r = l1.rpc.askrene_bias_node(
layer="test_layers",
node=l2.info["id"],
direction="out",
bias=-1,
relative=True,
description="testing node bias",
)
expect["node_biases"] = [
{
"node": l2.info["id"],
"in_bias": -6,
"out_bias": 2,
"timestamp": r["node_biases"][0]["timestamp"],
"description": "testing node bias",
}
]
listlayers = l1.rpc.askrene_listlayers("test_layers")
assert listlayers == {"layers": [expect]}
# Setting one direction bias, still the other remains
r = l1.rpc.askrene_bias_node(
layer="test_layers",
node=l2.info["id"],
direction="in",
bias=0,
relative=False,
)
expect["node_biases"] = [
{
"node": l2.info["id"],
"in_bias": 0,
"out_bias": 2,
"timestamp": r["node_biases"][0]["timestamp"],
}
]
listlayers = l1.rpc.askrene_listlayers("test_layers")
assert listlayers == {"layers": [expect]}
# If the bias in both direction is zero the entry is removed
r = l1.rpc.askrene_bias_node(
layer="test_layers",
node=l2.info["id"],
direction="out",
bias=0,
relative=False,
)
expect["node_biases"] = []
listlayers = l1.rpc.askrene_listlayers("test_layers")
assert listlayers == {"layers": [expect]}
def test_node_bias_persistence(node_factory):
"""Test node bias persistence."""
# remove xpay, since it creates a layer!
l1, l2 = node_factory.line_graph(
2, wait_for_announce=True, opts={"disable-plugin": "cln-xpay"}
)
expect = {
"layer": "mylayer",
"persistent": True,
"disabled_nodes": [],
"created_channels": [],
"channel_updates": [],
"constraints": [],
"biases": [],
"node_biases": [],
}
l1.rpc.askrene_create_layer(layer="mylayer", persistent=True)
r = l1.rpc.askrene_bias_node(
layer="mylayer", node=l2.info["id"], direction="out", bias=14, relative=False
)
expect["node_biases"] = [
{
"node": l2.info["id"],
"in_bias": 0,
"out_bias": 14,
"timestamp": r["node_biases"][0]["timestamp"],
}
]
assert l1.rpc.askrene_listlayers("mylayer") == {"layers": [expect]}
# restarting the node we see the same data again
l2.restart()
assert l1.rpc.askrene_listlayers("mylayer") == {"layers": [expect]}
r = l1.rpc.askrene_bias_node(
layer="mylayer",
node=l2.info["id"],
direction="in",
bias=11,
relative=False,
description="Some description",
)
expect["node_biases"] = [
{
"node": l2.info["id"],
"in_bias": 11,
"out_bias": 14,
"timestamp": r["node_biases"][0]["timestamp"],
"description": "Some description",
}
]
assert l1.rpc.askrene_listlayers("mylayer") == {"layers": [expect]}
# restarting the node we see the same data again
l2.restart()
assert l1.rpc.askrene_listlayers("mylayer") == {"layers": [expect]}
def test_node_bias_routes(node_factory):
"""Test getroutes with biased nodes."""
# There are many cheap routes that go through node 2:
# 0->2->x->1
# And a very expensive route that go through node 3:
# 0->3->1
gsfile, nodemap = generate_gossip_store(
[
GenChannel(0, 2, forward=GenChannel.Half(propfee=10)),
GenChannel(2, 11, forward=GenChannel.Half(propfee=10)),
GenChannel(2, 12, forward=GenChannel.Half(propfee=10)),
GenChannel(2, 13, forward=GenChannel.Half(propfee=10)),
GenChannel(2, 14, forward=GenChannel.Half(propfee=10)),
GenChannel(2, 15, forward=GenChannel.Half(propfee=10)),
GenChannel(2, 16, forward=GenChannel.Half(propfee=10)),
GenChannel(2, 17, forward=GenChannel.Half(propfee=10)),
GenChannel(2, 18, forward=GenChannel.Half(propfee=10)),
GenChannel(2, 19, forward=GenChannel.Half(propfee=10)),
GenChannel(11, 1, forward=GenChannel.Half(propfee=10)),
GenChannel(12, 1, forward=GenChannel.Half(propfee=10)),
GenChannel(13, 1, forward=GenChannel.Half(propfee=10)),
GenChannel(14, 1, forward=GenChannel.Half(propfee=10)),
GenChannel(15, 1, forward=GenChannel.Half(propfee=10)),
GenChannel(16, 1, forward=GenChannel.Half(propfee=10)),
GenChannel(17, 1, forward=GenChannel.Half(propfee=10)),
GenChannel(18, 1, forward=GenChannel.Half(propfee=10)),
GenChannel(19, 1, forward=GenChannel.Half(propfee=10)),
GenChannel(0, 3, forward=GenChannel.Half(propfee=1000)),
GenChannel(3, 1, forward=GenChannel.Half(propfee=1000)),
]
)
l1 = node_factory.get_node(gossip_store_file=gsfile.name)
l1.rpc.askrene_create_layer(layer="mylayer")
l1.rpc.askrene_bias_node(layer="mylayer", node=nodemap[2], direction="out", bias=-50)
# by default the best route goes through node 2
r = l1.rpc.getroutes(
source=nodemap[0],
destination=nodemap[1],
amount_msat=10000000,
layers=[],
maxfee_msat=1000000,
final_cltv=99,
)
assert len(r["routes"]) == 1
assert len(r["routes"][0]["path"]) == 3
assert r["routes"][0]["path"][0]["next_node_id"] == nodemap[2]
assert r["routes"][0]["path"][2]["next_node_id"] == nodemap[1]
# by using the layer that penalizes node 2, we end up routing through node 3
r = l1.rpc.getroutes(
source=nodemap[0],
destination=nodemap[1],
amount_msat=10000000,
layers=["mylayer"],
maxfee_msat=1000000,
final_cltv=99,
)
assert len(r["routes"]) == 1
assert len(r["routes"][0]["path"]) == 2
assert r["routes"][0]["path"][0]["next_node_id"] == nodemap[3]
assert r["routes"][0]["path"][1]["next_node_id"] == nodemap[1]
def test_layer_persistence(node_factory):
"""Test persistence of layers across restart"""
l1, l2 = node_factory.line_graph(2, wait_for_announce=True,
opts={'disable-plugin': 'cln-xpay'})
assert l1.rpc.askrene_listlayers() == {'layers': []}
with pytest.raises(RpcError, match="Unknown layer"):
l1.rpc.askrene_listlayers('test_layer_persistence')
l1.rpc.askrene_create_layer(layer='test_layer_persistence', persistent=True)
expect = {'layer': 'test_layer_persistence',
'persistent': True,
'disabled_nodes': [],
'created_channels': [],
'channel_updates': [],
'constraints': [],
'biases': [],
'node_biases': []}
assert l1.rpc.askrene_listlayers('test_layer_persistence') == {'layers': [expect]}
# Restart, (empty layer) should still be there.
l1.restart()
assert l1.rpc.askrene_listlayers('test_layer_persistence') == {'layers': [expect]}
# Re-creation of persistent layer is a noop.
l1.rpc.askrene_create_layer(layer='test_layer_persistence', persistent=True)
# Populate it.
l1.rpc.askrene_disable_node('test_layer_persistence', l1.info['id'])
l1.rpc.askrene_update_channel('test_layer_persistence', "0x0x1/0", False)
l1.rpc.askrene_create_channel('test_layer_persistence',
l2.info['id'],
l1.info['id'],
'0x0x1',
'1000000sat')
l1.rpc.askrene_update_channel(layer='test_layer_persistence',
short_channel_id_dir='0x0x1/0',
htlc_minimum_msat=100,
htlc_maximum_msat=900000000,
fee_base_msat=1,
fee_proportional_millionths=2,
cltv_expiry_delta=18)
l1.rpc.askrene_update_channel(layer='test_layer_persistence',
short_channel_id_dir='0x0x1/0',
enabled=True,
cltv_expiry_delta=19)
l1.rpc.askrene_inform_channel('test_layer_persistence',
'0x0x1/1',
100000,
'unconstrained')
scid12 = first_scid(l1, l2)
scid12dir = f"{scid12}/{direction(l1.info['id'], l2.info['id'])}"
l1.rpc.askrene_inform_channel(layer='test_layer_persistence',
short_channel_id_dir=scid12dir,
amount_msat=12341235,
inform='constrained')
expect = l1.rpc.askrene_listlayers('test_layer_persistence')
l1.restart()
assert l1.rpc.askrene_listlayers('test_layer_persistence') == expect
# Aging will cause a rewrite.
assert l1.rpc.askrene_age('test_layer_persistence', 1) == {'layer': 'test_layer_persistence', 'num_removed': 0}
assert l1.rpc.askrene_listlayers('test_layer_persistence') == expect
l1.restart()
assert l1.rpc.askrene_listlayers('test_layer_persistence') == expect
# Delete layer, it won't reappear.
assert l1.rpc.askrene_remove_layer('test_layer_persistence') == {}
assert l1.rpc.askrene_listlayers() == {'layers': []}
l1.restart()
assert l1.rpc.askrene_listlayers() == {'layers': []}
def check_route_as_expected(routes, paths):
"""Make sure all fields in paths are match those in routes"""
def dict_subset_eq(a, b):
"""Is every key in B is the same in A?"""
return all(a.get(key) == b[key] for key in b)
for path in paths:
found = False
for i in range(len(routes)):
route = routes[i]
if len(route['path']) != len(path):
continue
if all(dict_subset_eq(route['path'][i], path[i]) for i in range(len(path))):
del routes[i]
found = True
break
if not found:
raise ValueError("Could not find path {} in paths {}".format(path, routes))
if routes != []:
raise ValueError("Did not expect paths {}".format(routes))
def check_getroute_paths(node,
source,
destination,
amount_msat,
paths,
layers=[],
maxfee_msat=1000,
final_cltv=99):
"""Check that routes are as expected in result"""
getroutes = node.rpc.getroutes(source=source,
destination=destination,
amount_msat=amount_msat,
layers=layers,
maxfee_msat=maxfee_msat,
final_cltv=final_cltv)
assert getroutes['probability_ppm'] <= 1000000
# Total delivered should be amount we told it to send.
assert amount_msat == sum([r['amount_msat'] for r in getroutes['routes']])
check_route_as_expected(getroutes['routes'], paths)
def test_getroutes(node_factory):
"""Test getroutes call"""
gsfile, nodemap = generate_gossip_store([GenChannel(0, 1, forward=GenChannel.Half(propfee=10000)),
GenChannel(0, 2, capacity_sats=9000),
GenChannel(1, 3, forward=GenChannel.Half(propfee=20000)),
GenChannel(0, 2, capacity_sats=10000),
GenChannel(2, 4, forward=GenChannel.Half(delay=2000))])
# Set up l1 with this as the gossip_store
l1 = node_factory.get_node(gossip_store_file=gsfile.name)
# Too much should give a decent explanation.
dir01 = direction(nodemap[0], nodemap[1])
with pytest.raises(RpcError, match=rf"We could not find a usable set of paths\. The shortest path is 0x1x0, but 0x1x0/{dir01} isn't big enough to carry 1000000001msat\."):
l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[1],
amount_msat=1000000001,
layers=[],
maxfee_msat=100000000,
final_cltv=99)
# This should tell us source doesn't have enough.
with pytest.raises(RpcError, match=r"We could not find a usable set of paths\. Total source capacity is only 1019000000msat \(in 3 channels\)\."):
l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[1],
amount_msat=2000000001,
layers=[],
maxfee_msat=20000000,
final_cltv=99)
# This should tell us dest doesn't have enough.
with pytest.raises(RpcError, match=r"We could not find a usable set of paths\. Total destination capacity is only 1000000000msat \(in 1 channels\)\."):
l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[4],
amount_msat=1000000001,
layers=[],
maxfee_msat=30000000,
final_cltv=99)
# Disabling channels makes getroutes fail
dir01 = direction(nodemap[0], nodemap[1])
l1.rpc.askrene_create_layer('chans_disabled')
l1.rpc.askrene_update_channel(layer="chans_disabled",
short_channel_id_dir=f'0x1x0/{dir01}',
enabled=False)
with pytest.raises(RpcError, match=rf"We could not find a usable set of paths\. The shortest path is 0x1x0, but 0x1x0/{dir01} marked disabled by layer chans_disabled\."):
l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[1],
amount_msat=1000,
layers=["chans_disabled"],
maxfee_msat=1000,
final_cltv=99)
# Start easy
dir01 = direction(nodemap[0], nodemap[1])
assert l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[1],
amount_msat=1000,
layers=[],
maxfee_msat=1000,
final_cltv=99) == {'probability_ppm': 999999,
'routes': [{'probability_ppm': 999999,
'final_cltv': 99,
'amount_msat': 1000,
'path': [{'short_channel_id_dir': f'0x1x0/{dir01}',
'next_node_id': nodemap[1],
'amount_msat': 1010,
'delay': 99 + 6}]}]}
# Two hop, still easy.
dir13 = direction(nodemap[1], nodemap[3])
assert l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[3],
amount_msat=100000,
layers=[],
maxfee_msat=5000,
final_cltv=99) == {'probability_ppm': 999798,
'routes': [{'probability_ppm': 999798,
'final_cltv': 99,
'amount_msat': 100000,
'path': [{'short_channel_id_dir': f'0x1x0/{dir01}',
'next_node_id': nodemap[1],
'amount_msat': 103020,
'delay': 99 + 6 + 6},
{'short_channel_id_dir': f'3x3x2/{dir13}',
'next_node_id': nodemap[3],
'amount_msat': 102000,
'delay': 99 + 6}
]}]}
# Too expensive
with pytest.raises(RpcError, match="Could not find route without excessive cost"):
l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[3],
amount_msat=100000,
layers=[],
maxfee_msat=100,
final_cltv=99)
# Too much delay (if final delay too great!)
l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[4],
amount_msat=100000,
layers=[],
maxfee_msat=100,
final_cltv=6)
with pytest.raises(RpcError, match="Could not find route without excessive delays"):
l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[4],
amount_msat=100000,
layers=[],
maxfee_msat=100,
final_cltv=99)
# Two choices, but for <= 1000 sats we choose the larger.
dir02 = direction(nodemap[0], nodemap[2])
assert l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[2],
amount_msat=1000000,
layers=[],
maxfee_msat=5000,
final_cltv=99) == {'probability_ppm': 900000,
'routes': [{'probability_ppm': 900000,
'final_cltv': 99,
'amount_msat': 1000000,
'path': [{'short_channel_id_dir': f'3x2x3/{dir02}',
'next_node_id': nodemap[2],
'amount_msat': 1000001,
'delay': 99 + 6}]}]}
# For 10000 sats, we will split.
check_getroute_paths(l1,
nodemap[0],
nodemap[2],
10000000,
[[{'short_channel_id_dir': f'1x2x1/{dir02}',
'next_node_id': nodemap[2],
'amount_msat': 4500004,
'delay': 99 + 6}],
[{'short_channel_id_dir': f'3x2x3/{dir02}',
'next_node_id': nodemap[2],
'amount_msat': 5500005,
'delay': 99 + 6}]])
def test_getroutes_single_path(node_factory):
"""Test getroutes generating single path payments"""
gsfile, nodemap = generate_gossip_store(
[
GenChannel(0, 1),
GenChannel(1, 2, capacity_sats=9000),
GenChannel(1, 2, capacity_sats=10000),
]
)
# Set up l1 with this as the gossip_store
l1 = node_factory.get_node(gossip_store_file=gsfile.name)
# To be able to route this amount two parts are needed, therefore a single
# pay search will fail.
# FIXME: the explanation for the failure is wrong
with pytest.raises(RpcError):
l1.rpc.getroutes(
source=nodemap[1],
destination=nodemap[2],
amount_msat=10000001,
layers=["auto.no_mpp_support"],
maxfee_msat=1000,
final_cltv=99,
)
# For this amount, only one solution is possible
check_getroute_paths(
l1,
nodemap[1],
nodemap[2],
10000000,
[
[
{
"short_channel_id_dir": "3x2x2/1",
"next_node_id": nodemap[2],
"amount_msat": 10000010,
"delay": 99 + 6,
}
]
],
layers=["auto.no_mpp_support"],
)
# To be able to route this amount two parts are needed, therefore a single
# pay search will fail.
# FIXME: the explanation for the failure is wrong
with pytest.raises(RpcError):
l1.rpc.getroutes(
source=nodemap[0],
destination=nodemap[2],
amount_msat=10000001,
layers=["auto.no_mpp_support"],
maxfee_msat=1000,
final_cltv=99,
)
# For this amount, only one solution is possible
check_getroute_paths(
l1,
nodemap[0],
nodemap[2],
10000000,
[
[
{
"short_channel_id_dir": "0x1x0/1",
"next_node_id": nodemap[1],
"amount_msat": 10000020,
"delay": 99 + 6 + 6,
},
{
"short_channel_id_dir": "3x2x2/1",
"next_node_id": nodemap[2],
"amount_msat": 10000010,
"delay": 99 + 6,
},
]
],
layers=["auto.no_mpp_support"],
)
def test_getroutes_fee_fallback(node_factory):
"""Test getroutes call takes into account fees, if excessive"""
# 0 -> 1 -> 3: high capacity, high fee (1%)
# 0 -> 2 -> 3: low capacity, low fee.
# (We disable reverse, since it breaks median calc!)
gsfile, nodemap = generate_gossip_store([GenChannel(0, 1,
capacity_sats=20000,
forward=GenChannel.Half(propfee=10000),
reverse=GenChannel.Half(enabled=False)),
GenChannel(0, 2,
capacity_sats=10000,
reverse=GenChannel.Half(enabled=False)),
GenChannel(1, 3,
capacity_sats=20000,
forward=GenChannel.Half(propfee=10000),
reverse=GenChannel.Half(enabled=False)),
GenChannel(2, 3,
capacity_sats=10000,
reverse=GenChannel.Half(enabled=False))])
# Set up l1 with this as the gossip_store
l1 = node_factory.get_node(gossip_store_file=gsfile.name)
# Don't hit maxfee? Go easy path.
dir01 = direction(nodemap[0], nodemap[1])
dir13 = direction(nodemap[1], nodemap[3])
dir02 = direction(nodemap[0], nodemap[2])
dir23 = direction(nodemap[2], nodemap[3])
check_getroute_paths(l1,
nodemap[0],
nodemap[3],
10000,
maxfee_msat=201,
paths=[[{'short_channel_id_dir': f'0x1x0/{dir01}'},
{'short_channel_id_dir': f'3x3x2/{dir13}'}]])
# maxfee exceeded? lower prob path.
check_getroute_paths(l1,
nodemap[0],
nodemap[3],
10000,
maxfee_msat=200,
paths=[[{'short_channel_id_dir': f'1x2x1/{dir02}'},
{'short_channel_id_dir': f'5x3x3/{dir23}'}]])
def test_getroutes_auto_sourcefree(node_factory):
"""Test getroutes call with auto.sourcefree layer"""
gsfile, nodemap = generate_gossip_store([GenChannel(0, 1, forward=GenChannel.Half(propfee=10000)),
GenChannel(0, 2, capacity_sats=9000),
GenChannel(1, 3, forward=GenChannel.Half(propfee=20000)),
GenChannel(0, 2, capacity_sats=10000),
GenChannel(2, 4, forward=GenChannel.Half(delay=2000))])
# Set up l1 with this as the gossip_store
l1 = node_factory.get_node(gossip_store_file=gsfile.name)
# Without sourcefree:
dir01 = direction(nodemap[0], nodemap[1])
assert l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[1],
amount_msat=1000,
layers=[],
maxfee_msat=1000,
final_cltv=99) == {'probability_ppm': 999999,
'routes': [{'probability_ppm': 999999,
'final_cltv': 99,
'amount_msat': 1000,
'path': [{'short_channel_id_dir': f'0x1x0/{dir01}',
'next_node_id': nodemap[1],
'amount_msat': 1010,
'delay': 105}]}]}
# Start easy
assert l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[1],
amount_msat=1000,
layers=['auto.sourcefree'],
maxfee_msat=1000,
final_cltv=99) == {'probability_ppm': 999999,
'routes': [{'probability_ppm': 999999,
'final_cltv': 99,
'amount_msat': 1000,
'path': [{'short_channel_id_dir': f'0x1x0/{dir01}',
'next_node_id': nodemap[1],
'amount_msat': 1000,
'delay': 99}]}]}
# Two hop, still easy.
dir13 = direction(nodemap[1], nodemap[3])
assert l1.rpc.getroutes(source=nodemap[0],
destination=nodemap[3],
amount_msat=100000,