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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
//! DHT Core Engine with Kademlia routing
//!
//! Provides peer discovery and routing via a Kademlia DHT with k=8 buckets,
//! trust-weighted peer selection, and security-hardened maintenance tasks.
use crate::PeerId;
use crate::address::{MultiAddr, is_lan_ip};
use crate::security::{IP_EXACT_LIMIT, IPDiversityConfig, canonicalize_ip, ip_subnet_limit};
use anyhow::{Result, anyhow};
use parking_lot::Mutex as PlMutex;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tokio_util::sync::CancellationToken;
/// An [`Instant`] stored behind a synchronous mutex so it can be updated
/// from `&self` receivers.
///
/// The key property: reads and writes only need `&self`, so the routing
/// table's hot touch path (called on every inbound DHT message) can run
/// under a read lock on the routing table instead of an exclusive write
/// lock. The previous write-lock design serialised all readers behind
/// every touch, which at 1000 nodes became the dominant contention point.
///
/// Why a mutex instead of an atomic: `Instant` is opaque (no stable `u64`
/// representation) and can legitimately represent times in the past
/// (tests backdate `last_seen` to mark peers stale). Any epoch-based
/// `AtomicU64` encoding would have to either (a) panic/saturate on past
/// times, or (b) pick a process-lifetime epoch in the deep past, which
/// risks `Instant` underflow on recently booted systems. A
/// [`parking_lot::Mutex<Instant>`] sidesteps all of this and is still
/// extremely fast on the uncontended path (single CAS to acquire + store
/// + single CAS to release — microseconds).
#[derive(Debug)]
pub struct AtomicInstant(PlMutex<Instant>);
impl AtomicInstant {
/// Return a fresh `AtomicInstant` set to the current time.
pub fn now() -> Self {
Self(PlMutex::new(Instant::now()))
}
/// Wrap an existing `Instant`.
pub fn from_instant(i: Instant) -> Self {
Self(PlMutex::new(i))
}
/// Load the current value as an `Instant`.
pub fn load(&self) -> Instant {
*self.0.lock()
}
/// Atomically store the current time.
pub fn store_now(&self) {
*self.0.lock() = Instant::now();
}
/// Atomically store a specific `Instant`.
pub fn store(&self, i: Instant) {
*self.0.lock() = i;
}
/// Time elapsed since the stored instant.
pub fn elapsed(&self) -> Duration {
self.load().elapsed()
}
}
impl Clone for AtomicInstant {
fn clone(&self) -> Self {
Self(PlMutex::new(*self.0.lock()))
}
}
impl Default for AtomicInstant {
fn default() -> Self {
Self::now()
}
}
#[cfg(test)]
use crate::adaptive::trust::DEFAULT_NEUTRAL_TRUST;
/// DHT key type — now a direct alias for [`PeerId`].
///
/// Both types are `[u8; 32]` wrappers with identity conversions between them.
/// Using a single type eliminates keyspace mismatch bugs where BLAKE3-hashing
/// a PeerId into a second "DHT key" space caused nodes to land in wrong
/// Kademlia buckets.
pub type DhtKey = PeerId;
#[inline]
fn xor_distance_bytes(a: &[u8; 32], b: &[u8; 32]) -> [u8; 32] {
let mut out = [0u8; 32];
for (idx, byte) in out.iter_mut().enumerate() {
*byte = a[idx] ^ b[idx];
}
out
}
/// Maximum addresses stored per node to prevent memory exhaustion.
/// This cap is the last-line guard; in normal operation the per-IP-family
/// cap ([`NodeInfo::enforce_per_ip_family_cap`]) holds each external peer
/// to at most 2 IP addresses per family. Non-IP transports (Bluetooth,
/// LoRa) are outside the per-family cap and rely on this bound.
const MAX_ADDRESSES_PER_NODE: usize = 8;
/// Address classification for priority ordering and staleness eviction.
///
/// Priority: Relay > Direct > Unverified > Lan. The `merge_typed_address`
/// method uses this for insertion ordering and the eviction of excess
/// `Lan` / `Unverified` entries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AddressType {
/// Address through a MASQUE relay server (always reachable)
Relay,
/// Direct public IP address verified reachable without NAT traversal
Direct,
/// Self-published observed external address whose reachability has not
/// been confirmed by the local classifier. Published by cold-start nodes
/// that have not yet accepted an unsolicited inbound handshake and have
/// not yet acquired a relay. Dialers try these after Relay/Direct and
/// before LAN-only fallback
/// and must accept the possibility of a timeout.
Unverified,
/// LAN or other local-scope address. This reuses the old `NATted`
/// variant slot for wire compatibility with older nodes.
#[serde(alias = "NATted")]
Lan,
}
impl AddressType {
/// Priority index for ordering addresses by type. Lower is preferred.
///
/// Relay (0) → Direct (1) → Unverified (2) → Lan (3).
///
/// Used by [`NodeInfo::merge_typed_address`], [`KBucket::replace_node_addresses`],
/// [`DHTNode::addresses_by_priority`], and [`DhtNetworkManager::dialable_addresses_typed`]
/// to maintain a consistent ordering invariant.
pub const fn priority(self) -> u8 {
match self {
Self::Relay => 0,
Self::Direct => 1,
Self::Unverified => 2,
Self::Lan => 3,
}
}
/// Canonicalize an advertised type against the address itself.
///
/// A local-scope IP address is never accepted as Relay, Direct, or
/// Unverified, even if that is what a peer advertised. It may still be
/// stored as [`AddressType::Lan`] so same-LAN/same-WAN peers can use it.
pub(crate) fn for_advertised_address(addr: &MultiAddr, advertised: Self) -> Self {
if addr.ip().is_some_and(is_lan_ip) {
Self::Lan
} else {
advertised
}
}
}
/// Whether `addr` is worth storing in a peer's address record.
///
/// Filters out wildcard binds (`0.0.0.0` / `::`) and port `0` for any
/// IP-based transport (QUIC, TCP, UDP). Such addresses are never dialable:
/// they identify a *bind* socket on the publisher's side, not a routable
/// destination. Older saorsa-core builds (pre-self-address filter)
/// sometimes published their bind addresses verbatim, so receivers kept
/// warning on every dial attempt against the stored wildcard. Dropping
/// them at the store boundary stops the noise without changing dial logic
/// downstream — `is_dialable` (the consumer-side check at
/// [`DhtNetworkManager::is_dialable`]) keeps its existing rejection so an
/// untrusted address that slips through any future store path is still
/// caught at dial time.
///
/// Non-IP transports return `true` (filter does not apply) — the address
/// type itself encodes whatever reachability semantics are appropriate.
///
/// Loopback is intentionally NOT filtered here: local devnets legitimately
/// store loopback addresses, and the per-node `allow_loopback` config lives
/// at [`DhtCoreEngine::replace_node_addresses`].
pub(crate) fn is_storable_address(addr: &MultiAddr) -> bool {
let Some(sa) = addr.socket_addr() else {
return true;
};
!sa.ip().is_unspecified() && sa.port() != 0
}
/// Convenience alias for the internal callers that predate the method form.
const fn type_priority(t: AddressType) -> u8 {
t.priority()
}
/// Duration of no contact after which a peer is considered stale.
/// Stale peers lose trust protection and become eligible for revalidation-based eviction.
const LIVE_THRESHOLD: Duration = Duration::from_secs(900); // 15 minutes
/// Default trust score below which a peer is eligible for swap-out.
#[allow(dead_code)]
const DEFAULT_SWAP_THRESHOLD: f64 = 0.35;
/// Node information for routing.
///
/// The `addresses` field stores one or more typed [`MultiAddr`] values that are
/// always valid. Serializes each as a canonical `/`-delimited string.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeInfo {
pub id: PeerId,
pub addresses: Vec<MultiAddr>,
/// Type tag for each address, parallel to `addresses` by index.
/// Defaults to empty on deserialization (legacy nodes); callers treat
/// untagged addresses as `Unverified`.
#[serde(default)]
pub address_types: Vec<AddressType>,
/// Monotonic timestamp of last successful interaction.
///
/// Stored as an [`AtomicInstant`] so the routing table's touch path
/// can update it under a read lock, not a write lock. Uses `Instant`
/// under the hood to avoid NTP clock-jump issues. Skipped during
/// serialization — deserialized `NodeInfo` defaults to "just seen."
#[serde(skip, default = "AtomicInstant::now")]
pub last_seen: AtomicInstant,
}
impl NodeInfo {
/// Get the socket address from the first address. Returns `None` for
/// non-IP transports or when no addresses are stored.
#[must_use]
pub fn socket_addr(&self) -> Option<SocketAddr> {
self.addresses.first().and_then(MultiAddr::socket_addr)
}
/// Get the IP address from the first address. Returns `None` for
/// non-IP transports or when no addresses are stored.
#[must_use]
pub fn ip(&self) -> Option<IpAddr> {
self.addresses.first().and_then(MultiAddr::ip)
}
/// Return all distinct, canonicalized IP addresses across every address in
/// this node's address list. Useful for IP diversity checks that must
/// consider all addresses, not just the primary one.
fn all_ips(&self) -> HashSet<IpAddr> {
self.addresses
.iter()
.filter_map(|a| a.ip().map(canonicalize_ip))
.collect()
}
/// Drop every non-storable address (wildcard `0.0.0.0` / `::`, port-zero)
/// in place, keeping `addresses` and `address_types` index-aligned.
///
/// This is the record-level equivalent of the single-address filter in
/// [`Self::merge_typed_address`]. Admission paths that derive diversity
/// state from the raw address list (e.g. `DhtCoreEngine::add_node`
/// building `candidate_ips`) must call this first so a record carrying
/// both a wildcard and a routable address is admitted with only the
/// routable address, instead of being rejected wholesale by the
/// unspecified-IP guard before the bucket-side store filter can run.
pub fn retain_storable_addresses(&mut self) {
// Pad address_types so the index alignment holds before we filter
// (legacy records may carry fewer tags than addresses).
while self.address_types.len() < self.addresses.len() {
self.address_types.push(AddressType::Unverified);
}
// Rebuild both vectors in lockstep, keeping only storable addresses.
let addresses = std::mem::take(&mut self.addresses);
let address_types = std::mem::take(&mut self.address_types);
for (addr, addr_type) in addresses.into_iter().zip(address_types) {
if is_storable_address(&addr) {
self.addresses.push(addr);
self.address_types.push(addr_type);
}
}
}
/// Merge a new address with default type `Direct`.
/// Prefer `merge_typed_address` when the type is known.
pub fn merge_address(&mut self, addr: MultiAddr) {
self.merge_typed_address(addr, AddressType::Direct);
}
/// Merge a new address with an explicit type tag.
///
/// Insertion position depends on type priority: Relay → Direct →
/// Unverified → Lan. Relay addresses always go to the front. After
/// insertion, [`Self::enforce_per_ip_family_cap`] prunes the list so
/// the "at most 1 Relay + 1 WAN non-Relay + 1 LAN per IP family"
/// invariant holds.
pub fn merge_typed_address(&mut self, addr: MultiAddr, addr_type: AddressType) {
if !is_storable_address(&addr) {
return;
}
let addr_type = AddressType::for_advertised_address(&addr, addr_type);
// Ensure address_types is in sync with addresses (legacy compat).
// Trailing untagged entries are padded with `Unverified` so we do not
// claim direct-reachability for addresses whose publisher never
// asserted it — the whole point of the typed-record migration.
while self.address_types.len() < self.addresses.len() {
self.address_types.push(AddressType::Unverified);
}
// Remove existing duplicate (same address may be re-classified)
if let Some(pos) = self.addresses.iter().position(|a| a == &addr) {
self.addresses.remove(pos);
if pos < self.address_types.len() {
self.address_types.remove(pos);
}
}
// Insert based on type priority. Insertion order is what the cap
// uses to break "newest wins" ties: Relay / Direct / Unverified
// insert at the front of their tier so the newest sits at the
// lowest index among same-tier entries; Lan appends so the newest
// sits at the highest index.
match addr_type {
AddressType::Relay => {
self.addresses.insert(0, addr);
self.address_types.insert(0, AddressType::Relay);
}
AddressType::Direct => {
let pos = self
.address_types
.iter()
.position(|t| *t != AddressType::Relay)
.unwrap_or(self.addresses.len());
self.addresses.insert(pos, addr);
self.address_types.insert(pos, AddressType::Direct);
}
AddressType::Unverified => {
let pos = self
.address_types
.iter()
.position(|t| *t != AddressType::Relay && *t != AddressType::Direct)
.unwrap_or(self.addresses.len());
self.addresses.insert(pos, addr);
self.address_types.insert(pos, AddressType::Unverified);
}
AddressType::Lan => {
self.addresses.push(addr);
self.address_types.push(AddressType::Lan);
}
}
self.enforce_per_ip_family_cap();
// Last-line guard for non-IP transports (outside the per-family cap).
self.addresses.truncate(MAX_ADDRESSES_PER_NODE);
self.address_types.truncate(self.addresses.len());
}
/// Get the address type at the given index.
///
/// Local-scope IP addresses always return [`AddressType::Lan`], even if
/// the stored or legacy-advertised tag says otherwise. Other untagged
/// addresses return [`AddressType::Unverified`] because legacy records
/// that predate ADR-014 never asserted direct reachability.
pub fn address_type_at(&self, index: usize) -> AddressType {
let advertised = self
.address_types
.get(index)
.copied()
.unwrap_or(AddressType::Unverified);
self.addresses
.get(index)
.map(|addr| AddressType::for_advertised_address(addr, advertised))
.unwrap_or(advertised)
}
/// Enforce the per-IP-family address cap for an external peer.
///
/// For each IP family (IPv4, IPv6 — IPv4-mapped IPv6 is canonicalised
/// to IPv4 so it is counted against the IPv4 slot), keep at most:
///
/// - 1 [`AddressType::Relay`] (newest wins)
/// - 1 of {[`AddressType::Direct`], [`AddressType::Unverified`]} — the
/// entry with the highest priority tier present in that family wins,
/// newer entries within a tier win over older ones
/// - 1 [`AddressType::Lan`] address for same-LAN/same-WAN peers
///
/// That yields the invariant: at most 3 addresses per IP family, and
/// weaker WAN tiers (Unverified) never coexist with a stronger
/// same-family tier (Direct) — they add no useful WAN dial option once
/// the stronger one is known. A dual-stack peer may therefore hold
/// up to 6 IP addresses (3 per family).
///
/// Non-IP transport addresses (Bluetooth, LoRa) are left alone — they
/// have no IP family and are governed only by [`MAX_ADDRESSES_PER_NODE`].
///
/// "Newest wins" is encoded by the insertion positions in
/// [`Self::merge_typed_address`]: Relay, Direct, and Unverified insert
/// at the front of their tier, so the newest entry has the lowest
/// index; Lan appends, so the newest has the highest index.
///
/// This enforces the invariant for *external peers*. The routing
/// table never stores `NodeInfo` for self (admission rejects
/// self-insertion), so the self-record — held by the transport /
/// reachability driver — is unaffected by this cap.
fn enforce_per_ip_family_cap(&mut self) {
while self.address_types.len() < self.addresses.len() {
self.address_types.push(AddressType::Unverified);
}
self.address_types.truncate(self.addresses.len());
// Non-IP addresses are exempt from the per-family cap.
let mut keep: Vec<bool> = self.addresses.iter().map(|a| a.ip().is_none()).collect();
let family_matches = |addr: &MultiAddr, want_v4: bool| match addr.ip() {
Some(ip) => canonicalize_ip(ip).is_ipv4() == want_v4,
None => false,
};
for want_v4 in [true, false] {
let family: Vec<usize> = (0..self.addresses.len())
.filter(|&i| family_matches(&self.addresses[i], want_v4))
.collect();
if family.is_empty() {
continue;
}
// Slot 1: newest Relay for the family (lowest-index Relay).
if let Some(&i) = family
.iter()
.find(|&&i| self.address_types[i] == AddressType::Relay)
{
keep[i] = true;
}
// Slot 2: the single highest-priority WAN entry for the family.
// Precedence is Direct > Unverified. Within each tier, newer is
// at the lowest index.
let best_wan = [AddressType::Direct, AddressType::Unverified]
.iter()
.find_map(|tier| {
family
.iter()
.find(|&&i| self.address_types[i] == *tier)
.copied()
});
if let Some(i) = best_wan {
keep[i] = true;
}
// Slot 3: newest LAN address for peers that can use a
// local-scope route. LAN addresses are independent from WAN
// Direct/Unverified addresses; otherwise hybrid deployments
// would drop the local path that same-WAN peers need.
if let Some(&i) = family
.iter()
.rev()
.find(|&&i| self.address_types[i] == AddressType::Lan)
{
keep[i] = true;
}
}
for i in (0..keep.len()).rev() {
if !keep[i] {
self.addresses.remove(i);
self.address_types.remove(i);
}
}
}
/// Merge a typed address but only if it would upgrade the peer's record.
///
/// Unlike [`Self::merge_typed_address`], which blindly remove-and-reinserts
/// (and thus can *demote* a Relay/Direct entry to Unverified if gossip
/// arrives out of order), this variant no-ops when the address is already
/// present with a tag of equal-or-higher priority. New addresses are
/// always added.
///
/// Returns `true` when the state actually changed (new address appended
/// or an existing tag was promoted to a better tier), `false` otherwise.
///
/// Used for FIND_NODE gossip: a responder's view of a peer's addresses
/// is trusted enough to *upgrade* our local record, but not trusted
/// enough to overwrite an authoritative higher-priority tag we already
/// hold (typically from the peer's own `PublishAddressSet`).
pub fn merge_typed_address_upgrade_only(
&mut self,
addr: MultiAddr,
addr_type: AddressType,
) -> bool {
if !is_storable_address(&addr) {
return false;
}
let addr_type = AddressType::for_advertised_address(&addr, addr_type);
if let Some(pos) = self.addresses.iter().position(|a| a == &addr) {
let existing = self.address_type_at(pos);
if existing.priority() <= addr_type.priority() {
return false;
}
}
self.merge_typed_address(addr, addr_type);
true
}
}
/// K-bucket for Kademlia routing
struct KBucket {
nodes: Vec<NodeInfo>,
max_size: usize,
/// Monotonic timestamp of the last time this bucket was refreshed by
/// live-peer evidence (node added, updated, or touched).
last_refreshed_by_live_peer: Instant,
/// Monotonic timestamp of the last completed refresh probe for this
/// bucket. This is deliberately separate from live-peer refresh so failed
/// or empty probes can be deprioritised without masking stale buckets.
last_probe_finished: AtomicInstant,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct BucketRefreshCandidate {
pub(crate) index: usize,
pub(crate) refresh_debt: Duration,
pub(crate) live_peer_age: Duration,
pub(crate) probe_age: Duration,
}
#[derive(Debug, Clone, Copy)]
enum AddressReplaceMode {
/// The subject peer sent the address set over an authenticated channel.
/// This proves liveness, so the peer and bucket recency are refreshed.
AuthenticatedSelfPublish,
/// A third party repeated a sequence-bearing address set in FIND_NODE
/// gossip. The record may be fresh, but it is not evidence that the
/// subject peer is alive from our point of view.
GossipedRecord,
}
impl AddressReplaceMode {
const fn refreshes_liveness(self) -> bool {
matches!(self, Self::AuthenticatedSelfPublish)
}
}
impl KBucket {
fn new(max_size: usize) -> Self {
let now = Instant::now();
Self {
nodes: Vec::new(),
max_size,
last_refreshed_by_live_peer: now,
last_probe_finished: AtomicInstant::from_instant(now),
}
}
fn add_node(&mut self, mut node: NodeInfo) -> Result<()> {
// Drop wildcard / port-zero addresses up front — they are never
// dialable destinations (they identify a *bind* socket on the
// publisher's side) and storing them just produces dial-time noise
// every time the peer is selected as a candidate.
let pre_filter_len = node.addresses.len();
let mut kept_types = Vec::with_capacity(pre_filter_len);
let mut kept_addrs = Vec::with_capacity(pre_filter_len);
for (i, addr) in node.addresses.drain(..).enumerate() {
if is_storable_address(&addr) {
let ty = node
.address_types
.get(i)
.copied()
.unwrap_or(AddressType::Unverified);
kept_addrs.push(addr);
kept_types.push(ty);
}
}
let stripped = pre_filter_len - kept_addrs.len();
let kept_count = kept_addrs.len();
node.addresses = kept_addrs;
node.address_types = kept_types;
if stripped > 0 {
tracing::debug!(
node_id = %node.id.to_hex(),
stripped,
kept = kept_count,
"stripped non-dialable address(es) from incoming NodeInfo",
);
}
// Reject nodes with no addresses — a node without reachable
// addresses is useless in the routing table and would waste a slot.
if node.addresses.is_empty() {
return Err(anyhow!("NodeInfo has no addresses"));
}
// Cap addresses to prevent memory exhaustion from oversized lists
// arriving via deserialization or direct construction.
node.addresses.truncate(MAX_ADDRESSES_PER_NODE);
node.address_types.truncate(node.addresses.len());
for (i, addr) in node.addresses.iter().enumerate() {
let advertised = node
.address_types
.get(i)
.copied()
.unwrap_or(AddressType::Unverified);
if i < node.address_types.len() {
node.address_types[i] = AddressType::for_advertised_address(addr, advertised);
} else {
node.address_types
.push(AddressType::for_advertised_address(addr, advertised));
}
}
// If the node is already in this bucket, merge addresses using
// type-aware merge so relay addresses stay at the front and
// the parallel address_types vec stays in sync.
if let Some(pos) = self.nodes.iter().position(|n| n.id == node.id) {
let mut existing = self.nodes.remove(pos);
existing.last_seen.store(node.last_seen.load());
for (i, addr) in node.addresses.into_iter().enumerate() {
let addr_type = node
.address_types
.get(i)
.copied()
.unwrap_or(AddressType::Unverified);
existing.merge_typed_address(addr, addr_type);
}
self.nodes.push(existing);
self.last_refreshed_by_live_peer = Instant::now();
return Ok(());
}
if self.nodes.len() < self.max_size {
// External peers are bounded by the per-IP-family cap even on
// first insertion: an incoming `NodeInfo` could carry multiple
// same-family same-type addresses from deserialization or the
// connection handler batching advertised addresses.
node.enforce_per_ip_family_cap();
self.nodes.push(node);
self.last_refreshed_by_live_peer = Instant::now();
Ok(())
} else {
Err(anyhow!(
"K-bucket at capacity ({}/{})",
self.nodes.len(),
self.max_size
))
}
}
fn remove_node(&mut self, node_id: &PeerId) {
self.nodes.retain(|n| &n.id != node_id);
}
/// Slow path: update `last_seen`, merge an address, and reorder the
/// bucket so the touched node becomes the most-recently-seen entry.
///
/// Takes `&mut self` because merging an address may mutate the node's
/// address list. For the fast path (just bumping the timestamp when no
/// address merge is needed) see [`Self::touch_last_seen_if_merge_noop`].
fn touch_node_typed(
&mut self,
node_id: &PeerId,
address: Option<&MultiAddr>,
addr_type: AddressType,
) -> bool {
if let Some(pos) = self.nodes.iter().position(|n| &n.id == node_id) {
self.nodes[pos].last_seen.store_now();
if let Some(addr) = address {
// Loopback injection prevention (Design Section 6.3 rule 4):
let addr_is_loopback = addr
.ip()
.is_some_and(|ip| canonicalize_ip(ip).is_loopback());
let node_has_non_loopback = self.nodes[pos]
.addresses
.iter()
.any(|a| a.ip().is_some_and(|ip| !canonicalize_ip(ip).is_loopback()));
if !(addr_is_loopback && node_has_non_loopback) {
self.nodes[pos].merge_typed_address(addr.clone(), addr_type);
}
}
let node = self.nodes.remove(pos);
self.nodes.push(node);
self.last_refreshed_by_live_peer = Instant::now();
true
} else {
false
}
}
/// Merge `address` (with `addr_type`) into the peer's `NodeInfo` using
/// upgrade-only semantics: never demote a higher-priority tag already
/// on the same address.
///
/// **Pure address-set update.** Does NOT bump the peer's `last_seen`, does
/// NOT reorder the bucket (no MRU promotion), and does NOT bump the
/// bucket's `last_refreshed_by_live_peer` timestamp. Intended for FIND_NODE
/// gossip ingestion, where a responder's typed view of a *third*
/// peer is trusted enough to widen our known address set or promote
/// `Unverified` → `Direct`/`Relay`, but is **not** evidence of:
///
/// * peer-level liveness (covered by `last_seen` — bumping it from
/// gossip would let peers we cannot authenticate with ourselves
/// stay perpetually "fresh", indefinitely deferring the
/// [`DhtCoreEngine::stale_k_closest`] eviction worker), or
/// * bucket-level discovery activity (covered by
/// `last_refreshed_by_live_peer` — the bucket-refresh task uses it to
/// decide when to run a
/// FIND_NODE for a random key in this bucket's range, which is how
/// we discover *new* peers. Gossip about peers we already know is
/// not discovery; bumping `last_refreshed_by_live_peer` from gossip would
/// mask genuinely-stale buckets and silently suppress discovery as long as
/// some neighbour kept gossiping about a peer in that range).
///
/// Returns `true` when the merge changed the peer's address record
/// (a new address was appended, or an existing tag was promoted to a
/// higher-priority tier); `false` when the peer is absent, the
/// loopback-injection guard skipped the merge, or the merge was a
/// no-op (address already present with an equal-or-higher-priority
/// tag). The loopback-injection guard from [`Self::touch_node_typed`]
/// applies equally.
fn merge_typed_address_upgrade_only(
&mut self,
node_id: &PeerId,
address: &MultiAddr,
addr_type: AddressType,
) -> bool {
let Some(pos) = self.nodes.iter().position(|n| &n.id == node_id) else {
return false;
};
let addr_is_loopback = address
.ip()
.is_some_and(|ip| canonicalize_ip(ip).is_loopback());
let node_has_non_loopback = self.nodes[pos]
.addresses
.iter()
.any(|a| a.ip().is_some_and(|ip| !canonicalize_ip(ip).is_loopback()));
if addr_is_loopback && node_has_non_loopback {
return false;
}
self.nodes[pos].merge_typed_address_upgrade_only(address.clone(), addr_type)
}
/// Fast path: if `node_id` is in this bucket AND the optional address
/// merge would be a no-op (address is `None`, address is already
/// present **with the same `addr_type`**, or the loopback-injection
/// rule would skip the merge), atomically bump `last_seen` in place
/// and return `Some(true)`.
///
/// Returns:
/// - `Some(true)` — fast path succeeded, `last_seen` updated.
/// - `Some(false)` — node is not in this bucket.
/// - `None` — the address is either not yet present, or present with
/// a *different* type classification (e.g. learned as `Direct`,
/// now being promoted to `Relay`). The slow path must run so
/// [`merge_typed_address`] can re-insert at the type-priority
/// position. Without this guard the relay-promotion path in the
/// network bridge silently degrades to a `last_seen` bump and the
/// address ordering invariant is broken.
///
/// Only requires `&self` — no bucket mutation, just an atomic store on
/// [`NodeInfo::last_seen`]. This lets the hot touch path (called on
/// every inbound DHT message) run under a read lock on the routing
/// table instead of an exclusive write lock.
fn touch_last_seen_if_merge_noop(
&self,
node_id: &PeerId,
address: Option<&MultiAddr>,
addr_type: AddressType,
) -> Option<bool> {
let Some(pos) = self.nodes.iter().position(|n| &n.id == node_id) else {
return Some(false);
};
let node = &self.nodes[pos];
let merge_is_noop = match address {
None => true,
Some(addr) => {
let addr_type = AddressType::for_advertised_address(addr, addr_type);
// Already in the list → merge would reinsert at the same
// position, which is a no-op only if the existing entry
// has the same type classification. If the type differs
// we MUST escalate to the slow path so merge_typed_address
// can re-order by type priority.
if let Some(existing_pos) = node.addresses.iter().position(|a| a == addr) {
node.address_type_at(existing_pos) == addr_type
} else {
// Loopback-injection skip: if the candidate is
// loopback and the node already has a non-loopback
// address, the slow path would skip the merge entirely.
let addr_is_loopback = addr
.ip()
.is_some_and(|ip| canonicalize_ip(ip).is_loopback());
let node_has_non_loopback = node
.addresses
.iter()
.any(|a| a.ip().is_some_and(|ip| !canonicalize_ip(ip).is_loopback()));
addr_is_loopback && node_has_non_loopback
}
}
};
if merge_is_noop {
node.last_seen.store_now();
Some(true)
} else {
None
}
}
fn get_nodes(&self) -> &[NodeInfo] {
&self.nodes
}
fn find_node(&self, node_id: &PeerId) -> Option<&NodeInfo> {
self.nodes.iter().find(|n| &n.id == node_id)
}
/// Overwrite a peer's address list with `typed_addresses`.
///
/// Full-replace semantics for the `PublishAddressSet` wire op: the sender
/// is authoritative about its own reachable addresses and the receiver
/// drops any state the sender omits (e.g., a stale relay address after
/// the relay session closes).
///
/// The new list is sorted by [`type_priority`] (Relay → Direct → Lan)
/// to preserve the same ordering invariant that [`NodeInfo::merge_typed_address`]
/// maintains, then truncated to [`MAX_ADDRESSES_PER_NODE`].
///
/// Returns `true` when the peer was found and its addresses replaced,
/// `false` when the peer is not in this bucket.
fn replace_node_addresses(
&mut self,
node_id: &PeerId,
typed_addresses: Vec<(MultiAddr, AddressType)>,
) -> bool {
self.replace_node_addresses_with_mode(
node_id,
typed_addresses,
AddressReplaceMode::AuthenticatedSelfPublish,
)
}
/// Overwrite a peer's address list from a sequence-bearing FIND_NODE
/// gossip record without updating peer liveness or bucket recency.
fn replace_node_addresses_from_gossip(
&mut self,
node_id: &PeerId,
typed_addresses: Vec<(MultiAddr, AddressType)>,
) -> bool {
self.replace_node_addresses_with_mode(
node_id,
typed_addresses,
AddressReplaceMode::GossipedRecord,
)
}
fn replace_node_addresses_with_mode(
&mut self,
node_id: &PeerId,
typed_addresses: Vec<(MultiAddr, AddressType)>,
mode: AddressReplaceMode,
) -> bool {
let Some(pos) = self.nodes.iter().position(|n| &n.id == node_id) else {
return false;
};
let input_was_non_empty = !typed_addresses.is_empty();
let mut typed: Vec<(MultiAddr, AddressType)> = typed_addresses
.into_iter()
.filter(|(addr, _)| is_storable_address(addr))
.map(|(addr, ty)| {
let ty = AddressType::for_advertised_address(&addr, ty);
(addr, ty)
})
.collect();
// If filtering emptied a non-empty input (publisher sent only
// wildcards or other non-storable addresses), refuse the replace
// entirely. The caller (KademliaRoutingTable::replace_node_addresses_with_mode)
// gates `last_publish_seqs` on this return value, so refusing here
// preserves the peer's prior good addresses AND leaves the door
// open for a subsequent CORRECT publish at the same sequence number
// to land. Without this guard we would (a) wipe a working address
// list and (b) lock the peer out of future republishes ≤ this seq.
if typed.is_empty() && input_was_non_empty {
return false;
}
typed.sort_by_key(|(_, t)| type_priority(*t));
typed.truncate(MAX_ADDRESSES_PER_NODE);
let (addresses, address_types): (Vec<_>, Vec<_>) = typed.into_iter().unzip();
{
let node = &mut self.nodes[pos];
node.addresses = addresses;
node.address_types = address_types;
// Apply the per-IP-family cap on the incoming publish set: a
// peer is not expected to publish more than Relay + one WAN
// address + one LAN address per family, but a misbehaving sender
// could try to exceed that. The cap enforces the invariant
// regardless.
node.enforce_per_ip_family_cap();
}
if mode.refreshes_liveness() {
self.nodes[pos].last_seen.store_now();
// Move to tail (most recently seen).
let node = self.nodes.remove(pos);
self.nodes.push(node);
self.last_refreshed_by_live_peer = Instant::now();
}
true
}
}
/// Kademlia routing table
pub struct KademliaRoutingTable {
buckets: Vec<KBucket>,
node_id: PeerId,
/// Highest `PublishAddressSet` sequence number received from each peer.
///
/// Republishes with a lower-or-equal sequence than the stored value are
/// discarded to close the "relay-lost → relay-acquired" reorder race.
/// Stored alongside the routing table so the sequence check and the
/// address replacement are atomic under the same write lock.
last_publish_seqs: HashMap<PeerId, u64>,
}
impl KademliaRoutingTable {
fn new(node_id: PeerId, k_value: usize) -> Self {
let mut buckets = Vec::new();
for _ in 0..KADEMLIA_BUCKET_COUNT {
buckets.push(KBucket::new(k_value));
}
Self {
buckets,
node_id,
last_publish_seqs: HashMap::new(),
}
}
fn add_node(&mut self, node: NodeInfo) -> Result<()> {
let bucket_index = self
.get_bucket_index(&node.id)
.ok_or_else(|| anyhow!("cannot insert self into routing table"))?;
self.buckets[bucket_index].add_node(node)
}
fn remove_node(&mut self, node_id: &PeerId) {
if let Some(bucket_index) = self.get_bucket_index(node_id) {
self.buckets[bucket_index].remove_node(node_id);
}
self.last_publish_seqs.remove(node_id);
}
fn publish_seq_for(&self, node_id: &PeerId) -> u64 {
self.last_publish_seqs.get(node_id).copied().unwrap_or(0)
}
/// Merge a legacy relay hint only while the peer has no authoritative
/// `PublishAddressSet` record.
///
/// Once a publish sequence has been observed, the stored address list is
/// the owner's complete self-record for that sequence. Allowing legacy
/// ADD_ADDRESS hints to mutate it would let stale relay allocations
/// reappear after a newer direct-only publish removed them.
fn touch_legacy_relay_hint_if_unsequenced(
&mut self,
node_id: &PeerId,
address: &MultiAddr,
) -> bool {
if self.publish_seq_for(node_id) != 0 {
return false;
}
self.touch_node(node_id, Some(address), AddressType::Relay)
}
/// Replace a peer's advertised address list under a monotonic sender
/// sequence check.
///
/// Sequence `0` is reserved as the "no sequence observed" sentinel and is
/// discarded. Stale republishes (`seq <= stored seq for this peer`) are
/// also discarded. When `seq` is strictly greater than any previously
/// observed sequence from `node_id`, the peer's bucket entry is rewritten via
/// [`KBucket::replace_node_addresses`] and the stored sequence is
/// advanced. The whole check-and-apply runs under the caller's write
/// lock on the routing table, so concurrent republishes from the same
/// sender are serialised.
///
/// Returns `true` when addresses were replaced; `false` when the peer
/// is absent from the routing table or the message had an invalid/stale
/// sequence.
fn replace_node_addresses(
&mut self,
node_id: &PeerId,
typed_addresses: Vec<(MultiAddr, AddressType)>,
seq: u64,
) -> bool {
self.replace_node_addresses_with_mode(
node_id,
typed_addresses,
seq,
AddressReplaceMode::AuthenticatedSelfPublish,
)
}
fn replace_node_addresses_from_gossip(
&mut self,
node_id: &PeerId,
typed_addresses: Vec<(MultiAddr, AddressType)>,
seq: u64,
) -> bool {
self.replace_node_addresses_with_mode(
node_id,
typed_addresses,
seq,
AddressReplaceMode::GossipedRecord,
)
}
fn replace_node_addresses_with_mode(
&mut self,
node_id: &PeerId,
typed_addresses: Vec<(MultiAddr, AddressType)>,
seq: u64,
mode: AddressReplaceMode,
) -> bool {
if seq == 0 {
return false;
}
if let Some(&stored) = self.last_publish_seqs.get(node_id)
&& seq <= stored
{
return false;
}
let Some(bucket_index) = self.get_bucket_index(node_id) else {
return false;
};
let applied = match mode {
AddressReplaceMode::AuthenticatedSelfPublish => {
self.buckets[bucket_index].replace_node_addresses(node_id, typed_addresses)
}
AddressReplaceMode::GossipedRecord => self.buckets[bucket_index]
.replace_node_addresses_from_gossip(node_id, typed_addresses),
};
if applied {
self.last_publish_seqs.insert(*node_id, seq);
}
applied
}
/// Update `last_seen` (and optionally merge a typed address) for a node and
/// move it to the tail of its k-bucket. Returns `true` if the node was found.
fn touch_node(
&mut self,
node_id: &PeerId,
address: Option<&MultiAddr>,
addr_type: AddressType,
) -> bool {
match self.get_bucket_index(node_id) {
Some(bucket_index) => {
self.buckets[bucket_index].touch_node_typed(node_id, address, addr_type)
}
None => false,
}
}
/// Pure address-set merge for an existing routing-table entry.
///
/// Like [`Self::touch_node`] but never demotes a higher-priority tag
/// on the same address, and does NOT bump `last_seen` or reorder the
/// bucket — see [`KBucket::merge_typed_address_upgrade_only`] for the
/// rationale (gossip ingestion must not refresh peer liveness).
///
/// Returns `true` when the merge changed the peer's address record;
/// `false` for missing peer, no-op merge, or loopback-skip.
fn merge_typed_address_upgrade_only(
&mut self,
node_id: &PeerId,
address: &MultiAddr,
addr_type: AddressType,
) -> bool {
match self.get_bucket_index(node_id) {
Some(bucket_index) => self.buckets[bucket_index]
.merge_typed_address_upgrade_only(node_id, address, addr_type),
None => false,
}
}
/// Fast path for the touch operation.
///
/// Returns:
/// - `Some(true)` — node found and `last_seen` updated atomically.
/// - `Some(false)` — node is not in the routing table (fast-path result
/// is authoritative; no fallback needed).
/// - `None` — node is present but the address merge would not be a
/// no-op (either the address is missing, or its type classification
/// differs from `addr_type`); the caller must escalate to
/// [`Self::touch_node`] under a write lock.
///
/// Only takes `&self` so this can run under a `RwLock::read()` guard.
fn try_touch_last_seen(
&self,
node_id: &PeerId,
address: Option<&MultiAddr>,
addr_type: AddressType,
) -> Option<bool> {
let bucket_index = self.get_bucket_index(node_id)?;
self.buckets[bucket_index].touch_last_seen_if_merge_noop(node_id, address, addr_type)
}
fn find_closest_nodes(&self, key: &DhtKey, count: usize) -> Vec<NodeInfo> {
// Collect ALL entries from every bucket. Bucket index correlates with
// distance from *self*, not from key K — peers in distant buckets can
// be closer to K than peers in nearby buckets. The routing table holds
// at most 256 * K_BUCKET_SIZE entries, so a full scan is trivially fast.
let mut candidates: Vec<(NodeInfo, [u8; 32])> = Vec::with_capacity(count * 2);
for bucket in &self.buckets {
for node in bucket.get_nodes() {
let distance = xor_distance_bytes(node.id.to_bytes(), key.as_bytes());
candidates.push((node.clone(), distance));
}
}
// Sort by distance
candidates.sort_by_key(|a| a.1);
// Return top `count` nodes
candidates
.into_iter()
.take(count)
.map(|(node, _)| node)
.collect()
}
fn find_closest_nodes_with_publish_seq(
&self,
key: &DhtKey,
count: usize,
) -> Vec<(NodeInfo, u64)> {
self.find_closest_nodes(key, count)
.into_iter()
.map(|node| {
let seq = self.publish_seq_for(&node.id);
(node, seq)
})
.collect()
}
/// Returns the k-bucket index for a key, or `None` when the key equals
/// the local node ID (XOR distance is zero — no valid bucket exists).
fn get_bucket_index_for_key(&self, key: &DhtKey) -> Option<usize> {
let distance = xor_distance_bytes(self.node_id.to_bytes(), key.as_bytes());
// Find first bit that differs
for i in 0..256 {
let byte_index = i / 8;
let bit_index = 7 - (i % 8);
if (distance[byte_index] >> bit_index) & 1 == 1 {
return Some(i);
}
}
None // XOR distance is zero — key equals local node ID
}
/// Look up a node by its exact peer ID. O(K) scan of the target bucket.
fn find_node_by_id(&self, node_id: &PeerId) -> Option<&NodeInfo> {
let bucket_index = self.get_bucket_index(node_id)?;
self.buckets[bucket_index].find_node(node_id)
}
/// Total number of nodes across all buckets.
pub fn node_count(&self) -> usize {
self.buckets.iter().map(|b| b.get_nodes().len()).sum()
}
/// Return all nodes from every k-bucket.
///
/// The routing table holds at most `256 * k_value` entries, so
/// collecting them into a `Vec` is inexpensive.
fn all_nodes(&self) -> Vec<NodeInfo> {
self.buckets
.iter()
.flat_map(|b| b.get_nodes().iter().cloned())
.collect()
}
fn all_nodes_with_publish_seq(&self) -> Vec<(NodeInfo, u64)> {
self.all_nodes()
.into_iter()
.map(|node| {
let seq = self.publish_seq_for(&node.id);
(node, seq)
})
.collect()
}
/// Returns the k-bucket index for a peer, or `None` when the peer ID
/// equals the local node ID (self-insertion is forbidden).
fn get_bucket_index(&self, node_id: &PeerId) -> Option<usize> {
self.get_bucket_index_for_key(&DhtKey::from_bytes(*node_id.to_bytes()))
}
/// Compute the K-closest peer IDs to self.
fn k_closest_ids(&self, k: usize) -> Vec<PeerId> {
self.find_closest_nodes(&self.node_id, k)
.into_iter()
.map(|n| n.id)
.collect()
}
/// Return refresh candidates for every bucket.
///
/// Refresh debt is bounded by both clocks: recent live-peer evidence and a
/// recent refresh probe each make the bucket low priority. This keeps bucket
/// maintenance continuous without needing a separate stale-age threshold.
fn bucket_refresh_candidates(&self) -> Vec<BucketRefreshCandidate> {
let now = Instant::now();
self.buckets
.iter()
.enumerate()
.map(|(index, bucket)| {
let live_peer_age =
now.saturating_duration_since(bucket.last_refreshed_by_live_peer);
let probe_age = now.saturating_duration_since(bucket.last_probe_finished.load());
let refresh_debt = live_peer_age.min(probe_age);
BucketRefreshCandidate {
index,
refresh_debt,
live_peer_age,
probe_age,
}
})
.collect()
}
fn mark_bucket_probe_finished(&self, bucket_idx: usize) -> bool {
let Some(bucket) = self.buckets.get(bucket_idx) else {
return false;
};
bucket.last_probe_finished.store_now();
true
}
}
// ---------------------------------------------------------------------------
// Address parsing and subnet masking helpers for diversity checks
// ---------------------------------------------------------------------------
/// One entry in the tier-check array used by `find_ip_swap_in_scope`.
type IpSwapTier = (
usize,
usize,
Option<(PeerId, [u8; 32], Instant)>,
&'static str,
);
/// Zero out the host bits of an IPv4 address beyond `prefix_len`.
fn mask_ipv4(addr: Ipv4Addr, prefix_len: u8) -> Ipv4Addr {
let bits = u32::from(addr);
let mask = if prefix_len >= 32 {
u32::MAX
} else {
u32::MAX << (32 - prefix_len)
};
Ipv4Addr::from(bits & mask)
}
/// Zero out the host bits of an IPv6 address beyond `prefix_len`.
fn mask_ipv6(addr: Ipv6Addr, prefix_len: u8) -> Ipv6Addr {
let bits = u128::from(addr);
let mask = if prefix_len >= 128 {
u128::MAX
} else {
u128::MAX << (128 - prefix_len)
};
Ipv6Addr::from(bits & mask)
}
/// Default K parameter — number of closest nodes per bucket.
/// Used only by test helpers; production code reads from config.
#[cfg(test)]
const DEFAULT_K: usize = 20;
// IP_EXACT_LIMIT and ip_subnet_limit are imported from crate::security
// to keep a single source of truth for diversity constants.
/// Number of K-buckets in Kademlia routing table (one per bit in 256-bit key space)
const KADEMLIA_BUCKET_COUNT: usize = 256;
/// Trust score above which a peer is protected from swap-closer eviction.
/// Well-trusted peers (score >= 0.7) keep their routing table slot even
/// when a closer but less-proven peer arrives.
const TRUST_PROTECTION_THRESHOLD: f64 = 0.7;
/// Diagnostic statistics for the routing table.
#[allow(dead_code)]
pub struct RoutingTableStats {
/// Total peers across all buckets.
pub total_peers: usize,
/// Per-bucket peer counts (256 entries).
pub bucket_counts: Vec<usize>,
/// Number of peers whose last_seen exceeds LIVE_THRESHOLD.
pub stale_peer_count: usize,
}
/// Events emitted by routing table mutations.
///
/// These are returned from admission and removal operations so the caller
/// (DhtNetworkManager) can broadcast them without re-acquiring the lock.
#[derive(Debug, Clone)]
pub enum RoutingTableEvent {
/// A new peer was inserted into the routing table.
PeerAdded(PeerId),
/// A peer was removed from the routing table (swap-out, eviction, or departure).
PeerRemoved(PeerId),
/// The set of K-closest peers to self changed.
/// Fields retained for the design API; the network manager uses snapshot
/// diffing instead of consuming these directly.
#[allow(dead_code)]
KClosestPeersChanged { old: Vec<PeerId>, new: Vec<PeerId> },
}
/// Result of a peer admission attempt, including stale revalidation requests.
///
/// When a candidate cannot be admitted because the target bucket is full and no
/// swap-closer peer exists, the core engine checks for stale peers that could be
/// revalidated. If stale peers are found, the caller (DhtNetworkManager) must
/// release the write lock, ping the stale peers, evict non-responders, and then
/// call [`DhtCoreEngine::re_evaluate_admission`].
#[derive(Debug)]
pub enum AdmissionResult {
/// Peer was admitted (inserted or updated). Contains emitted events.
Admitted(Vec<RoutingTableEvent>),
/// Admission requires stale peer revalidation before it can proceed.
/// The caller must release the write lock, ping the stale peers, evict
/// non-responders, and then call `re_evaluate_admission`.
StaleRevalidationNeeded {
/// The candidate peer waiting for admission.
candidate: NodeInfo,
/// All candidate IPs (for re-evaluation after revalidation).
candidate_ips: Vec<IpAddr>,
/// The candidate's target bucket index (for per-bucket revalidation guard).
candidate_bucket_idx: usize,
/// Stale peers that should be pinged. Each entry is `(peer_id, bucket_index)`.
/// May include peers from multiple buckets when routing-neighborhood
/// violators are merged (Design Section 7.5).
stale_peers: Vec<(PeerId, usize)>,
},
}
/// Main DHT Core Engine
pub struct DhtCoreEngine {
node_id: PeerId,
routing_table: Arc<RwLock<KademliaRoutingTable>>,
/// Kademlia K parameter — bucket capacity and close-group size.
k_value: usize,
/// IP diversity limits — checked against the live routing table on each
/// `add_node` call rather than maintained as incremental counters.
ip_diversity_config: IPDiversityConfig,
/// Allow loopback addresses in the routing table.
///
/// Set once at construction from `NodeConfig.allow_loopback` and never
/// mutated — `NodeConfig` is the single source of truth. Kept separate
/// from `IPDiversityConfig` to prevent duplication and drift.
allow_loopback: bool,
/// Trust score below which a peer is eligible for swap-out.
swap_threshold: f64,
/// Duration of no contact after which a peer is considered stale.
/// Defaults to [`LIVE_THRESHOLD`]; overridden in tests to avoid
/// `Instant` subtraction overflow on Windows (where `Instant` starts
/// at process creation and cannot represent times before it).
live_threshold: Duration,
/// Shutdown token for background maintenance tasks
shutdown: CancellationToken,
}
impl DhtCoreEngine {
/// Create new DHT engine for testing with default K value.
#[cfg(test)]
pub fn new_for_tests(node_id: PeerId) -> Result<Self> {
Self::new(node_id, DEFAULT_K, false, DEFAULT_SWAP_THRESHOLD)
}
/// Expose the routing table for test-only direct manipulation (e.g. setting `last_seen`).
#[cfg(test)]
pub(crate) fn routing_table_for_test(&self) -> &Arc<RwLock<KademliaRoutingTable>> {
&self.routing_table
}
/// Create a new DHT core engine.
pub(crate) fn new(
node_id: PeerId,
k_value: usize,
allow_loopback: bool,
swap_threshold: f64,
) -> Result<Self> {
if k_value < 4 {
return Err(anyhow!("k_value must be >= 4 (got {k_value})"));
}
if !(0.0..1.0).contains(&swap_threshold) || swap_threshold.is_nan() {
return Err(anyhow!(
"swap_threshold must be in [0.0, 1.0), got {swap_threshold}"
));
}
Ok(Self {
node_id,
routing_table: Arc::new(RwLock::new(KademliaRoutingTable::new(node_id, k_value))),
k_value,
ip_diversity_config: IPDiversityConfig::default(),
allow_loopback,
swap_threshold,
live_threshold: LIVE_THRESHOLD,
shutdown: CancellationToken::new(),
})
}
/// Override the IP diversity configuration.
pub fn set_ip_diversity_config(&mut self, config: IPDiversityConfig) {
self.ip_diversity_config = config;
}
/// Set whether loopback addresses are allowed in the routing table.
#[cfg(test)]
pub fn set_allow_loopback(&mut self, allow: bool) {
self.allow_loopback = allow;
}
/// Override the live threshold for testing.
///
/// On Windows, `Instant` starts at process creation, so tests cannot
/// subtract large durations without overflow. Setting a small threshold
/// (e.g. 1 second) lets tests use a correspondingly small subtraction.
#[cfg(test)]
pub fn set_live_threshold(&mut self, threshold: Duration) {
self.live_threshold = threshold;
}
/// Get this node's peer ID.
#[allow(dead_code)]
pub fn node_id(&self) -> &PeerId {
&self.node_id
}
/// Return K-closest peer IDs whose `last_seen` exceeds the live threshold.
///
/// Used by the self-lookup task to revalidate stale close-group members
/// and evict offline peers promptly.
pub(crate) async fn stale_k_closest(&self) -> Vec<PeerId> {
let routing = self.routing_table.read().await;
routing
.find_closest_nodes(&self.node_id, self.k_value)
.into_iter()
.filter(|n| n.last_seen.elapsed() > self.live_threshold)
.map(|n| n.id)
.collect()
}
/// Return refresh candidates for every bucket.
pub(crate) async fn bucket_refresh_candidates(&self) -> Vec<BucketRefreshCandidate> {
self.routing_table.read().await.bucket_refresh_candidates()
}
/// Mark a bucket refresh probe as completed without changing live-peer
/// freshness.
pub(crate) async fn mark_bucket_probe_finished(&self, bucket_idx: usize) -> bool {
self.routing_table
.read()
.await
.mark_bucket_probe_finished(bucket_idx)
}
/// Generate a random key that would fall into the specified bucket index
/// relative to this node's ID.
///
/// Used for bucket refresh: looking up a random key in a selected bucket's
/// range discovers new peers that populate that bucket.
///
/// Returns `None` if `bucket_idx` is out of range (>= 256).
pub(crate) fn generate_random_key_for_bucket(&self, bucket_idx: usize) -> Option<DhtKey> {
if bucket_idx >= KADEMLIA_BUCKET_COUNT {
return None;
}
let self_bytes = self.node_id.to_bytes();
// Construct a XOR distance with its leading set bit at position bucket_idx.
// Bucket index i means the first differing bit (from MSB) is at position i.
let byte_idx = bucket_idx / 8;
let bit_idx = 7 - (bucket_idx % 8);
// Use a random PeerId as an entropy source (avoids `rng.gen()` which
// conflicts with the `gen` keyword reserved in Rust edition 2024).
let random_bytes = PeerId::random();
let mut distance = [0u8; 32];
// Set the leading bit at bucket_idx
distance[byte_idx] = 1 << bit_idx;
// Fill random bits below the leading bit in the same byte
let below_mask = (1u8 << bit_idx).wrapping_sub(1);
distance[byte_idx] |= random_bytes.to_bytes()[byte_idx] & below_mask;
// Fill remaining bytes randomly
distance[(byte_idx + 1)..32].copy_from_slice(&random_bytes.to_bytes()[(byte_idx + 1)..32]);
// Key = self XOR distance
let mut result = [0u8; 32];
for (i, byte) in result.iter_mut().enumerate() {
*byte = self_bytes[i] ^ distance[i];
}
Some(DhtKey::from_bytes(result))
}
/// Number of peers currently in the routing table.
pub async fn routing_table_size(&self) -> usize {
self.routing_table.read().await.node_count()
}
/// Remove a peer from the routing table by ID.
///
/// Returns events describing the mutation (`PeerRemoved` if the peer was
/// present, and optionally `KClosestPeersChanged` when the close-group shifted).
/// Returns an empty vec if the peer was not in the routing table.
pub async fn remove_node_by_id(&mut self, peer_id: &PeerId) -> Vec<RoutingTableEvent> {
let mut routing = self.routing_table.write().await;
// Only emit events if the peer is actually present.
if routing.find_node_by_id(peer_id).is_none() {
return Vec::new();
}
let k_before = routing.k_closest_ids(self.k_value);
routing.remove_node(peer_id);
let k_after = routing.k_closest_ids(self.k_value);
let mut events = vec![RoutingTableEvent::PeerRemoved(*peer_id)];
if k_before != k_after {
events.push(RoutingTableEvent::KClosestPeersChanged {
old: k_before,
new: k_after,
});
}
events
}
/// Signal background tasks to stop
pub fn signal_shutdown(&self) {
self.shutdown.cancel();
}
/// Find nodes closest to a key
pub async fn find_nodes(&self, key: &DhtKey, count: usize) -> Result<Vec<NodeInfo>> {
let routing = self.routing_table.read().await;
Ok(routing.find_closest_nodes(key, count))
}
/// Find nodes closest to a key and include the latest authoritative
/// `PublishAddressSet` sequence known for each returned record.
pub async fn find_nodes_with_publish_seq(
&self,
key: &DhtKey,
count: usize,
) -> Result<Vec<(NodeInfo, u64)>> {
let routing = self.routing_table.read().await;
Ok(routing.find_closest_nodes_with_publish_seq(key, count))
}
/// Find nodes closest to a key, including self as a candidate.
/// Used by consumers for storage responsibility determination.
#[allow(dead_code)]
pub async fn find_nodes_with_self(&self, key: &DhtKey, count: usize) -> Result<Vec<NodeInfo>> {
let routing = self.routing_table.read().await;
let mut candidates = routing.find_closest_nodes(key, count);
// Insert self as a candidate
let self_info = NodeInfo {
id: self.node_id,
addresses: vec![],
address_types: vec![],
last_seen: AtomicInstant::now(),
};
let self_dist = xor_distance_bytes(self.node_id.to_bytes(), key.as_bytes());
// Find insertion point to maintain sorted order
let pos = candidates
.iter()
.position(|n| xor_distance_bytes(n.id.to_bytes(), key.as_bytes()) > self_dist)
.unwrap_or(candidates.len());
candidates.insert(pos, self_info);
candidates.truncate(count);
Ok(candidates)
}
/// Look up a node's addresses from the routing table by peer ID.
///
/// Returns the stored addresses if the peer is in the routing table,
/// an empty vec otherwise. O(K) scan of the target k-bucket.
///
/// Production code paths now use [`Self::get_node_addresses_typed`]
/// for address-type-aware priority sorting (ADR-014). This untyped
/// variant is retained as a public API for external consumers and is
/// exercised by in-crate tests.
#[allow(dead_code)]
pub async fn get_node_addresses(&self, peer_id: &PeerId) -> Vec<MultiAddr> {
let routing = self.routing_table.read().await;
routing
.find_node_by_id(peer_id)
.map(|n| n.addresses.clone())
.unwrap_or_default()
}
/// Get a peer's addresses paired with their [`AddressType`] tags.
///
/// Used by [`crate::dht_network_manager::DhtNetworkManager::peer_addresses_for_dial_typed`]
/// to sort candidates by type priority (Relay first) per ADR-014.
pub async fn get_node_addresses_typed(
&self,
peer_id: &PeerId,
) -> Vec<(MultiAddr, AddressType)> {
let routing = self.routing_table.read().await;
routing
.find_node_by_id(peer_id)
.map(|n| {
n.addresses
.iter()
.enumerate()
.map(|(i, addr)| (addr.clone(), n.address_type_at(i)))
.collect()
})
.unwrap_or_default()
}
/// Check whether a peer is present in the routing table.
pub async fn has_node(&self, peer_id: &PeerId) -> bool {
let routing = self.routing_table.read().await;
routing.find_node_by_id(peer_id).is_some()
}
/// Return every peer currently in the routing table.
///
/// The routing table holds at most `256 * k_value` entries, so
/// collecting them is inexpensive.
#[allow(dead_code)]
pub async fn all_nodes(&self) -> Vec<NodeInfo> {
self.routing_table.read().await.all_nodes()
}
pub async fn all_nodes_with_publish_seq(&self) -> Vec<(NodeInfo, u64)> {
self.routing_table.read().await.all_nodes_with_publish_seq()
}
/// Build diagnostic statistics for the routing table.
#[allow(dead_code)]
pub async fn routing_table_stats(&self) -> RoutingTableStats {
let routing = self.routing_table.read().await;
let bucket_counts: Vec<usize> = routing
.buckets
.iter()
.map(|b| b.get_nodes().len())
.collect();
let total_peers: usize = bucket_counts.iter().sum();
let stale_peer_count = routing
.buckets
.iter()
.flat_map(|b| b.get_nodes())
.filter(|n| n.last_seen.elapsed() > self.live_threshold)
.count();
RoutingTableStats {
total_peers,
bucket_counts,
stale_peer_count,
}
}
/// Record a successful interaction with a peer by updating its `last_seen`
/// timestamp (and optionally its address) and moving it to the tail of its
/// k-bucket (most recently seen).
///
/// Standard Kademlia: any successful RPC implicitly proves liveness, so the
/// routing table should reflect this without requiring dedicated pings.
/// Passing the current address ensures stale addresses are replaced when a
/// peer reconnects from a different endpoint.
///
/// Non-local addresses passed here are classified
/// [`AddressType::Unverified`]: a successful RPC with us proves
/// reachability from *us* to the peer (possibly through a NAT mapping we
/// opened), not public cold-dialability. Local-scope addresses are
/// canonicalized to [`AddressType::Lan`] by the typed merge path. Callers
/// with authoritative type information must use [`Self::touch_node_typed`].
pub async fn touch_node(&self, node_id: &PeerId, address: Option<&MultiAddr>) -> bool {
let mut routing = self.routing_table.write().await;
routing.touch_node(node_id, address, AddressType::Unverified)
}
/// Touch a peer's routing-table entry with an optional typed address.
///
/// **Fast path (read lock + atomic store):** If the peer is in the
/// routing table and the address merge would be a no-op (address is
/// `None`, or it's already in the peer's list, or the loopback rule
/// would skip it), this updates `last_seen` atomically under a read
/// lock with no bucket mutation.
///
/// **Slow path (write lock):** If an actual address merge is needed,
/// the method escalates to a write lock and uses the full
/// `touch_node` flow.
///
/// This split removes the write lock from the common hot path — at
/// 1000 nodes the touch is called on every inbound DHT message, and
/// the write-lock version was the dominant contention point on the
/// routing table.
pub async fn touch_node_typed(
&self,
node_id: &PeerId,
address: Option<&MultiAddr>,
addr_type: AddressType,
) -> bool {
// Fast path: read lock + atomic last_seen store. The fast path
// ALSO requires the address (if any) to already be present with
// the same type classification — see `touch_last_seen_if_merge_noop`.
// Promotion of an existing address from one classification to
// another (e.g. Direct → Relay) is intentionally pushed to the
// slow path so the bucket-level `merge_typed_address` can re-order.
{
let routing = self.routing_table.read().await;
match routing.try_touch_last_seen(node_id, address, addr_type) {
Some(true) => return true,
Some(false) => return false,
// Merge is non-trivial — fall through to the write-lock path.
None => {}
}
}
// Slow path: address merge or re-classification needed, take write lock.
let mut routing = self.routing_table.write().await;
routing.touch_node(node_id, address, addr_type)
}
/// Merge a peer-advertised relay hint only if the peer has never sent an
/// authoritative `PublishAddressSet`.
///
/// Legacy ADD_ADDRESS frames remain useful for peers that predate typed
/// self-record publishing. After any publish sequence has been stored for
/// the peer, only a newer `PublishAddressSet` may change its address list.
pub async fn touch_legacy_relay_hint_if_unsequenced(
&self,
node_id: &PeerId,
address: &MultiAddr,
) -> bool {
let mut routing = self.routing_table.write().await;
routing.touch_legacy_relay_hint_if_unsequenced(node_id, address)
}
/// Merge `address` (with `addr_type`) into an existing peer's record
/// using upgrade-only semantics: never demote a higher-priority tag
/// already on the same address.
///
/// **Pure address-set update.** Does NOT bump `last_seen` and does
/// NOT reorder the bucket. Intended for FIND_NODE gossip ingestion:
/// a responder's typed view is trusted enough to widen our record
/// (new addresses) or promote a cold-start `Unverified` to
/// `Direct`/`Relay`, but it is **not** evidence that the subject
/// peer is alive from *our* point of view — only direct authenticated
/// activity (handled by [`Self::touch_node_typed`] via
/// [`crate::dht_network_manager::DhtNetworkManager::handle_dht_message`])
/// refreshes liveness.
///
/// Without this gating, a chatty network would defer
/// [`Self::stale_k_closest`] eviction indefinitely for every peer
/// some authenticated neighbour happens to mention — including
/// peers we cannot authenticate with ourselves (e.g., older
/// protocol versions whose identity exchange always times out).
///
/// Returns `true` when the merge changed the peer's address record
/// (a new address was appended, or an existing tag was promoted to
/// a higher-priority tier); `false` for missing peer, no-op merge,
/// or loopback-skip — see
/// [`KBucket::merge_typed_address_upgrade_only`] for the full
/// classification.
pub async fn merge_typed_address_upgrade_only(
&self,
node_id: &PeerId,
address: &MultiAddr,
addr_type: AddressType,
) -> bool {
// No fast path: the read-locked fast path is only valid when the
// merge is a no-op. For the upgrade-only variant the decision
// ("would this upgrade the tag?") requires inspecting the stored
// tag, which must happen under the write lock to avoid a TOCTOU
// race with a concurrent PublishAddressSet replace.
let mut routing = self.routing_table.write().await;
routing.merge_typed_address_upgrade_only(node_id, address, addr_type)
}
/// Replace a peer's advertised address list with `typed_addresses`, under
/// a monotonic-sequence guard.
///
/// Implements the receive side of the `PublishAddressSet` wire op: the
/// sender is authoritative about its own reachable addresses and the
/// receiver drops any address the sender omits. This authenticated path is
/// the source of fresh address records; later FIND_NODE gossip may propagate
/// the same replacement through [`Self::replace_node_addresses_from_gossip`]
/// without refreshing liveness.
///
/// - Empty input address lists are rejected outright (returns `false`).
/// - Filtering happens in two stages with **different empty-result
/// semantics**, because they guard against different things:
/// - *Loopback* (this method, via [`Self::filter_publish_address_set`],
/// skipped when [`Self::allow_loopback`] is set for devnets/tests):
/// if stripping loopback empties a non-empty input, the **empty set
/// is still applied**. A publisher that legitimately drops to zero
/// reachable addresses must not keep stale ones alive, and
/// `last_publish_seqs` advances normally.
/// - *Wildcard / port-zero* ([`KBucket::replace_node_addresses_with_mode`]
/// via `is_storable_address`): if this empties a non-empty input the
/// replace is **refused** — prior good addresses are preserved and
/// `last_publish_seqs` is NOT advanced, so a corrected republish at
/// the same `seq` can still land. Wildcard-only is treated as a
/// malformed publish, not an intentional "I have no addresses", so
/// callers and tests must not assume all filter-empty publishes
/// share the same outcome.
/// - `seq` must be non-zero and strictly exceed the last sequence
/// observed from `node_id`; zero, older, or duplicate sequences are
/// ignored.
///
/// Returns `true` when the peer's addresses were replaced, `false`
/// otherwise (peer absent, stale sequence, empty input list, or a
/// wildcard-only input whose prior addresses were preserved).
pub async fn replace_node_addresses(
&self,
node_id: &PeerId,
typed_addresses: Vec<(MultiAddr, AddressType)>,
seq: u64,
) -> bool {
let Some(filtered) = self.filter_publish_address_set(typed_addresses) else {
return false;
};
let mut routing = self.routing_table.write().await;
routing.replace_node_addresses(node_id, filtered, seq)
}
/// Replace a peer's advertised address list from sequence-bearing gossip
/// without refreshing liveness.
///
/// Uses the same filtering and monotonic-sequence guard as
/// [`Self::replace_node_addresses`], but does not update `last_seen`,
/// bucket MRU order, or bucket refresh timestamps. A third-party
/// FIND_NODE response can propagate a newer address record, but only
/// direct authenticated traffic from the subject peer proves liveness.
pub(crate) async fn replace_node_addresses_from_gossip(
&self,
node_id: &PeerId,
typed_addresses: Vec<(MultiAddr, AddressType)>,
seq: u64,
) -> bool {
let Some(filtered) = self.filter_publish_address_set(typed_addresses) else {
return false;
};
let mut routing = self.routing_table.write().await;
routing.replace_node_addresses_from_gossip(node_id, filtered, seq)
}
fn filter_publish_address_set(
&self,
typed_addresses: Vec<(MultiAddr, AddressType)>,
) -> Option<Vec<(MultiAddr, AddressType)>> {
if typed_addresses.is_empty() {
return None;
}
let allow_loopback = self.allow_loopback;
let filtered: Vec<(MultiAddr, AddressType)> = typed_addresses
.into_iter()
.filter(|(addr, _)| {
if allow_loopback {
return true;
}
!addr
.ip()
.is_some_and(|ip| canonicalize_ip(ip).is_loopback())
})
.map(|(addr, ty)| {
let ty = AddressType::for_advertised_address(&addr, ty);
(addr, ty)
})
.collect();
Some(filtered)
}
/// Add a node to the DHT with security checks.
///
/// IP subnet diversity is enforced per-bucket and for the K closest
/// nodes to self, with closer peers swapped in when they contend for
/// the same slot.
///
/// `trust_score` is a closure that returns the current trust score for
/// any peer ID. Well-trusted peers (above [`TRUST_PROTECTION_THRESHOLD`])
/// are protected from swap-closer eviction. This decouples the routing
/// table from the trust engine implementation.
///
/// Returns [`AdmissionResult::Admitted`] on success, or
/// [`AdmissionResult::StaleRevalidationNeeded`] when the target bucket is
/// full and stale peers may be evicted after revalidation. The caller
/// (DhtNetworkManager) must handle the revalidation flow.
pub async fn add_node(
&mut self,
mut node: NodeInfo,
trust_score: &impl Fn(&PeerId) -> f64,
) -> Result<AdmissionResult> {
// Reject self-insertion — a node must never appear in its own routing table.
if node.id == self.node_id {
return Err(anyhow!("cannot add self to routing table"));
}
let peer_id = node.id;
// Strip wildcard / port-zero addresses before any admission logic runs.
// Without this, a NodeInfo carrying both /ip4/0.0.0.0/... and a valid
// routable address would be rejected wholesale by the unspecified-IP
// check in `add_with_diversity` — the per-address store filter in
// `KBucket::add_node` never gets a chance to run. Sanitizing here lets
// mixed records through with only their routable addresses retained,
// matching the store-side filter applied at the bucket boundary.
node.retain_storable_addresses();
// A record left with no addresses after sanitization carried nothing
// but wildcard / port-zero entries. It is not a non-IP transport, so
// it must not fall through to the non-IP bypass below — reject it.
if node.addresses.is_empty() {
return Err(anyhow!(
"all addresses were wildcard / port-zero; nothing storable"
));
}
// Extract ALL IP addresses from the candidate for diversity checking.
// If candidate has no IP-based addresses, it's a non-IP transport — bypass diversity.
let candidate_ips: Vec<IpAddr> = node
.addresses
.iter()
.filter_map(|a| a.ip().map(canonicalize_ip))
.collect::<HashSet<_>>()
.into_iter()
.collect();
if candidate_ips.is_empty() {
// Non-IP transports (Bluetooth, LoRa, etc.) bypass IP diversity.
let mut routing = self.routing_table.write().await;
// Update short-circuit: if peer already exists, merge addresses and
// refresh last_seen without emitting PeerAdded (matches the main
// diversity path's update logic at the "Design step 5" block).
if routing.find_node_by_id(&peer_id).is_some() {
for (i, addr) in node.addresses.iter().enumerate() {
routing.touch_node(&peer_id, Some(addr), node.address_type_at(i));
}
return Ok(AdmissionResult::Admitted(vec![]));
}
let k_before = routing.k_closest_ids(self.k_value);
routing.add_node(node)?;
let k_after = routing.k_closest_ids(self.k_value);
let mut events = vec![RoutingTableEvent::PeerAdded(peer_id)];
if k_before != k_after {
events.push(RoutingTableEvent::KClosestPeersChanged {
old: k_before,
new: k_after,
});
}
return Ok(AdmissionResult::Admitted(events));
}
// Single write lock covers diversity checks and insertion to avoid
// a TOCTOU race.
let mut routing = self.routing_table.write().await;
self.add_with_diversity(&mut routing, node, &candidate_ips, trust_score, true)
}
/// Convenience method for tests: add a node with neutral trust (0.5).
///
/// Preserves existing swap-closer behavior for tests that don't care
/// about trust scoring. Maps [`AdmissionResult::Admitted`] to its events
/// and treats [`AdmissionResult::StaleRevalidationNeeded`] as an error
/// (unit tests don't have network access to ping stale peers).
#[cfg(test)]
pub async fn add_node_no_trust(&mut self, node: NodeInfo) -> Result<Vec<RoutingTableEvent>> {
match self.add_node(node, &|_| DEFAULT_NEUTRAL_TRUST).await? {
AdmissionResult::Admitted(events) => Ok(events),
AdmissionResult::StaleRevalidationNeeded { .. } => Err(anyhow!(
"stale revalidation needed (not available in unit tests)"
)),
}
}
/// Check IP diversity within a scoped set of nodes and return a swap
/// candidate if the scope is over-limit but the candidate is closer.
///
/// Returns:
/// - `Ok(None)` — scope is within limits (or candidate is loopback)
/// - `Ok(Some(peer_id))` — scope exceeds a limit but the candidate is
/// closer than the farthest violating peer; swap that peer out
/// - `Err` — scope exceeds a limit and the candidate cannot swap in
///
/// Trust protection: the farthest peer is only swapped out when its trust
/// score is below [`TRUST_PROTECTION_THRESHOLD`]. Well-trusted peers hold
/// their slot even when a closer candidate arrives.
fn find_ip_swap_in_scope(
&self,
nodes: &[NodeInfo],
candidate_id: &PeerId,
candidate_ip: IpAddr,
candidate_distance: &[u8; 32],
scope_name: &str,
trust_score: &impl Fn(&PeerId) -> f64,
) -> Result<Option<PeerId>> {
// Loopback candidates bypass IP diversity entirely.
if candidate_ip.is_loopback() {
return Ok(None);
}
let cfg = &self.ip_diversity_config;
match candidate_ip {
IpAddr::V4(v4) => {
// IPv4 limits: use config override if set, otherwise default
let limit_ip = cfg.max_per_ip.unwrap_or(IP_EXACT_LIMIT);
let limit_subnet = cfg.max_per_subnet.unwrap_or(ip_subnet_limit(self.k_value));
let cand_24 = mask_ipv4(v4, 24);
// Single pass: count exact-IP and /24 matches, track farthest at each.
// Check ALL addresses of each existing node to prevent diversity
// bypass via address rotation (e.g. touch_node prepending a new address).
// Each node is counted at most once per tier to avoid double-counting
// multi-homed peers.
let mut count_ip: usize = 0;
let mut count_subnet: usize = 0;
let mut farthest_ip: Option<(PeerId, [u8; 32], Instant)> = None;
let mut farthest_subnet: Option<(PeerId, [u8; 32], Instant)> = None;
for n in nodes {
if n.id == *candidate_id {
continue;
}
let existing_ips = n.all_ips();
if existing_ips.is_empty() {
continue;
}
let dist = xor_distance_bytes(self.node_id.to_bytes(), n.id.to_bytes());
// Check if any of this node's addresses match the candidate's
// exact IP or /24 subnet. Count each node at most once per tier.
let mut matched_ip = false;
let mut matched_subnet = false;
for existing_ip in &existing_ips {
if existing_ip.is_loopback() {
continue;
}
let IpAddr::V4(existing_v4) = existing_ip else {
continue;
};
if !matched_ip && *existing_v4 == v4 {
matched_ip = true;
}
if !matched_subnet && mask_ipv4(*existing_v4, 24) == cand_24 {
matched_subnet = true;
}
}
if matched_ip {
count_ip += 1;
if farthest_ip.as_ref().is_none_or(|(_, d, _)| dist > *d) {
farthest_ip = Some((n.id, dist, n.last_seen.load()));
}
}
if matched_subnet {
count_subnet += 1;
if farthest_subnet.as_ref().is_none_or(|(_, d, _)| dist > *d) {
farthest_subnet = Some((n.id, dist, n.last_seen.load()));
}
}
}
// Check tiers narrowest-first: a swap at exact-IP also fixes /24
let tiers: [IpSwapTier; 2] = [
(count_ip, limit_ip, farthest_ip, "exact-IP"),
(count_subnet, limit_subnet, farthest_subnet, "/24"),
];
for (count, limit, farthest, tier_name) in &tiers {
if *count >= *limit {
if let Some((far_id, far_dist, far_last_seen)) = farthest
&& candidate_distance < far_dist
&& (trust_score(far_id) < TRUST_PROTECTION_THRESHOLD
|| far_last_seen.elapsed() > self.live_threshold)
{
return Ok(Some(*far_id));
}
return Err(anyhow!(
"IP diversity: {tier_name} limit ({limit}) exceeded in {scope_name}"
));
}
}
}
IpAddr::V6(v6) => {
// IPv6 limits: use config override if set, otherwise default
let limit_ip = cfg.max_per_ip.unwrap_or(IP_EXACT_LIMIT);
let limit_subnet = cfg.max_per_subnet.unwrap_or(ip_subnet_limit(self.k_value));
let cand_48 = mask_ipv6(v6, 48);
// Single pass: count exact-IPv6 and /48 matches.
// Check ALL addresses per node (see IPv4 branch comment).
let mut count_ip: usize = 0;
let mut count_subnet: usize = 0;
let mut farthest_ip: Option<(PeerId, [u8; 32], Instant)> = None;
let mut farthest_subnet: Option<(PeerId, [u8; 32], Instant)> = None;
for n in nodes {
if n.id == *candidate_id {
continue;
}
let existing_ips = n.all_ips();
if existing_ips.is_empty() {
continue;
}
let dist = xor_distance_bytes(self.node_id.to_bytes(), n.id.to_bytes());
let mut matched_ip = false;
let mut matched_subnet = false;
for existing_ip in &existing_ips {
if existing_ip.is_loopback() {
continue;
}
let IpAddr::V6(existing_v6) = existing_ip else {
continue;
};
if !matched_ip && *existing_v6 == v6 {
matched_ip = true;
}
if !matched_subnet && mask_ipv6(*existing_v6, 48) == cand_48 {
matched_subnet = true;
}
}
if matched_ip {
count_ip += 1;
if farthest_ip.as_ref().is_none_or(|(_, d, _)| dist > *d) {
farthest_ip = Some((n.id, dist, n.last_seen.load()));
}
}
if matched_subnet {
count_subnet += 1;
if farthest_subnet.as_ref().is_none_or(|(_, d, _)| dist > *d) {
farthest_subnet = Some((n.id, dist, n.last_seen.load()));
}
}
}
let tiers: [IpSwapTier; 2] = [
(count_ip, limit_ip, farthest_ip, "exact-IP"),
(count_subnet, limit_subnet, farthest_subnet, "/48"),
];
for (count, limit, farthest, tier_name) in &tiers {
if *count >= *limit {
if let Some((far_id, far_dist, far_last_seen)) = farthest
&& candidate_distance < far_dist
&& (trust_score(far_id) < TRUST_PROTECTION_THRESHOLD
|| far_last_seen.elapsed() > self.live_threshold)
{
return Ok(Some(*far_id));
}
return Err(anyhow!(
"IP diversity: {tier_name} limit ({limit}) exceeded in {scope_name}"
));
}
}
}
}
Ok(None)
}
/// Collect stale peers from a bucket.
///
/// Returns `(peer_id, bucket_index)` pairs for all peers in the target
/// bucket whose `last_seen` exceeds the given `threshold`.
fn collect_stale_peers_in_bucket(
routing: &KademliaRoutingTable,
bucket_idx: usize,
threshold: Duration,
) -> Vec<(PeerId, usize)> {
routing.buckets[bucket_idx]
.nodes
.iter()
.filter(|n| n.last_seen.elapsed() > threshold)
.map(|n| (n.id, bucket_idx))
.collect()
}
/// Add a node with per-bucket and close-group IP diversity enforcement.
///
/// Enforces that no IP subnet exceeds its limit within any single
/// k-bucket or within the K closest nodes to self.
///
/// When a candidate would exceed a limit, it may still be admitted if it
/// is closer (XOR distance) to self than the farthest violating peer in
/// the scope — the farther peer is evicted and the candidate takes its
/// slot, preserving the count while improving routing quality.
///
/// Trust protection is forwarded to [`Self::find_ip_swap_in_scope`] so
/// that well-trusted peers resist eviction.
///
/// When `allow_stale_revalidation` is `true` and the bucket is at capacity
/// with no swap candidate, stale peers are identified and
/// [`AdmissionResult::StaleRevalidationNeeded`] is returned so the caller
/// can ping them and retry. When `false` (re-evaluation after revalidation),
/// a full bucket is a hard rejection to prevent infinite revalidation loops.
fn add_with_diversity(
&self,
routing: &mut KademliaRoutingTable,
node: NodeInfo,
candidate_ips: &[IpAddr],
trust_score: &impl Fn(&PeerId) -> f64,
allow_stale_revalidation: bool,
) -> Result<AdmissionResult> {
let peer_id = node.id;
// --- Reject invalid addresses ---
// Multicast and unspecified addresses are never valid peer endpoints.
if candidate_ips
.iter()
.any(|ip| ip.is_unspecified() || ip.is_multicast())
{
return Err(anyhow!(
"IP diversity: multicast or unspecified addresses rejected"
));
}
// --- Reject any loopback addresses when loopback is disallowed (M2) ---
if !self.allow_loopback && candidate_ips.iter().any(|ip| ip.is_loopback()) {
return Err(anyhow!(
"IP diversity: loopback addresses rejected (allow_loopback=false)"
));
}
// --- Loopback handling ---
let all_loopback = candidate_ips.iter().all(|ip| ip.is_loopback());
if all_loopback {
if !self.allow_loopback {
return Err(anyhow!(
"IP diversity: loopback addresses rejected (allow_loopback=false)"
));
}
// Loopback with allow_loopback=true bypasses all diversity checks.
// Update short-circuit: if peer already exists, merge addresses and
// refresh last_seen without emitting PeerAdded.
if routing.find_node_by_id(&peer_id).is_some() {
for (i, addr) in node.addresses.iter().enumerate() {
routing.touch_node(&peer_id, Some(addr), node.address_type_at(i));
}
return Ok(AdmissionResult::Admitted(vec![]));
}
let k_before = routing.k_closest_ids(self.k_value);
routing.add_node(node)?;
let k_after = routing.k_closest_ids(self.k_value);
let mut events = vec![RoutingTableEvent::PeerAdded(peer_id)];
if k_before != k_after {
events.push(RoutingTableEvent::KClosestPeersChanged {
old: k_before,
new: k_after,
});
}
return Ok(AdmissionResult::Admitted(events));
}
let bucket_idx = routing
.get_bucket_index(&node.id)
.ok_or_else(|| anyhow!("cannot insert self into routing table"))?;
let candidate_distance = xor_distance_bytes(self.node_id.to_bytes(), node.id.to_bytes());
// === Update short-circuit (Design step 5) ===
// If peer already exists, merge addresses, refresh last_seen, move to tail.
// Skip diversity and capacity checks — the peer already holds its slot.
// The update path doesn't change membership, just position within a bucket.
// K-closest computation is distance-based, not position-based, so the set
// won't change. Return an empty events vec.
if let Some(pos) = routing.buckets[bucket_idx]
.nodes
.iter()
.position(|n| n.id == node.id)
{
let existing = &mut routing.buckets[bucket_idx].nodes[pos];
existing.last_seen.store_now();
// Merge each address from the candidate, respecting loopback injection prevention
for (i, addr) in node.addresses.iter().enumerate() {
let addr_is_loopback = addr
.ip()
.is_some_and(|ip| canonicalize_ip(ip).is_loopback());
let existing_has_non_loopback = existing
.addresses
.iter()
.any(|a| a.ip().is_some_and(|ip| !canonicalize_ip(ip).is_loopback()));
// Don't merge loopback addresses into a non-loopback-admitted peer
if addr_is_loopback && existing_has_non_loopback {
continue;
}
existing.merge_typed_address(addr.clone(), node.address_type_at(i));
}
// Move to tail (most recently seen)
let updated = routing.buckets[bucket_idx].nodes.remove(pos);
routing.buckets[bucket_idx].nodes.push(updated);
routing.buckets[bucket_idx].last_refreshed_by_live_peer = Instant::now();
return Ok(AdmissionResult::Admitted(Vec::new()));
}
// === Per-bucket IP diversity ===
// Run diversity checks for each non-loopback candidate IP independently.
// After identifying a swap for one IP, exclude that peer from subsequent
// checks so that each IP sees the state after prior swaps — preventing
// over-eviction when a candidate has multiple IPs.
let mut all_bucket_swaps: Vec<PeerId> = Vec::new();
for &candidate_ip in candidate_ips {
if candidate_ip.is_loopback() {
continue;
}
let bucket_view: Vec<NodeInfo> = routing.buckets[bucket_idx]
.nodes
.iter()
.filter(|n| !all_bucket_swaps.contains(&n.id))
.cloned()
.collect();
let swap = self.find_ip_swap_in_scope(
&bucket_view,
&node.id,
candidate_ip,
&candidate_distance,
"bucket",
trust_score,
)?;
if let Some(id) = swap
&& !all_bucket_swaps.contains(&id)
{
all_bucket_swaps.push(id);
}
}
// === Close-group setup ===
let close_group = routing.find_closest_nodes(&self.node_id, self.k_value);
let effective_close_len = close_group
.iter()
.filter(|n| !all_bucket_swaps.contains(&n.id))
.count();
let candidate_in_close = effective_close_len < self.k_value
|| close_group
.iter()
.rfind(|n| !all_bucket_swaps.contains(&n.id))
.map(|n| {
candidate_distance
< xor_distance_bytes(self.node_id.to_bytes(), n.id.to_bytes())
})
.unwrap_or(true);
let mut all_close_swaps: Vec<PeerId> = Vec::new();
if candidate_in_close {
// Build hypothetical close group as Vec<NodeInfo>
let mut hyp_close: Vec<NodeInfo> = close_group
.iter()
.filter(|n| !all_bucket_swaps.contains(&n.id) && n.id != node.id)
.cloned()
.collect();
hyp_close.push(node.clone());
hyp_close.sort_by(|a, b| {
let da = xor_distance_bytes(self.node_id.to_bytes(), a.id.to_bytes());
let db = xor_distance_bytes(self.node_id.to_bytes(), b.id.to_bytes());
da.cmp(&db)
});
hyp_close.truncate(self.k_value);
// === Close-group IP diversity ===
// Exclude prior close-group swaps from each subsequent check to
// prevent over-eviction (same rationale as the bucket loop above).
for &candidate_ip in candidate_ips {
if candidate_ip.is_loopback() {
continue;
}
let close_view: Vec<NodeInfo> = hyp_close
.iter()
.filter(|n| !all_close_swaps.contains(&n.id))
.cloned()
.collect();
let swap = self.find_ip_swap_in_scope(
&close_view,
&node.id,
candidate_ip,
&candidate_distance,
"close-group",
trust_score,
)?;
if let Some(id) = swap {
// Deduplicate: don't plan a close swap that's already a bucket swap
if !all_bucket_swaps.contains(&id) && !all_close_swaps.contains(&id) {
all_close_swaps.push(id);
}
}
}
}
// === Capacity pre-check ===
// Verify the insertion will succeed before executing any swaps.
{
let bucket = &routing.buckets[bucket_idx];
let already_exists = bucket.nodes.iter().any(|n| n.id == node.id);
let has_room = bucket.nodes.len() < bucket.max_size;
let swap_frees_slot = !all_bucket_swaps.is_empty()
|| all_close_swaps
.iter()
.any(|id| routing.get_bucket_index(id) == Some(bucket_idx));
if !already_exists && !has_room && !swap_frees_slot {
// --- Trust-based swap-out (lazy eviction) ---
// When a bucket is full and no IP-diversity swap is available,
// find the lowest-trust peer below swap_threshold and replace
// it directly. No revalidation ping needed.
// Only swap when the candidate itself is above the threshold
// to avoid replacing a low-trust peer with an even worse one.
if self.swap_threshold > 0.0 && trust_score(&peer_id) >= self.swap_threshold {
let lowest = bucket
.nodes
.iter()
.map(|n| (n.id, trust_score(&n.id)))
.filter(|(_, score)| *score < self.swap_threshold)
.min_by(|(_, a), (_, b)| {
a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
});
if let Some((swap_id, _)) = lowest {
all_bucket_swaps.push(swap_id);
}
}
// Re-check capacity after potential trust swap
let swap_frees_slot_now = !all_bucket_swaps.is_empty()
|| all_close_swaps
.iter()
.any(|id| routing.get_bucket_index(id) == Some(bucket_idx));
if !swap_frees_slot_now {
if allow_stale_revalidation {
let mut stale_peers = Self::collect_stale_peers_in_bucket(
routing,
bucket_idx,
self.live_threshold,
);
// Merge stale routing-neighborhood violators (Design Section 7.5):
// close-group swap targets that are stale and not already in the
// bucket-level set. Evicting these may resolve the close-group
// diversity violation and (if they happen to reside in the same
// bucket) free capacity for the candidate.
for close_swap_id in &all_close_swaps {
if stale_peers.iter().any(|(id, _)| id == close_swap_id) {
continue;
}
if let Some(swap_bucket_idx) = routing.get_bucket_index(close_swap_id)
&& let Some(swap_node) = routing.find_node_by_id(close_swap_id)
&& swap_node.last_seen.elapsed() > self.live_threshold
{
stale_peers.push((*close_swap_id, swap_bucket_idx));
}
}
if !stale_peers.is_empty() {
return Ok(AdmissionResult::StaleRevalidationNeeded {
candidate: node,
candidate_ips: candidate_ips.to_vec(),
candidate_bucket_idx: bucket_idx,
stale_peers,
});
}
}
return Err(anyhow!(
"K-bucket at capacity ({}/{}) with no stale peers",
bucket.nodes.len(),
bucket.max_size,
));
}
}
}
// === Snapshot K-closest BEFORE mutation ===
let k_before = routing.k_closest_ids(self.k_value);
// === Execute all swaps (deduplicated) ===
let mut executed: Vec<PeerId> = Vec::with_capacity(2);
for swap_id in all_bucket_swaps
.iter()
.chain(all_close_swaps.iter())
.copied()
{
if !executed.contains(&swap_id) {
routing.remove_node(&swap_id);
executed.push(swap_id);
}
}
routing.add_node(node)?;
// === Build events ===
let mut events: Vec<RoutingTableEvent> = Vec::with_capacity(executed.len() + 2);
for removed_id in &executed {
events.push(RoutingTableEvent::PeerRemoved(*removed_id));
}
events.push(RoutingTableEvent::PeerAdded(peer_id));
// === Snapshot K-closest AFTER mutation ===
let k_after = routing.k_closest_ids(self.k_value);
if k_before != k_after {
events.push(RoutingTableEvent::KClosestPeersChanged {
old: k_before,
new: k_after,
});
}
Ok(AdmissionResult::Admitted(events))
}
/// Re-evaluate admission after stale peers have been evicted by the caller.
///
/// Called by the network manager after pinging stale peers and evicting
/// non-responders. Re-runs IP diversity, trust-based swap-out, and capacity
/// checks with `allow_stale_revalidation: false` to prevent infinite
/// revalidation loops.
pub(crate) async fn re_evaluate_admission(
&mut self,
candidate: NodeInfo,
candidate_ips: &[IpAddr],
trust_score: &impl Fn(&PeerId) -> f64,
) -> Result<Vec<RoutingTableEvent>> {
let mut routing = self.routing_table.write().await;
match self.add_with_diversity(&mut routing, candidate, candidate_ips, trust_score, false)? {
AdmissionResult::Admitted(events) => Ok(events),
AdmissionResult::StaleRevalidationNeeded { .. } => {
// Design: re-evaluation MUST NOT trigger a second revalidation round.
// The `allow_stale_revalidation: false` flag should prevent this path,
// but we handle it defensively.
Err(anyhow!("K-bucket still at capacity after revalidation"))
}
}
}
}
// Manual Debug implementation to avoid cascade of Debug requirements
impl std::fmt::Debug for DhtCoreEngine {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DhtCoreEngine")
.field("node_id", &self.node_id)
.field("routing_table", &"Arc<RwLock<KademliaRoutingTable>>")
.field("k_value", &self.k_value)
.field("ip_diversity_config", &self.ip_diversity_config)
.field("allow_loopback", &self.allow_loopback)
.field("swap_threshold", &self.swap_threshold)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::address::TransportAddr;
use std::collections::HashSet;
#[tokio::test]
async fn test_xor_distance() {
let key1 = DhtKey::from_bytes([0u8; 32]);
let key2 = DhtKey::from_bytes([255u8; 32]);
let distance = key1.distance(&key2);
assert_eq!(distance, [255u8; 32]);
}
/// Helper: create a NodeInfo with a deterministic PeerId derived from a
/// single byte. Keeps tests concise.
fn make_node(byte: u8, address: &str) -> NodeInfo {
NodeInfo {
id: PeerId::from_bytes([byte; 32]),
addresses: vec![address.parse::<MultiAddr>().unwrap()],
address_types: vec![AddressType::Direct],
last_seen: AtomicInstant::now(),
}
}
// -----------------------------------------------------------------------
// KBucket::touch_node tests
// -----------------------------------------------------------------------
#[test]
fn test_touch_node_merges_address() {
let k = 8;
let mut bucket = KBucket::new(k);
let node = make_node(1, "/ip4/1.2.3.4/udp/9000/quic");
bucket.add_node(node).unwrap();
// Touch with a new same-family-same-type (IPv4 Direct) address.
// The per-IP-family cap keeps the newest Direct and drops the old
// one — both cannot coexist under the "1 Direct per IPv4" rule.
let new_addr: MultiAddr = "/ip4/5.6.7.8/udp/9000/quic".parse().unwrap();
let found = bucket.touch_node_typed(
&PeerId::from_bytes([1u8; 32]),
Some(&new_addr),
AddressType::Direct,
);
assert!(found);
let addrs = &bucket.get_nodes().last().unwrap().addresses;
assert_eq!(addrs, &vec![new_addr]);
}
#[test]
fn test_touch_node_none_preserves_addresses() {
let k = 8;
let mut bucket = KBucket::new(k);
let node = make_node(1, "/ip4/1.2.3.4/udp/9000/quic");
bucket.add_node(node).unwrap();
let found =
bucket.touch_node_typed(&PeerId::from_bytes([1u8; 32]), None, AddressType::Direct);
assert!(found);
let expected: MultiAddr = "/ip4/1.2.3.4/udp/9000/quic".parse().unwrap();
assert_eq!(bucket.get_nodes().last().unwrap().addresses, vec![expected]);
}
#[test]
fn test_touch_node_moves_to_tail() {
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/1.1.1.1/udp/9000/quic"))
.unwrap();
bucket
.add_node(make_node(2, "/ip4/2.2.2.2/udp/9000/quic"))
.unwrap();
bucket
.add_node(make_node(3, "/ip4/3.3.3.3/udp/9000/quic"))
.unwrap();
// Touch the first node — it should move to the tail
bucket.touch_node_typed(&PeerId::from_bytes([1u8; 32]), None, AddressType::Direct);
let ids: Vec<u8> = bucket
.get_nodes()
.iter()
.map(|n| n.id.to_bytes()[0])
.collect();
assert_eq!(ids, vec![2, 3, 1]);
}
#[test]
fn test_touch_node_missing_returns_false() {
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/1.1.1.1/udp/9000/quic"))
.unwrap();
let new_addr: MultiAddr = "/ip4/9.9.9.9/udp/9000/quic".parse().unwrap();
let found = bucket.touch_node_typed(
&PeerId::from_bytes([99u8; 32]),
Some(&new_addr),
AddressType::Direct,
);
assert!(!found);
}
// -----------------------------------------------------------------------
// KBucket::merge_typed_address_upgrade_only tests
//
// The gossip-ingestion path: merges a third party's view of an existing
// peer's addresses without claiming the peer is alive from our point of
// view. Liveness (`last_seen`) and bucket-MRU position must be preserved
// — see the rationale on `KBucket::merge_typed_address_upgrade_only`.
//
// The robust pattern here is capture-before-merge / compare-after-merge:
// any leaked `store_now()` would write a strictly later `Instant` than
// the captured snapshot (the merge does a Vec scan, mutex unlock, and
// assertion code in between), so exact-equality detects refresh leaks
// without depending on system uptime or clock granularity.
// -----------------------------------------------------------------------
#[test]
fn gossip_merge_does_not_bump_last_seen() {
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/1.1.1.1/udp/9000/quic"))
.unwrap();
let before = bucket.nodes[0].last_seen.load();
let gossiped: MultiAddr = "/ip4/9.9.9.9/udp/9000/quic".parse().unwrap();
let changed = bucket.merge_typed_address_upgrade_only(
&PeerId::from_bytes([1u8; 32]),
&gossiped,
AddressType::Relay,
);
assert!(changed, "merge of new address should report a state change");
assert_eq!(
bucket.nodes[0].last_seen.load(),
before,
"gossip ingestion must not refresh last_seen"
);
}
#[test]
fn gossip_merge_does_not_reorder_bucket() {
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/1.1.1.1/udp/9000/quic"))
.unwrap();
bucket
.add_node(make_node(2, "/ip4/2.2.2.2/udp/9000/quic"))
.unwrap();
bucket
.add_node(make_node(3, "/ip4/3.3.3.3/udp/9000/quic"))
.unwrap();
// Insertion order (head = LRU, tail = MRU): [1, 2, 3].
// touch_node_typed would move peer 1 to the tail. Gossip-merge must
// NOT, otherwise unauthenticated gossip could shield bad peers from
// LRU-driven eviction.
let gossiped: MultiAddr = "/ip4/8.8.8.8/udp/9000/quic".parse().unwrap();
bucket.merge_typed_address_upgrade_only(
&PeerId::from_bytes([1u8; 32]),
&gossiped,
AddressType::Relay,
);
let ids: Vec<u8> = bucket
.get_nodes()
.iter()
.map(|n| n.id.to_bytes()[0])
.collect();
assert_eq!(
ids,
vec![1, 2, 3],
"gossip ingestion must preserve bucket order"
);
}
#[test]
fn gossip_merge_adds_new_address() {
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/1.1.1.1/udp/9000/quic"))
.unwrap();
// A previously unseen Direct address from gossip. Should be added
// and the merge should report a state change.
let gossiped: MultiAddr = "/ip4/7.7.7.7/udp/9000/quic".parse().unwrap();
let changed = bucket.merge_typed_address_upgrade_only(
&PeerId::from_bytes([1u8; 32]),
&gossiped,
AddressType::Direct,
);
assert!(changed);
assert!(
bucket.nodes[0].addresses.iter().any(|a| a == &gossiped),
"gossip ingestion must merge a previously-unseen address"
);
}
#[test]
fn gossip_merge_returns_false_for_missing_peer() {
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/1.1.1.1/udp/9000/quic"))
.unwrap();
let gossiped: MultiAddr = "/ip4/9.9.9.9/udp/9000/quic".parse().unwrap();
let changed = bucket.merge_typed_address_upgrade_only(
&PeerId::from_bytes([42u8; 32]),
&gossiped,
AddressType::Direct,
);
assert!(
!changed,
"missing peer should return false (gossip never inserts new identities)"
);
}
#[test]
fn gossip_merge_returns_false_when_already_known_with_same_tag() {
// The return value signals "did the merge change anything",
// not "is the peer in the bucket". When gossip reports an
// already-known address with the same tag classification, the
// merge is a no-op and must report `false` so a future caller
// can gate downstream work (logging, event emission, etc.) on
// genuine record changes.
let k = 8;
let mut bucket = KBucket::new(k);
let addr_str = "/ip4/1.1.1.1/udp/9000/quic";
bucket.add_node(make_node(1, addr_str)).unwrap();
// Promote the existing address to `Direct` so the redundant
// gossip below cannot upgrade it from the default `Unverified`.
let known: MultiAddr = addr_str.parse().unwrap();
bucket.nodes[0].merge_typed_address_upgrade_only(known.clone(), AddressType::Direct);
let changed = bucket.merge_typed_address_upgrade_only(
&PeerId::from_bytes([1u8; 32]),
&known,
AddressType::Direct,
);
assert!(
!changed,
"no-op merge (same address, same tag) must report false"
);
}
#[test]
fn gossip_merge_does_not_bump_live_peer_refresh() {
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/1.1.1.1/udp/9000/quic"))
.unwrap();
let before = bucket.last_refreshed_by_live_peer;
let gossiped: MultiAddr = "/ip4/8.8.8.8/udp/9000/quic".parse().unwrap();
let changed = bucket.merge_typed_address_upgrade_only(
&PeerId::from_bytes([1u8; 32]),
&gossiped,
AddressType::Relay,
);
assert!(changed);
assert_eq!(
bucket.last_refreshed_by_live_peer, before,
"gossip ingestion is not bucket-level discovery — live-peer refresh must not advance"
);
}
// -----------------------------------------------------------------------
// KBucket::replace_node_addresses tests (full-replace semantics)
// -----------------------------------------------------------------------
#[test]
fn replace_addresses_overwrites_existing_list() {
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/1.1.1.1/udp/9000/quic"))
.unwrap();
let new_direct: MultiAddr = "/ip4/2.2.2.2/udp/9001/quic".parse().unwrap();
let new_relay: MultiAddr = "/ip4/3.3.3.3/udp/9002/quic".parse().unwrap();
let typed = vec![
(new_direct.clone(), AddressType::Direct),
(new_relay.clone(), AddressType::Relay),
];
let replaced = bucket.replace_node_addresses(&PeerId::from_bytes([1u8; 32]), typed);
assert!(replaced);
let node = bucket.find_node(&PeerId::from_bytes([1u8; 32])).unwrap();
// Relay is first, Direct second — matches NodeInfo::merge_typed_address ordering.
assert_eq!(node.addresses, vec![new_relay, new_direct]);
assert_eq!(
node.address_types,
vec![AddressType::Relay, AddressType::Direct]
);
}
#[test]
fn replace_addresses_canonicalizes_local_scope_direct_to_lan() {
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/1.1.1.1/udp/9000/quic"))
.unwrap();
let private: MultiAddr = "/ip4/192.168.1.10/udp/9001/quic".parse().unwrap();
let typed = vec![(private.clone(), AddressType::Direct)];
assert!(bucket.replace_node_addresses(&PeerId::from_bytes([1u8; 32]), typed));
let node = bucket.find_node(&PeerId::from_bytes([1u8; 32])).unwrap();
assert_eq!(node.addresses, vec![private]);
assert_eq!(node.address_types, vec![AddressType::Lan]);
}
#[test]
fn replace_addresses_missing_peer_returns_false() {
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/1.1.1.1/udp/9000/quic"))
.unwrap();
let typed = vec![(
"/ip4/2.2.2.2/udp/9000/quic".parse().unwrap(),
AddressType::Direct,
)];
let replaced = bucket.replace_node_addresses(&PeerId::from_bytes([42u8; 32]), typed);
assert!(!replaced);
}
#[test]
fn replace_addresses_collapses_under_per_ip_family_cap() {
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/1.1.1.1/udp/9000/quic"))
.unwrap();
// A misbehaving publisher sends 12 same-family same-type
// addresses. The per-IP-family cap collapses them to one IPv4
// Direct regardless of the `MAX_ADDRESSES_PER_NODE` sizing.
let typed: Vec<(MultiAddr, AddressType)> = (0..12)
.map(|i| {
(
format!("/ip4/203.0.113.{}/udp/9000/quic", i + 1)
.parse()
.unwrap(),
AddressType::Direct,
)
})
.collect();
assert!(bucket.replace_node_addresses(&PeerId::from_bytes([1u8; 32]), typed));
let node = bucket.find_node(&PeerId::from_bytes([1u8; 32])).unwrap();
assert_eq!(node.addresses.len(), 1);
assert_eq!(node.address_types, vec![AddressType::Direct]);
}
// -----------------------------------------------------------------------
// KademliaRoutingTable::replace_node_addresses — sequence monotonicity
// -----------------------------------------------------------------------
#[test]
fn replace_addresses_seq_monotonic() {
let local_id = PeerId::from_bytes([0u8; 32]);
let mut table = KademliaRoutingTable::new(local_id, 8);
let peer = PeerId::from_bytes([1u8; 32]);
table
.add_node(NodeInfo {
id: peer,
addresses: vec!["/ip4/1.1.1.1/udp/9000/quic".parse().unwrap()],
address_types: vec![AddressType::Direct],
last_seen: AtomicInstant::now(),
})
.unwrap();
let first: Vec<(MultiAddr, AddressType)> = vec![(
"/ip4/2.2.2.2/udp/9000/quic".parse().unwrap(),
AddressType::Direct,
)];
let second: Vec<(MultiAddr, AddressType)> = vec![(
"/ip4/3.3.3.3/udp/9000/quic".parse().unwrap(),
AddressType::Direct,
)];
assert!(table.replace_node_addresses(&peer, first.clone(), 10));
// Same seq → rejected
assert!(!table.replace_node_addresses(&peer, second.clone(), 10));
// Lower seq → rejected
assert!(!table.replace_node_addresses(&peer, second.clone(), 5));
// Higher seq → accepted, addresses replaced
assert!(table.replace_node_addresses(&peer, second.clone(), 20));
let bucket_index = table.get_bucket_index(&peer).unwrap();
let node = table.buckets[bucket_index].find_node(&peer).unwrap();
assert_eq!(
node.addresses,
vec!["/ip4/3.3.3.3/udp/9000/quic".parse::<MultiAddr>().unwrap()]
);
}
#[test]
fn replace_addresses_rejects_zero_publish_seq() {
let local_id = PeerId::from_bytes([0u8; 32]);
let mut table = KademliaRoutingTable::new(local_id, 8);
let peer = PeerId::from_bytes([1u8; 32]);
let initial_addr = "/ip4/1.1.1.1/udp/9000/quic".parse::<MultiAddr>().unwrap();
table
.add_node(NodeInfo {
id: peer,
addresses: vec![initial_addr.clone()],
address_types: vec![AddressType::Unverified],
last_seen: AtomicInstant::now(),
})
.unwrap();
let zero_publish: Vec<(MultiAddr, AddressType)> = vec![(
"/ip4/2.2.2.2/udp/9000/quic".parse().unwrap(),
AddressType::Direct,
)];
assert!(!table.replace_node_addresses(&peer, zero_publish.clone(), 0));
assert!(!table.replace_node_addresses_from_gossip(&peer, zero_publish, 0));
assert_eq!(table.publish_seq_for(&peer), 0);
let bucket_index = table.get_bucket_index(&peer).unwrap();
let node = table.buckets[bucket_index].find_node(&peer).unwrap();
assert_eq!(node.addresses, vec![initial_addr]);
assert_eq!(node.address_types, vec![AddressType::Unverified]);
}
#[test]
fn legacy_relay_hint_updates_unsequenced_record() {
let local_id = PeerId::from_bytes([0u8; 32]);
let mut table = KademliaRoutingTable::new(local_id, 8);
let peer = PeerId::from_bytes([1u8; 32]);
table
.add_node(NodeInfo {
id: peer,
addresses: vec!["/ip4/1.1.1.1/udp/9000/quic".parse().unwrap()],
address_types: vec![AddressType::Unverified],
last_seen: AtomicInstant::now(),
})
.unwrap();
let relay = "/ip4/198.51.100.7/udp/46973/quic"
.parse::<MultiAddr>()
.unwrap();
assert!(table.touch_legacy_relay_hint_if_unsequenced(&peer, &relay));
let bucket_index = table.get_bucket_index(&peer).unwrap();
let node = table.buckets[bucket_index].find_node(&peer).unwrap();
assert_eq!(node.addresses[0], relay);
assert_eq!(node.address_types[0], AddressType::Relay);
assert_eq!(table.publish_seq_for(&peer), 0);
}
#[test]
fn legacy_relay_hint_does_not_mutate_sequenced_record() {
let local_id = PeerId::from_bytes([0u8; 32]);
let mut table = KademliaRoutingTable::new(local_id, 8);
let peer = PeerId::from_bytes([1u8; 32]);
table
.add_node(NodeInfo {
id: peer,
addresses: vec!["/ip4/1.1.1.1/udp/9000/quic".parse().unwrap()],
address_types: vec![AddressType::Unverified],
last_seen: AtomicInstant::now(),
})
.unwrap();
let direct_only: Vec<(MultiAddr, AddressType)> = vec![(
"/ip4/203.0.113.9/udp/60488/quic".parse().unwrap(),
AddressType::Direct,
)];
assert!(table.replace_node_addresses(&peer, direct_only.clone(), 20));
let stale_relay = "/ip4/198.51.100.7/udp/46973/quic"
.parse::<MultiAddr>()
.unwrap();
assert!(!table.touch_legacy_relay_hint_if_unsequenced(&peer, &stale_relay));
let bucket_index = table.get_bucket_index(&peer).unwrap();
let node = table.buckets[bucket_index].find_node(&peer).unwrap();
assert_eq!(
node.addresses,
vec![
"/ip4/203.0.113.9/udp/60488/quic"
.parse::<MultiAddr>()
.unwrap()
]
);
assert_eq!(node.address_types, vec![AddressType::Direct]);
assert_eq!(table.publish_seq_for(&peer), 20);
}
#[test]
fn replace_addresses_from_gossip_does_not_refresh_liveness() {
let local_id = PeerId::from_bytes([0u8; 32]);
let mut table = KademliaRoutingTable::new(local_id, 8);
let peer = PeerId::from_bytes([1u8; 32]);
table
.add_node(NodeInfo {
id: peer,
addresses: vec!["/ip4/1.1.1.1/udp/9000/quic".parse().unwrap()],
address_types: vec![AddressType::Direct],
last_seen: AtomicInstant::now(),
})
.unwrap();
let bucket_index = table.get_bucket_index(&peer).unwrap();
let before_last_seen = table.buckets[bucket_index]
.find_node(&peer)
.unwrap()
.last_seen
.load();
let before_last_refreshed = table.buckets[bucket_index].last_refreshed_by_live_peer;
let gossiped: Vec<(MultiAddr, AddressType)> = vec![(
"/ip4/2.2.2.2/udp/9000/quic".parse().unwrap(),
AddressType::Relay,
)];
assert!(table.replace_node_addresses_from_gossip(&peer, gossiped, 10));
let node = table.buckets[bucket_index].find_node(&peer).unwrap();
assert_eq!(
node.addresses,
vec!["/ip4/2.2.2.2/udp/9000/quic".parse::<MultiAddr>().unwrap()]
);
assert_eq!(node.address_types, vec![AddressType::Relay]);
assert_eq!(
node.last_seen.load(),
before_last_seen,
"third-party gossip must not prove subject-peer liveness"
);
assert_eq!(
table.buckets[bucket_index].last_refreshed_by_live_peer, before_last_refreshed,
"third-party gossip must not count as bucket discovery activity"
);
assert_eq!(table.publish_seq_for(&peer), 10);
}
#[test]
fn remove_node_clears_publish_seq() {
let local_id = PeerId::from_bytes([0u8; 32]);
let mut table = KademliaRoutingTable::new(local_id, 8);
let peer = PeerId::from_bytes([1u8; 32]);
table
.add_node(NodeInfo {
id: peer,
addresses: vec!["/ip4/1.1.1.1/udp/9000/quic".parse().unwrap()],
address_types: vec![AddressType::Direct],
last_seen: AtomicInstant::now(),
})
.unwrap();
let typed = vec![(
"/ip4/2.2.2.2/udp/9000/quic".parse().unwrap(),
AddressType::Direct,
)];
assert!(table.replace_node_addresses(&peer, typed.clone(), 100));
table.remove_node(&peer);
assert!(!table.last_publish_seqs.contains_key(&peer));
// Re-add and verify the seq counter was cleared (lower seq now accepted).
table
.add_node(NodeInfo {
id: peer,
addresses: vec!["/ip4/1.1.1.1/udp/9000/quic".parse().unwrap()],
address_types: vec![AddressType::Direct],
last_seen: AtomicInstant::now(),
})
.unwrap();
assert!(table.replace_node_addresses(&peer, typed, 50));
}
// -----------------------------------------------------------------------
// find_closest_nodes tests — boundary bucket indices
// -----------------------------------------------------------------------
#[test]
fn test_find_closest_nodes_no_duplicates_at_bucket_zero() {
let local_id = PeerId::from_bytes([0u8; 32]);
let mut table = KademliaRoutingTable::new(local_id, 8);
// Insert nodes that land in different buckets. XOR with [0;32]
// means the bucket index is the leading-bit position of the node id.
// Byte 0 = 0x80 → bucket 0, byte 0 = 0x40 → bucket 1, etc.
let mut id_bytes = [0u8; 32];
id_bytes[0] = 0x80; // bucket 0
table
.add_node(NodeInfo {
id: PeerId::from_bytes(id_bytes),
addresses: vec!["/ip4/10.0.0.1/udp/9000/quic".parse().unwrap()],
last_seen: AtomicInstant::now(),
address_types: vec![],
})
.unwrap();
id_bytes = [0u8; 32];
id_bytes[0] = 0x40; // bucket 1
table
.add_node(NodeInfo {
id: PeerId::from_bytes(id_bytes),
addresses: vec!["/ip4/10.0.0.2/udp/9000/quic".parse().unwrap()],
last_seen: AtomicInstant::now(),
address_types: vec![],
})
.unwrap();
// Search for a key that targets bucket 0
let mut key_bytes = [0u8; 32];
key_bytes[0] = 0x80;
let key = DhtKey::from_bytes(key_bytes);
let results = table.find_closest_nodes(&key, 8);
// Verify no duplicates by collecting IDs into a set
let mut seen = HashSet::new();
for node in &results {
assert!(seen.insert(node.id), "Duplicate node {:?}", node.id);
}
assert_eq!(results.len(), 2);
}
#[test]
fn test_find_closest_nodes_no_duplicates_at_bucket_255() {
let local_id = PeerId::from_bytes([0u8; 32]);
let mut table = KademliaRoutingTable::new(local_id, 8);
// Bucket 255 requires the differing bit at position 255 (last bit
// of last byte). XOR distance with [0;32] is the id itself, so we
// need id where only the very last bit is set.
let mut id_bytes = [0u8; 32];
id_bytes[31] = 0x01; // bucket 255
table
.add_node(NodeInfo {
id: PeerId::from_bytes(id_bytes),
addresses: vec!["/ip4/10.0.0.1/udp/9000/quic".parse().unwrap()],
last_seen: AtomicInstant::now(),
address_types: vec![],
})
.unwrap();
id_bytes = [0u8; 32];
id_bytes[31] = 0x02; // bucket 254
table
.add_node(NodeInfo {
id: PeerId::from_bytes(id_bytes),
addresses: vec!["/ip4/10.0.0.2/udp/9000/quic".parse().unwrap()],
last_seen: AtomicInstant::now(),
address_types: vec![],
})
.unwrap();
let mut key_bytes = [0u8; 32];
key_bytes[31] = 0x01;
let key = DhtKey::from_bytes(key_bytes);
let results = table.find_closest_nodes(&key, 8);
let mut seen = HashSet::new();
for node in &results {
assert!(seen.insert(node.id), "Duplicate node {:?}", node.id);
}
assert_eq!(results.len(), 2);
}
#[test]
fn test_find_closest_nodes_returns_sorted_by_distance() {
let local_id = PeerId::from_bytes([0u8; 32]);
let mut table = KademliaRoutingTable::new(local_id, 8);
// Insert 5 nodes at varying distances
for i in 0..5u8 {
let mut id_bytes = [0u8; 32];
id_bytes[0] = 0x80 >> i; // buckets 0,1,2,3,4
table
.add_node(NodeInfo {
id: PeerId::from_bytes(id_bytes),
addresses: vec![
format!("/ip4/10.0.0.{}/udp/9000/quic", i + 1)
.parse()
.unwrap(),
],
last_seen: AtomicInstant::now(),
address_types: vec![],
})
.unwrap();
}
let key = DhtKey::from_bytes([0u8; 32]);
let results = table.find_closest_nodes(&key, 3);
assert_eq!(results.len(), 3);
// Results should be sorted by XOR distance to key
for window in results.windows(2) {
let d0 = xor_distance_bytes(window[0].id.to_bytes(), key.as_bytes());
let d1 = xor_distance_bytes(window[1].id.to_bytes(), key.as_bytes());
assert!(d0 <= d1, "Results not sorted by distance");
}
}
#[test]
fn test_find_closest_nodes_empty_table() {
let local_id = PeerId::from_bytes([0u8; 32]);
let table = KademliaRoutingTable::new(local_id, 8);
let key = DhtKey::from_bytes([42u8; 32]);
let results = table.find_closest_nodes(&key, 8);
assert!(results.is_empty());
}
// -----------------------------------------------------------------------
// check_diversity loopback gating tests
// -----------------------------------------------------------------------
#[tokio::test]
async fn test_loopback_rejected_when_allow_loopback_false() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
// Default has allow_loopback = false
assert!(!dht.allow_loopback);
let loopback_node = make_node(1, "/ip4/127.0.0.1/udp/9000/quic");
let result = dht.add_node_no_trust(loopback_node).await;
assert!(result.is_err());
let err_msg = result.unwrap_err().to_string();
assert!(
err_msg.contains("loopback"),
"expected loopback rejection, got: {err_msg}"
);
}
#[tokio::test]
async fn test_loopback_v6_rejected_when_allow_loopback_false() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
assert!(!dht.allow_loopback);
let loopback_node = make_node(2, "/ip6/::1/udp/9000/quic");
let result = dht.add_node_no_trust(loopback_node).await;
assert!(result.is_err());
let err_msg = result.unwrap_err().to_string();
assert!(
err_msg.contains("loopback"),
"expected loopback rejection, got: {err_msg}"
);
}
#[tokio::test]
async fn test_loopback_accepted_when_allow_loopback_true() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
dht.set_allow_loopback(true);
let loopback_node = make_node(1, "/ip4/127.0.0.1/udp/9000/quic");
let result = dht.add_node_no_trust(loopback_node).await;
assert!(result.is_ok(), "loopback should be accepted: {:?}", result);
}
#[tokio::test]
async fn test_non_loopback_unaffected_by_allow_loopback_flag() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
// allow_loopback = false should not affect normal addresses
assert!(!dht.allow_loopback);
let normal_node = make_node(1, "/ip4/10.0.0.1/udp/9000/quic");
let result = dht.add_node_no_trust(normal_node).await;
assert!(
result.is_ok(),
"non-loopback should be accepted: {:?}",
result
);
}
#[tokio::test]
async fn replace_addresses_applies_empty_set_after_filtering_all_entries() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let peer = PeerId::from_bytes([1u8; 32]);
dht.add_node_no_trust(make_node(1, "/ip4/198.51.100.1/udp/9000/quic"))
.await
.unwrap();
let loopback_only = vec![(
"/ip4/127.0.0.1/udp/9001/quic".parse().unwrap(),
AddressType::Direct,
)];
assert!(dht.replace_node_addresses(&peer, loopback_only, 1).await);
assert!(dht.get_node_addresses(&peer).await.is_empty());
}
// -----------------------------------------------------------------------
// IPv4 diversity: static floor overrides low dynamic limit
// -----------------------------------------------------------------------
/// Testnet config effectively disables IP diversity limits, allowing
/// many nodes from the same IP in a single bucket.
#[tokio::test]
async fn test_testnet_config_disables_ip_diversity() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
// Testnet config sets all IP limits to usize::MAX.
dht.set_ip_diversity_config(IPDiversityConfig::testnet());
// All nodes land in bucket 0 (id[0]=0x80, self=[0;32]).
// Vary id[31] for uniqueness.
for i in 1..=8u8 {
let mut id = [0u8; 32];
id[0] = 0x80;
id[31] = i;
let node = NodeInfo {
id: PeerId::from_bytes(id),
addresses: vec!["/ip4/203.0.113.1/udp/9000/quic".parse().unwrap()],
last_seen: AtomicInstant::now(),
address_types: vec![],
};
let result = dht.add_node_no_trust(node).await;
assert!(
result.is_ok(),
"node {i} from same IP should be accepted with testnet config: {:?}",
result
);
}
}
// -----------------------------------------------------------------------
// KBucket::add_node address validation tests
// -----------------------------------------------------------------------
#[test]
fn test_add_node_rejects_empty_addresses() {
let mut bucket = KBucket::new(8);
let node = NodeInfo {
id: PeerId::from_bytes([1u8; 32]),
addresses: vec![],
last_seen: AtomicInstant::now(),
address_types: vec![],
};
assert!(bucket.add_node(node).is_err());
}
#[test]
fn test_add_node_oversized_same_family_collapses_to_cap() {
let mut bucket = KBucket::new(8);
// An incoming `NodeInfo` with many same-family, same-type
// addresses collapses under the per-IP-family cap on insertion.
// Legacy `address_types: vec![]` means each entry is treated as
// `Unverified`, so the cap keeps exactly one Unverified per family.
let addresses: Vec<MultiAddr> = (1..=MAX_ADDRESSES_PER_NODE + 4)
.map(|i| format!("/ip4/10.0.0.{}/udp/9000/quic", i).parse().unwrap())
.collect();
let node = NodeInfo {
id: PeerId::from_bytes([1u8; 32]),
addresses,
last_seen: AtomicInstant::now(),
address_types: vec![],
};
bucket.add_node(node).unwrap();
let stored = &bucket.get_nodes()[0].addresses;
assert_eq!(stored.len(), 1);
}
#[test]
fn test_add_node_replace_collapses_under_cap() {
let mut bucket = KBucket::new(8);
bucket
.add_node(make_node(1, "/ip4/1.1.1.1/udp/9000/quic"))
.unwrap();
assert_eq!(bucket.get_nodes()[0].addresses.len(), 1);
// Re-add the peer with an oversized Direct-tagged list. The
// duplicate-admission path merges each address via
// `merge_typed_address`, and the per-IP-family cap keeps exactly
// one Direct per family.
let addresses: Vec<MultiAddr> = (1..=MAX_ADDRESSES_PER_NODE + 4)
.map(|i| {
format!("/ip4/203.0.113.{}/udp/9000/quic", i)
.parse()
.unwrap()
})
.collect();
let address_types = vec![AddressType::Direct; addresses.len()];
let replacement = NodeInfo {
id: PeerId::from_bytes([1u8; 32]),
addresses,
last_seen: AtomicInstant::now(),
address_types,
};
bucket.add_node(replacement).unwrap();
let stored = &bucket.get_nodes().last().unwrap().addresses;
assert_eq!(stored.len(), 1);
}
// -----------------------------------------------------------------------
// Helper: create a NodeInfo with an explicit id byte array
// -----------------------------------------------------------------------
fn make_node_with_addr(id_bytes: [u8; 32], address: &str) -> NodeInfo {
NodeInfo {
id: PeerId::from_bytes(id_bytes),
addresses: vec![address.parse::<MultiAddr>().unwrap()],
last_seen: AtomicInstant::now(),
address_types: vec![],
}
}
/// Live threshold used by tests: 1 second.
///
/// Production uses 900 s, but on Windows `Instant` starts at process
/// creation time, so subtracting large durations panics. Tests call
/// `set_live_threshold(TEST_LIVE_THRESHOLD)` and then set `last_seen`
/// to `Instant::now() - TEST_STALE_AGE` which is safe on every platform.
const TEST_LIVE_THRESHOLD: Duration = Duration::from_secs(1);
/// How far back to set `last_seen` so peers exceed `TEST_LIVE_THRESHOLD`.
const TEST_STALE_AGE: Duration = Duration::from_secs(2);
// -----------------------------------------------------------------------
// Test 4: low-trust peer admission (lazy swap-out model)
// -----------------------------------------------------------------------
#[tokio::test]
async fn test_low_trust_candidate_still_admitted() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let node = make_node(1, "/ip4/10.0.0.1/udp/9000/quic");
let peer_id = node.id;
// Candidate with trust below swap threshold is still admitted
// (lazy swap-out model: no admission blocking)
let result = dht
.add_node(node, &|id| {
if *id == peer_id { 0.1 } else { 0.5 }
})
.await;
assert!(result.is_ok(), "low-trust candidate should be admitted");
assert!(dht.has_node(&peer_id).await);
}
// -----------------------------------------------------------------------
// Test 13: update short-circuit
// -----------------------------------------------------------------------
#[tokio::test]
async fn test_duplicate_admission_updates_existing() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let node = make_node(1, "/ip4/10.0.0.1/udp/9000/quic");
let peer_id = node.id;
dht.add_node_no_trust(node).await.unwrap();
// Re-add same peer with a new same-family (IPv4 Direct) address.
let updated = NodeInfo {
id: peer_id,
addresses: vec!["/ip4/10.0.0.2/udp/9000/quic".parse().unwrap()],
last_seen: AtomicInstant::now(),
address_types: vec![AddressType::Direct],
};
let result = dht.add_node_no_trust(updated).await;
assert!(result.is_ok(), "update short-circuit should succeed");
// Per-IP-family cap: the newest IPv4 Direct wins; the old one is
// dropped rather than kept alongside.
let addrs = dht.get_node_addresses(&peer_id).await;
assert_eq!(
addrs,
vec!["/ip4/10.0.0.2/udp/9000/quic".parse::<MultiAddr>().unwrap()]
);
}
// -----------------------------------------------------------------------
// Test 14: loopback injection prevention
// -----------------------------------------------------------------------
#[tokio::test]
async fn test_loopback_injection_prevented_in_touch() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let node = make_node(1, "/ip4/10.0.0.1/udp/9000/quic");
let peer_id = node.id;
dht.add_node_no_trust(node).await.unwrap();
// Touch with a loopback address — should be silently rejected
let loopback_addr: MultiAddr = "/ip4/127.0.0.1/udp/9000/quic".parse().unwrap();
dht.touch_node(&peer_id, Some(&loopback_addr)).await;
let addrs = dht.get_node_addresses(&peer_id).await;
assert_eq!(addrs.len(), 1, "loopback should not be merged");
assert_ne!(addrs[0], loopback_addr);
}
// -----------------------------------------------------------------------
// Test 21: staleness-gated trust protection
// -----------------------------------------------------------------------
#[tokio::test]
async fn test_stale_trusted_peer_can_be_swapped() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
dht.set_live_threshold(TEST_LIVE_THRESHOLD);
// Two peers in bucket 0, same IP (exact-IP limit = 2)
let mut id_far = [0u8; 32];
id_far[0] = 0xFF;
let far_node = make_node_with_addr(id_far, "/ip4/10.0.1.1/udp/9000/quic");
dht.add_node_no_trust(far_node).await.unwrap();
let mut id_mid = [0u8; 32];
id_mid[0] = 0xFE;
dht.add_node_no_trust(make_node_with_addr(id_mid, "/ip4/10.0.1.1/udp/9001/quic"))
.await
.unwrap();
// Make the far peer stale by manipulating last_seen
{
let mut routing = dht.routing_table_for_test().write().await;
let bucket_idx = routing
.get_bucket_index(&PeerId::from_bytes(id_far))
.unwrap();
let node = routing.buckets[bucket_idx]
.nodes
.iter_mut()
.find(|n| n.id == PeerId::from_bytes(id_far))
.unwrap();
// Set last_seen to exceed the test live threshold
node.last_seen.store(Instant::now() - TEST_STALE_AGE);
}
// A closer candidate with the same IP
let mut id_close = [0u8; 32];
id_close[0] = 0x80;
let far_peer = PeerId::from_bytes(id_far);
// Far peer has trust 0.8 (above TRUST_PROTECTION_THRESHOLD) but is STALE
let trust_fn = |peer_id: &PeerId| -> f64 { if *peer_id == far_peer { 0.8 } else { 0.5 } };
let result = dht
.add_node(
make_node_with_addr(id_close, "/ip4/10.0.1.1/udp/9002/quic"),
&trust_fn,
)
.await;
// Should succeed — stale peer loses trust protection
assert!(
result.is_ok(),
"stale trusted peer should be swappable: {:?}",
result
);
assert!(
!dht.has_node(&far_peer).await,
"stale far peer should be evicted"
);
assert!(dht.has_node(&PeerId::from_bytes(id_close)).await);
}
// -----------------------------------------------------------------------
// Test 22: live well-trusted peer holds slot
// -----------------------------------------------------------------------
#[tokio::test]
async fn test_live_trusted_peer_holds_slot() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let mut id_far = [0u8; 32];
id_far[0] = 0xFF;
dht.add_node_no_trust(make_node_with_addr(id_far, "/ip4/10.0.1.1/udp/9000/quic"))
.await
.unwrap();
let mut id_mid = [0u8; 32];
id_mid[0] = 0xFE;
dht.add_node_no_trust(make_node_with_addr(id_mid, "/ip4/10.0.1.1/udp/9001/quic"))
.await
.unwrap();
// Far peer is live (just added, last_seen is now) and trusted (0.8)
let far_peer = PeerId::from_bytes(id_far);
let trust_fn = |peer_id: &PeerId| -> f64 { if *peer_id == far_peer { 0.8 } else { 0.5 } };
let mut id_close = [0u8; 32];
id_close[0] = 0x80;
let result = dht
.add_node(
make_node_with_addr(id_close, "/ip4/10.0.1.1/udp/9002/quic"),
&trust_fn,
)
.await;
// Should be rejected — live trusted peer holds its slot
assert!(result.is_err());
assert!(dht.has_node(&far_peer).await);
}
// -----------------------------------------------------------------------
// Routing table event tests
// -----------------------------------------------------------------------
#[tokio::test]
async fn test_peer_added_event_on_insertion() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let node = make_node(1, "/ip4/10.0.0.1/udp/9000/quic");
let peer_id = node.id;
let events = dht.add_node_no_trust(node).await.unwrap();
assert!(
events
.iter()
.any(|e| matches!(e, RoutingTableEvent::PeerAdded(id) if *id == peer_id)),
"expected PeerAdded event for inserted peer"
);
}
#[tokio::test]
async fn test_peer_removed_event_on_removal() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let node = make_node(1, "/ip4/10.0.0.1/udp/9000/quic");
let peer_id = node.id;
dht.add_node_no_trust(node).await.unwrap();
let events = dht.remove_node_by_id(&peer_id).await;
assert!(
events
.iter()
.any(|e| matches!(e, RoutingTableEvent::PeerRemoved(id) if *id == peer_id)),
"expected PeerRemoved event for removed peer"
);
}
#[tokio::test]
async fn test_k_closest_changed_event_on_first_insertion() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
// Add a node close to self — should trigger KClosestPeersChanged (going from empty to 1)
let mut id = [0u8; 32];
id[31] = 0x01; // bucket 255, very close to self
let node = NodeInfo {
id: PeerId::from_bytes(id),
addresses: vec!["/ip4/10.0.0.1/udp/9000/quic".parse().unwrap()],
last_seen: AtomicInstant::now(),
address_types: vec![],
};
let events = dht.add_node_no_trust(node).await.unwrap();
assert!(
events
.iter()
.any(|e| matches!(e, RoutingTableEvent::KClosestPeersChanged { .. })),
"adding first close peer should trigger KClosestPeersChanged"
);
}
#[tokio::test]
async fn test_update_short_circuit_no_events() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let node = make_node(1, "/ip4/10.0.0.1/udp/9000/quic");
dht.add_node_no_trust(node.clone()).await.unwrap();
// Re-add same peer — update path, no events
let events = dht.add_node_no_trust(node).await.unwrap();
assert!(
events.is_empty(),
"update short-circuit should produce no events"
);
}
#[tokio::test]
async fn test_swap_eviction_produces_both_events() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
dht.set_live_threshold(TEST_LIVE_THRESHOLD);
// Two peers in bucket 0, same IP (exact-IP limit = 2)
let mut id_far = [0u8; 32];
id_far[0] = 0xFF;
dht.add_node_no_trust(make_node_with_addr(id_far, "/ip4/10.0.1.1/udp/9000/quic"))
.await
.unwrap();
let mut id_mid = [0u8; 32];
id_mid[0] = 0xFE;
dht.add_node_no_trust(make_node_with_addr(id_mid, "/ip4/10.0.1.1/udp/9001/quic"))
.await
.unwrap();
// Make the far peer stale for swap eligibility
{
let mut routing = dht.routing_table_for_test().write().await;
let bucket_idx = routing
.get_bucket_index(&PeerId::from_bytes(id_far))
.unwrap();
let node = routing.buckets[bucket_idx]
.nodes
.iter_mut()
.find(|n| n.id == PeerId::from_bytes(id_far))
.unwrap();
node.last_seen.store(Instant::now() - TEST_STALE_AGE);
}
// A closer candidate with the same IP triggers swap
let mut id_close = [0u8; 32];
id_close[0] = 0x80;
let far_peer = PeerId::from_bytes(id_far);
let close_peer = PeerId::from_bytes(id_close);
let result = dht
.add_node(
make_node_with_addr(id_close, "/ip4/10.0.1.1/udp/9002/quic"),
&|peer_id| if *peer_id == far_peer { 0.8 } else { 0.5 },
)
.await
.unwrap();
let events = match result {
AdmissionResult::Admitted(events) => events,
other => panic!("expected Admitted, got {:?}", other),
};
assert!(
events
.iter()
.any(|e| matches!(e, RoutingTableEvent::PeerRemoved(id) if *id == far_peer)),
"swap should produce PeerRemoved for evicted peer"
);
assert!(
events
.iter()
.any(|e| matches!(e, RoutingTableEvent::PeerAdded(id) if *id == close_peer)),
"swap should produce PeerAdded for new peer"
);
}
#[tokio::test]
async fn test_k_closest_changed_on_removal() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let node = make_node(1, "/ip4/10.0.0.1/udp/9000/quic");
let peer_id = node.id;
dht.add_node_no_trust(node).await.unwrap();
let events = dht.remove_node_by_id(&peer_id).await;
assert!(
events
.iter()
.any(|e| matches!(e, RoutingTableEvent::KClosestPeersChanged { .. })),
"removing a peer should trigger KClosestPeersChanged"
);
}
// -----------------------------------------------------------------------
// Stale peer revalidation tests (Phase 5)
// -----------------------------------------------------------------------
#[tokio::test]
async fn test_stale_revalidation_needed_when_bucket_full_with_stale_peers() {
// Use k=4 (minimum valid K) so the bucket fills quickly.
let mut dht = DhtCoreEngine::new(
PeerId::from_bytes([0u8; 32]),
4,
false,
DEFAULT_SWAP_THRESHOLD,
)
.unwrap();
dht.set_ip_diversity_config(crate::security::IPDiversityConfig::testnet());
dht.set_live_threshold(TEST_LIVE_THRESHOLD);
// Fill bucket 0 with 4 peers (k=4).
for i in 1..=4u8 {
let mut id = [0u8; 32];
id[0] = 0x80;
id[31] = i;
dht.add_node_no_trust(make_node_with_addr(
id,
&format!("/ip4/10.0.0.{i}/udp/9000/quic"),
))
.await
.unwrap();
}
// Make all peers stale.
{
let mut routing = dht.routing_table_for_test().write().await;
let mut id_a = [0u8; 32];
id_a[0] = 0x80;
id_a[31] = 1;
let bucket_idx = routing.get_bucket_index(&PeerId::from_bytes(id_a)).unwrap();
for node in &mut routing.buckets[bucket_idx].nodes {
node.last_seen.store(Instant::now() - TEST_STALE_AGE);
}
}
// New candidate for bucket 0 — bucket is full, but stale peers exist.
let mut id_new = [0u8; 32];
id_new[0] = 0x80;
id_new[31] = 5;
let result = dht
.add_node(
make_node_with_addr(id_new, "/ip4/10.0.0.5/udp/9000/quic"),
&|_| DEFAULT_NEUTRAL_TRUST,
)
.await
.unwrap();
match result {
AdmissionResult::StaleRevalidationNeeded {
candidate,
candidate_ips,
candidate_bucket_idx: _,
stale_peers,
} => {
assert_eq!(candidate.id, PeerId::from_bytes(id_new));
assert!(!candidate_ips.is_empty());
assert_eq!(stale_peers.len(), 4, "all peers should be stale");
}
AdmissionResult::Admitted(_) => panic!("expected StaleRevalidationNeeded"),
}
}
#[tokio::test]
async fn test_no_stale_revalidation_when_bucket_full_no_stale() {
// Use k=4 (minimum valid K) so the bucket fills quickly.
let mut dht = DhtCoreEngine::new(
PeerId::from_bytes([0u8; 32]),
4,
false,
DEFAULT_SWAP_THRESHOLD,
)
.unwrap();
dht.set_ip_diversity_config(crate::security::IPDiversityConfig::testnet());
// Fill bucket 0 with 4 fresh (live) peers.
for i in 1..=4u8 {
let mut id = [0u8; 32];
id[0] = 0x80;
id[31] = i;
dht.add_node_no_trust(make_node_with_addr(
id,
&format!("/ip4/10.0.0.{i}/udp/9000/quic"),
))
.await
.unwrap();
}
// New candidate — bucket full, no stale peers → hard rejection.
let mut id_new = [0u8; 32];
id_new[0] = 0x80;
id_new[31] = 5;
let result = dht
.add_node(
make_node_with_addr(id_new, "/ip4/10.0.0.5/udp/9000/quic"),
&|_| DEFAULT_NEUTRAL_TRUST,
)
.await;
assert!(result.is_err());
let msg = result.unwrap_err().to_string();
assert!(
msg.contains("no stale peers"),
"error should mention no stale peers, got: {msg}"
);
}
#[tokio::test]
async fn test_re_evaluate_admission_after_eviction() {
// Use k=4 (minimum valid K) so the bucket fills quickly.
let mut dht = DhtCoreEngine::new(
PeerId::from_bytes([0u8; 32]),
4,
false,
DEFAULT_SWAP_THRESHOLD,
)
.unwrap();
dht.set_ip_diversity_config(crate::security::IPDiversityConfig::testnet());
// Fill bucket 0 with 4 peers.
for i in 1..=4u8 {
let mut id = [0u8; 32];
id[0] = 0x80;
id[31] = i;
dht.add_node_no_trust(make_node_with_addr(
id,
&format!("/ip4/10.0.0.{i}/udp/9000/quic"),
))
.await
.unwrap();
}
// Evict one peer (simulating revalidation outcome).
let mut id_a = [0u8; 32];
id_a[0] = 0x80;
id_a[31] = 1;
dht.remove_node_by_id(&PeerId::from_bytes(id_a)).await;
// Re-evaluate admission — should succeed now that there's room.
let mut id_new = [0u8; 32];
id_new[0] = 0x80;
id_new[31] = 5;
let candidate = make_node_with_addr(id_new, "/ip4/10.0.0.5/udp/9000/quic");
let candidate_ips = vec!["10.0.0.5".parse().unwrap()];
let events = dht
.re_evaluate_admission(candidate, &candidate_ips, &|_| DEFAULT_NEUTRAL_TRUST)
.await
.unwrap();
assert!(
events.iter().any(
|e| matches!(e, RoutingTableEvent::PeerAdded(id) if *id == PeerId::from_bytes(id_new))
),
"re-evaluation should produce PeerAdded"
);
assert!(dht.has_node(&PeerId::from_bytes(id_new)).await);
}
#[tokio::test]
async fn test_re_evaluate_admits_low_trust_candidate() {
let mut dht = DhtCoreEngine::new(
PeerId::from_bytes([0u8; 32]),
20,
false,
DEFAULT_SWAP_THRESHOLD,
)
.unwrap();
let mut id = [0u8; 32];
id[0] = 0x80;
let candidate = make_node_with_addr(id, "/ip4/10.0.0.1/udp/9000/quic");
let candidate_ips = vec!["10.0.0.1".parse().unwrap()];
// Trust below swap threshold — should still be admitted
let result = dht
.re_evaluate_admission(candidate, &candidate_ips, &|_| 0.1)
.await;
assert!(
result.is_ok(),
"low-trust candidate should be admitted via re-evaluate"
);
}
#[tokio::test]
async fn test_re_evaluate_does_not_trigger_second_revalidation() {
// Use k=4 (minimum valid K) so the bucket fills quickly.
let mut dht = DhtCoreEngine::new(
PeerId::from_bytes([0u8; 32]),
4,
false,
DEFAULT_SWAP_THRESHOLD,
)
.unwrap();
dht.set_ip_diversity_config(crate::security::IPDiversityConfig::testnet());
dht.set_live_threshold(TEST_LIVE_THRESHOLD);
// Fill bucket 0 with 4 stale peers.
for i in 1..=4u8 {
let mut id = [0u8; 32];
id[0] = 0x80;
id[31] = i;
dht.add_node_no_trust(make_node_with_addr(
id,
&format!("/ip4/10.0.0.{i}/udp/9000/quic"),
))
.await
.unwrap();
}
// Make all stale.
{
let mut routing = dht.routing_table_for_test().write().await;
let mut id_a = [0u8; 32];
id_a[0] = 0x80;
id_a[31] = 1;
let bucket_idx = routing.get_bucket_index(&PeerId::from_bytes(id_a)).unwrap();
for node in &mut routing.buckets[bucket_idx].nodes {
node.last_seen.store(Instant::now() - TEST_STALE_AGE);
}
}
// re_evaluate_admission with full bucket and stale peers should reject,
// NOT return StaleRevalidationNeeded (no second round).
let mut id_new = [0u8; 32];
id_new[0] = 0x80;
id_new[31] = 5;
let candidate = make_node_with_addr(id_new, "/ip4/10.0.0.5/udp/9000/quic");
let candidate_ips = vec!["10.0.0.5".parse().unwrap()];
let result = dht
.re_evaluate_admission(candidate, &candidate_ips, &|_| DEFAULT_NEUTRAL_TRUST)
.await;
assert!(result.is_err());
let msg = result.unwrap_err().to_string();
assert!(
msg.contains("no stale peers"),
"re-evaluation should not trigger another revalidation round, got: {msg}"
);
}
#[tokio::test]
async fn test_collect_stale_peers_in_bucket() {
let mut dht = DhtCoreEngine::new(
PeerId::from_bytes([0u8; 32]),
20,
false,
DEFAULT_SWAP_THRESHOLD,
)
.unwrap();
dht.set_live_threshold(TEST_LIVE_THRESHOLD);
// Add a fresh peer.
let mut id_fresh = [0u8; 32];
id_fresh[0] = 0x80;
id_fresh[31] = 1;
dht.add_node_no_trust(make_node_with_addr(id_fresh, "/ip4/10.0.0.1/udp/9000/quic"))
.await
.unwrap();
// Add a stale peer.
let mut id_stale = [0u8; 32];
id_stale[0] = 0x80;
id_stale[31] = 2;
dht.add_node_no_trust(make_node_with_addr(id_stale, "/ip4/10.0.0.2/udp/9000/quic"))
.await
.unwrap();
{
let mut routing = dht.routing_table_for_test().write().await;
let bucket_idx = routing
.get_bucket_index(&PeerId::from_bytes(id_stale))
.unwrap();
// Make one peer stale.
let node = routing.buckets[bucket_idx]
.nodes
.iter_mut()
.find(|n| n.id == PeerId::from_bytes(id_stale))
.unwrap();
node.last_seen.store(Instant::now() - TEST_STALE_AGE);
let stale = DhtCoreEngine::collect_stale_peers_in_bucket(
&routing,
bucket_idx,
TEST_LIVE_THRESHOLD,
);
assert_eq!(stale.len(), 1);
assert_eq!(stale[0].0, PeerId::from_bytes(id_stale));
}
}
// -----------------------------------------------------------------------
// generate_random_key_for_bucket tests
// -----------------------------------------------------------------------
#[tokio::test]
async fn test_generate_random_key_for_bucket_lands_in_correct_bucket() {
let local_id = PeerId::random();
let dht = DhtCoreEngine::new_for_tests(local_id).unwrap();
// Test a selection of bucket indices across the key space.
let test_indices: Vec<usize> = vec![0, 1, 7, 8, 15, 127, 128, 200, 255];
for bucket_idx in test_indices {
let key = dht
.generate_random_key_for_bucket(bucket_idx)
.expect("should produce a key for valid bucket index");
// Verify the generated key falls into the expected bucket by computing
// the XOR distance and checking the leading bit position.
let distance = xor_distance_bytes(local_id.to_bytes(), key.as_bytes());
let leading_bit = leading_bit_position(&distance);
assert_eq!(
leading_bit,
Some(bucket_idx),
"key for bucket {bucket_idx} has wrong leading bit position: {leading_bit:?}"
);
}
}
#[tokio::test]
async fn test_generate_random_key_for_bucket_out_of_range() {
let dht = DhtCoreEngine::new_for_tests(PeerId::random()).unwrap();
assert!(dht.generate_random_key_for_bucket(256).is_none());
assert!(dht.generate_random_key_for_bucket(1000).is_none());
}
#[tokio::test]
async fn test_generate_random_key_for_bucket_produces_different_keys() {
let dht = DhtCoreEngine::new_for_tests(PeerId::random()).unwrap();
let mut keys = HashSet::new();
for _ in 0..10 {
let key = dht.generate_random_key_for_bucket(100).unwrap();
keys.insert(key);
}
// With 10 random keys, they should not all be identical.
assert!(
keys.len() > 1,
"generate_random_key_for_bucket should produce distinct keys"
);
}
#[tokio::test]
async fn test_bucket_refresh_candidates_returns_all_buckets_when_fresh() {
let dht = DhtCoreEngine::new_for_tests(PeerId::random()).unwrap();
let candidates = dht.bucket_refresh_candidates().await;
assert_eq!(
candidates.len(),
KADEMLIA_BUCKET_COUNT,
"bucket refresh should continuously rank all buckets"
);
}
#[tokio::test]
async fn bucket_refresh_candidates_use_probe_debt() {
let dht = DhtCoreEngine::new_for_tests(PeerId::random()).unwrap();
let bucket_idx = 7;
let live_age = Duration::from_secs(2);
let probe_age = Duration::from_millis(50);
{
let mut routing = dht.routing_table_for_test().write().await;
let bucket = &mut routing.buckets[bucket_idx];
bucket.last_refreshed_by_live_peer = instant_ago(live_age);
bucket.last_probe_finished.store(instant_ago(probe_age));
}
let candidates = dht.bucket_refresh_candidates().await;
let candidate = candidates
.into_iter()
.find(|candidate| candidate.index == bucket_idx)
.expect("bucket should be returned");
assert!(candidate.live_peer_age >= live_age);
assert!(candidate.probe_age >= probe_age);
assert!(
candidate.refresh_debt < live_age,
"recent probe should limit refresh debt: {:?}",
candidate.refresh_debt
);
}
#[tokio::test]
async fn marking_bucket_probe_finished_does_not_refresh_live_peer_timestamp() {
let dht = DhtCoreEngine::new_for_tests(PeerId::random()).unwrap();
let bucket_idx = 11;
let old_live = instant_ago(Duration::from_secs(2));
let old_probe = instant_ago(Duration::from_millis(50));
{
let mut routing = dht.routing_table_for_test().write().await;
let bucket = &mut routing.buckets[bucket_idx];
bucket.last_refreshed_by_live_peer = old_live;
bucket.last_probe_finished.store(old_probe);
}
assert!(dht.mark_bucket_probe_finished(bucket_idx).await);
let routing = dht.routing_table_for_test().read().await;
let bucket = &routing.buckets[bucket_idx];
assert_eq!(bucket.last_refreshed_by_live_peer, old_live);
assert!(bucket.last_probe_finished.load() > old_probe);
}
#[tokio::test]
async fn test_node_id_accessor() {
let id = PeerId::random();
let dht = DhtCoreEngine::new_for_tests(id).unwrap();
assert_eq!(*dht.node_id(), id);
}
/// Helper: find the position of the first set bit (from MSB) in a 32-byte distance.
/// Returns `None` for an all-zero distance.
fn leading_bit_position(distance: &[u8; 32]) -> Option<usize> {
for i in 0..256 {
let byte_index = i / 8;
let bit_index = 7 - (i % 8);
if (distance[byte_index] >> bit_index) & 1 == 1 {
return Some(i);
}
}
None
}
/// Return an `Instant` approximately `duration` in the past without
/// assuming the runner's monotonic clock has already existed that long.
fn instant_ago(duration: Duration) -> Instant {
if let Some(instant) = Instant::now().checked_sub(duration) {
return instant;
}
std::thread::sleep(duration.saturating_add(Duration::from_millis(1)));
Instant::now()
.checked_sub(duration)
.expect("runner Instant should be old enough after sleeping")
}
// =======================================================================
// Phase 8: Integration test matrix — missing coverage
// =======================================================================
// -----------------------------------------------------------------------
// Test 12: Non-IP transport bypass
// -----------------------------------------------------------------------
/// A peer with a non-IP address (Bluetooth) should bypass all IP diversity
/// checks and be admitted up to bucket capacity.
#[tokio::test]
async fn test_non_ip_transport_bypasses_diversity() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
// Create a node with a Bluetooth-only address (no IP).
let mut id = [0u8; 32];
id[0] = 0x80;
id[31] = 1;
let bt_addr = MultiAddr::new(TransportAddr::Bluetooth {
mac: [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0x01],
channel: 5,
});
let node = NodeInfo {
id: PeerId::from_bytes(id),
addresses: vec![bt_addr],
last_seen: AtomicInstant::now(),
address_types: vec![],
};
let result = dht.add_node_no_trust(node).await;
assert!(
result.is_ok(),
"non-IP transport should bypass diversity: {:?}",
result
);
assert!(dht.has_node(&PeerId::from_bytes(id)).await);
// Add several more Bluetooth-only nodes to the same bucket — all should succeed
// because IP diversity is not checked for non-IP transports.
for i in 2..=5u8 {
let mut node_id = [0u8; 32];
node_id[0] = 0x80;
node_id[31] = i;
let bt = MultiAddr::new(TransportAddr::Bluetooth {
mac: [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, i],
channel: 5,
});
let n = NodeInfo {
id: PeerId::from_bytes(node_id),
addresses: vec![bt],
last_seen: AtomicInstant::now(),
address_types: vec![],
};
let r = dht.add_node_no_trust(n).await;
assert!(r.is_ok(), "Bluetooth node {i} should be admitted: {:?}", r);
}
}
// -----------------------------------------------------------------------
// Test 26: Local lookup self-exclusion
// -----------------------------------------------------------------------
/// `find_nodes` (local lookup) must never return self, even when searching
/// for our own key.
#[tokio::test]
async fn test_local_lookup_excludes_self() {
let self_id = PeerId::from_bytes([0u8; 32]);
let mut dht = DhtCoreEngine::new_for_tests(self_id).unwrap();
dht.add_node_no_trust(make_node(1, "/ip4/10.0.0.1/udp/9000/quic"))
.await
.unwrap();
// Search for self's own key — self should NOT appear in results
// because self is never in its own routing table.
let results = dht
.find_nodes(&DhtKey::from_bytes([0u8; 32]), 10)
.await
.unwrap();
assert!(
results.iter().all(|n| n.id != self_id),
"self must be excluded from local lookup results"
);
// But other peers should still be returned.
assert_eq!(results.len(), 1, "expected the one added peer");
}
// -----------------------------------------------------------------------
// Test 29: find_nodes_with_self includes self
// -----------------------------------------------------------------------
/// `find_nodes_with_self` must include self as a candidate, correctly
/// positioned by XOR distance.
#[tokio::test]
async fn test_find_nodes_with_self_includes_self() {
let self_id = PeerId::from_bytes([0u8; 32]);
let mut dht = DhtCoreEngine::new_for_tests(self_id).unwrap();
dht.add_node_no_trust(make_node(1, "/ip4/10.0.0.1/udp/9000/quic"))
.await
.unwrap();
// Search for self's own key — distance is zero, so self should be first.
let results = dht
.find_nodes_with_self(&DhtKey::from_bytes([0u8; 32]), 10)
.await
.unwrap();
assert!(
results.iter().any(|n| n.id == self_id),
"self should be included in find_nodes_with_self results"
);
// Self should be first (distance 0 to the search key)
assert_eq!(results[0].id, self_id, "self should be the closest match");
}
// -----------------------------------------------------------------------
// Test 36: Peer removal via remove_node_by_id
// -----------------------------------------------------------------------
/// Removing a peer by ID should produce PeerRemoved events.
#[tokio::test]
async fn test_peer_removal_produces_events() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let node = make_node(1, "/ip4/10.0.0.1/udp/9000/quic");
let peer_id = node.id;
dht.add_node_no_trust(node).await.unwrap();
assert!(dht.has_node(&peer_id).await);
// Graceful removal (e.g. peer departed).
let events = dht.remove_node_by_id(&peer_id).await;
assert!(
!dht.has_node(&peer_id).await,
"peer must be gone after removal"
);
assert!(
events
.iter()
.any(|e| matches!(e, RoutingTableEvent::PeerRemoved(id) if *id == peer_id)),
"expected PeerRemoved event"
);
}
// -----------------------------------------------------------------------
// Test 36 extension: removing an absent peer is a no-op
// -----------------------------------------------------------------------
#[tokio::test]
async fn test_remove_absent_peer_produces_no_events() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let absent_peer = PeerId::from_bytes([99u8; 32]);
let events = dht.remove_node_by_id(&absent_peer).await;
assert!(
events.is_empty(),
"removing a peer not in the routing table should produce no events"
);
}
// -----------------------------------------------------------------------
// Test 49: Trust protection prevents eclipse displacement (live peers)
// -----------------------------------------------------------------------
/// An attacker with a closer ID cannot displace a live well-trusted peer.
/// Only low-trust, stale, or empty slots can be taken.
#[tokio::test]
async fn test_eclipse_resistance_live_trusted_peers() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
// Fill 2 same-IP slots in bucket 0 with trusted, live peers.
let mut id_a = [0u8; 32];
id_a[0] = 0xFF;
dht.add_node_no_trust(make_node_with_addr(id_a, "/ip4/10.0.1.1/udp/9000/quic"))
.await
.unwrap();
let mut id_b = [0u8; 32];
id_b[0] = 0xFE;
dht.add_node_no_trust(make_node_with_addr(id_b, "/ip4/10.0.1.1/udp/9001/quic"))
.await
.unwrap();
// Attacker generates a much closer ID with the same IP.
let mut id_attacker = [0u8; 32];
id_attacker[0] = 0x80;
// Both existing peers are live (just added) and well-trusted.
let peer_a = PeerId::from_bytes(id_a);
let peer_b = PeerId::from_bytes(id_b);
let trust_fn = |peer_id: &PeerId| -> f64 {
if *peer_id == peer_a || *peer_id == peer_b {
0.9 // well above TRUST_PROTECTION_THRESHOLD
} else {
0.5
}
};
let result = dht
.add_node(
make_node_with_addr(id_attacker, "/ip4/10.0.1.1/udp/9002/quic"),
&trust_fn,
)
.await;
// Should be rejected — both peers are live and well-trusted.
assert!(
result.is_err(),
"attacker should not displace live trusted peers"
);
assert!(dht.has_node(&peer_a).await, "peer A must survive");
assert!(dht.has_node(&peer_b).await, "peer B must survive");
}
// -----------------------------------------------------------------------
// Test 50: Stale trust-protected peer displaced by attacker
// -----------------------------------------------------------------------
/// A well-trusted but stale peer can be displaced by a closer candidate.
/// This is correct: a stale peer should not block admission indefinitely.
#[tokio::test]
async fn test_stale_trusted_peer_displaced_by_closer_candidate() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
dht.set_live_threshold(TEST_LIVE_THRESHOLD);
let mut id_far = [0u8; 32];
id_far[0] = 0xFF;
dht.add_node_no_trust(make_node_with_addr(id_far, "/ip4/10.0.1.1/udp/9000/quic"))
.await
.unwrap();
let mut id_mid = [0u8; 32];
id_mid[0] = 0xFE;
dht.add_node_no_trust(make_node_with_addr(id_mid, "/ip4/10.0.1.1/udp/9001/quic"))
.await
.unwrap();
// Make the far peer stale.
{
let mut routing = dht.routing_table_for_test().write().await;
let bucket_idx = routing
.get_bucket_index(&PeerId::from_bytes(id_far))
.unwrap();
let node = routing.buckets[bucket_idx]
.nodes
.iter_mut()
.find(|n| n.id == PeerId::from_bytes(id_far))
.unwrap();
node.last_seen.store(Instant::now() - TEST_STALE_AGE);
}
let far_peer = PeerId::from_bytes(id_far);
// Far peer is well-trusted but STALE.
let trust_fn = |peer_id: &PeerId| -> f64 { if *peer_id == far_peer { 0.9 } else { 0.5 } };
let mut id_closer = [0u8; 32];
id_closer[0] = 0x80;
let result = dht
.add_node(
make_node_with_addr(id_closer, "/ip4/10.0.1.1/udp/9002/quic"),
&trust_fn,
)
.await;
// Should succeed: stale peer loses trust protection.
assert!(
result.is_ok(),
"stale well-trusted peer should be displaceable: {:?}",
result
);
assert!(
!dht.has_node(&far_peer).await,
"stale peer should be evicted"
);
assert!(
dht.has_node(&PeerId::from_bytes(id_closer)).await,
"closer candidate should be admitted"
);
}
// -----------------------------------------------------------------------
// Test 56: Consumer event for peer not in routing table
// -----------------------------------------------------------------------
/// Trust events for peers not in the routing table should not affect the
/// routing table. (TrustEngine records the score independently.)
#[tokio::test]
async fn test_trust_event_for_absent_peer_does_not_affect_rt() {
let dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let absent_peer = PeerId::from_bytes([42u8; 32]);
// Peer is not in the routing table.
assert!(!dht.has_node(&absent_peer).await);
// The routing table should remain unchanged after trust events
// (trust is tracked externally in TrustEngine, not in the RT).
let size_before = dht.routing_table_size().await;
assert!(!dht.has_node(&absent_peer).await);
let size_after = dht.routing_table_size().await;
assert_eq!(size_before, size_after, "routing table should be unchanged");
}
// -----------------------------------------------------------------------
// Trust-based swap-out tests
// -----------------------------------------------------------------------
/// When a bucket is full, the lowest-trust peer below swap_threshold is
/// replaced by a new candidate without revalidation.
#[tokio::test]
async fn test_trust_swap_out_replaces_lowest_trust_peer() {
// K=4 so we can fill a bucket quickly. All peers go into the
// high-bit bucket (byte 0 has bit 7 set, our node_id is [0; 32]).
let mut dht = DhtCoreEngine::new(
PeerId::from_bytes([0u8; 32]),
4,
false,
DEFAULT_SWAP_THRESHOLD,
)
.unwrap();
// Fill bucket with 4 peers, each on a unique IP
let mut ids: Vec<[u8; 32]> = Vec::new();
for i in 0..4u8 {
let mut id = [0u8; 32];
id[0] = 0x80 + i; // all land in same bucket (bit 7 set)
ids.push(id);
let addr = format!("/ip4/10.0.{}.1/udp/9000/quic", i);
dht.add_node(make_node_with_addr(id, &addr), &|_| 0.5)
.await
.unwrap();
}
// New candidate on a unique IP
let mut new_id = [0u8; 32];
new_id[0] = 0x84;
let new_peer = PeerId::from_bytes(new_id);
let low_trust_peer = PeerId::from_bytes(ids[2]);
// Peer ids[2] has trust 0.05 (below 0.35 threshold), others at 0.5
let result = dht
.add_node(
make_node_with_addr(new_id, "/ip4/10.0.4.1/udp/9000/quic"),
&|id| {
if *id == low_trust_peer { 0.05 } else { 0.5 }
},
)
.await
.unwrap();
let events = match result {
AdmissionResult::Admitted(events) => events,
other => panic!("expected Admitted, got {other:?}"),
};
assert!(
events
.iter()
.any(|e| matches!(e, RoutingTableEvent::PeerRemoved(id) if *id == low_trust_peer)),
"low-trust peer should be swapped out"
);
assert!(
events
.iter()
.any(|e| matches!(e, RoutingTableEvent::PeerAdded(id) if *id == new_peer)),
"new candidate should be added"
);
assert!(dht.has_node(&new_peer).await);
assert!(!dht.has_node(&low_trust_peer).await);
}
/// When multiple peers are below the swap threshold, only the lowest-trust
/// peer is swapped out.
#[tokio::test]
async fn test_trust_swap_out_picks_lowest_when_multiple_below_threshold() {
let mut dht = DhtCoreEngine::new(
PeerId::from_bytes([0u8; 32]),
4,
false,
DEFAULT_SWAP_THRESHOLD,
)
.unwrap();
let mut ids: Vec<[u8; 32]> = Vec::new();
for i in 0..4u8 {
let mut id = [0u8; 32];
id[0] = 0x80 + i;
ids.push(id);
let addr = format!("/ip4/10.0.{}.1/udp/9000/quic", i);
dht.add_node(make_node_with_addr(id, &addr), &|_| 0.5)
.await
.unwrap();
}
let peer_a = PeerId::from_bytes(ids[1]); // will have trust 0.10
let peer_b = PeerId::from_bytes(ids[3]); // will have trust 0.05
let mut new_id = [0u8; 32];
new_id[0] = 0x84;
let result = dht
.add_node(
make_node_with_addr(new_id, "/ip4/10.0.4.1/udp/9000/quic"),
&|id| {
if *id == peer_a {
0.10
} else if *id == peer_b {
0.05
} else {
0.5
}
},
)
.await
.unwrap();
let events = match result {
AdmissionResult::Admitted(events) => events,
other => panic!("expected Admitted, got {other:?}"),
};
// Only the lowest-trust peer (0.05) should be evicted
assert!(
events
.iter()
.any(|e| matches!(e, RoutingTableEvent::PeerRemoved(id) if *id == peer_b)),
"peer with lowest trust (0.05) should be swapped out"
);
assert!(
dht.has_node(&peer_a).await,
"peer with trust 0.10 should remain (only one swap needed)"
);
}
/// When all peers in the bucket are above the swap threshold, no trust-based
/// swap occurs and the system falls through to stale revalidation.
#[tokio::test]
async fn test_no_trust_swap_when_all_peers_above_threshold() {
let mut dht = DhtCoreEngine::new(
PeerId::from_bytes([0u8; 32]),
4,
false,
DEFAULT_SWAP_THRESHOLD,
)
.unwrap();
for i in 0..4u8 {
let mut id = [0u8; 32];
id[0] = 0x80 + i;
let addr = format!("/ip4/10.0.{}.1/udp/9000/quic", i);
dht.add_node(make_node_with_addr(id, &addr), &|_| 0.5)
.await
.unwrap();
}
let mut new_id = [0u8; 32];
new_id[0] = 0x84;
// All peers at neutral (0.5) — no trust-based swap possible
let result = dht
.add_node(
make_node_with_addr(new_id, "/ip4/10.0.4.1/udp/9000/quic"),
&|_| 0.5,
)
.await;
// Should get StaleRevalidationNeeded (default allow_stale_revalidation=true
// in add_node) or error — NOT Admitted
match result {
Ok(AdmissionResult::Admitted(_)) => {
panic!("should not be admitted when bucket is full with no low-trust peers")
}
Ok(AdmissionResult::StaleRevalidationNeeded { .. }) => {
// Expected: falls through to stale revalidation
}
Err(_) => {
// Also acceptable: no stale peers found
}
}
}
/// With swap_threshold = 0.0, trust-based swap-out is disabled.
#[tokio::test]
async fn test_no_trust_swap_when_threshold_is_zero() {
let mut dht = DhtCoreEngine::new(
PeerId::from_bytes([0u8; 32]),
4,
false,
0.0, // disabled
)
.unwrap();
let mut ids: Vec<[u8; 32]> = Vec::new();
for i in 0..4u8 {
let mut id = [0u8; 32];
id[0] = 0x80 + i;
ids.push(id);
let addr = format!("/ip4/10.0.{}.1/udp/9000/quic", i);
dht.add_node(make_node_with_addr(id, &addr), &|_| 0.5)
.await
.unwrap();
}
let low_peer = PeerId::from_bytes(ids[0]);
let mut new_id = [0u8; 32];
new_id[0] = 0x84;
// Even with a peer at trust 0.01, threshold=0 means no swap
let result = dht
.add_node(
make_node_with_addr(new_id, "/ip4/10.0.4.1/udp/9000/quic"),
&|id| if *id == low_peer { 0.01 } else { 0.5 },
)
.await;
match result {
Ok(AdmissionResult::Admitted(_)) => {
panic!("should not be admitted when swap is disabled and bucket is full")
}
_ => {
// Expected: stale revalidation or error
}
}
// Low-trust peer should still be in the table
assert!(dht.has_node(&low_peer).await);
}
// -----------------------------------------------------------------------
// AddressType::Unverified tests
// -----------------------------------------------------------------------
#[test]
fn address_type_priority_is_relay_direct_unverified_lan() {
assert!(AddressType::Relay.priority() < AddressType::Direct.priority());
assert!(AddressType::Direct.priority() < AddressType::Unverified.priority());
assert!(AddressType::Unverified.priority() < AddressType::Lan.priority());
}
#[test]
fn address_type_accepts_legacy_natted_name_as_lan() {
let decoded: AddressType = serde_json::from_str("\"NATted\"").unwrap();
assert_eq!(decoded, AddressType::Lan);
}
#[test]
fn local_scope_address_type_is_canonicalized_to_lan() {
let mut node = NodeInfo {
id: PeerId::from_bytes([1u8; 32]),
addresses: Vec::new(),
address_types: Vec::new(),
last_seen: AtomicInstant::now(),
};
let private: MultiAddr = "/ip4/192.168.1.10/udp/9000/quic".parse().unwrap();
node.merge_typed_address(private.clone(), AddressType::Direct);
assert_eq!(node.addresses, vec![private]);
assert_eq!(node.address_types, vec![AddressType::Lan]);
assert_eq!(node.address_type_at(0), AddressType::Lan);
}
#[test]
fn mapped_local_scope_address_type_is_canonicalized_to_lan() {
let cases = [
(
"/ip6/::ffff:192.168.1.10/udp/9000/quic",
AddressType::Direct,
),
(
"/ip6/::ffff:127.0.0.1/udp/9001/quic",
AddressType::Unverified,
),
("/ip6/::ffff:100.64.0.1/udp/9002/quic", AddressType::Relay),
];
for (idx, (addr, advertised)) in cases.into_iter().enumerate() {
let mut node = NodeInfo {
id: PeerId::from_bytes([idx as u8; 32]),
addresses: Vec::new(),
address_types: Vec::new(),
last_seen: AtomicInstant::now(),
};
let addr: MultiAddr = addr.parse().unwrap();
node.merge_typed_address(addr.clone(), advertised);
assert_eq!(node.addresses, vec![addr], "case {idx}");
assert_eq!(node.address_types, vec![AddressType::Lan], "case {idx}");
assert_eq!(node.address_type_at(0), AddressType::Lan, "case {idx}");
}
}
#[test]
fn merge_same_family_keeps_relay_best_wan_and_lan() {
// Under the per-IP-family cap: at most 1 Relay + 1 WAN
// non-Relay (Direct/Unverified) + 1 Lan per family. Direct is the
// strongest WAN tier, but it must not evict the local path that
// same-WAN peers can use.
let mut node = make_node(1, "/ip4/203.0.113.1/udp/9000/quic");
let direct = node.addresses[0].clone();
let relay: MultiAddr = "/ip4/198.51.100.1/udp/9000/quic".parse().unwrap();
let unverified: MultiAddr = "/ip4/203.0.113.2/udp/9000/quic".parse().unwrap();
let lan: MultiAddr = "/ip4/192.168.1.4/udp/9000/quic".parse().unwrap();
node.merge_typed_address(lan.clone(), AddressType::Lan);
node.merge_typed_address(unverified, AddressType::Unverified);
node.merge_typed_address(relay.clone(), AddressType::Relay);
assert_eq!(
node.address_types,
vec![AddressType::Relay, AddressType::Direct, AddressType::Lan]
);
assert_eq!(node.addresses, vec![relay, direct, lan]);
}
#[test]
fn merge_unverified_caps_at_one_per_ip_family() {
// Per the per-IP-family cap, a peer with a same-family Direct
// (from `make_node`) retains it and any subsequent Unverified in
// that family is dropped. If the Direct is absent, the cap keeps
// exactly one Unverified per IP family — the newest.
let mut node = make_node(1, "/ip4/10.0.0.1/udp/9000/quic");
for i in 0..4 {
let addr: MultiAddr = format!("/ip4/10.1.0.{}/udp/9000/quic", i).parse().unwrap();
node.merge_typed_address(addr, AddressType::Unverified);
}
// Direct dominates Unverified within the same family.
let direct_count = node
.address_types
.iter()
.filter(|t| **t == AddressType::Direct)
.count();
let unverified_count = node
.address_types
.iter()
.filter(|t| **t == AddressType::Unverified)
.count();
assert_eq!(direct_count, 1);
assert_eq!(unverified_count, 0);
}
// -----------------------------------------------------------------------
// Per-IP-family cap — targeted tests
// -----------------------------------------------------------------------
fn node_with(addresses: Vec<(&str, AddressType)>) -> NodeInfo {
NodeInfo {
id: PeerId::from_bytes([1u8; 32]),
addresses: addresses
.iter()
.map(|(a, _)| a.parse::<MultiAddr>().unwrap())
.collect(),
address_types: addresses.iter().map(|(_, t)| *t).collect(),
last_seen: AtomicInstant::now(),
}
}
#[test]
fn cap_allows_relay_plus_best_non_relay_per_family() {
let mut node = node_with(vec![
("/ip4/10.0.0.1/udp/9000/quic", AddressType::Relay),
("/ip4/1.1.1.1/udp/9000/quic", AddressType::Direct),
("/ip6/2001:db8::1/udp/9000/quic", AddressType::Relay),
("/ip6/2001:db8::2/udp/9000/quic", AddressType::Direct),
]);
node.enforce_per_ip_family_cap();
assert_eq!(node.addresses.len(), 4);
}
#[test]
fn cap_direct_dominates_unverified_same_family() {
let mut node = node_with(vec![
("/ip4/1.1.1.1/udp/9000/quic", AddressType::Direct),
("/ip4/2.2.2.2/udp/9000/quic", AddressType::Unverified),
]);
node.enforce_per_ip_family_cap();
assert_eq!(node.address_types, vec![AddressType::Direct]);
assert_eq!(
node.addresses,
vec!["/ip4/1.1.1.1/udp/9000/quic".parse().unwrap()]
);
}
#[test]
fn cap_direct_preserves_lan_same_family() {
let mut node = node_with(vec![
("/ip4/1.1.1.1/udp/9000/quic", AddressType::Direct),
("/ip4/192.168.1.20/udp/9000/quic", AddressType::Lan),
]);
node.enforce_per_ip_family_cap();
assert_eq!(
node.address_types,
vec![AddressType::Direct, AddressType::Lan]
);
}
#[test]
fn cap_unverified_preserves_lan_same_family() {
let mut node = node_with(vec![
("/ip4/2.2.2.2/udp/9000/quic", AddressType::Unverified),
("/ip4/192.168.1.30/udp/9000/quic", AddressType::Lan),
]);
node.enforce_per_ip_family_cap();
assert_eq!(
node.address_types,
vec![AddressType::Unverified, AddressType::Lan]
);
}
#[test]
fn cap_relay_plus_unverified_allowed() {
let mut node = node_with(vec![
("/ip4/10.0.0.1/udp/9000/quic", AddressType::Relay),
("/ip4/2.2.2.2/udp/9000/quic", AddressType::Unverified),
]);
node.enforce_per_ip_family_cap();
assert_eq!(
node.address_types,
vec![AddressType::Relay, AddressType::Unverified]
);
}
#[test]
fn cap_ipv4_and_ipv6_are_independent() {
// IPv4 has only an Unverified, IPv6 has a Direct. The IPv6 Direct
// must not cross-drop the IPv4 Unverified — precedence is scoped
// to the same family.
let mut node = node_with(vec![
("/ip4/2.2.2.2/udp/9000/quic", AddressType::Unverified),
("/ip6/2001:db8::1/udp/9000/quic", AddressType::Direct),
]);
node.enforce_per_ip_family_cap();
assert_eq!(node.addresses.len(), 2);
}
#[test]
fn cap_merge_direct_then_lan_keeps_both() {
let mut node = node_with(vec![("/ip4/1.1.1.1/udp/9000/quic", AddressType::Direct)]);
node.merge_typed_address(
"/ip4/192.168.1.20/udp/9000/quic".parse().unwrap(),
AddressType::Lan,
);
assert_eq!(
node.address_types,
vec![AddressType::Direct, AddressType::Lan]
);
}
#[test]
fn cap_merge_lan_then_direct_keeps_both() {
let mut node = node_with(vec![("/ip4/192.168.1.20/udp/9000/quic", AddressType::Lan)]);
node.merge_typed_address(
"/ip4/1.1.1.1/udp/9000/quic".parse().unwrap(),
AddressType::Direct,
);
assert_eq!(
node.address_types,
vec![AddressType::Direct, AddressType::Lan]
);
assert_eq!(
node.addresses,
vec![
"/ip4/1.1.1.1/udp/9000/quic".parse().unwrap(),
"/ip4/192.168.1.20/udp/9000/quic".parse().unwrap()
]
);
}
#[test]
fn cap_newest_relay_replaces_stale_same_family_relay() {
let mut node = node_with(vec![(
"/ip4/198.51.100.1/udp/9000/quic",
AddressType::Relay,
)]);
node.merge_typed_address(
"/ip4/198.51.100.2/udp/9000/quic".parse().unwrap(),
AddressType::Relay,
);
assert_eq!(
node.addresses,
vec!["/ip4/198.51.100.2/udp/9000/quic".parse().unwrap()]
);
assert_eq!(node.address_types, vec![AddressType::Relay]);
}
#[test]
fn cap_newest_relay_preserves_different_family_relay() {
let mut node = node_with(vec![("/ip6/2001:db8::1/udp/9000/quic", AddressType::Relay)]);
node.merge_typed_address(
"/ip4/198.51.100.1/udp/9000/quic".parse().unwrap(),
AddressType::Relay,
);
let mut relays: Vec<_> = node
.addresses
.iter()
.zip(node.address_types.iter())
.filter(|(_, t)| **t == AddressType::Relay)
.map(|(a, _)| a.to_string())
.collect();
relays.sort();
assert_eq!(
relays,
vec![
"/ip4/198.51.100.1/udp/9000/quic".to_string(),
"/ip6/2001:db8::1/udp/9000/quic".to_string(),
]
);
}
#[test]
fn cap_normalizes_legacy_multi_entry_input() {
let mut node = node_with(vec![
("/ip4/1.1.1.1/udp/9000/quic", AddressType::Direct),
("/ip4/2.2.2.2/udp/9000/quic", AddressType::Direct),
("/ip4/3.3.3.3/udp/9000/quic", AddressType::Direct),
]);
node.enforce_per_ip_family_cap();
assert_eq!(node.addresses.len(), 1);
}
#[test]
fn untagged_address_type_falls_back_to_unverified() {
// NodeInfo::address_type_at — an untagged index must not claim
// Direct-reachability; legacy records never asserted it.
let node = NodeInfo {
id: PeerId::from_bytes([1u8; 32]),
addresses: vec![
"/ip4/203.0.113.10/udp/9000/quic".parse().unwrap(),
"/ip4/203.0.113.11/udp/9000/quic".parse().unwrap(),
],
address_types: vec![], // legacy: no tags at all
last_seen: AtomicInstant::now(),
};
assert_eq!(node.address_type_at(0), AddressType::Unverified);
assert_eq!(node.address_type_at(1), AddressType::Unverified);
}
#[test]
fn merge_typed_address_upgrade_only_promotes_unverified_to_direct() {
let addr: MultiAddr = "/ip4/203.0.113.10/udp/9000/quic".parse().unwrap();
let mut node = NodeInfo {
id: PeerId::from_bytes([1u8; 32]),
addresses: vec![addr.clone()],
address_types: vec![AddressType::Unverified],
last_seen: AtomicInstant::now(),
};
let changed = node.merge_typed_address_upgrade_only(addr.clone(), AddressType::Direct);
assert!(changed);
assert_eq!(node.address_type_at(0), AddressType::Direct);
}
#[test]
fn merge_typed_address_upgrade_only_refuses_to_demote() {
// Existing Relay must not be demoted by incoming Unverified/Direct
// arriving out of order via FIND_NODE gossip.
let addr: MultiAddr = "/ip4/203.0.113.10/udp/9000/quic".parse().unwrap();
for incoming in [AddressType::Unverified, AddressType::Direct] {
let mut node = NodeInfo {
id: PeerId::from_bytes([1u8; 32]),
addresses: vec![addr.clone()],
address_types: vec![AddressType::Relay],
last_seen: AtomicInstant::now(),
};
let changed = node.merge_typed_address_upgrade_only(addr.clone(), incoming);
assert!(!changed, "unexpected change for incoming {:?}", incoming);
assert_eq!(node.address_type_at(0), AddressType::Relay);
assert_eq!(node.addresses.len(), 1);
}
}
#[test]
fn merge_typed_address_upgrade_only_adds_new_address() {
// A new address is always added, regardless of tag — this is how a
// peer XOR-far from every PublishAddressSet source learns about
// its neighbours' Relay/Direct addresses via gossip.
let existing: MultiAddr = "/ip4/203.0.113.10/udp/9000/quic".parse().unwrap();
let new_relay: MultiAddr = "/ip4/192.0.2.7/udp/44100/quic".parse().unwrap();
let mut node = NodeInfo {
id: PeerId::from_bytes([1u8; 32]),
addresses: vec![existing.clone()],
address_types: vec![AddressType::Unverified],
last_seen: AtomicInstant::now(),
};
let changed = node.merge_typed_address_upgrade_only(new_relay.clone(), AddressType::Relay);
assert!(changed);
assert_eq!(node.addresses.len(), 2);
// Relay sorts to the front.
assert_eq!(node.addresses[0], new_relay);
assert_eq!(node.address_type_at(0), AddressType::Relay);
}
#[test]
fn merge_typed_address_upgrade_only_idempotent_on_same_tag() {
let addr: MultiAddr = "/ip4/203.0.113.10/udp/9000/quic".parse().unwrap();
let mut node = NodeInfo {
id: PeerId::from_bytes([1u8; 32]),
addresses: vec![addr.clone()],
address_types: vec![AddressType::Direct],
last_seen: AtomicInstant::now(),
};
let changed = node.merge_typed_address_upgrade_only(addr.clone(), AddressType::Direct);
assert!(!changed);
assert_eq!(node.addresses.len(), 1);
assert_eq!(node.address_type_at(0), AddressType::Direct);
}
// -----------------------------------------------------------------------
// Wildcard-address store-side filter tests (silences ~66k WARN/3.7h
// observed on prod where peers running older saorsa-core publish their
// bind-side `0.0.0.0` / `::` addresses verbatim).
// -----------------------------------------------------------------------
#[test]
fn is_storable_address_rejects_wildcard_v4() {
let addr: MultiAddr = "/ip4/0.0.0.0/udp/9000/quic".parse().unwrap();
assert!(!is_storable_address(&addr));
}
#[test]
fn is_storable_address_rejects_wildcard_v6() {
let addr: MultiAddr = "/ip6/::/udp/9000/quic".parse().unwrap();
assert!(!is_storable_address(&addr));
}
#[test]
fn is_storable_address_rejects_port_zero() {
let addr: MultiAddr = "/ip4/192.0.2.1/udp/0/quic".parse().unwrap();
assert!(!is_storable_address(&addr));
}
#[test]
fn is_storable_address_accepts_routable() {
let addr: MultiAddr = "/ip4/203.0.113.10/udp/9000/quic".parse().unwrap();
assert!(is_storable_address(&addr));
}
#[test]
fn is_storable_address_accepts_loopback_for_devnet() {
// Loopback is intentionally accepted — local devnets need it. The
// per-node `allow_loopback` config gates routing-table admission
// separately.
let v4: MultiAddr = "/ip4/127.0.0.1/udp/9000/quic".parse().unwrap();
let v6: MultiAddr = "/ip6/::1/udp/9000/quic".parse().unwrap();
assert!(is_storable_address(&v4));
assert!(is_storable_address(&v6));
}
#[test]
fn merge_typed_address_drops_wildcard_silently() {
let mut node = NodeInfo {
id: PeerId::from_bytes([1u8; 32]),
addresses: vec![],
address_types: vec![],
last_seen: AtomicInstant::now(),
};
let wildcard: MultiAddr = "/ip6/::/udp/55928/quic".parse().unwrap();
node.merge_typed_address(wildcard, AddressType::Direct);
assert!(node.addresses.is_empty());
assert!(node.address_types.is_empty());
}
#[test]
fn merge_typed_address_upgrade_only_returns_false_on_wildcard() {
let mut node = NodeInfo {
id: PeerId::from_bytes([1u8; 32]),
addresses: vec![],
address_types: vec![],
last_seen: AtomicInstant::now(),
};
let wildcard: MultiAddr = "/ip4/0.0.0.0/udp/10000/quic".parse().unwrap();
let changed = node.merge_typed_address_upgrade_only(wildcard, AddressType::Direct);
assert!(!changed);
assert!(node.addresses.is_empty());
}
#[test]
fn replace_node_addresses_strips_wildcards_keeps_routable() {
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/203.0.113.1/udp/9000/quic"))
.unwrap();
// Publish a mixed set: one routable + one wildcard.
let routable: MultiAddr = "/ip4/198.51.100.5/udp/10000/quic".parse().unwrap();
let wildcard: MultiAddr = "/ip4/0.0.0.0/udp/10000/quic".parse().unwrap();
let typed = vec![
(routable.clone(), AddressType::Direct),
(wildcard, AddressType::Direct),
];
let applied = bucket.replace_node_addresses(&PeerId::from_bytes([1u8; 32]), typed);
assert!(applied);
let node = bucket.get_nodes().last().unwrap();
assert_eq!(node.addresses, vec![routable]);
assert_eq!(node.address_types, vec![AddressType::Direct]);
}
#[test]
fn add_node_strips_wildcards_from_incoming_record() {
let k = 8;
let mut bucket = KBucket::new(k);
let routable: MultiAddr = "/ip4/198.51.100.5/udp/10000/quic".parse().unwrap();
let wildcard: MultiAddr = "/ip6/::/udp/10000/quic".parse().unwrap();
let node = NodeInfo {
id: PeerId::from_bytes([42u8; 32]),
addresses: vec![wildcard, routable.clone()],
address_types: vec![AddressType::Direct, AddressType::Direct],
last_seen: AtomicInstant::now(),
};
bucket.add_node(node).unwrap();
let stored = bucket.get_nodes().last().unwrap();
assert_eq!(stored.addresses, vec![routable]);
assert_eq!(stored.address_types, vec![AddressType::Direct]);
}
#[test]
fn add_node_rejects_record_with_only_wildcard_addresses() {
let k = 8;
let mut bucket = KBucket::new(k);
let wildcard: MultiAddr = "/ip4/0.0.0.0/udp/10000/quic".parse().unwrap();
let node = NodeInfo {
id: PeerId::from_bytes([42u8; 32]),
addresses: vec![wildcard],
address_types: vec![AddressType::Direct],
last_seen: AtomicInstant::now(),
};
// After filtering, addresses is empty — add_node rejects the slot.
let result = bucket.add_node(node);
assert!(result.is_err());
}
/// Engine-level (P2): a mixed wildcard + routable record must be admitted
/// through the public `DhtCoreEngine::add_node` path with only the
/// routable address stored. Before the sanitize step, `candidate_ips`
/// was built from the raw address list and the unspecified-IP guard in
/// `add_with_diversity` rejected the whole record before the bucket-side
/// store filter could run.
#[tokio::test]
async fn engine_add_node_admits_mixed_wildcard_and_routable() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let routable: MultiAddr = "/ip4/198.51.100.7/udp/10000/quic".parse().unwrap();
let wildcard: MultiAddr = "/ip6/::/udp/10000/quic".parse().unwrap();
let peer = PeerId::from_bytes([7u8; 32]);
let node = NodeInfo {
id: peer,
addresses: vec![wildcard, routable.clone()],
address_types: vec![AddressType::Direct, AddressType::Direct],
last_seen: AtomicInstant::now(),
};
let events = dht.add_node_no_trust(node).await.unwrap();
assert!(
events
.iter()
.any(|e| matches!(e, RoutingTableEvent::PeerAdded(p) if *p == peer)),
"mixed record should be admitted, got events: {events:?}"
);
let stored = dht.get_node_addresses(&peer).await;
assert_eq!(
stored,
vec![routable],
"only the routable address should survive sanitization"
);
}
/// Engine-level: a record carrying *only* wildcard addresses has nothing
/// storable left after sanitization and must be rejected by the public
/// `add_node` path (the empty `candidate_ips` early-out / bucket filter).
#[tokio::test]
async fn engine_add_node_rejects_only_wildcard_record() {
let mut dht = DhtCoreEngine::new_for_tests(PeerId::from_bytes([0u8; 32])).unwrap();
let wildcard: MultiAddr = "/ip4/0.0.0.0/udp/10000/quic".parse().unwrap();
let peer = PeerId::from_bytes([9u8; 32]);
let node = NodeInfo {
id: peer,
addresses: vec![wildcard],
address_types: vec![AddressType::Direct],
last_seen: AtomicInstant::now(),
};
let result = dht.add_node_no_trust(node).await;
assert!(
result.is_err(),
"record with only wildcard addresses must not be admitted"
);
assert!(
dht.get_node_addresses(&peer).await.is_empty(),
"rejected peer must not appear in the routing table"
);
}
#[test]
fn is_storable_address_rejects_tcp_wildcard() {
// The dialable_socket_addr() helper only matches QUIC; the filter
// must use socket_addr() to also catch TCP / raw UDP wildcards.
let tcp_wildcard: MultiAddr = "/ip4/0.0.0.0/tcp/9000".parse().unwrap();
assert!(!is_storable_address(&tcp_wildcard));
}
#[test]
fn is_storable_address_rejects_udp_wildcard_v6() {
let udp_wildcard: MultiAddr = "/ip6/::/udp/9000".parse().unwrap();
assert!(!is_storable_address(&udp_wildcard));
}
#[test]
fn replace_node_addresses_preserves_state_when_filter_empties_input() {
// If a publisher sends a non-empty set that gets entirely filtered
// out (e.g. only wildcards), the bucket must NOT wipe the peer's
// existing good addresses. The caller relies on `false` to skip
// advancing the per-peer publish sequence.
let k = 8;
let mut bucket = KBucket::new(k);
let original: MultiAddr = "/ip4/203.0.113.42/udp/9000/quic".parse().unwrap();
bucket
.add_node(NodeInfo {
id: PeerId::from_bytes([7u8; 32]),
addresses: vec![original.clone()],
address_types: vec![AddressType::Direct],
last_seen: AtomicInstant::now(),
})
.unwrap();
let wildcard: MultiAddr = "/ip6/::/udp/55928/quic".parse().unwrap();
let typed = vec![(wildcard, AddressType::Direct)];
let applied = bucket.replace_node_addresses(&PeerId::from_bytes([7u8; 32]), typed);
assert!(!applied, "filter-empty publish must not be applied");
let node = bucket.get_nodes().last().unwrap();
assert_eq!(
node.addresses,
vec![original],
"original addresses must be preserved"
);
}
#[test]
fn replace_node_addresses_strips_wildcards_with_relay_and_direct() {
// Mixed-tier publish: Relay + Direct + wildcard. Filter drops the
// wildcard, type-priority sort keeps Relay first, Direct second.
let k = 8;
let mut bucket = KBucket::new(k);
bucket
.add_node(make_node(1, "/ip4/203.0.113.1/udp/9000/quic"))
.unwrap();
let relay: MultiAddr = "/ip4/198.51.100.1/udp/8443/quic".parse().unwrap();
let direct: MultiAddr = "/ip4/198.51.100.5/udp/10000/quic".parse().unwrap();
let wildcard: MultiAddr = "/ip4/0.0.0.0/udp/10000/quic".parse().unwrap();
let typed = vec![
(direct.clone(), AddressType::Direct),
(wildcard, AddressType::Direct),
(relay.clone(), AddressType::Relay),
];
let applied = bucket.replace_node_addresses(&PeerId::from_bytes([1u8; 32]), typed);
assert!(applied);
let node = bucket.get_nodes().last().unwrap();
assert_eq!(node.addresses, vec![relay, direct]);
assert_eq!(
node.address_types,
vec![AddressType::Relay, AddressType::Direct]
);
}
}