ant-quic 0.26.5

QUIC transport protocol with advanced NAT traversal for P2P networks
Documentation
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
// Copyright 2024 Saorsa Labs Ltd.
//
// This Saorsa Network Software is licensed under the General Public License (GPL), version 3.
// Please see the file LICENSE-GPL, or visit <http://www.gnu.org/licenses/> for the full text.
//
// Full details available at https://saorsalabs.com/licenses

use std::{
    collections::{HashMap, VecDeque},
    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
    time::Duration,
};

use crate::shared::{ConnectionId, normalize_socket_addr};
use tracing::{debug, info, trace, warn};

use super::{PortPredictor, PortPredictorConfig};
use crate::{Instant, VarInt};

fn allow_loopback_from_env() -> bool {
    matches!(
        std::env::var("ANT_QUIC_ALLOW_LOOPBACK")
            .unwrap_or_default()
            .trim()
            .to_ascii_lowercase()
            .as_str(),
        "1" | "true" | "yes"
    )
}

/// NAT traversal state for a QUIC connection
///
/// This manages address candidate discovery, validation, and coordination
/// for establishing direct P2P connections through NATs.
///
/// v0.13.0: All nodes are symmetric P2P nodes - no role distinction.
/// Every node can initiate, accept, and coordinate NAT traversal.
#[derive(Debug)]
pub(super) struct NatTraversalState {
    // v0.13.0: role field removed - all nodes are symmetric P2P nodes
    /// Candidate addresses we've advertised to the peer
    pub(super) local_candidates: HashMap<VarInt, AddressCandidate>,
    /// Candidate addresses received from the peer
    pub(super) remote_candidates: HashMap<VarInt, AddressCandidate>,
    /// Generated candidate pairs for connectivity testing
    pub(super) candidate_pairs: Vec<CandidatePair>,
    /// Index for fast pair lookup by remote address (maintained during generation)
    pub(super) pair_index: HashMap<SocketAddr, usize>,
    /// Currently active path validation attempts, keyed by challenge token.
    ///
    /// Keyed by `u64` challenge token (not SocketAddr) so that validation
    /// succeeds even if the peer's NAT rebinds between PATH_CHALLENGE and
    /// PATH_RESPONSE. The challenge token is the stable correlator per
    /// draft-seemann-quic-nat-traversal-02.
    pub(super) active_validations: HashMap<u64, PathValidationState>,
    /// Coordination state for simultaneous hole punching
    pub(super) coordination: Option<CoordinationState>,
    /// Sequence number for address advertisements
    pub(super) next_sequence: VarInt,
    /// Maximum candidates we're willing to handle
    pub(super) max_candidates: u32,
    /// Timeout for coordination rounds
    pub(super) coordination_timeout: Duration,
    /// Statistics for this NAT traversal session
    pub(super) stats: NatTraversalStats,
    /// Security validation state
    pub(super) security_state: SecurityValidationState,
    /// Network condition monitoring for adaptive timeouts
    pub(super) network_monitor: NetworkConditionMonitor,
    /// Resource management and cleanup coordinator
    pub(super) resource_manager: ResourceCleanupCoordinator,
    /// Coordination support - all nodes can coordinate (v0.13.0: always enabled)
    pub(super) bootstrap_coordinator: Option<BootstrapCoordinator>,
    /// Port predictor for symmetric NAT traversal
    pub(super) port_predictor: PortPredictor,
}
// v0.13.0: NatTraversalRole enum removed - all nodes are symmetric P2P nodes
// Every node can initiate, accept, and coordinate NAT traversal without role distinction.
/// Address candidate with metadata
#[derive(Debug, Clone)]
pub(super) struct AddressCandidate {
    /// The socket address
    pub(super) address: SocketAddr,
    /// Priority for ICE-like selection (higher = better)
    pub(super) priority: u32,
    /// How this candidate was discovered
    pub(super) source: CandidateSource,
    /// When this candidate was first learned
    pub(super) discovered_at: Instant,
    /// Current state of this candidate
    pub(super) state: CandidateState,
    /// Number of validation attempts for this candidate
    pub(super) attempt_count: u32,
    /// Last validation attempt time
    pub(super) last_attempt: Option<Instant>,
}
/// How an address candidate was discovered
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CandidateSource {
    /// Local network interface
    Local,
    /// Observed by a bootstrap node
    ///
    /// When present, `by_node` identifies the coordinator that reported the
    /// observation using its node identifier.
    Observed {
        /// Identifier of the coordinator that observed our address
        by_node: Option<VarInt>,
    },
    /// Received from peer via AddAddress frame
    Peer,
    /// Generated prediction for symmetric NAT
    Predicted,
}
/// Current state of a candidate address
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CandidateState {
    /// Newly discovered, not yet tested
    New,
    /// Currently being validated
    Validating,
    /// Successfully validated and usable
    Valid,
    /// Validation failed
    Failed,
    /// Removed by peer or expired
    Removed,
}
/// State of an individual path validation attempt
///
/// Keyed by challenge token (`u64`) in `active_validations`, not by SocketAddr.
/// This ensures validation succeeds even if the peer's NAT rebinds between
/// PATH_CHALLENGE and PATH_RESPONSE (the challenge token is the stable correlator).
#[derive(Debug)]
#[allow(dead_code)]
pub(super) struct PathValidationState {
    /// Challenge value sent (also the key in active_validations)
    pub(super) challenge: u64,
    /// Candidate sequence this validation is for
    pub(super) sequence: VarInt,
    /// The address we sent the PATH_CHALLENGE to
    pub(super) target_addr: SocketAddr,
    /// When the challenge was sent
    pub(super) sent_at: Instant,
    /// Number of retransmissions
    pub(super) retry_count: u32,
    /// Maximum retries allowed
    pub(super) max_retries: u32,
    /// Associated with a coordination round (if any)
    pub(super) coordination_round: Option<VarInt>,
    /// Adaptive timeout state
    pub(super) timeout_state: AdaptiveTimeoutState,
    /// Last retry attempt time
    pub(super) last_retry_at: Option<Instant>,
}
/// Coordination state for simultaneous hole punching
#[derive(Debug)]
#[allow(dead_code)]
pub(super) struct CoordinationState {
    /// Current coordination round number
    pub(super) round: VarInt,
    /// Addresses we're punching to in this round
    pub(super) punch_targets: Vec<PunchTarget>,
    /// When this round started (coordination phase)
    pub(super) round_start: Instant,
    /// When hole punching should begin (synchronized time)
    pub(super) punch_start: Instant,
    /// Duration of this coordination round
    pub(super) round_duration: Duration,
    /// Current state of this coordination round
    pub(super) state: CoordinationPhase,
    /// Whether we've sent our PUNCH_ME_NOW to coordinator
    pub(super) punch_request_sent: bool,
    /// Whether we've received peer's PUNCH_ME_NOW via coordinator
    pub(super) peer_punch_received: bool,
    /// Retry count for this round
    pub(super) retry_count: u32,
    /// Maximum retries before giving up
    pub(super) max_retries: u32,
    /// Adaptive timeout state for coordination
    pub(super) timeout_state: AdaptiveTimeoutState,
    /// Last retry attempt time
    pub(super) last_retry_at: Option<Instant>,
}
/// Phases of the coordination protocol
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub(crate) enum CoordinationPhase {
    /// Waiting to start coordination
    Idle,
    /// Sending PUNCH_ME_NOW to coordinator
    Requesting,
    /// Waiting for peer's PUNCH_ME_NOW via coordinator
    Coordinating,
    /// Grace period before synchronized hole punching
    Preparing,
    /// Actively sending PATH_CHALLENGE packets
    Punching,
    /// Waiting for PATH_RESPONSE validation
    Validating,
    /// This round completed successfully
    Succeeded,
    /// This round failed, may retry
    Failed,
}
/// Target for hole punching in a coordination round
#[derive(Debug, Clone)]
pub(super) struct PunchTarget {
    /// Remote address to punch to
    pub(super) remote_addr: SocketAddr,
    /// Sequence number of the remote candidate
    pub(super) remote_sequence: VarInt,
    /// Challenge value for validation
    pub(super) challenge: u64,
}
/// Actions to take when handling NAT traversal timeouts
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum TimeoutAction {
    /// Retry candidate discovery
    RetryDiscovery,
    /// Retry coordination with bootstrap node
    RetryCoordination,
    /// Start path validation for discovered candidates
    StartValidation,
    /// NAT traversal completed successfully
    Complete,
    /// NAT traversal failed
    Failed,
}

/// Candidate pair for ICE-like connectivity testing
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(super) struct CandidatePair {
    /// Sequence of remote candidate
    pub(super) remote_sequence: VarInt,
    /// Our local address for this pair
    pub(super) local_addr: SocketAddr,
    /// Remote address we're testing connectivity to
    pub(super) remote_addr: SocketAddr,
    /// Combined priority for pair ordering (higher = better)
    pub(super) priority: u64,
    /// Current state of this pair
    pub(super) state: PairState,
    /// Type classification for this pair
    pub(super) pair_type: PairType,
    /// When this pair was created
    pub(super) created_at: Instant,
    /// When validation was last attempted
    pub(super) last_check: Option<Instant>,
}
/// State of a candidate pair during validation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub(super) enum PairState {
    /// Waiting to be tested
    Waiting,
    /// Validation succeeded - this pair works
    Succeeded,
    /// Validation failed
    Failed,
    /// Temporarily frozen (waiting for other pairs)
    Frozen,
}
/// Type classification for candidate pairs (based on ICE)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) enum PairType {
    /// Both candidates are on local network
    HostToHost,
    /// Local is host, remote is server reflexive (through NAT)
    HostToServerReflexive,
    /// Local is server reflexive, remote is host
    ServerReflexiveToHost,
    /// Both are server reflexive (both behind NAT)
    ServerReflexiveToServerReflexive,
    /// One side is peer reflexive (learned from peer)
    PeerReflexive,
}
/// Type of address candidate (following ICE terminology)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum CandidateType {
    /// Host candidate - directly reachable local interface
    Host,
    /// Server reflexive - public address observed by bootstrap node
    ServerReflexive,
    /// Peer reflexive - address learned from incoming packets
    PeerReflexive,
}

/// Calculate ICE-like priority for an address candidate
/// Based on RFC 8445 Section 5.1.2.1
#[allow(dead_code)]
fn calculate_candidate_priority(
    candidate_type: CandidateType,
    local_preference: u16,
    component_id: u8,
) -> u32 {
    let type_preference = match candidate_type {
        CandidateType::Host => 126,
        CandidateType::PeerReflexive => 110,
        CandidateType::ServerReflexive => 100,
    };
    // ICE priority formula: (2^24 * type_pref) + (2^8 * local_pref) + component_id
    (1u32 << 24) * type_preference + (1u32 << 8) * local_preference as u32 + component_id as u32
}

/// Calculate combined priority for a candidate pair
/// Based on RFC 8445 Section 6.1.2.3
fn calculate_pair_priority(local_priority: u32, remote_priority: u32) -> u64 {
    let g = local_priority as u64;
    let d = remote_priority as u64;
    // ICE pair priority formula: 2^32 * MIN(G,D) + 2 * MAX(G,D) + (G>D ? 1 : 0)
    (1u64 << 32) * g.min(d) + 2 * g.max(d) + if g > d { 1 } else { 0 }
}

/// Determine candidate type from source information
fn classify_candidate_type(source: CandidateSource) -> CandidateType {
    match source {
        CandidateSource::Local => CandidateType::Host,
        CandidateSource::Observed { .. } => CandidateType::ServerReflexive,
        CandidateSource::Peer => CandidateType::PeerReflexive,
        CandidateSource::Predicted => CandidateType::ServerReflexive, // Symmetric NAT prediction
    }
}
/// Determine pair type from individual candidate types
fn classify_pair_type(local_type: CandidateType, remote_type: CandidateType) -> PairType {
    match (local_type, remote_type) {
        (CandidateType::Host, CandidateType::Host) => PairType::HostToHost,
        (CandidateType::Host, CandidateType::ServerReflexive) => PairType::HostToServerReflexive,
        (CandidateType::ServerReflexive, CandidateType::Host) => PairType::ServerReflexiveToHost,
        (CandidateType::ServerReflexive, CandidateType::ServerReflexive) => {
            PairType::ServerReflexiveToServerReflexive
        }
        (CandidateType::PeerReflexive, _) | (_, CandidateType::PeerReflexive) => {
            PairType::PeerReflexive
        }
    }
}
/// Check if two candidates are compatible for pairing
fn are_candidates_compatible(local: &AddressCandidate, remote: &AddressCandidate) -> bool {
    // Must be same address family (IPv4 with IPv4, IPv6 with IPv6)
    match (local.address, remote.address) {
        (SocketAddr::V4(_), SocketAddr::V4(_)) => true,
        (SocketAddr::V6(_), SocketAddr::V6(_)) => true,
        _ => false, // No IPv4/IPv6 mixing for now
    }
}
/// Statistics for NAT traversal attempts
#[derive(Debug, Default, Clone)]
#[allow(dead_code)]
pub(crate) struct NatTraversalStats {
    /// Total candidates received from peer
    pub(super) remote_candidates_received: u32,
    /// Total candidates we've advertised
    pub(super) local_candidates_sent: u32,
    /// Successful validations
    pub(super) validations_succeeded: u32,
    /// Failed validations
    pub(super) validations_failed: u32,
    /// Coordination rounds attempted
    pub(super) coordination_rounds: u32,
    /// Successful coordinations
    pub(super) successful_coordinations: u32,
    /// Failed coordinations
    pub(super) failed_coordinations: u32,
    /// Timed out coordinations
    pub(super) timed_out_coordinations: u32,
    /// Coordination failures due to poor network conditions
    pub(super) coordination_failures: u32,
    /// Successful direct connections established
    pub(super) direct_connections: u32,
    /// Security validation rejections
    pub(super) security_rejections: u32,
    /// Rate limiting violations
    pub(super) rate_limit_violations: u32,
    /// Invalid address rejections
    pub(super) invalid_address_rejections: u32,
    /// Suspicious coordination attempts
    pub(super) suspicious_coordination_attempts: u32,
    /// Callback probes received (TryConnectToResponse)
    pub(super) callback_probes_received: u32,
    /// Callback probes that succeeded
    pub(super) callback_probes_successful: u32,
    /// Callback probes that failed
    pub(super) callback_probes_failed: u32,
    /// Predicted candidates generated
    pub(super) predicted_candidates_generated: u32,
}
/// Security validation state for rate limiting and attack detection
#[derive(Debug)]
#[allow(dead_code)]
pub(super) struct SecurityValidationState {
    /// Rate limiting: track candidate additions per time window
    candidate_rate_tracker: VecDeque<Instant>,
    /// Maximum candidates per time window
    max_candidates_per_window: u32,
    /// Rate limiting time window
    rate_window: Duration,
    /// Coordination request tracking for suspicious patterns
    coordination_requests: VecDeque<CoordinationRequest>,
    /// Maximum coordination requests per time window
    max_coordination_per_window: u32,
    /// Address validation cache to avoid repeated validation
    address_validation_cache: HashMap<SocketAddr, AddressValidationResult>,
    /// Cache timeout for address validation
    validation_cache_timeout: Duration,
}
/// Coordination request tracking for security analysis
#[derive(Debug, Clone)]
struct CoordinationRequest {
    /// When the request was made
    timestamp: Instant,
}
/// Result of address validation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AddressValidationResult {
    /// Address is valid and safe
    Valid,
    /// Address is invalid (malformed, reserved, etc.)
    Invalid,
    /// Address is suspicious (potential attack)
    Suspicious,
}
/// Adaptive timeout state for network condition awareness
#[derive(Debug, Clone)]
pub(super) struct AdaptiveTimeoutState {
    /// Current timeout value
    current_timeout: Duration,
    /// Minimum allowed timeout
    min_timeout: Duration,
    /// Maximum allowed timeout
    max_timeout: Duration,
    /// Base timeout for exponential backoff
    base_timeout: Duration,
    /// Current backoff multiplier
    backoff_multiplier: f64,
    /// Maximum backoff multiplier
    max_backoff_multiplier: f64,
    /// Jitter factor for randomization
    jitter_factor: f64,
    /// Smoothed round-trip time estimation
    srtt: Option<Duration>,
    /// Round-trip time variance
    rttvar: Option<Duration>,
    /// Last successful round-trip time
    last_rtt: Option<Duration>,
    /// Number of consecutive timeouts
    consecutive_timeouts: u32,
    /// Number of successful responses
    successful_responses: u32,
}
/// Network condition monitoring for adaptive behavior
#[derive(Debug)]
#[allow(dead_code)]
pub(super) struct NetworkConditionMonitor {
    /// Recent round-trip time measurements
    rtt_samples: VecDeque<Duration>,
    /// Maximum samples to keep
    max_samples: usize,
    /// Packet loss rate estimation
    packet_loss_rate: f64,
    /// Congestion window estimate
    congestion_window: u32,
    /// Network quality score (0.0 = poor, 1.0 = excellent)
    quality_score: f64,
    /// Last quality update time
    last_quality_update: Instant,
    /// Quality measurement interval
    quality_update_interval: Duration,
    /// Timeout statistics
    timeout_stats: TimeoutStatistics,
}
/// Statistics for timeout behavior
#[derive(Debug, Default)]
struct TimeoutStatistics {
    /// Total timeout events
    total_timeouts: u64,
    /// Total successful responses
    total_responses: u64,
    /// Average response time
    avg_response_time: Duration,
    /// Timeout rate (0.0 = no timeouts, 1.0 = all timeouts)
    timeout_rate: f64,
    /// Last update time
    last_update: Option<Instant>,
}
#[allow(dead_code)]
impl SecurityValidationState {
    /// Create new security validation state with default settings
    fn new() -> Self {
        Self {
            candidate_rate_tracker: VecDeque::new(),
            max_candidates_per_window: 20, // Max 20 candidates per 60 seconds
            rate_window: Duration::from_secs(60),
            coordination_requests: VecDeque::new(),
            max_coordination_per_window: 5, // Max 5 coordination requests per 60 seconds
            address_validation_cache: HashMap::new(),
            validation_cache_timeout: Duration::from_secs(300), // 5 minute cache
        }
    }
    /// Create new security validation state with custom rate limits
    fn new_with_limits(
        max_candidates_per_window: u32,
        max_coordination_per_window: u32,
        rate_window: Duration,
    ) -> Self {
        Self {
            candidate_rate_tracker: VecDeque::new(),
            max_candidates_per_window,
            rate_window,
            coordination_requests: VecDeque::new(),
            max_coordination_per_window,
            address_validation_cache: HashMap::new(),
            validation_cache_timeout: Duration::from_secs(300),
        }
    }
    /// Enhanced rate limiting with adaptive thresholds
    ///
    /// This implements adaptive rate limiting that adjusts based on network conditions
    /// and detected attack patterns to prevent flooding while maintaining usability.
    fn is_adaptive_rate_limited(&mut self, peer_id: [u8; 32], now: Instant) -> bool {
        // Clean up old entries first
        self.cleanup_rate_tracker(now);
        self.cleanup_coordination_tracker(now);
        // Calculate current request rate
        let _current_candidate_rate =
            self.candidate_rate_tracker.len() as f64 / self.rate_window.as_secs_f64();
        let _current_coordination_rate =
            self.coordination_requests.len() as f64 / self.rate_window.as_secs_f64();

        // Adaptive threshold based on peer behavior
        let peer_reputation = self.calculate_peer_reputation(peer_id);
        let adaptive_candidate_limit =
            (self.max_candidates_per_window as f64 * peer_reputation) as u32;
        let adaptive_coordination_limit =
            (self.max_coordination_per_window as f64 * peer_reputation) as u32;

        // Check if either limit is exceeded
        if self.candidate_rate_tracker.len() >= adaptive_candidate_limit as usize {
            debug!(
                "Adaptive candidate rate limit exceeded for peer {:?}: {} >= {}",
                hex::encode(&peer_id[..8]),
                self.candidate_rate_tracker.len(),
                adaptive_candidate_limit
            );
            return true;
        }

        if self.coordination_requests.len() >= adaptive_coordination_limit as usize {
            debug!(
                "Adaptive coordination rate limit exceeded for peer {:?}: {} >= {}",
                hex::encode(&peer_id[..8]),
                self.coordination_requests.len(),
                adaptive_coordination_limit
            );
            return true;
        }

        false
    }

    /// Calculate peer reputation score (0.0 = bad, 1.0 = good)
    ///
    /// This implements a simple reputation system to adjust rate limits
    /// based on peer behavior patterns.
    fn calculate_peer_reputation(&self, _peer_id: [u8; 32]) -> f64 {
        // Simplified reputation calculation
        // In production, this would track:
        // - Historical success rates
        // - Suspicious behavior patterns
        // - Coordination completion rates
        // - Address validation failures
        // For now, return a default good reputation
        // This can be enhanced with persistent peer reputation storage
        1.0
    }

    /// Implement amplification attack mitigation
    ///
    /// This prevents the bootstrap node from being used as an amplifier
    /// in DDoS attacks by limiting server-initiated validation packets.
    fn validate_amplification_limits(
        &mut self,
        source_addr: SocketAddr,
        target_addr: SocketAddr,
        now: Instant,
    ) -> Result<(), NatTraversalError> {
        // Check if we're being asked to send too many packets to the same target
        let amplification_key = (source_addr, target_addr);
        // Simple amplification protection: limit packets per source-target pair
        // In production, this would be more sophisticated with:
        // - Bandwidth tracking
        // - Packet size ratios
        // - Geographic analysis
        // - Temporal pattern analysis

        // For now, implement basic per-pair rate limiting
        if self.is_amplification_suspicious(amplification_key, now) {
            warn!(
                "Potential amplification attack detected: {} -> {}",
                source_addr, target_addr
            );
            return Err(NatTraversalError::SuspiciousCoordination);
        }

        Ok(())
    }

    /// Check for suspicious amplification patterns
    fn is_amplification_suspicious(
        &self,
        _amplification_key: (SocketAddr, SocketAddr),
        _now: Instant,
    ) -> bool {
        // Simplified amplification detection
        // In production, this would track:
        // - Request/response ratios
        // - Bandwidth amplification factors
        // - Temporal clustering of requests
        // - Geographic distribution analysis
        // For now, return false (no amplification detected)
        // This can be enhanced with persistent amplification tracking
        false
    }

    /// Generate cryptographically secure random values for coordination rounds
    ///
    /// This ensures that coordination rounds use secure random values to prevent
    /// prediction attacks and ensure proper synchronization security.
    fn generate_secure_coordination_round(&self) -> VarInt {
        // Use cryptographically secure random number generation
        let secure_random: u64 = rand::random();
        // Ensure the value is within reasonable bounds for VarInt
        let bounded_random = secure_random % 1000000; // Limit to reasonable range

        VarInt::from_u64(bounded_random).unwrap_or(VarInt::from_u32(1))
    }

    /// Enhanced address validation with security checks
    ///
    /// This performs comprehensive address validation including:
    /// - Basic format validation
    /// - Security threat detection
    /// - Amplification attack prevention
    /// - Suspicious pattern recognition
    fn enhanced_address_validation(
        &mut self,
        addr: SocketAddr,
        source_addr: SocketAddr,
        now: Instant,
    ) -> Result<AddressValidationResult, NatTraversalError> {
        // First, perform basic address validation
        let basic_result = self.validate_address(addr, now);
        match basic_result {
            AddressValidationResult::Invalid => {
                return Err(NatTraversalError::InvalidAddress);
            }
            AddressValidationResult::Suspicious => {
                return Err(NatTraversalError::SuspiciousCoordination);
            }
            AddressValidationResult::Valid => {
                // Continue with enhanced validation
            }
        }

        // Check for amplification attack patterns
        self.validate_amplification_limits(source_addr, addr, now)?;

        // Additional security checks
        if self.is_address_in_suspicious_range(addr) {
            warn!("Address in suspicious range detected: {}", addr);
            return Err(NatTraversalError::SuspiciousCoordination);
        }

        if self.is_coordination_pattern_suspicious(source_addr, addr, now) {
            warn!(
                "Suspicious coordination pattern detected: {} -> {}",
                source_addr, addr
            );
            return Err(NatTraversalError::SuspiciousCoordination);
        }

        Ok(AddressValidationResult::Valid)
    }

    /// Check if address is in a suspicious range
    fn is_address_in_suspicious_range(&self, addr: SocketAddr) -> bool {
        let allow_loopback = allow_loopback_from_env();
        match addr.ip() {
            IpAddr::V4(ipv4) => {
                // Check for addresses commonly used in attacks
                let octets = ipv4.octets();
                // Reject certain reserved ranges that shouldn't be used for P2P
                if octets[0] == 0 || (!allow_loopback && octets[0] == 127) {
                    return true;
                }

                // Check for test networks (RFC 5737)
                if octets[0] == 192 && octets[1] == 0 && octets[2] == 2 {
                    return true;
                }
                if octets[0] == 198 && octets[1] == 51 && octets[2] == 100 {
                    return true;
                }
                if octets[0] == 203 && octets[1] == 0 && octets[2] == 113 {
                    return true;
                }

                false
            }
            IpAddr::V6(ipv6) => {
                // Check for suspicious IPv6 ranges
                if ipv6.is_unspecified() || (!allow_loopback && ipv6.is_loopback()) {
                    return true;
                }

                // Check for documentation ranges (RFC 3849)
                let segments = ipv6.segments();
                if segments[0] == 0x2001 && segments[1] == 0x0db8 {
                    return true;
                }

                false
            }
        }
    }

    /// Check for suspicious coordination patterns
    fn is_coordination_pattern_suspicious(
        &self,
        _source_addr: SocketAddr,
        _target_addr: SocketAddr,
        _now: Instant,
    ) -> bool {
        // Simplified pattern detection
        // In production, this would analyze:
        // - Temporal patterns (too frequent requests)
        // - Geographic patterns (unusual source/target combinations)
        // - Behavioral patterns (consistent with known attack signatures)
        // - Network topology patterns (suspicious routing)
        // For now, return false (no suspicious patterns detected)
        // This can be enhanced with machine learning-based pattern detection
        false
    }

    /// Check if candidate rate limit is exceeded
    fn is_candidate_rate_limited(&mut self, now: Instant) -> bool {
        // Clean up old entries
        self.cleanup_rate_tracker(now);
        // Check if we've exceeded the rate limit
        if self.candidate_rate_tracker.len() >= self.max_candidates_per_window as usize {
            return true;
        }

        // Record this attempt
        self.candidate_rate_tracker.push_back(now);
        false
    }

    /// Check if coordination rate limit is exceeded
    fn is_coordination_rate_limited(&mut self, now: Instant) -> bool {
        // Clean up old entries
        self.cleanup_coordination_tracker(now);
        // Check if we've exceeded the rate limit
        if self.coordination_requests.len() >= self.max_coordination_per_window as usize {
            return true;
        }

        // Record this attempt
        let request = CoordinationRequest { timestamp: now };
        self.coordination_requests.push_back(request);
        false
    }

    /// Clean up old rate tracking entries
    fn cleanup_rate_tracker(&mut self, now: Instant) {
        let cutoff = now - self.rate_window;
        while let Some(&front_time) = self.candidate_rate_tracker.front() {
            if front_time < cutoff {
                self.candidate_rate_tracker.pop_front();
            } else {
                break;
            }
        }
    }
    /// Clean up old coordination tracking entries
    fn cleanup_coordination_tracker(&mut self, now: Instant) {
        let cutoff = now - self.rate_window;
        while let Some(front_request) = self.coordination_requests.front() {
            if front_request.timestamp < cutoff {
                self.coordination_requests.pop_front();
            } else {
                break;
            }
        }
    }
    /// Validate an address for security concerns
    fn validate_address(&mut self, addr: SocketAddr, now: Instant) -> AddressValidationResult {
        // Check cache first
        if let Some(&cached_result) = self.address_validation_cache.get(&addr) {
            return cached_result;
        }
        let result = self.perform_address_validation(addr);

        // Cache the result
        self.address_validation_cache.insert(addr, result);

        // Clean up old cache entries periodically
        if self.address_validation_cache.len() > 1000 {
            self.cleanup_address_cache(now);
        }

        result
    }

    /// Perform actual address validation
    fn perform_address_validation(&self, addr: SocketAddr) -> AddressValidationResult {
        let allow_loopback = allow_loopback_from_env();
        match addr.ip() {
            IpAddr::V4(ipv4) => {
                // Check for invalid IPv4 addresses
                if ipv4.is_unspecified() || ipv4.is_broadcast() {
                    return AddressValidationResult::Invalid;
                }
                if ipv4.is_loopback() && !allow_loopback {
                    return AddressValidationResult::Invalid;
                }
                // Check for suspicious addresses
                if ipv4.is_multicast() || ipv4.is_documentation() {
                    return AddressValidationResult::Suspicious;
                }

                // Check for reserved ranges that shouldn't be used for P2P
                if ipv4.octets()[0] == 0 || (!allow_loopback && ipv4.octets()[0] == 127) {
                    return AddressValidationResult::Invalid;
                }

                // Check for common attack patterns
                if self.is_suspicious_ipv4(ipv4) {
                    return AddressValidationResult::Suspicious;
                }
            }
            IpAddr::V6(ipv6) => {
                // Check for invalid IPv6 addresses
                if ipv6.is_unspecified() || ipv6.is_multicast() {
                    return AddressValidationResult::Invalid;
                }
                if ipv6.is_loopback() && !allow_loopback {
                    return AddressValidationResult::Invalid;
                }

                // Check for suspicious IPv6 addresses
                if self.is_suspicious_ipv6(ipv6) {
                    return AddressValidationResult::Suspicious;
                }
            }
        }

        // Check port range
        if addr.port() == 0 || addr.port() < 1024 {
            return AddressValidationResult::Suspicious;
        }

        AddressValidationResult::Valid
    }

    /// Check for suspicious IPv4 patterns
    fn is_suspicious_ipv4(&self, ipv4: Ipv4Addr) -> bool {
        let octets = ipv4.octets();
        // Check for patterns that might indicate scanning or attacks
        // Sequential or patterned addresses
        if octets[0] == octets[1] && octets[1] == octets[2] && octets[2] == octets[3] {
            return true;
        }

        // Check for addresses in ranges commonly used for attacks
        // This is a simplified check - production would have more sophisticated patterns
        false
    }

    /// Check for suspicious IPv6 patterns
    fn is_suspicious_ipv6(&self, ipv6: Ipv6Addr) -> bool {
        let segments = ipv6.segments();
        // Check for obvious patterns
        if segments.iter().all(|&s| s == segments[0]) {
            return true;
        }

        false
    }

    /// Clean up old address validation cache entries
    fn cleanup_address_cache(&mut self, _now: Instant) {
        // Simple cleanup - remove random entries to keep size bounded
        // In production, this would use LRU or timestamp-based cleanup
        if self.address_validation_cache.len() > 500 {
            let keys_to_remove: Vec<_> = self
                .address_validation_cache
                .keys()
                .take(self.address_validation_cache.len() / 2)
                .copied()
                .collect();
            for key in keys_to_remove {
                self.address_validation_cache.remove(&key);
            }
        }
    }

    /// Comprehensive path validation for PUNCH_ME_NOW frames
    ///
    /// This performs security-critical validation to prevent various attacks:
    /// - Address spoofing prevention
    /// - Reflection attack mitigation
    /// - Coordination request validation
    /// - Rate limiting enforcement
    fn validate_punch_me_now_frame(
        &mut self,
        frame: &crate::frame::PunchMeNow,
        source_addr: SocketAddr,
        peer_id: [u8; 32],
        now: Instant,
    ) -> Result<(), NatTraversalError> {
        // 1. Rate limiting validation
        if self.is_coordination_rate_limited(now) {
            debug!(
                "PUNCH_ME_NOW frame rejected: coordination rate limit exceeded for peer {:?}",
                hex::encode(&peer_id[..8])
            );
            return Err(NatTraversalError::RateLimitExceeded);
        }
        // 2. Address validation - validate the address claimed in the frame
        let addr_validation = self.validate_address(frame.address, now);
        match addr_validation {
            AddressValidationResult::Invalid => {
                debug!(
                    "PUNCH_ME_NOW frame rejected: invalid address {:?} from peer {:?}",
                    frame.address,
                    hex::encode(&peer_id[..8])
                );
                return Err(NatTraversalError::InvalidAddress);
            }
            AddressValidationResult::Suspicious => {
                debug!(
                    "PUNCH_ME_NOW frame rejected: suspicious address {:?} from peer {:?}",
                    frame.address,
                    hex::encode(&peer_id[..8])
                );
                return Err(NatTraversalError::SuspiciousCoordination);
            }
            AddressValidationResult::Valid => {
                // Continue validation
            }
        }

        // 3. Source address consistency validation
        // The frame's address should reasonably relate to the actual source
        if !self.validate_address_consistency(frame.address, source_addr) {
            debug!(
                "PUNCH_ME_NOW frame rejected: address consistency check failed. Frame claims {:?}, but received from {:?}",
                frame.address, source_addr
            );
            return Err(NatTraversalError::SuspiciousCoordination);
        }

        // 4. Coordination parameters validation
        if !self.validate_coordination_parameters(frame) {
            debug!(
                "PUNCH_ME_NOW frame rejected: invalid coordination parameters from peer {:?}",
                hex::encode(&peer_id[..8])
            );
            return Err(NatTraversalError::SuspiciousCoordination);
        }

        // 5. Target peer validation (if present)
        if let Some(target_peer_id) = frame.target_peer_id {
            if !self.validate_target_peer_request(peer_id, target_peer_id, frame) {
                debug!(
                    "PUNCH_ME_NOW frame rejected: invalid target peer request from {:?} to {:?}",
                    hex::encode(&peer_id[..8]),
                    hex::encode(&target_peer_id[..8])
                );
                return Err(NatTraversalError::SuspiciousCoordination);
            }
        }

        // 6. Resource limits validation
        if !self.validate_resource_limits(frame) {
            debug!(
                "PUNCH_ME_NOW frame rejected: resource limits exceeded from peer {:?}",
                hex::encode(&peer_id[..8])
            );
            return Err(NatTraversalError::ResourceLimitExceeded);
        }

        debug!(
            "PUNCH_ME_NOW frame validation passed for peer {:?}",
            hex::encode(&peer_id[..8])
        );
        Ok(())
    }

    /// Validate address consistency between claimed and observed addresses
    ///
    /// This prevents address spoofing by ensuring the claimed local address
    /// is reasonably consistent with the observed source address.
    fn validate_address_consistency(
        &self,
        claimed_addr: SocketAddr,
        observed_addr: SocketAddr,
    ) -> bool {
        // For P2P NAT traversal, the port will typically be different due to NAT,
        // but the IP should be consistent unless there's multi-homing or proxying
        // Check if IPs are in the same family
        match (claimed_addr.ip(), observed_addr.ip()) {
            (IpAddr::V4(claimed_ip), IpAddr::V4(observed_ip)) => {
                // For IPv4, allow same IP or addresses in same private range
                if claimed_ip == observed_ip {
                    return true;
                }

                // Allow within same private network (simplified check)
                if self.are_in_same_private_network_v4(claimed_ip, observed_ip) {
                    return true;
                }

                // Allow certain NAT scenarios where external IP differs
                // This is a simplified check - production would be more sophisticated
                !claimed_ip.is_private() && !observed_ip.is_private()
            }
            (IpAddr::V6(claimed_ip), IpAddr::V6(observed_ip)) => {
                // For IPv6, be more lenient due to complex addressing
                claimed_ip == observed_ip || self.are_in_same_prefix_v6(claimed_ip, observed_ip)
            }
            _ => {
                // Mismatched IP families - suspicious
                false
            }
        }
    }

    /// Check if two IPv4 addresses are in the same private network
    fn are_in_same_private_network_v4(&self, ip1: Ipv4Addr, ip2: Ipv4Addr) -> bool {
        // Check common private ranges
        let ip1_octets = ip1.octets();
        let ip2_octets = ip2.octets();
        // 10.0.0.0/8
        if ip1_octets[0] == 10 && ip2_octets[0] == 10 {
            return true;
        }

        // 172.16.0.0/12
        if ip1_octets[0] == 172
            && ip2_octets[0] == 172
            && (16..=31).contains(&ip1_octets[1])
            && (16..=31).contains(&ip2_octets[1])
        {
            return true;
        }

        // 192.168.0.0/16
        if ip1_octets[0] == 192
            && ip1_octets[1] == 168
            && ip2_octets[0] == 192
            && ip2_octets[1] == 168
        {
            return true;
        }

        false
    }

    /// Check if two IPv6 addresses are in the same prefix
    fn are_in_same_prefix_v6(&self, ip1: Ipv6Addr, ip2: Ipv6Addr) -> bool {
        // Simplified IPv6 prefix check - compare first 64 bits
        let segments1 = ip1.segments();
        let segments2 = ip2.segments();
        segments1[0] == segments2[0]
            && segments1[1] == segments2[1]
            && segments1[2] == segments2[2]
            && segments1[3] == segments2[3]
    }

    /// Validate coordination parameters for security
    fn validate_coordination_parameters(&self, frame: &crate::frame::PunchMeNow) -> bool {
        // Check round number is reasonable (not too large to prevent overflow attacks)
        if frame.round.into_inner() > 1000000 {
            return false;
        }
        // Check target sequence is reasonable
        if frame.paired_with_sequence_number.into_inner() > 10000 {
            return false;
        }

        // Validate address is not obviously invalid
        match frame.address.ip() {
            IpAddr::V4(ipv4) => {
                // Reject obviously invalid addresses
                !ipv4.is_unspecified() && !ipv4.is_broadcast() && !ipv4.is_multicast()
            }
            IpAddr::V6(ipv6) => {
                // Reject obviously invalid addresses
                !ipv6.is_unspecified() && !ipv6.is_multicast()
            }
        }
    }

    /// Validate target peer request for potential abuse
    fn validate_target_peer_request(
        &self,
        requesting_peer: [u8; 32],
        target_peer: [u8; 32],
        _frame: &crate::frame::PunchMeNow,
    ) -> bool {
        // Prevent self-coordination (peer requesting coordination with itself)
        if requesting_peer == target_peer {
            return false;
        }
        // Additional validation could include:
        // - Check if target peer is known/registered
        // - Validate target peer hasn't opted out of coordination
        // - Check for suspicious patterns in target peer selection

        true
    }

    /// Validate resource limits for the coordination request
    fn validate_resource_limits(&self, _frame: &crate::frame::PunchMeNow) -> bool {
        // Check current load and resource usage
        // This is a simplified check - production would monitor:
        // - Active coordination sessions
        // - Memory usage
        // - Network bandwidth
        // - CPU utilization
        // For now, just check if we have too many active coordination requests
        self.coordination_requests.len() < self.max_coordination_per_window as usize
    }
}

impl AdaptiveTimeoutState {
    /// Create new adaptive timeout state with default values
    pub(crate) fn new() -> Self {
        let base_timeout = Duration::from_millis(1000); // 1 second base
        Self {
            current_timeout: base_timeout,
            min_timeout: Duration::from_millis(100),
            max_timeout: Duration::from_secs(30),
            base_timeout,
            backoff_multiplier: 1.0,
            max_backoff_multiplier: 8.0,
            jitter_factor: 0.1, // 10% jitter
            srtt: None,
            rttvar: None,
            last_rtt: None,
            consecutive_timeouts: 0,
            successful_responses: 0,
        }
    }
    /// Update timeout based on successful response
    fn update_success(&mut self, rtt: Duration) {
        self.last_rtt = Some(rtt);
        self.successful_responses += 1;
        self.consecutive_timeouts = 0;
        // Update smoothed RTT using TCP algorithm
        match self.srtt {
            None => {
                self.srtt = Some(rtt);
                self.rttvar = Some(rtt / 2);
            }
            Some(srtt) => {
                let rttvar = self.rttvar.unwrap_or(rtt / 2);
                let abs_diff = rtt.abs_diff(srtt);

                self.rttvar = Some(rttvar * 3 / 4 + abs_diff / 4);
                self.srtt = Some(srtt * 7 / 8 + rtt / 8);
            }
        }

        // Reduce backoff multiplier on success
        self.backoff_multiplier = (self.backoff_multiplier * 0.8).max(1.0);

        // Update current timeout
        self.calculate_current_timeout();
    }

    /// Update timeout based on timeout event
    fn update_timeout(&mut self) {
        self.consecutive_timeouts += 1;
        // Exponential backoff with bounds
        self.backoff_multiplier = (self.backoff_multiplier * 2.0).min(self.max_backoff_multiplier);

        // Update current timeout
        self.calculate_current_timeout();
    }

    /// Calculate current timeout based on conditions
    fn calculate_current_timeout(&mut self) {
        let base_timeout = if let (Some(srtt), Some(rttvar)) = (self.srtt, self.rttvar) {
            // Use TCP-style RTO calculation: RTO = SRTT + 4 * RTTVAR
            srtt + rttvar * 4
        } else {
            self.base_timeout
        };
        // Apply backoff multiplier
        let timeout = base_timeout.mul_f64(self.backoff_multiplier);

        // Apply jitter to prevent thundering herd
        let jitter = 1.0 + (rand::random::<f64>() - 0.5) * 2.0 * self.jitter_factor;
        let timeout = timeout.mul_f64(jitter);

        // Bound the timeout
        self.current_timeout = timeout.clamp(self.min_timeout, self.max_timeout);
    }

    /// Get current timeout value
    fn get_timeout(&self) -> Duration {
        self.current_timeout
    }
    /// Check if retry should be attempted
    fn should_retry(&self, max_retries: u32) -> bool {
        self.consecutive_timeouts < max_retries
    }
    /// Get retry delay with exponential backoff
    fn get_retry_delay(&self) -> Duration {
        let delay = self.current_timeout.mul_f64(self.backoff_multiplier);
        delay.clamp(self.min_timeout, self.max_timeout)
    }
}
/// Resource management limits and cleanup configuration
#[derive(Debug)]
#[allow(dead_code)]
pub(super) struct ResourceManagementConfig {
    /// Maximum number of active validations
    max_active_validations: usize,
    /// Maximum number of local candidates
    max_local_candidates: usize,
    /// Maximum number of remote candidates
    max_remote_candidates: usize,
    /// Maximum number of candidate pairs to generate.
    ///
    /// This limit prevents DoS attacks via unbounded memory allocation when
    /// receiving many candidates from peers. Both full regeneration
    /// (`generate_candidate_pairs`) and incremental generation
    /// (`add_pairs_for_local_candidate`, `add_pairs_for_remote_candidate`)
    /// respect this limit.
    ///
    /// Default: 200 (see `ResourceManagementConfig::new()`)
    max_candidate_pairs: usize,
    /// Maximum coordination rounds to keep in history
    max_coordination_history: usize,
    /// Cleanup interval for expired resources
    cleanup_interval: Duration,
    /// Timeout for stale candidates
    candidate_timeout: Duration,
    /// Timeout for path validations
    validation_timeout: Duration,
    /// Timeout for coordination rounds
    coordination_timeout: Duration,
    /// Memory pressure threshold (0.0 = no pressure, 1.0 = maximum pressure)
    memory_pressure_threshold: f64,
    /// Aggressive cleanup mode threshold
    aggressive_cleanup_threshold: f64,
}
/// Resource usage statistics and monitoring
#[derive(Debug, Default)]
#[allow(dead_code)]
pub(super) struct ResourceStats {
    /// Current number of active validations
    active_validations: usize,
    /// Current number of local candidates
    local_candidates: usize,
    /// Current number of remote candidates
    remote_candidates: usize,
    /// Current number of candidate pairs
    candidate_pairs: usize,
    /// Peak memory usage
    peak_memory_usage: usize,
    /// Number of cleanup operations performed
    cleanup_operations: u64,
    /// Number of resources cleaned up
    resources_cleaned: u64,
    /// Number of resource allocation failures
    allocation_failures: u64,
    /// Last cleanup time
    last_cleanup: Option<Instant>,
    /// Memory pressure level (0.0 = no pressure, 1.0 = maximum pressure)
    memory_pressure: f64,
}
/// Resource cleanup coordinator
#[derive(Debug)]
pub(super) struct ResourceCleanupCoordinator {
    /// Configuration for resource limits
    config: ResourceManagementConfig,
    /// Resource usage statistics
    stats: ResourceStats,
    /// Last cleanup time
    last_cleanup: Option<Instant>,
    /// Cleanup operation counter
    cleanup_counter: u64,
    /// Shutdown flag
    shutdown_requested: bool,
}
impl ResourceManagementConfig {
    /// Create new resource management configuration with production-ready defaults
    fn new() -> Self {
        Self {
            max_active_validations: 100,
            max_local_candidates: 50,
            max_remote_candidates: 100,
            max_candidate_pairs: 200,
            max_coordination_history: 10,
            cleanup_interval: Duration::from_secs(30),
            candidate_timeout: Duration::from_secs(300), // 5 minutes
            validation_timeout: Duration::from_secs(30),
            coordination_timeout: Duration::from_secs(60),
            memory_pressure_threshold: 0.75,
            aggressive_cleanup_threshold: 0.90,
        }
    }
}
#[allow(dead_code)]
impl ResourceCleanupCoordinator {
    /// Create new resource cleanup coordinator
    fn new() -> Self {
        Self {
            config: ResourceManagementConfig::new(),
            stats: ResourceStats::default(),
            last_cleanup: None,
            cleanup_counter: 0,
            shutdown_requested: false,
        }
    }
    /// Check if resource limits are exceeded
    fn check_resource_limits(&self, state: &NatTraversalState) -> bool {
        state.active_validations.len() > self.config.max_active_validations
            || state.local_candidates.len() > self.config.max_local_candidates
            || state.remote_candidates.len() > self.config.max_remote_candidates
            || state.candidate_pairs.len() > self.config.max_candidate_pairs
    }
    /// Calculate current memory pressure level
    fn calculate_memory_pressure(
        &mut self,
        active_validations_len: usize,
        local_candidates_len: usize,
        remote_candidates_len: usize,
        candidate_pairs_len: usize,
    ) -> f64 {
        let total_limit = self.config.max_active_validations
            + self.config.max_local_candidates
            + self.config.max_remote_candidates
            + self.config.max_candidate_pairs;
        let current_usage = active_validations_len
            + local_candidates_len
            + remote_candidates_len
            + candidate_pairs_len;

        let pressure = current_usage as f64 / total_limit as f64;
        self.stats.memory_pressure = pressure;
        pressure
    }

    /// Determine if cleanup is needed
    fn should_cleanup(&self, now: Instant) -> bool {
        if self.shutdown_requested {
            return true;
        }
        match self.last_cleanup {
            Some(last) => {
                let interval = if self.stats.memory_pressure > self.config.memory_pressure_threshold
                {
                    self.config.cleanup_interval / 2
                } else {
                    self.config.cleanup_interval
                };
                now.duration_since(last) > interval
            }
            None => true,
        }
    }

    /// Check if resource levels allow for generating predicted candidates
    fn is_prediction_allowed(&self, _now: Instant) -> bool {
        // Only allow prediction if memory pressure is below aggressive threshold
        // and we aren't already shutting down
        self.stats.memory_pressure < self.config.aggressive_cleanup_threshold
            && !self.shutdown_requested
    }

    /// Perform cleanup of expired resources
    fn cleanup_expired_resources(
        &mut self,
        active_validations: &mut HashMap<u64, PathValidationState>,
        local_candidates: &mut HashMap<VarInt, AddressCandidate>,
        remote_candidates: &mut HashMap<VarInt, AddressCandidate>,
        candidate_pairs: &mut Vec<CandidatePair>,
        coordination: &mut Option<CoordinationState>,
        now: Instant,
    ) -> u64 {
        let mut cleaned = 0;
        // Clean up expired path validations
        cleaned += self.cleanup_expired_validations(active_validations, now);

        // Clean up stale candidates
        cleaned += self.cleanup_stale_candidates(local_candidates, remote_candidates, now);

        // Clean up failed candidate pairs
        cleaned += self.cleanup_failed_pairs(candidate_pairs, now);

        // Clean up old coordination state
        cleaned += self.cleanup_old_coordination(coordination, now);

        // Update statistics
        self.stats.cleanup_operations += 1;
        self.stats.resources_cleaned += cleaned;
        self.last_cleanup = Some(now);
        self.cleanup_counter += 1;

        debug!("Cleaned up {} expired resources", cleaned);
        cleaned
    }

    /// Clean up expired path validations
    fn cleanup_expired_validations(
        &mut self,
        active_validations: &mut HashMap<u64, PathValidationState>,
        now: Instant,
    ) -> u64 {
        let mut cleaned = 0;
        let validation_timeout = self.config.validation_timeout;
        active_validations.retain(|_challenge, validation| {
            let is_expired = now.duration_since(validation.sent_at) > validation_timeout;
            if is_expired {
                cleaned += 1;
                trace!(
                    "Cleaned up expired validation for {}",
                    validation.target_addr
                );
            }
            !is_expired
        });

        cleaned
    }

    /// Clean up stale candidates
    fn cleanup_stale_candidates(
        &mut self,
        local_candidates: &mut HashMap<VarInt, AddressCandidate>,
        remote_candidates: &mut HashMap<VarInt, AddressCandidate>,
        now: Instant,
    ) -> u64 {
        let mut cleaned = 0;
        let candidate_timeout = self.config.candidate_timeout;
        // Clean up local candidates
        local_candidates.retain(|_seq, candidate| {
            let is_stale = now.duration_since(candidate.discovered_at) > candidate_timeout
                || candidate.state == CandidateState::Failed
                || candidate.state == CandidateState::Removed;
            if is_stale {
                cleaned += 1;
                trace!("Cleaned up stale local candidate {:?}", candidate.address);
            }
            !is_stale
        });

        // Clean up remote candidates
        remote_candidates.retain(|_seq, candidate| {
            let is_stale = now.duration_since(candidate.discovered_at) > candidate_timeout
                || candidate.state == CandidateState::Failed
                || candidate.state == CandidateState::Removed;
            if is_stale {
                cleaned += 1;
                trace!("Cleaned up stale remote candidate {:?}", candidate.address);
            }
            !is_stale
        });

        cleaned
    }

    /// Clean up failed candidate pairs
    fn cleanup_failed_pairs(
        &mut self,
        candidate_pairs: &mut Vec<CandidatePair>,
        now: Instant,
    ) -> u64 {
        let mut cleaned = 0;
        let pair_timeout = self.config.candidate_timeout;
        candidate_pairs.retain(|pair| {
            let is_stale = now.duration_since(pair.created_at) > pair_timeout
                || pair.state == PairState::Failed;
            if is_stale {
                cleaned += 1;
                trace!(
                    "Cleaned up failed candidate pair {:?} -> {:?}",
                    pair.local_addr, pair.remote_addr
                );
            }
            !is_stale
        });

        cleaned
    }

    /// Clean up old coordination state
    fn cleanup_old_coordination(
        &mut self,
        coordination: &mut Option<CoordinationState>,
        now: Instant,
    ) -> u64 {
        let mut cleaned = 0;
        if let Some(coord) = coordination {
            let is_expired =
                now.duration_since(coord.round_start) > self.config.coordination_timeout;
            let is_failed = coord.state == CoordinationPhase::Failed;

            if is_expired || is_failed {
                let round = coord.round;
                *coordination = None;
                cleaned += 1;
                trace!("Cleaned up old coordination state for round {}", round);
            }
        }

        cleaned
    }

    /// Perform aggressive cleanup when under memory pressure
    fn aggressive_cleanup(
        &mut self,
        active_validations: &mut HashMap<u64, PathValidationState>,
        local_candidates: &mut HashMap<VarInt, AddressCandidate>,
        remote_candidates: &mut HashMap<VarInt, AddressCandidate>,
        candidate_pairs: &mut Vec<CandidatePair>,
        now: Instant,
    ) -> u64 {
        let mut cleaned = 0;
        // More aggressive timeout for candidates
        let aggressive_timeout = self.config.candidate_timeout / 2;

        // Clean up older candidates first
        local_candidates.retain(|_seq, candidate| {
            let keep = now.duration_since(candidate.discovered_at) <= aggressive_timeout
                && candidate.state != CandidateState::Failed;
            if !keep {
                cleaned += 1;
            }
            keep
        });

        remote_candidates.retain(|_seq, candidate| {
            let keep = now.duration_since(candidate.discovered_at) <= aggressive_timeout
                && candidate.state != CandidateState::Failed;
            if !keep {
                cleaned += 1;
            }
            keep
        });

        // Clean up waiting candidate pairs
        candidate_pairs.retain(|pair| {
            let keep = pair.state != PairState::Waiting
                || now.duration_since(pair.created_at) <= aggressive_timeout;
            if !keep {
                cleaned += 1;
            }
            keep
        });

        // Clean up old validations more aggressively
        active_validations.retain(|_challenge, validation| {
            let keep = now.duration_since(validation.sent_at) <= self.config.validation_timeout / 2;
            if !keep {
                cleaned += 1;
            }
            keep
        });

        warn!(
            "Aggressive cleanup removed {} resources due to memory pressure",
            cleaned
        );
        cleaned
    }

    /// Request graceful shutdown and cleanup
    fn request_shutdown(&mut self) {
        self.shutdown_requested = true;
        debug!("Resource cleanup coordinator shutdown requested");
    }
    /// Perform final cleanup during shutdown
    fn shutdown_cleanup(
        &mut self,
        active_validations: &mut HashMap<u64, PathValidationState>,
        local_candidates: &mut HashMap<VarInt, AddressCandidate>,
        remote_candidates: &mut HashMap<VarInt, AddressCandidate>,
        candidate_pairs: &mut Vec<CandidatePair>,
        coordination: &mut Option<CoordinationState>,
    ) -> u64 {
        let mut cleaned = 0;
        // Clear all resources
        cleaned += active_validations.len() as u64;
        active_validations.clear();

        cleaned += local_candidates.len() as u64;
        local_candidates.clear();

        cleaned += remote_candidates.len() as u64;
        remote_candidates.clear();

        cleaned += candidate_pairs.len() as u64;
        candidate_pairs.clear();

        if coordination.is_some() {
            *coordination = None;
            cleaned += 1;
        }

        info!("Shutdown cleanup removed {} resources", cleaned);
        cleaned
    }

    /// Get current resource usage statistics
    fn get_resource_stats(&self) -> &ResourceStats {
        &self.stats
    }
    /// Update resource usage statistics
    fn update_stats(
        &mut self,
        active_validations_len: usize,
        local_candidates_len: usize,
        remote_candidates_len: usize,
        candidate_pairs_len: usize,
    ) {
        self.stats.active_validations = active_validations_len;
        self.stats.local_candidates = local_candidates_len;
        self.stats.remote_candidates = remote_candidates_len;
        self.stats.candidate_pairs = candidate_pairs_len;
        // Update peak memory usage
        let current_usage = self.stats.active_validations
            + self.stats.local_candidates
            + self.stats.remote_candidates
            + self.stats.candidate_pairs;

        if current_usage > self.stats.peak_memory_usage {
            self.stats.peak_memory_usage = current_usage;
        }
    }

    /// Perform resource cleanup based on current state
    pub(super) fn perform_cleanup(&mut self, now: Instant) {
        self.last_cleanup = Some(now);
        self.cleanup_counter += 1;
        // Update cleanup statistics
        self.stats.cleanup_operations += 1;

        debug!("Performed resource cleanup #{}", self.cleanup_counter);
    }
}

#[allow(dead_code)]
impl NetworkConditionMonitor {
    /// Create new network condition monitor
    fn new() -> Self {
        Self {
            rtt_samples: VecDeque::new(),
            max_samples: 20,
            packet_loss_rate: 0.0,
            congestion_window: 10,
            quality_score: 0.8, // Start with good quality assumption
            last_quality_update: Instant::now(),
            quality_update_interval: Duration::from_secs(10),
            timeout_stats: TimeoutStatistics::default(),
        }
    }
    /// Record a successful response time
    fn record_success(&mut self, rtt: Duration, now: Instant) {
        // Add RTT sample
        self.rtt_samples.push_back(rtt);
        if self.rtt_samples.len() > self.max_samples {
            self.rtt_samples.pop_front();
        }
        // Update timeout statistics
        self.timeout_stats.total_responses += 1;
        self.update_timeout_stats(now);

        // Update quality score
        self.update_quality_score(now);
    }

    /// Record a timeout event
    fn record_timeout(&mut self, now: Instant) {
        self.timeout_stats.total_timeouts += 1;
        self.update_timeout_stats(now);
        // Update quality score
        self.update_quality_score(now);
    }

    /// Update timeout statistics
    fn update_timeout_stats(&mut self, now: Instant) {
        let total_attempts = self.timeout_stats.total_responses + self.timeout_stats.total_timeouts;
        if total_attempts > 0 {
            self.timeout_stats.timeout_rate =
                self.timeout_stats.total_timeouts as f64 / total_attempts as f64;
        }

        // Calculate average response time
        if !self.rtt_samples.is_empty() {
            let total_rtt: Duration = self.rtt_samples.iter().sum();
            self.timeout_stats.avg_response_time = total_rtt / self.rtt_samples.len() as u32;
        }

        self.timeout_stats.last_update = Some(now);
    }

    /// Update network quality score
    fn update_quality_score(&mut self, now: Instant) {
        if now.duration_since(self.last_quality_update) < self.quality_update_interval {
            return;
        }
        // Quality factors
        let timeout_factor = 1.0 - self.timeout_stats.timeout_rate;
        let rtt_factor = self.calculate_rtt_factor();
        let consistency_factor = self.calculate_consistency_factor();

        // Weighted quality score
        let new_quality = (timeout_factor * 0.4) + (rtt_factor * 0.3) + (consistency_factor * 0.3);

        // Smooth the quality score
        self.quality_score = self.quality_score * 0.7 + new_quality * 0.3;
        self.last_quality_update = now;
    }

    /// Calculate RTT factor for quality score
    fn calculate_rtt_factor(&self) -> f64 {
        if self.rtt_samples.is_empty() {
            return 0.5; // Neutral score
        }
        let avg_rtt = self.timeout_stats.avg_response_time;

        // Good RTT: < 50ms = 1.0, Poor RTT: > 1000ms = 0.0
        let rtt_ms = avg_rtt.as_millis() as f64;
        let factor = 1.0 - (rtt_ms - 50.0) / 950.0;
        factor.clamp(0.0, 1.0)
    }

    /// Calculate consistency factor for quality score
    fn calculate_consistency_factor(&self) -> f64 {
        if self.rtt_samples.len() < 3 {
            return 0.5; // Neutral score
        }
        // Calculate RTT variance
        let mean_rtt = self.timeout_stats.avg_response_time;
        let variance: f64 = self
            .rtt_samples
            .iter()
            .map(|rtt| {
                let diff = (*rtt).abs_diff(mean_rtt);
                diff.as_millis() as f64
            })
            .map(|diff| diff * diff)
            .sum::<f64>()
            / self.rtt_samples.len() as f64;

        let std_dev = variance.sqrt();

        // Low variance = high consistency
        let consistency = 1.0 - (std_dev / 1000.0).min(1.0);
        consistency.clamp(0.0, 1.0)
    }

    /// Get current network quality score
    fn get_quality_score(&self) -> f64 {
        self.quality_score
    }
    /// Get estimated RTT based on recent samples
    fn get_estimated_rtt(&self) -> Option<Duration> {
        if self.rtt_samples.is_empty() {
            return None;
        }
        Some(self.timeout_stats.avg_response_time)
    }

    /// Check if network conditions are suitable for coordination
    fn is_suitable_for_coordination(&self) -> bool {
        // Require reasonable quality for coordination attempts
        self.quality_score >= 0.3 && self.timeout_stats.timeout_rate < 0.5
    }
    /// Get estimated packet loss rate
    fn get_packet_loss_rate(&self) -> f64 {
        self.packet_loss_rate
    }

    /// Get recommended timeout multiplier based on conditions
    fn get_timeout_multiplier(&self) -> f64 {
        let base_multiplier = 1.0;

        // Adjust based on quality score
        let quality_multiplier = if self.quality_score < 0.3 {
            2.0 // Poor quality, increase timeouts
        } else if self.quality_score > 0.8 {
            0.8 // Good quality, reduce timeouts
        } else {
            1.0 // Neutral
        };

        // Adjust based on packet loss
        let loss_multiplier = 1.0 + (self.packet_loss_rate * 2.0);

        base_multiplier * quality_multiplier * loss_multiplier
    }

    /// Clean up old samples and statistics
    fn cleanup(&mut self, now: Instant) {
        // Remove old RTT samples (keep only recent ones)
        let _cutoff_time = now - Duration::from_secs(60);

        // Reset statistics if they're too old
        if let Some(last_update) = self.timeout_stats.last_update {
            if now.duration_since(last_update) > Duration::from_secs(300) {
                self.timeout_stats = TimeoutStatistics::default();
            }
        }
    }
}

#[allow(dead_code)]
impl NatTraversalState {
    /// Create new NAT traversal state with given configuration
    ///
    /// v0.13.0: Role parameter removed - all nodes are symmetric P2P nodes.
    /// Every node can initiate, accept, and coordinate NAT traversal.
    pub(super) fn new(max_candidates: u32, coordination_timeout: Duration) -> Self {
        // v0.13.0: All nodes can coordinate - always create coordinator
        let bootstrap_coordinator = Some(BootstrapCoordinator::new(BootstrapConfig::default()));

        Self {
            // v0.13.0: role field removed - all nodes are symmetric
            local_candidates: HashMap::new(),
            remote_candidates: HashMap::new(),
            candidate_pairs: Vec::new(),
            pair_index: HashMap::new(),
            active_validations: HashMap::new(),
            coordination: None,
            next_sequence: VarInt::from_u32(1),
            max_candidates,
            coordination_timeout,
            stats: NatTraversalStats::default(),
            security_state: SecurityValidationState::new(),
            network_monitor: NetworkConditionMonitor::new(),
            resource_manager: ResourceCleanupCoordinator::new(),
            bootstrap_coordinator,
            port_predictor: PortPredictor::new(PortPredictorConfig::default()),
        }
    }

    fn next_sequence_u32(&mut self) -> VarInt {
        let current_raw = self.next_sequence.into_inner();
        let current = match u32::try_from(current_raw) {
            Ok(value) => value,
            Err(_) => {
                warn!(
                    "NAT traversal sequence out of range ({}), resetting to u32::MAX",
                    current_raw
                );
                u32::MAX
            }
        };
        if current == u32::MAX {
            warn!("NAT traversal sequence wrapped at u32::MAX");
        }
        self.next_sequence = VarInt::from_u32(current.wrapping_add(1));
        VarInt::from_u32(current)
    }

    /// Add a remote candidate from AddAddress frame with security validation
    pub(super) fn add_remote_candidate(
        &mut self,
        sequence: VarInt,
        address: SocketAddr,
        priority: VarInt,
        now: Instant,
    ) -> Result<(), NatTraversalError> {
        // Resource management: Check if we should reject new resources
        if self.should_reject_new_resources(now) {
            debug!(
                "Rejecting new candidate due to resource limits: {}",
                address
            );
            return Err(NatTraversalError::ResourceLimitExceeded);
        }
        // Security validation: Check rate limiting
        if self.security_state.is_candidate_rate_limited(now) {
            self.stats.rate_limit_violations += 1;
            debug!("Rate limit exceeded for candidate addition: {}", address);
            return Err(NatTraversalError::RateLimitExceeded);
        }

        // Security validation: Validate address format and safety
        match self.security_state.validate_address(address, now) {
            AddressValidationResult::Invalid => {
                self.stats.invalid_address_rejections += 1;
                self.stats.security_rejections += 1;
                debug!("Invalid address rejected: {}", address);
                return Err(NatTraversalError::InvalidAddress);
            }
            AddressValidationResult::Suspicious => {
                self.stats.security_rejections += 1;
                debug!("Suspicious address rejected: {}", address);
                return Err(NatTraversalError::SecurityValidationFailed);
            }
            AddressValidationResult::Valid => {
                // Continue with normal processing
            }
        }

        // Check candidate count limit
        if self.remote_candidates.len() >= self.max_candidates as usize {
            return Err(NatTraversalError::TooManyCandidates);
        }

        // Check for duplicate addresses (different sequence, same address)
        if self.remote_candidates.values().any(|c| {
            normalize_socket_addr(c.address) == normalize_socket_addr(address)
                && c.state != CandidateState::Removed
        }) {
            return Err(NatTraversalError::DuplicateAddress);
        }

        let candidate = AddressCandidate {
            address,
            priority: priority.into_inner() as u32,
            source: CandidateSource::Peer,
            discovered_at: now,
            state: CandidateState::New,
            attempt_count: 0,
            last_attempt: None,
        };

        self.remote_candidates.insert(sequence, candidate);
        self.stats.remote_candidates_received += 1;

        // Incrementally add pairs for this new remote candidate (O(n) vs O(n*m))
        self.add_pairs_for_remote_candidate(sequence, now);

        // Feed the predictor and potentially generate new candidates
        // Only consider global unicast addresses (public IPs) for prediction
        if !address.ip().is_loopback() && !address.ip().is_unspecified() {
            // Record the observation
            self.port_predictor.record_observation(address, now);

            // Try to generate predictions immediately
            self.generate_predicted_candidates(address.ip(), now);
        }

        trace!(
            "Added remote candidate: {} with priority {}",
            address, priority
        );
        Ok(())
    }

    /// Generate predicted candidates based on observation history
    fn generate_predicted_candidates(&mut self, ip: IpAddr, now: Instant) {
        if !self.resource_manager.is_prediction_allowed(now) {
            return;
        }

        let predictions = self.port_predictor.predict_ports(ip);
        for port in predictions {
            let predicted_addr = SocketAddr::new(ip, port);

            // Don't add if we already have this candidate
            if self
                .remote_candidates
                .values()
                .any(|c| normalize_socket_addr(c.address) == normalize_socket_addr(predicted_addr))
            {
                continue;
            }

            // Don't exceed limits
            if self.remote_candidates.len() >= self.max_candidates as usize {
                break;
            }

            // Create a pseudo-sequence number for predicted candidates
            // We use a high range to avoid compact collision with real frames
            // Base offset: 1B + (port * 1000) to keep them reasonably unique but deterministic
            let seq_num = 1_000_000_000 + (port as u64);
            let sequence = VarInt::from_u64(seq_num).unwrap_or(self.next_sequence);

            let candidate = AddressCandidate {
                address: predicted_addr,
                priority: 1, // Low priority for predicted
                source: CandidateSource::Predicted,
                discovered_at: now,
                state: CandidateState::New,
                attempt_count: 0,
                last_attempt: None,
            };

            debug!("Added predicted candidate: {}", predicted_addr);
            self.remote_candidates.insert(sequence, candidate);
            self.stats.predicted_candidates_generated += 1;

            // Incrementally add pairs for this new remote candidate (O(n) vs O(n*m))
            self.add_pairs_for_remote_candidate(sequence, now);
        }
    }

    /// Remove a candidate by sequence number
    pub(super) fn remove_candidate(&mut self, sequence: VarInt) -> bool {
        if let Some(candidate) = self.remote_candidates.get_mut(&sequence) {
            candidate.state = CandidateState::Removed;
            // Cancel any active validation for this candidate (look up by sequence, not address)
            self.active_validations
                .retain(|_, v| v.sequence != sequence);
            true
        } else {
            false
        }
    }

    /// Add a local candidate that we've discovered
    pub(super) fn add_local_candidate(
        &mut self,
        address: SocketAddr,
        source: CandidateSource,
        now: Instant,
    ) -> VarInt {
        let sequence = self.next_sequence_u32();
        // Calculate priority for this candidate
        let candidate_type = classify_candidate_type(source);
        let local_preference = self.calculate_local_preference(address);
        let priority = calculate_candidate_priority(candidate_type, local_preference, 1);

        let candidate = AddressCandidate {
            address,
            priority,
            source,
            discovered_at: now,
            state: CandidateState::New,
            attempt_count: 0,
            last_attempt: None,
        };

        self.local_candidates.insert(sequence, candidate);
        self.stats.local_candidates_sent += 1;

        // Incrementally add pairs for this new local candidate (O(m) vs O(n*m))
        self.add_pairs_for_local_candidate(sequence, now);

        sequence
    }

    /// Calculate local preference for address prioritization
    fn calculate_local_preference(&self, addr: SocketAddr) -> u16 {
        match addr {
            SocketAddr::V4(v4) => {
                if v4.ip().is_loopback() {
                    0 // Lowest priority
                } else if v4.ip().is_private() {
                    65000 // High priority for local network
                } else {
                    32000 // Medium priority for public addresses
                }
            }
            SocketAddr::V6(v6) => {
                if v6.ip().is_loopback() {
                    0
                } else if v6.ip().segments()[0] == 0xfe80 {
                    // Link-local IPv6 check
                    30000 // Link-local gets medium-low priority
                } else {
                    50000 // IPv6 generally gets good priority
                }
            }
        }
    }
    /// Generate all possible candidate pairs from local and remote candidates
    ///
    /// Note: This is O(n*m) where n=local candidates, m=remote candidates.
    /// For incremental updates when adding single candidates, use
    /// `add_pairs_for_local_candidate` or `add_pairs_for_remote_candidate`.
    pub(super) fn generate_candidate_pairs(&mut self, now: Instant) {
        self.candidate_pairs.clear();
        self.pair_index.clear();
        // Pre-allocate capacity to avoid reallocations
        let estimated_capacity = self.local_candidates.len() * self.remote_candidates.len();
        self.candidate_pairs.reserve(estimated_capacity);
        self.pair_index.reserve(estimated_capacity);

        // Cache compatibility checks to avoid repeated work
        let mut compatibility_cache: HashMap<(SocketAddr, SocketAddr), bool> = HashMap::new();

        for local_candidate in self.local_candidates.values() {
            // Skip removed candidates early
            if local_candidate.state == CandidateState::Removed {
                continue;
            }

            // Pre-classify local candidate type once
            let local_type = classify_candidate_type(local_candidate.source);

            for (remote_seq, remote_candidate) in &self.remote_candidates {
                // Skip removed candidates
                if remote_candidate.state == CandidateState::Removed {
                    continue;
                }

                // Check compatibility with caching
                let cache_key = (local_candidate.address, remote_candidate.address);
                let compatible = *compatibility_cache.entry(cache_key).or_insert_with(|| {
                    are_candidates_compatible(local_candidate, remote_candidate)
                });

                if !compatible {
                    continue;
                }

                // Calculate combined priority
                let pair_priority =
                    calculate_pair_priority(local_candidate.priority, remote_candidate.priority);

                // Classify pair type (local already classified)
                let remote_type = classify_candidate_type(remote_candidate.source);
                let pair_type = classify_pair_type(local_type, remote_type);

                let pair = CandidatePair {
                    remote_sequence: *remote_seq,
                    local_addr: local_candidate.address,
                    remote_addr: remote_candidate.address,
                    priority: pair_priority,
                    state: PairState::Waiting,
                    pair_type,
                    created_at: now,
                    last_check: None,
                };

                // Store index for O(1) lookup
                let index = self.candidate_pairs.len();
                self.pair_index.insert(remote_candidate.address, index);
                self.candidate_pairs.push(pair);
            }
        }

        self.sort_and_reindex_pairs();

        trace!("Generated {} candidate pairs", self.candidate_pairs.len());
    }

    /// Sort pairs by priority and rebuild the index.
    /// Called after adding pairs to maintain sorted order.
    ///
    /// Note: pair_index maps remote_addr to the index of the HIGHEST PRIORITY pair
    /// with that remote address. When multiple pairs share the same remote_addr
    /// (but have different local_addr), only the highest priority one is indexed.
    /// This is intentional - lookups by remote_addr return the best pair for that peer.
    fn sort_and_reindex_pairs(&mut self) {
        // Sort pairs by priority (highest first) - use unstable sort for better performance
        self.candidate_pairs
            .sort_unstable_by(|a, b| b.priority.cmp(&a.priority));

        // Rebuild index after sorting - since pairs are sorted by priority (highest first),
        // we iterate in reverse to ensure the HIGHEST priority pair for each remote_addr
        // ends up in the index (last insert wins, and we want the first/highest priority one)
        self.pair_index.clear();
        for (idx, pair) in self.candidate_pairs.iter().enumerate().rev() {
            self.pair_index.insert(pair.remote_addr, idx);
        }
    }

    /// Incrementally add pairs for a newly added local candidate.
    /// This is O(m) where m = remote candidates, vs O(n*m) for full regeneration.
    pub(super) fn add_pairs_for_local_candidate(&mut self, local_seq: VarInt, now: Instant) {
        // Check if we're already at the limit
        let max_pairs = self.resource_manager.config.max_candidate_pairs;
        if self.candidate_pairs.len() >= max_pairs {
            trace!("Skipping pair generation for local candidate - at limit ({max_pairs})");
            return;
        }

        let local_candidate = match self.local_candidates.get(&local_seq) {
            Some(c) if c.state != CandidateState::Removed => c,
            _ => return,
        };

        let local_type = classify_candidate_type(local_candidate.source);
        let local_addr = local_candidate.address;
        let local_priority = local_candidate.priority;

        // Calculate how many pairs we can still add
        let remaining_capacity = max_pairs.saturating_sub(self.candidate_pairs.len());

        // Collect pairs to add (avoid borrow issues), respecting the limit
        let new_pairs: Vec<_> = self
            .remote_candidates
            .iter()
            .filter(|(_, rc)| rc.state != CandidateState::Removed)
            .filter(|(_, rc)| {
                // Check compatibility inline to avoid needing local_candidate borrow
                let local_is_v4 = local_addr.is_ipv4();
                let remote_is_v4 = rc.address.is_ipv4();
                local_is_v4 == remote_is_v4
            })
            .take(remaining_capacity)
            .map(|(remote_seq, rc)| {
                let pair_priority = calculate_pair_priority(local_priority, rc.priority);
                let remote_type = classify_candidate_type(rc.source);
                let pair_type = classify_pair_type(local_type, remote_type);
                CandidatePair {
                    remote_sequence: *remote_seq,
                    local_addr,
                    remote_addr: rc.address,
                    priority: pair_priority,
                    state: PairState::Waiting,
                    pair_type,
                    created_at: now,
                    last_check: None,
                }
            })
            .collect();

        if new_pairs.is_empty() {
            return;
        }

        self.candidate_pairs.extend(new_pairs);
        self.sort_and_reindex_pairs();

        trace!(
            "Added pairs for local candidate, total: {}",
            self.candidate_pairs.len()
        );
    }

    /// Incrementally add pairs for a newly added remote candidate.
    /// This is O(n) where n = local candidates, vs O(n*m) for full regeneration.
    pub(super) fn add_pairs_for_remote_candidate(&mut self, remote_seq: VarInt, now: Instant) {
        // Check if we're already at the limit
        let max_pairs = self.resource_manager.config.max_candidate_pairs;
        if self.candidate_pairs.len() >= max_pairs {
            trace!("Skipping pair generation for remote candidate - at limit ({max_pairs})");
            return;
        }

        let remote_candidate = match self.remote_candidates.get(&remote_seq) {
            Some(c) if c.state != CandidateState::Removed => c,
            _ => return,
        };

        let remote_type = classify_candidate_type(remote_candidate.source);
        let remote_addr = remote_candidate.address;
        let remote_priority = remote_candidate.priority;
        let remote_is_v4 = remote_addr.is_ipv4();

        // Calculate how many pairs we can still add
        let remaining_capacity = max_pairs.saturating_sub(self.candidate_pairs.len());

        // Collect pairs to add (avoid borrow issues), respecting the limit
        let new_pairs: Vec<_> = self
            .local_candidates
            .values()
            .filter(|lc| lc.state != CandidateState::Removed)
            .filter(|lc| lc.address.is_ipv4() == remote_is_v4)
            .take(remaining_capacity)
            .map(|lc| {
                let local_type = classify_candidate_type(lc.source);
                let pair_priority = calculate_pair_priority(lc.priority, remote_priority);
                let pair_type = classify_pair_type(local_type, remote_type);
                CandidatePair {
                    remote_sequence: remote_seq,
                    local_addr: lc.address,
                    remote_addr,
                    priority: pair_priority,
                    state: PairState::Waiting,
                    pair_type,
                    created_at: now,
                    last_check: None,
                }
            })
            .collect();

        if new_pairs.is_empty() {
            return;
        }

        self.candidate_pairs.extend(new_pairs);
        self.sort_and_reindex_pairs();

        trace!(
            "Added pairs for remote candidate, total: {}",
            self.candidate_pairs.len()
        );
    }

    /// Get the highest priority pairs ready for validation
    pub(super) fn get_next_validation_pairs(
        &mut self,
        max_concurrent: usize,
    ) -> Vec<&mut CandidatePair> {
        // Since pairs are sorted by priority (highest first), we can stop early
        // once we find enough waiting pairs or reach lower priority pairs
        let mut result = Vec::with_capacity(max_concurrent);
        for pair in self.candidate_pairs.iter_mut() {
            if pair.state == PairState::Waiting {
                result.push(pair);
                if result.len() >= max_concurrent {
                    break;
                }
            }
        }

        result
    }

    /// Find a candidate pair by remote address
    pub(super) fn find_pair_by_remote_addr(
        &mut self,
        addr: SocketAddr,
    ) -> Option<&mut CandidatePair> {
        // Use index for O(1) lookup instead of O(n) linear search
        if let Some(&index) = self.pair_index.get(&addr) {
            self.candidate_pairs.get_mut(index)
        } else {
            None
        }
    }
    /// Mark a pair as succeeded and handle promotion
    pub(super) fn mark_pair_succeeded(&mut self, remote_addr: SocketAddr) -> bool {
        // Find the pair and get its type and priority
        let (succeeded_type, succeeded_priority) = {
            if let Some(pair) = self.find_pair_by_remote_addr(remote_addr) {
                pair.state = PairState::Succeeded;
                (pair.pair_type, pair.priority)
            } else {
                return false;
            }
        };
        // Freeze lower priority pairs of the same type to avoid unnecessary testing
        for other_pair in &mut self.candidate_pairs {
            if other_pair.pair_type == succeeded_type
                && other_pair.priority < succeeded_priority
                && other_pair.state == PairState::Waiting
            {
                other_pair.state = PairState::Frozen;
            }
        }

        true
    }

    /// Get the best succeeded pair for each address family
    pub(super) fn get_best_succeeded_pairs(&self) -> Vec<&CandidatePair> {
        let mut best_ipv4: Option<&CandidatePair> = None;
        let mut best_ipv6: Option<&CandidatePair> = None;
        for pair in &self.candidate_pairs {
            if pair.state != PairState::Succeeded {
                continue;
            }

            match pair.remote_addr {
                SocketAddr::V4(_) => {
                    if best_ipv4.is_none_or(|best| pair.priority > best.priority) {
                        best_ipv4 = Some(pair);
                    }
                }
                SocketAddr::V6(_) => {
                    if best_ipv6.is_none_or(|best| pair.priority > best.priority) {
                        best_ipv6 = Some(pair);
                    }
                }
            }
        }

        let mut result = Vec::new();
        if let Some(pair) = best_ipv4 {
            result.push(pair);
        }
        if let Some(pair) = best_ipv6 {
            result.push(pair);
        }
        result
    }

    /// Get candidates ready for validation, sorted by priority
    pub(super) fn get_validation_candidates(&self) -> Vec<(VarInt, &AddressCandidate)> {
        let mut candidates: Vec<_> = self
            .remote_candidates
            .iter()
            .filter(|(_, c)| c.state == CandidateState::New)
            .map(|(k, v)| (*k, v))
            .collect();
        // Sort by priority (higher priority first)
        candidates.sort_by(|a, b| b.1.priority.cmp(&a.1.priority));
        candidates
    }

    /// Start validation for a candidate address with security checks
    pub(super) fn start_validation(
        &mut self,
        sequence: VarInt,
        challenge: u64,
        now: Instant,
    ) -> Result<(), NatTraversalError> {
        let candidate = self
            .remote_candidates
            .get_mut(&sequence)
            .ok_or(NatTraversalError::UnknownCandidate)?;
        if candidate.state != CandidateState::New {
            return Err(NatTraversalError::InvalidCandidateState);
        }

        // Security validation: Check for validation abuse patterns
        if Self::is_validation_suspicious(candidate, now) {
            self.stats.security_rejections += 1;
            debug!(
                "Suspicious validation attempt rejected for address {}",
                candidate.address
            );
            return Err(NatTraversalError::SecurityValidationFailed);
        }

        // Security validation: Limit concurrent validations
        if self.active_validations.len() >= 10 {
            debug!(
                "Too many concurrent validations, rejecting new validation for {}",
                candidate.address
            );
            return Err(NatTraversalError::SecurityValidationFailed);
        }

        // Update candidate state
        let target_addr = candidate.address;
        candidate.state = CandidateState::Validating;
        candidate.attempt_count += 1;
        candidate.last_attempt = Some(now);

        // Track validation state keyed by challenge token (not SocketAddr)
        // so NAT rebinding between challenge and response doesn't break lookup.
        let validation = PathValidationState {
            challenge,
            sequence,
            target_addr,
            sent_at: now,
            retry_count: 0,
            max_retries: 3, // TODO: Make configurable
            coordination_round: self.coordination.as_ref().map(|c| c.round),
            timeout_state: AdaptiveTimeoutState::new(),
            last_retry_at: None,
        };

        self.active_validations.insert(challenge, validation);
        trace!(
            "Started validation for candidate {} (seq {}) with challenge {}",
            target_addr, sequence, challenge
        );
        Ok(())
    }

    /// Check if a validation request shows suspicious patterns
    fn is_validation_suspicious(candidate: &AddressCandidate, now: Instant) -> bool {
        // Check for excessive retry attempts
        if candidate.attempt_count > 10 {
            return true;
        }
        // Check for rapid retry patterns
        if let Some(last_attempt) = candidate.last_attempt {
            let time_since_last = now.duration_since(last_attempt);
            if time_since_last < Duration::from_millis(100) {
                return true; // Too frequent attempts
            }
        }

        // Check if this candidate was recently failed
        if candidate.state == CandidateState::Failed {
            let time_since_discovery = now.duration_since(candidate.discovered_at);
            if time_since_discovery < Duration::from_secs(60) {
                return true; // Recently failed, shouldn't retry so soon
            }
        }

        false
    }

    /// Handle successful validation response
    ///
    /// Looks up the validation by challenge token (not by address), so this
    /// succeeds even if the peer's NAT rebinds between PATH_CHALLENGE and
    /// PATH_RESPONSE.
    pub(super) fn handle_validation_success(
        &mut self,
        remote_addr: SocketAddr,
        challenge: u64,
        now: Instant,
    ) -> Result<VarInt, NatTraversalError> {
        // Look up validation by challenge token — stable across NAT rebinds.
        // The old code looked up by SocketAddr which failed when addresses changed.
        let validation = self
            .active_validations
            .get_mut(&challenge)
            .ok_or(NatTraversalError::NoActiveValidation)?;

        let sequence = validation.sequence;

        // Calculate RTT and update adaptive timeout
        let rtt = now.duration_since(validation.sent_at);
        validation.timeout_state.update_success(rtt);

        // Update network monitor
        self.network_monitor.record_success(rtt, now);

        // Update candidate state
        let candidate = self
            .remote_candidates
            .get_mut(&sequence)
            .ok_or(NatTraversalError::UnknownCandidate)?;

        // If the response came from a different address than expected, update
        // the candidate's address to reflect the peer's current NAT mapping.
        if normalize_socket_addr(candidate.address) != normalize_socket_addr(remote_addr) {
            debug!(
                "NAT rebind detected during validation: expected {}, got {}. Updating candidate.",
                candidate.address, remote_addr
            );
            candidate.address = remote_addr;
        }

        candidate.state = CandidateState::Valid;
        self.active_validations.remove(&challenge);
        self.stats.validations_succeeded += 1;

        trace!(
            "Validation successful for {} (seq {}) with RTT {:?}",
            remote_addr, sequence, rtt
        );
        Ok(sequence)
    }

    /// Start a new coordination round for simultaneous hole punching with security validation
    pub(super) fn start_coordination_round(
        &mut self,
        targets: Vec<PunchTarget>,
        now: Instant,
    ) -> Result<VarInt, NatTraversalError> {
        // Security validation: Check rate limiting for coordination requests
        if self.security_state.is_coordination_rate_limited(now) {
            self.stats.rate_limit_violations += 1;
            debug!(
                "Rate limit exceeded for coordination request with {} targets",
                targets.len()
            );
            return Err(NatTraversalError::RateLimitExceeded);
        }
        // Security validation: Check for suspicious coordination patterns
        if self.is_coordination_suspicious(&targets, now) {
            self.stats.suspicious_coordination_attempts += 1;
            self.stats.security_rejections += 1;
            debug!(
                "Suspicious coordination request rejected with {} targets",
                targets.len()
            );
            return Err(NatTraversalError::SuspiciousCoordination);
        }

        // Security validation: Validate all target addresses
        for target in &targets {
            match self
                .security_state
                .validate_address(target.remote_addr, now)
            {
                AddressValidationResult::Invalid => {
                    self.stats.invalid_address_rejections += 1;
                    self.stats.security_rejections += 1;
                    debug!(
                        "Invalid target address in coordination: {}",
                        target.remote_addr
                    );
                    return Err(NatTraversalError::InvalidAddress);
                }
                AddressValidationResult::Suspicious => {
                    self.stats.security_rejections += 1;
                    debug!(
                        "Suspicious target address in coordination: {}",
                        target.remote_addr
                    );
                    return Err(NatTraversalError::SecurityValidationFailed);
                }
                AddressValidationResult::Valid => {
                    // Continue with normal processing
                }
            }
        }

        let round = self.next_sequence_u32();

        // Calculate synchronized punch time (grace period for coordination)
        let coordination_grace = Duration::from_millis(500); // 500ms for coordination
        let punch_start = now + coordination_grace;

        self.coordination = Some(CoordinationState {
            round,
            punch_targets: targets,
            round_start: now,
            punch_start,
            round_duration: self.coordination_timeout,
            state: CoordinationPhase::Requesting,
            punch_request_sent: false,
            peer_punch_received: false,
            retry_count: 0,
            max_retries: 3,
            timeout_state: AdaptiveTimeoutState::new(),
            last_retry_at: None,
        });

        self.stats.coordination_rounds += 1;
        trace!(
            "Started coordination round {} with {} targets",
            round,
            self.coordination
                .as_ref()
                .map(|c| c.punch_targets.len())
                .unwrap_or(0)
        );
        Ok(round)
    }

    pub(super) fn prime_passive_coordination_target(
        &mut self,
        incoming_round: VarInt,
        target: PunchTarget,
        now: Instant,
    ) -> Result<(), NatTraversalError> {
        if self.is_peer_coordination_suspicious(incoming_round, now) {
            self.stats.suspicious_coordination_attempts += 1;
            self.stats.security_rejections += 1;
            debug!(
                "Suspicious passive coordination request rejected for round {}",
                incoming_round
            );
            return Err(NatTraversalError::SuspiciousCoordination);
        }

        if let Some(coord) = &mut self.coordination
            && coord.round == incoming_round
            && matches!(
                coord.state,
                CoordinationPhase::Requesting
                    | CoordinationPhase::Coordinating
                    | CoordinationPhase::Preparing
            )
        {
            if !coord.punch_targets.iter().any(|existing| {
                existing.remote_addr == target.remote_addr
                    && existing.remote_sequence == target.remote_sequence
            }) {
                coord.punch_targets.push(target);
            }
            coord.peer_punch_received = true;
            coord.state = CoordinationPhase::Preparing;

            let network_rtt = self
                .network_monitor
                .get_estimated_rtt()
                .unwrap_or(Duration::from_millis(100));
            let quality_score = self.network_monitor.get_quality_score();
            let base_grace = Duration::from_millis(150);
            let rtt_factor = (network_rtt.as_millis() as f64 / 100.0).clamp(0.5, 3.0);
            let quality_factor = (2.0 - quality_score).clamp(1.0, 2.0);
            let adaptive_grace = Duration::from_millis(
                (base_grace.as_millis() as f64 * rtt_factor * quality_factor) as u64,
            );
            coord.punch_start = now + adaptive_grace;
            return Ok(());
        }

        let coordination_grace = Duration::from_millis(500);
        let punch_start = now + coordination_grace;
        self.coordination = Some(CoordinationState {
            round: incoming_round,
            punch_targets: vec![target],
            round_start: now,
            punch_start,
            round_duration: self.coordination_timeout,
            state: CoordinationPhase::Preparing,
            punch_request_sent: false,
            peer_punch_received: true,
            retry_count: 0,
            max_retries: 3,
            timeout_state: AdaptiveTimeoutState::new(),
            last_retry_at: None,
        });

        Ok(())
    }

    /// Check if a coordination request shows suspicious patterns
    fn is_coordination_suspicious(&self, targets: &[PunchTarget], _now: Instant) -> bool {
        // Check for excessive number of targets
        if targets.len() > 20 {
            return true;
        }
        // Check for duplicate targets
        let mut seen_addresses = std::collections::HashSet::new();
        for target in targets {
            if !seen_addresses.insert(target.remote_addr) {
                return true; // Duplicate target
            }
        }

        // Check for patterns that might indicate scanning
        if targets.len() > 5 {
            // Check if all targets are in sequential IP ranges (potential scan)
            let mut ipv4_addresses: Vec<_> = targets
                .iter()
                .filter_map(|t| match t.remote_addr.ip() {
                    IpAddr::V4(ipv4) => Some(u32::from(ipv4)),
                    _ => None,
                })
                .collect();

            if ipv4_addresses.len() >= 3 {
                ipv4_addresses.sort();
                let mut sequential_count = 1;
                for i in 1..ipv4_addresses.len() {
                    if ipv4_addresses[i] == ipv4_addresses[i - 1] + 1 {
                        sequential_count += 1;
                        if sequential_count >= 3 {
                            return true; // Sequential IPs detected
                        }
                    } else {
                        sequential_count = 1;
                    }
                }
            }
        }

        false
    }

    /// Get the current coordination phase
    pub(super) fn get_coordination_phase(&self) -> Option<CoordinationPhase> {
        self.coordination.as_ref().map(|c| c.state)
    }
    /// Check if we need to send PUNCH_ME_NOW frame
    pub(super) fn should_send_punch_request(&self) -> bool {
        if let Some(coord) = &self.coordination {
            coord.state == CoordinationPhase::Requesting && !coord.punch_request_sent
        } else {
            false
        }
    }
    /// Mark that we've sent our PUNCH_ME_NOW request
    pub(super) fn mark_punch_request_sent(&mut self) {
        if let Some(coord) = &mut self.coordination {
            coord.punch_request_sent = true;
            coord.state = CoordinationPhase::Coordinating;
            trace!("PUNCH_ME_NOW sent, waiting for peer coordination");
        }
    }
    /// Handle receiving peer's PUNCH_ME_NOW (via coordinator) with security validation
    pub(super) fn handle_peer_punch_request(
        &mut self,
        peer_round: VarInt,
        now: Instant,
    ) -> Result<bool, NatTraversalError> {
        // Security validation: Check if this is a valid coordination request
        if self.is_peer_coordination_suspicious(peer_round, now) {
            self.stats.suspicious_coordination_attempts += 1;
            self.stats.security_rejections += 1;
            debug!(
                "Suspicious peer coordination request rejected for round {}",
                peer_round
            );
            return Err(NatTraversalError::SuspiciousCoordination);
        }
        if let Some(coord) = &mut self.coordination {
            if coord.round == peer_round {
                match coord.state {
                    CoordinationPhase::Coordinating | CoordinationPhase::Requesting => {
                        coord.peer_punch_received = true;
                        coord.state = CoordinationPhase::Preparing;

                        // Calculate adaptive grace period based on network conditions
                        let network_rtt = self
                            .network_monitor
                            .get_estimated_rtt()
                            .unwrap_or(Duration::from_millis(100));
                        let quality_score = self.network_monitor.get_quality_score();

                        // Scale grace period: good networks get shorter delays
                        let base_grace = Duration::from_millis(150);
                        let rtt_factor = (network_rtt.as_millis() as f64 / 100.0).clamp(0.5, 3.0);
                        let quality_factor = (2.0 - quality_score).clamp(1.0, 2.0);

                        let adaptive_grace = Duration::from_millis(
                            (base_grace.as_millis() as f64 * rtt_factor * quality_factor) as u64,
                        );

                        coord.punch_start = now + adaptive_grace;

                        trace!(
                            "Peer coordination received, punch starts in {:?} (RTT: {:?}, quality: {:.2})",
                            adaptive_grace, network_rtt, quality_score
                        );
                        Ok(true)
                    }
                    CoordinationPhase::Preparing => {
                        // Already in preparation phase, just acknowledge
                        trace!("Peer coordination confirmed during preparation");
                        Ok(true)
                    }
                    _ => {
                        debug!(
                            "Received coordination in unexpected phase: {:?}",
                            coord.state
                        );
                        Ok(false)
                    }
                }
            } else {
                debug!(
                    "Received coordination for wrong round: {} vs {}",
                    peer_round, coord.round
                );
                Ok(false)
            }
        } else {
            debug!("Received peer coordination but no active round");
            Ok(false)
        }
    }

    /// Check if a peer coordination request is suspicious
    fn is_peer_coordination_suspicious(&self, peer_round: VarInt, _now: Instant) -> bool {
        // Check for round number anomalies
        if peer_round.into_inner() == 0 {
            return true; // Invalid round number
        }
        // Check if round is too far in the future or past
        if let Some(coord) = &self.coordination {
            let our_round = coord.round.into_inner();
            let peer_round_num = peer_round.into_inner();

            // Allow some variance but reject extreme differences
            if peer_round_num > our_round + 100 || peer_round_num + 100 < our_round {
                return true;
            }
        }

        false
    }

    /// Check if it's time to start hole punching
    pub(super) fn should_start_punching(&self, now: Instant) -> bool {
        if let Some(coord) = &self.coordination {
            match coord.state {
                CoordinationPhase::Preparing => now >= coord.punch_start,
                CoordinationPhase::Coordinating => {
                    // Check if we have peer confirmation and grace period elapsed
                    coord.peer_punch_received && now >= coord.punch_start
                }
                _ => false,
            }
        } else {
            false
        }
    }
    /// Start the synchronized hole punching phase
    pub(super) fn start_punching_phase(&mut self, now: Instant) {
        if let Some(coord) = &mut self.coordination {
            coord.state = CoordinationPhase::Punching;
            // Calculate precise timing for coordinated transmission
            let network_rtt = self
                .network_monitor
                .get_estimated_rtt()
                .unwrap_or(Duration::from_millis(100));

            // Add small random jitter to avoid thundering herd
            let jitter_ms: u64 = rand::random::<u64>() % 11;
            let jitter = Duration::from_millis(jitter_ms);
            let transmission_time = coord.punch_start + network_rtt / 2 + jitter;

            // Update punch start time with precise calculation
            coord.punch_start = transmission_time.max(now);

            trace!(
                "Starting synchronized hole punching at {:?} (RTT: {:?}, jitter: {:?})",
                coord.punch_start, network_rtt, jitter
            );
        }
    }

    /// Get punch targets for the current round
    pub(super) fn get_punch_targets_from_coordination(&self) -> Option<&[PunchTarget]> {
        self.coordination
            .as_ref()
            .map(|c| c.punch_targets.as_slice())
    }
    /// Mark coordination as validating (PATH_CHALLENGE sent)
    pub(super) fn mark_coordination_validating(&mut self) {
        if let Some(coord) = &mut self.coordination {
            if coord.state == CoordinationPhase::Punching {
                coord.state = CoordinationPhase::Validating;
                trace!("Coordination moved to validation phase");
            }
        }
    }
    /// Handle successful path validation during coordination
    pub(super) fn handle_coordination_success(
        &mut self,
        remote_addr: SocketAddr,
        now: Instant,
    ) -> bool {
        if let Some(coord) = &mut self.coordination {
            // Check if this address was one of our punch targets
            let was_target = coord
                .punch_targets
                .iter()
                .any(|target| target.remote_addr == remote_addr);
            if was_target && coord.state == CoordinationPhase::Validating {
                // Calculate RTT and update adaptive timeout
                let rtt = now.duration_since(coord.round_start);
                coord.timeout_state.update_success(rtt);
                self.network_monitor.record_success(rtt, now);

                coord.state = CoordinationPhase::Succeeded;
                self.stats.direct_connections += 1;
                trace!(
                    "Coordination succeeded via {} with RTT {:?}",
                    remote_addr, rtt
                );
                true
            } else {
                false
            }
        } else {
            false
        }
    }

    /// Handle coordination failure and determine if we should retry
    pub(super) fn handle_coordination_failure(&mut self, now: Instant) -> bool {
        if let Some(coord) = &mut self.coordination {
            coord.retry_count += 1;
            coord.timeout_state.update_timeout();
            self.network_monitor.record_timeout(now);
            // Check network conditions before retrying
            if coord.timeout_state.should_retry(coord.max_retries)
                && self.network_monitor.is_suitable_for_coordination()
            {
                // Retry with adaptive timeout
                coord.state = CoordinationPhase::Requesting;
                coord.punch_request_sent = false;
                coord.peer_punch_received = false;
                coord.round_start = now;
                coord.last_retry_at = Some(now);

                // Use adaptive timeout for retry delay
                let retry_delay = coord.timeout_state.get_retry_delay();

                // Factor in network quality for retry timing
                let quality_multiplier = 2.0 - self.network_monitor.get_quality_score();
                let adjusted_delay = Duration::from_millis(
                    (retry_delay.as_millis() as f64 * quality_multiplier) as u64,
                );

                coord.punch_start = now + adjusted_delay;

                trace!(
                    "Coordination failed, retrying round {} (attempt {}) with delay {:?} (quality: {:.2})",
                    coord.round,
                    coord.retry_count + 1,
                    adjusted_delay,
                    self.network_monitor.get_quality_score()
                );
                true
            } else {
                coord.state = CoordinationPhase::Failed;
                self.stats.coordination_failures += 1;

                if !self.network_monitor.is_suitable_for_coordination() {
                    trace!(
                        "Coordination failed due to poor network conditions (quality: {:.2})",
                        self.network_monitor.get_quality_score()
                    );
                } else {
                    trace!("Coordination failed after {} attempts", coord.retry_count);
                }
                false
            }
        } else {
            false
        }
    }

    /// Check if the current coordination round has timed out
    pub(super) fn check_coordination_timeout(&mut self, now: Instant) -> bool {
        if let Some(coord) = &mut self.coordination {
            let timeout = coord.timeout_state.get_timeout();
            let elapsed = now.duration_since(coord.round_start);
            if elapsed > timeout {
                trace!(
                    "Coordination round {} timed out after {:?} (adaptive timeout: {:?})",
                    coord.round, elapsed, timeout
                );
                self.handle_coordination_failure(now);
                true
            } else {
                false
            }
        } else {
            false
        }
    }

    /// Check for validation timeouts and handle retries
    ///
    /// Returns the target addresses of expired validations.
    pub(super) fn check_validation_timeouts(&mut self, now: Instant) -> Vec<SocketAddr> {
        let mut expired_challenges = Vec::new();
        let mut retry_challenges = Vec::new();

        for (&challenge, validation) in &mut self.active_validations {
            let timeout = validation.timeout_state.get_timeout();
            let elapsed = now.duration_since(validation.sent_at);

            if elapsed >= timeout {
                if validation
                    .timeout_state
                    .should_retry(validation.max_retries)
                {
                    retry_challenges.push(challenge);
                } else {
                    expired_challenges.push(challenge);
                }
            }
        }

        // Handle retries
        for challenge in retry_challenges {
            if let Some(validation) = self.active_validations.get_mut(&challenge) {
                validation.retry_count += 1;
                validation.sent_at = now;
                validation.last_retry_at = Some(now);
                validation.timeout_state.update_timeout();

                trace!(
                    "Retrying validation for {} (attempt {})",
                    validation.target_addr,
                    validation.retry_count + 1
                );
            }
        }

        // Remove expired validations, collect their target addresses
        let mut expired_addrs = Vec::new();
        for challenge in &expired_challenges {
            if let Some(validation) = self.active_validations.remove(challenge) {
                expired_addrs.push(validation.target_addr);
                self.network_monitor.record_timeout(now);
                trace!("Validation expired for {}", validation.target_addr);
            }
        }

        expired_addrs
    }

    /// Schedule validation retries for active validations that need retry
    pub(super) fn schedule_validation_retries(&mut self, now: Instant) -> Vec<SocketAddr> {
        let mut retry_addresses = Vec::new();

        for validation in self.active_validations.values_mut() {
            let elapsed = now.duration_since(validation.sent_at);
            let timeout = validation.timeout_state.get_timeout();

            if elapsed > timeout
                && validation
                    .timeout_state
                    .should_retry(validation.max_retries)
            {
                validation.retry_count += 1;
                validation.last_retry_at = Some(now);
                validation.sent_at = now;
                validation.timeout_state.update_timeout();

                retry_addresses.push(validation.target_addr);
                trace!(
                    "Scheduled retry {} for validation to {}",
                    validation.retry_count, validation.target_addr
                );
            }
        }

        retry_addresses
    }

    /// Update network conditions and cleanup
    pub(super) fn update_network_conditions(&mut self, now: Instant) {
        self.network_monitor.cleanup(now);

        // Update timeout multiplier based on network conditions
        let multiplier = self.network_monitor.get_timeout_multiplier();

        // Apply network-aware timeout adjustments to active validations
        for validation in self.active_validations.values_mut() {
            if multiplier > 1.5 {
                // Poor network conditions - be more patient
                validation.timeout_state.backoff_multiplier =
                    (validation.timeout_state.backoff_multiplier * 1.2)
                        .min(validation.timeout_state.max_backoff_multiplier);
            } else if multiplier < 0.8 {
                // Good network conditions - be more aggressive
                validation.timeout_state.backoff_multiplier =
                    (validation.timeout_state.backoff_multiplier * 0.9).max(1.0);
            }
        }
    }

    /// Check if coordination should be retried now
    pub(super) fn should_retry_coordination(&self, now: Instant) -> bool {
        if let Some(coord) = &self.coordination {
            if coord.retry_count > 0 {
                if let Some(last_retry) = coord.last_retry_at {
                    let retry_delay = coord.timeout_state.get_retry_delay();
                    return now.duration_since(last_retry) >= retry_delay;
                }
            }
        }
        false
    }

    /// Perform resource management and cleanup
    pub(super) fn perform_resource_management(&mut self, now: Instant) -> u64 {
        // Update resource usage statistics
        self.resource_manager.update_stats(
            self.active_validations.len(),
            self.local_candidates.len(),
            self.remote_candidates.len(),
            self.candidate_pairs.len(),
        );

        // Calculate current memory pressure
        let memory_pressure = self.resource_manager.calculate_memory_pressure(
            self.active_validations.len(),
            self.local_candidates.len(),
            self.remote_candidates.len(),
            self.candidate_pairs.len(),
        );

        // Perform cleanup if needed
        let mut cleaned = 0;

        if self.resource_manager.should_cleanup(now) {
            cleaned += self.resource_manager.cleanup_expired_resources(
                &mut self.active_validations,
                &mut self.local_candidates,
                &mut self.remote_candidates,
                &mut self.candidate_pairs,
                &mut self.coordination,
                now,
            );

            // If memory pressure is high, perform aggressive cleanup
            if memory_pressure > self.resource_manager.config.aggressive_cleanup_threshold {
                cleaned += self.resource_manager.aggressive_cleanup(
                    &mut self.active_validations,
                    &mut self.local_candidates,
                    &mut self.remote_candidates,
                    &mut self.candidate_pairs,
                    now,
                );
            }
        }

        cleaned
    }

    /// Check if we should reject new resources due to limits
    pub(super) fn should_reject_new_resources(&mut self, _now: Instant) -> bool {
        // Update stats and check limits
        self.resource_manager.update_stats(
            self.active_validations.len(),
            self.local_candidates.len(),
            self.remote_candidates.len(),
            self.candidate_pairs.len(),
        );
        let memory_pressure = self.resource_manager.calculate_memory_pressure(
            self.active_validations.len(),
            self.local_candidates.len(),
            self.remote_candidates.len(),
            self.candidate_pairs.len(),
        );
        // Reject if memory pressure is too high
        if memory_pressure > self.resource_manager.config.memory_pressure_threshold {
            self.resource_manager.stats.allocation_failures += 1;
            return true;
        }

        // Reject if hard limits are exceeded
        if self.resource_manager.check_resource_limits(self) {
            self.resource_manager.stats.allocation_failures += 1;
            return true;
        }

        false
    }

    /// Get the next timeout instant for NAT traversal operations
    pub(super) fn get_next_timeout(&self, now: Instant) -> Option<Instant> {
        let mut next_timeout = None;
        // Check coordination timeout
        if let Some(coord) = &self.coordination {
            match coord.state {
                CoordinationPhase::Requesting | CoordinationPhase::Coordinating => {
                    let timeout_at = coord.round_start + self.coordination_timeout;
                    next_timeout =
                        Some(next_timeout.map_or(timeout_at, |t: Instant| t.min(timeout_at)));
                }
                CoordinationPhase::Preparing => {
                    // Punch start time is when we should start punching
                    next_timeout = Some(
                        next_timeout
                            .map_or(coord.punch_start, |t: Instant| t.min(coord.punch_start)),
                    );
                }
                CoordinationPhase::Punching | CoordinationPhase::Validating => {
                    // Check for coordination round timeout
                    let timeout_at = coord.round_start + coord.timeout_state.get_timeout();
                    next_timeout =
                        Some(next_timeout.map_or(timeout_at, |t: Instant| t.min(timeout_at)));
                }
                _ => {}
            }
        }

        // Check validation timeouts
        for validation in self.active_validations.values() {
            let timeout_at = validation.sent_at + validation.timeout_state.get_timeout();
            next_timeout = Some(next_timeout.map_or(timeout_at, |t: Instant| t.min(timeout_at)));
        }

        // Check resource cleanup interval
        if self.resource_manager.should_cleanup(now) {
            // Schedule cleanup soon
            let cleanup_at = now + Duration::from_secs(1);
            next_timeout = Some(next_timeout.map_or(cleanup_at, |t: Instant| t.min(cleanup_at)));
        }

        next_timeout
    }

    /// Handle timeout events and return actions to take
    pub(super) fn handle_timeout(
        &mut self,
        now: Instant,
    ) -> Result<Vec<TimeoutAction>, NatTraversalError> {
        let mut actions = Vec::new();
        // Handle coordination timeouts
        if let Some(coord) = &mut self.coordination {
            match coord.state {
                CoordinationPhase::Requesting | CoordinationPhase::Coordinating => {
                    let timeout_at = coord.round_start + self.coordination_timeout;
                    if now >= timeout_at {
                        coord.retry_count += 1;
                        if coord.retry_count >= coord.max_retries {
                            debug!("Coordination failed after {} retries", coord.retry_count);
                            coord.state = CoordinationPhase::Failed;
                            actions.push(TimeoutAction::Failed);
                        } else {
                            debug!(
                                "Coordination timeout, retrying ({}/{})",
                                coord.retry_count, coord.max_retries
                            );
                            coord.state = CoordinationPhase::Requesting;
                            coord.round_start = now;
                            actions.push(TimeoutAction::RetryCoordination);
                        }
                    }
                }
                CoordinationPhase::Preparing => {
                    // Check if it's time to start punching
                    if now >= coord.punch_start {
                        debug!("Starting coordinated hole punching");
                        coord.state = CoordinationPhase::Punching;
                        actions.push(TimeoutAction::StartValidation);
                    }
                }
                CoordinationPhase::Punching | CoordinationPhase::Validating => {
                    let timeout_at = coord.round_start + coord.timeout_state.get_timeout();
                    if now >= timeout_at {
                        coord.retry_count += 1;
                        if coord.retry_count >= coord.max_retries {
                            debug!("Validation failed after {} retries", coord.retry_count);
                            coord.state = CoordinationPhase::Failed;
                            actions.push(TimeoutAction::Failed);
                        } else {
                            debug!(
                                "Validation timeout, retrying ({}/{})",
                                coord.retry_count, coord.max_retries
                            );
                            coord.state = CoordinationPhase::Punching;
                            actions.push(TimeoutAction::StartValidation);
                        }
                    }
                }
                CoordinationPhase::Succeeded => {
                    actions.push(TimeoutAction::Complete);
                }
                CoordinationPhase::Failed => {
                    actions.push(TimeoutAction::Failed);
                }
                _ => {}
            }
        }

        // Handle validation timeouts
        let mut expired_challenges = Vec::new();
        for (&challenge, validation) in &mut self.active_validations {
            let timeout_at = validation.sent_at + validation.timeout_state.get_timeout();
            if now >= timeout_at {
                validation.retry_count += 1;
                if validation.retry_count >= validation.max_retries {
                    debug!(
                        "Path validation failed for {}: max retries exceeded",
                        validation.target_addr
                    );
                    expired_challenges.push(challenge);
                } else {
                    debug!(
                        "Path validation timeout for {}, retrying ({}/{})",
                        validation.target_addr, validation.retry_count, validation.max_retries
                    );
                    validation.sent_at = now;
                    validation.last_retry_at = Some(now);
                    actions.push(TimeoutAction::StartValidation);
                }
            }
        }

        // Remove expired validations
        for challenge in expired_challenges {
            self.active_validations.remove(&challenge);
        }

        // Handle resource cleanup
        if self.resource_manager.should_cleanup(now) {
            self.resource_manager.perform_cleanup(now);
        }

        // Update network condition monitoring
        self.network_monitor.update_quality_score(now);

        // If no coordination is active and we have candidates, try to start discovery
        if self.coordination.is_none()
            && !self.local_candidates.is_empty()
            && !self.remote_candidates.is_empty()
        {
            actions.push(TimeoutAction::RetryDiscovery);
        }

        Ok(actions)
    }

    /// Handle address observation for P2P nodes
    ///
    /// This method is called when a peer connects, allowing this node
    /// to observe the peer's public address. v0.13.0: All nodes can observe
    /// addresses - no bootstrap role required.
    pub(super) fn handle_address_observation(
        &mut self,
        peer_id: [u8; 32],
        observed_address: SocketAddr,
        connection_id: crate::shared::ConnectionId,
        now: Instant,
    ) -> Result<Option<crate::frame::AddAddress>, NatTraversalError> {
        if self.bootstrap_coordinator.is_none() {
            // Not a bootstrap node
            return Ok(None);
        }

        let sequence = self.next_sequence_u32();
        if let Some(bootstrap_coordinator) = &mut self.bootstrap_coordinator {
            let connection_context = ConnectionContext {
                connection_id,
                original_destination: observed_address, // For now, use same as observed
                                                        // v0.13.0: peer_role removed - all nodes are symmetric
            };

            // Observe the peer's address
            bootstrap_coordinator.observe_peer_address(
                peer_id,
                observed_address,
                connection_context,
                now,
            )?;

            // Generate ADD_ADDRESS frame to inform peer of their observed address
            let priority = VarInt::from_u32(100); // Server-reflexive priority
            let add_address_frame =
                bootstrap_coordinator.generate_add_address_frame(peer_id, sequence, priority);

            Ok(add_address_frame)
        } else {
            // Not a bootstrap node
            Ok(None)
        }
    }

    /// Handle PUNCH_ME_NOW frame for bootstrap coordination
    ///
    /// This processes coordination requests from peers and facilitates
    /// hole punching between them.
    pub(super) fn handle_punch_me_now_frame(
        &mut self,
        from_peer: [u8; 32],
        source_addr: SocketAddr,
        frame: &crate::frame::PunchMeNow,
        now: Instant,
    ) -> Result<Option<crate::frame::PunchMeNow>, NatTraversalError> {
        if let Some(bootstrap_coordinator) = &mut self.bootstrap_coordinator {
            bootstrap_coordinator.process_punch_me_now_frame(from_peer, source_addr, frame, now)
        } else {
            // Not a bootstrap node - this frame should not be processed here
            Ok(None)
        }
    }
    /// Get the most recently observed address for a peer.
    ///
    /// Returns the freshest address from the peer's observation history,
    /// surviving NAT rebinds.
    pub(super) fn get_observed_address(&self, peer_id: [u8; 32]) -> Option<SocketAddr> {
        self.bootstrap_coordinator
            .as_ref()
            .and_then(|coord| coord.peer_index.get(&peer_id)?.most_recent_addr())
    }

    /// Record a successful TryConnectTo callback probe
    ///
    /// Called when we receive a TryConnectToResponse indicating success.
    /// This confirms that the source address can reach us.
    pub(super) fn record_successful_callback_probe(
        &mut self,
        request_id: VarInt,
        source_address: SocketAddr,
    ) {
        debug!(
            "Recording successful callback probe: request_id={}, source={}",
            request_id, source_address
        );
        // Update statistics
        self.stats.callback_probes_received += 1;
        self.stats.callback_probes_successful += 1;

        // The successful probe confirms that 'source_address' can connect to us
        // This is useful for understanding NAT traversal capabilities
    }

    /// Record a failed TryConnectTo callback probe
    ///
    /// Called when we receive a TryConnectToResponse indicating failure.
    pub(super) fn record_failed_callback_probe(
        &mut self,
        request_id: VarInt,
        error_code: Option<crate::frame::TryConnectError>,
    ) {
        debug!(
            "Recording failed callback probe: request_id={}, error={:?}",
            request_id, error_code
        );
        // Update statistics
        self.stats.callback_probes_received += 1;
        self.stats.callback_probes_failed += 1;
    }

    /// Start candidate discovery process
    pub(super) fn start_candidate_discovery(&mut self) -> Result<(), NatTraversalError> {
        debug!("Starting candidate discovery for NAT traversal");
        // Initialize discovery state if needed
        if self.local_candidates.is_empty() {
            // Add local interface candidates
            // This would be populated by the candidate discovery manager
            debug!("Local candidates will be populated by discovery manager");
        }

        Ok(())
    }

    /// Queue an ADD_ADDRESS frame for transmission
    pub(super) fn queue_add_address_frame(
        &mut self,
        sequence: VarInt,
        address: SocketAddr,
        priority: u32,
    ) -> Result<(), NatTraversalError> {
        debug!(
            "Queuing ADD_ADDRESS frame: seq={}, addr={}, priority={}",
            sequence, address, priority
        );

        // Add to local candidates if not already present
        let candidate = AddressCandidate {
            address,
            priority,
            source: CandidateSource::Local,
            discovered_at: Instant::now(),
            state: CandidateState::New,
            attempt_count: 0,
            last_attempt: None,
        };

        // Check if candidate already exists
        if !self
            .local_candidates
            .values()
            .any(|c| normalize_socket_addr(c.address) == normalize_socket_addr(address))
        {
            self.local_candidates.insert(sequence, candidate);
        }

        Ok(())
    }
}

/// Errors that can occur during NAT traversal
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub(crate) enum NatTraversalError {
    /// Too many candidates received
    TooManyCandidates,
    /// Duplicate address for different sequence
    DuplicateAddress,
    /// Unknown candidate sequence
    UnknownCandidate,
    /// Candidate in wrong state for operation
    InvalidCandidateState,
    /// No active validation for address
    NoActiveValidation,
    /// Challenge value mismatch
    ChallengeMismatch,
    /// Coordination round not active
    NoActiveCoordination,
    /// Security validation failed
    SecurityValidationFailed,
    /// Rate limit exceeded
    RateLimitExceeded,
    /// Invalid address format
    InvalidAddress,
    /// Suspicious coordination request
    SuspiciousCoordination,
    /// Resource limit exceeded
    ResourceLimitExceeded,
}
impl std::fmt::Display for NatTraversalError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TooManyCandidates => write!(f, "too many candidates"),
            Self::DuplicateAddress => write!(f, "duplicate address"),
            Self::UnknownCandidate => write!(f, "unknown candidate"),
            Self::InvalidCandidateState => write!(f, "invalid candidate state"),
            Self::NoActiveValidation => write!(f, "no active validation"),
            Self::ChallengeMismatch => write!(f, "challenge mismatch"),
            Self::NoActiveCoordination => write!(f, "no active coordination"),
            Self::SecurityValidationFailed => write!(f, "security validation failed"),
            Self::RateLimitExceeded => write!(f, "rate limit exceeded"),
            Self::InvalidAddress => write!(f, "invalid address"),
            Self::SuspiciousCoordination => write!(f, "suspicious coordination request"),
            Self::ResourceLimitExceeded => write!(f, "resource limit exceeded"),
        }
    }
}

impl std::error::Error for NatTraversalError {}

/// Security statistics for monitoring and debugging
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct SecurityStats {
    /// Total security rejections
    pub total_security_rejections: u32,
    /// Rate limiting violations
    pub rate_limit_violations: u32,
    /// Invalid address rejections
    pub invalid_address_rejections: u32,
    /// Suspicious coordination attempts
    pub suspicious_coordination_attempts: u32,
    /// Number of active validations
    pub active_validations: usize,
    /// Number of cached address validations
    pub cached_address_validations: usize,
    /// Current candidate addition rate
    pub current_candidate_rate: usize,
    /// Current coordination request rate
    pub current_coordination_rate: usize,
}
/// Bootstrap coordinator state machine for NAT traversal coordination
///
/// This manages the bootstrap node's role in observing client addresses,
/// coordinating hole punching, and relaying coordination messages.
///
/// All lookups are by PeerId (stable, cryptographic identity), never by
/// SocketAddr alone. This ensures NAT rebinding does not break coordination.
#[derive(Debug)]
pub(crate) struct BootstrapCoordinator {
    /// Primary peer index: PeerId → observed addresses and metadata.
    ///
    /// This is the authoritative source for peer address information.
    /// Addresses are updated on every new observation so coordination always
    /// uses the most recent address, surviving NAT rebinds.
    peer_index: HashMap<PeerId, ObservedPeer>,
    /// Minimal coordination table keyed by round id
    coordination_table: HashMap<VarInt, CoordinationEntry>,
    /// Security validator for coordination requests
    security_validator: SecurityValidationState,
    /// Statistics for bootstrap operations
    stats: BootstrapStats,
}
// Removed legacy CoordinationSessionId type
/// Peer identifier for bootstrap coordination
type PeerId = [u8; 32];
/// Observed peer with full address history.
///
/// Stores all observed addresses for a peer (most recent first) so that
/// NAT rebinding does not cause stale address lookups during coordination.
#[derive(Debug, Clone)]
struct ObservedPeer {
    /// Observed addresses, most recent first. Capped at MAX_ADDRESSES_PER_PEER.
    addresses: Vec<SocketAddr>,
    /// Total observation count across all addresses
    observation_count: u32,
    /// When the most recent observation was made
    last_updated: Instant,
}

/// Maximum number of addresses to track per peer
const MAX_ADDRESSES_PER_PEER: usize = 8;
/// Maximum lifetime for a coordination entry before it is reaped.
const COORDINATION_ENTRY_TTL: Duration = Duration::from_secs(60);

impl ObservedPeer {
    fn new(addr: SocketAddr, now: Instant) -> Self {
        Self {
            addresses: vec![addr],
            observation_count: 1,
            last_updated: now,
        }
    }

    /// Add or promote an address observation. Most recent is always first.
    fn observe_address(&mut self, addr: SocketAddr, now: Instant) {
        self.observation_count += 1;
        self.last_updated = now;

        // Remove existing entry for this address (we'll re-insert at front)
        self.addresses
            .retain(|a| normalize_socket_addr(*a) != normalize_socket_addr(addr));

        // Insert at front (most recent)
        self.addresses.insert(0, addr);

        // Cap the list
        self.addresses.truncate(MAX_ADDRESSES_PER_PEER);
    }

    /// Get the most recently observed address
    fn most_recent_addr(&self) -> Option<SocketAddr> {
        self.addresses.first().copied()
    }
}

/// Minimal coordination record linking two peers for a round.
///
/// Does NOT cache address hints — addresses are looked up fresh from
/// peer_index at coordination time to avoid stale NAT mappings.
#[derive(Debug, Clone)]
struct CoordinationEntry {
    peer_b: Option<PeerId>,
    created_at: Instant,
    completed: bool,
}
/// Record of observed peer information
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct PeerObservationRecord {
    /// The peer's unique identifier
    peer_id: PeerId,
    /// Last observed public address
    observed_address: SocketAddr,
    /// When this observation was made
    observed_at: Instant,
    /// Connection context for this observation
    connection_context: ConnectionContext,
    /// Whether this peer can participate in coordination
    can_coordinate: bool,
    /// Number of successful coordinations
    coordination_count: u32,
    /// Average coordination success rate
    success_rate: f64,
}

/// Connection context for address observations
///
/// v0.13.0: peer_role field removed - all nodes are symmetric P2P nodes.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct ConnectionContext {
    /// Connection ID for this observation
    connection_id: ConnectionId,
    /// Original destination address (what peer thought it was connecting to)
    original_destination: SocketAddr,
    // v0.13.0: peer_role field removed - all nodes are symmetric P2P nodes
}

// Transport parameters for NAT traversal removed (legacy)

// AddressObservation removed — address tracking is now per-peer in ObservedPeer.
// This prevents stale address lookups when NAT rebinds occur.

// Removed coordination session scaffolding
/// Pending coordination request awaiting peer participation (stub implementation)
/// Configuration for bootstrap coordinator behavior (stub implementation)
#[derive(Debug, Clone, Default)]
pub(crate) struct BootstrapConfig {
    _unused: (),
}
/// Statistics for bootstrap operations
#[derive(Debug, Clone, Default)]
pub(crate) struct BootstrapStats {
    /// Total address observations made
    total_observations: u64,
    /// Total coordination sessions facilitated
    total_coordinations: u64,
    /// Successful coordinations
    successful_coordinations: u64,
    /// Security rejections
    security_rejections: u64,
}
// Removed session state machine enums and recovery actions
impl BootstrapCoordinator {
    /// Create a new bootstrap coordinator
    pub(crate) fn new(_config: BootstrapConfig) -> Self {
        Self {
            peer_index: HashMap::new(),
            coordination_table: HashMap::new(),
            security_validator: SecurityValidationState::new(),
            stats: BootstrapStats::default(),
        }
    }
    /// Observe a peer's address from an incoming connection
    ///
    /// This is called when a peer connects to this bootstrap node,
    /// allowing us to observe their public address.
    ///
    /// The observation is stored by PeerId (stable identity), not by
    /// SocketAddr. When a peer's NAT rebinds, the new address is added
    /// to the front of the peer's address list, keeping coordination fresh.
    pub(crate) fn observe_peer_address(
        &mut self,
        peer_id: PeerId,
        observed_address: SocketAddr,
        _connection_context: ConnectionContext,
        now: Instant,
    ) -> Result<(), NatTraversalError> {
        // Security validation
        match self
            .security_validator
            .validate_address(observed_address, now)
        {
            AddressValidationResult::Valid => {}
            AddressValidationResult::Invalid => {
                self.stats.security_rejections += 1;
                return Err(NatTraversalError::InvalidAddress);
            }
            AddressValidationResult::Suspicious => {
                self.stats.security_rejections += 1;
                return Err(NatTraversalError::SecurityValidationFailed);
            }
        }

        // Rate limiting check
        if self.security_validator.is_candidate_rate_limited(now) {
            self.stats.security_rejections += 1;
            return Err(NatTraversalError::RateLimitExceeded);
        }

        // Update peer index — keyed by PeerId, not SocketAddr.
        // New addresses are promoted to the front of the list so that
        // coordination always uses the most recent NAT mapping.
        self.peer_index
            .entry(peer_id)
            .and_modify(|peer| peer.observe_address(observed_address, now))
            .or_insert_with(|| ObservedPeer::new(observed_address, now));

        self.stats.total_observations += 1;

        debug!(
            "Observed peer {:?} at address {} (total observations: {})",
            hex::encode(&peer_id[..8]),
            observed_address,
            self.stats.total_observations
        );

        Ok(())
    }

    /// Generate ADD_ADDRESS frame for a peer based on observation
    ///
    /// Returns the most recently observed address for this peer, which
    /// survives NAT rebinds because the peer_index tracks address history.
    pub(crate) fn generate_add_address_frame(
        &self,
        peer_id: PeerId,
        sequence: VarInt,
        priority: VarInt,
    ) -> Option<crate::frame::AddAddress> {
        let addr = self.peer_index.get(&peer_id)?.most_recent_addr()?;
        Some(crate::frame::AddAddress {
            sequence,
            address: addr,
            priority,
        })
    }

    /// Process a PUNCH_ME_NOW frame from a peer
    ///
    /// This handles coordination requests from peers wanting to establish
    /// direct connections through NAT traversal.
    pub(crate) fn process_punch_me_now_frame(
        &mut self,
        from_peer: PeerId,
        source_addr: SocketAddr,
        frame: &crate::frame::PunchMeNow,
        now: Instant,
    ) -> Result<Option<crate::frame::PunchMeNow>, NatTraversalError> {
        // Enhanced security validation with adaptive rate limiting
        if self
            .security_validator
            .is_adaptive_rate_limited(from_peer, now)
        {
            self.stats.security_rejections += 1;
            debug!(
                "PUNCH_ME_NOW frame rejected: adaptive rate limit exceeded for peer {:?}",
                hex::encode(&from_peer[..8])
            );
            return Err(NatTraversalError::RateLimitExceeded);
        }
        // Enhanced address validation with amplification protection
        self.security_validator
            .enhanced_address_validation(frame.address, source_addr, now)
            .inspect_err(|&e| {
                self.stats.security_rejections += 1;
                debug!(
                    "PUNCH_ME_NOW frame address validation failed from peer {:?}: {:?}",
                    hex::encode(&from_peer[..8]),
                    e
                );
            })?;

        // Comprehensive security validation
        self.security_validator
            .validate_punch_me_now_frame(frame, source_addr, from_peer, now)
            .inspect_err(|&e| {
                self.stats.security_rejections += 1;
                debug!(
                    "PUNCH_ME_NOW frame validation failed from peer {:?}: {:?}",
                    hex::encode(&from_peer[..8]),
                    e
                );
            })?;

        self.cleanup_expired_sessions(now);
        self.cleanup_completed_sessions();

        // Track coordination entry — no address_hint stored (looked up fresh
        // from peer_index to avoid stale NAT mappings).
        let entry = self
            .coordination_table
            .entry(frame.round)
            .or_insert(CoordinationEntry {
                peer_b: frame.target_peer_id,
                created_at: now,
                completed: false,
            });
        // Update target if provided later
        if let Some(peer_b) = frame.target_peer_id {
            if entry.peer_b.is_none() {
                entry.peer_b = Some(peer_b);
            }
        }

        // If we have a target, echo back with swapped target to coordinate
        if let Some(_target_peer_id) = frame.target_peer_id {
            let coordination_frame = crate::frame::PunchMeNow {
                round: frame.round,
                paired_with_sequence_number: frame.paired_with_sequence_number,
                address: frame.address,
                target_peer_id: Some(from_peer),
            };
            self.stats.total_coordinations += 1;
            Ok(Some(coordination_frame))
        } else {
            // Response path: mark the round complete and increment success metric.
            entry.completed = true;
            self.stats.successful_coordinations += 1;
            Ok(None)
        }
    }

    // Removed legacy session tracking helpers
    // Generate secure coordination round using cryptographically secure random values (legacy removed)

    // Perform comprehensive security validation for coordination requests (legacy removed)

    pub(crate) fn cleanup_expired_sessions(&mut self, now: Instant) {
        self.coordination_table
            .retain(|_, entry| now.duration_since(entry.created_at) < COORDINATION_ENTRY_TTL);
    }

    // Get bootstrap statistics (legacy removed)

    // Removed peer coordination success-rate tracking and full registry

    #[allow(dead_code)]
    pub(crate) fn poll_session_state_machine(&mut self, _now: Instant) -> Vec<()> {
        // Legacy session state machine removed
        Vec::new()
    }

    // Check if a session should advance its state (legacy removed)
    // Advance session state based on event (legacy removed)

    fn cleanup_completed_sessions(&mut self) {
        self.coordination_table.retain(|_, entry| !entry.completed);
    }

    // Legacy retry mechanism removed

    // Handle coordination errors with appropriate recovery strategies (legacy removed)

    #[allow(dead_code)]
    fn estimate_peer_rtt(&self, peer_id: &PeerId) -> Option<Duration> {
        // Simple estimation based on peer record
        // In a real implementation, this would use historical RTT data
        let _ = peer_id;
        None
    }
    // Coordinate hole punching between two peers (legacy removed)
    // This method implemented the core coordination logic for establishing
    // direct P2P connections through NAT traversal.

    // Relay coordination frame between peers (legacy removed)
    // This method handled the relay of coordination messages between peers
    // to facilitate synchronized hole punching.

    // Implement round-based synchronization protocol (legacy removed)
    // This managed the timing and synchronization of hole punching rounds
    // to maximize the chances of successful NAT traversal.

    // Get coordination session by ID (legacy removed)

    // Get mutable coordination session by ID (legacy removed)

    // Mark coordination session as successful (legacy removed)

    // Mark coordination session as failed (legacy removed)

    #[allow(dead_code)]
    pub(crate) fn get_peer_record(&self, _peer_id: PeerId) -> Option<&PeerObservationRecord> {
        // Legacy API kept for callers; we no longer maintain full records
        None
    }
}

// Multi-destination packet transmission manager for NAT traversal
//
// This component handles simultaneous packet transmission to multiple candidate
// addresses during hole punching attempts, maximizing the chances of successful
// NAT traversal by sending packets to all viable destinations concurrently.
// TODO: Implement multi-path transmission infrastructure when needed
// This would include MultiDestinationTransmitter for sending packets to multiple
// destinations simultaneously for improved NAT traversal success rates.
// TODO: Fix nat_traversal_tests module imports
// #[cfg(test)]
// #[path = "nat_traversal_tests.rs"]
// mod tests;

#[cfg(test)]
mod tests {
    use super::*;

    // v0.13.0: Role parameter removed - all nodes are symmetric P2P nodes
    fn create_test_state() -> NatTraversalState {
        NatTraversalState::new(
            10,                      // max_candidates
            Duration::from_secs(30), // coordination_timeout
        )
    }

    #[test]
    fn test_cleanup_expired_coordination_entries() {
        let mut coordinator = BootstrapCoordinator::new(BootstrapConfig::default());
        let now = Instant::now();
        coordinator.coordination_table.insert(
            VarInt::from_u32(1),
            CoordinationEntry {
                peer_b: None,
                created_at: now - COORDINATION_ENTRY_TTL - Duration::from_secs(1),
                completed: false,
            },
        );
        coordinator.coordination_table.insert(
            VarInt::from_u32(2),
            CoordinationEntry {
                peer_b: None,
                created_at: now,
                completed: false,
            },
        );

        coordinator.cleanup_expired_sessions(now);

        assert_eq!(coordinator.coordination_table.len(), 1);
        assert!(
            coordinator
                .coordination_table
                .contains_key(&VarInt::from_u32(2))
        );
    }

    #[test]
    fn test_cleanup_completed_coordination_entries() {
        let mut coordinator = BootstrapCoordinator::new(BootstrapConfig::default());
        let now = Instant::now();
        coordinator.coordination_table.insert(
            VarInt::from_u32(1),
            CoordinationEntry {
                peer_b: None,
                created_at: now,
                completed: true,
            },
        );
        coordinator.coordination_table.insert(
            VarInt::from_u32(2),
            CoordinationEntry {
                peer_b: None,
                created_at: now,
                completed: false,
            },
        );

        coordinator.cleanup_completed_sessions();

        assert_eq!(coordinator.coordination_table.len(), 1);
        assert!(
            coordinator
                .coordination_table
                .contains_key(&VarInt::from_u32(2))
        );
    }

    #[test]
    fn test_add_quic_discovered_address() {
        // Test that QUIC-discovered addresses are properly added as local candidates
        let mut state = create_test_state();
        let now = Instant::now();

        // Add a QUIC-discovered address (using add_local_candidate with Observed source)
        let discovered_addr = SocketAddr::from(([1, 2, 3, 4], 5678));
        let seq = state.add_local_candidate(
            discovered_addr,
            CandidateSource::Observed { by_node: None },
            now,
        );

        // Verify it was added correctly
        assert_eq!(state.local_candidates.len(), 1);
        let candidate = state.local_candidates.get(&seq).unwrap();
        assert_eq!(candidate.address, discovered_addr);
        assert!(matches!(candidate.source, CandidateSource::Observed { .. }));
        assert_eq!(candidate.state, CandidateState::New);

        // Verify priority is set appropriately for server-reflexive
        assert!(candidate.priority > 0);
    }

    #[test]
    fn test_add_multiple_quic_discovered_addresses() {
        // Test adding multiple QUIC-discovered addresses
        let mut state = create_test_state();
        let now = Instant::now();

        let addrs = vec![
            SocketAddr::from(([1, 2, 3, 4], 5678)),
            SocketAddr::from(([5, 6, 7, 8], 9012)),
            SocketAddr::from(([2001, 0xdb8, 0, 0, 0, 0, 0, 1], 443)),
        ];

        let mut sequences = Vec::new();
        for addr in &addrs {
            let seq =
                state.add_local_candidate(*addr, CandidateSource::Observed { by_node: None }, now);
            sequences.push(seq);
        }

        // Verify all were added
        assert_eq!(state.local_candidates.len(), 3);

        // Verify each address
        for (seq, addr) in sequences.iter().zip(&addrs) {
            let candidate = state.local_candidates.get(seq).unwrap();
            assert_eq!(candidate.address, *addr);
            assert!(matches!(candidate.source, CandidateSource::Observed { .. }));
        }
    }

    #[test]
    fn test_quic_discovered_addresses_in_local_candidates() {
        // Test that QUIC-discovered addresses are included in local candidates
        let mut state = create_test_state();
        let now = Instant::now();

        // Add a discovered address
        let addr = SocketAddr::from(([192, 168, 1, 100], 5000));
        let seq = state.add_local_candidate(addr, CandidateSource::Observed { by_node: None }, now);

        // Verify it's in local candidates for advertisement
        assert!(state.local_candidates.contains_key(&seq));
        let candidate = state.local_candidates.get(&seq).unwrap();
        assert_eq!(candidate.address, addr);

        // Verify it has appropriate priority for server-reflexive
        assert!(matches!(candidate.source, CandidateSource::Observed { .. }));
    }

    #[test]
    fn test_quic_discovered_addresses_included_in_hole_punching() {
        // Test that QUIC-discovered addresses are used in hole punching
        let mut state = create_test_state();
        let now = Instant::now();

        // Add a local discovered address
        let local_addr = SocketAddr::from(([192, 168, 1, 100], 5000));
        state.add_local_candidate(local_addr, CandidateSource::Observed { by_node: None }, now);

        // Add a remote candidate (using valid public IP, not documentation range)
        let remote_addr = SocketAddr::from(([1, 2, 3, 4], 6000));
        let priority = VarInt::from_u32(100);
        state
            .add_remote_candidate(VarInt::from_u32(1), remote_addr, priority, now)
            .expect("add remote candidate should succeed");

        // Generate candidate pairs
        state.generate_candidate_pairs(now);

        // Should have one pair
        assert_eq!(state.candidate_pairs.len(), 1);
        let pair = &state.candidate_pairs[0];
        assert_eq!(pair.local_addr, local_addr);
        assert_eq!(pair.remote_addr, remote_addr);
    }

    #[test]
    fn test_prioritize_quic_discovered_over_predicted() {
        // Test that QUIC-discovered addresses have higher priority than predicted
        let mut state = create_test_state();
        let now = Instant::now();

        // Add a predicted address
        let predicted_addr = SocketAddr::from(([1, 2, 3, 4], 5000));
        let predicted_seq =
            state.add_local_candidate(predicted_addr, CandidateSource::Predicted, now);

        // Add a QUIC-discovered address
        let discovered_addr = SocketAddr::from(([1, 2, 3, 4], 5001));
        let discovered_seq = state.add_local_candidate(
            discovered_addr,
            CandidateSource::Observed { by_node: None },
            now,
        );

        // Compare priorities
        let predicted_priority = state.local_candidates.get(&predicted_seq).unwrap().priority;
        let discovered_priority = state
            .local_candidates
            .get(&discovered_seq)
            .unwrap()
            .priority;

        // QUIC-discovered (server-reflexive) should have higher priority than predicted
        // Both are server-reflexive type, but observed addresses should get higher local preference
        assert!(discovered_priority >= predicted_priority);
    }

    #[test]
    fn test_integration_with_nat_traversal_flow() {
        // Test full integration with NAT traversal flow
        let mut state = create_test_state();
        let now = Instant::now();

        // Add both local interface and QUIC-discovered addresses
        let local_addr = SocketAddr::from(([192, 168, 1, 2], 5000));
        state.add_local_candidate(local_addr, CandidateSource::Local, now);

        let discovered_addr = SocketAddr::from(([44, 55, 66, 77], 5000));
        state.add_local_candidate(
            discovered_addr,
            CandidateSource::Observed { by_node: None },
            now,
        );

        // Add remote candidates (using valid public IPs)
        let remote1 = SocketAddr::from(([93, 184, 215, 123], 6000));
        let remote2 = SocketAddr::from(([172, 217, 16, 34], 7000));
        let priority = VarInt::from_u32(100);
        state
            .add_remote_candidate(VarInt::from_u32(1), remote1, priority, now)
            .expect("add remote candidate should succeed");
        state
            .add_remote_candidate(VarInt::from_u32(2), remote2, priority, now)
            .expect("add remote candidate should succeed");

        // Generate candidate pairs
        state.generate_candidate_pairs(now);

        // Should have 4 pairs (2 local × 2 remote)
        assert_eq!(state.candidate_pairs.len(), 4);

        // Verify QUIC-discovered addresses are included
        let discovered_pairs: Vec<_> = state
            .candidate_pairs
            .iter()
            .filter(|p| p.local_addr == discovered_addr)
            .collect();
        assert_eq!(discovered_pairs.len(), 2);
    }

    #[test]
    fn test_incremental_pair_generation_local() {
        // Test that add_pairs_for_local_candidate produces correct results
        let mut state = create_test_state();
        let now = Instant::now();

        // Add two remote candidates first
        let remote1 = SocketAddr::from(([93, 184, 215, 1], 6000));
        let remote2 = SocketAddr::from(([93, 184, 215, 2], 7000));
        state
            .add_remote_candidate(VarInt::from_u32(1), remote1, VarInt::from_u32(100), now)
            .expect("add remote candidate should succeed");
        state
            .add_remote_candidate(VarInt::from_u32(2), remote2, VarInt::from_u32(200), now)
            .expect("add remote candidate should succeed");

        // Now add a local candidate - this triggers incremental pair generation
        let local_addr = SocketAddr::from(([192, 168, 1, 10], 5000));
        let _local_seq = state.add_local_candidate(local_addr, CandidateSource::Local, now);

        // Should have 2 pairs (1 local × 2 remote)
        assert_eq!(state.candidate_pairs.len(), 2);

        // Verify both remote candidates are paired with the local
        let paired_remotes: Vec<_> = state
            .candidate_pairs
            .iter()
            .map(|p| p.remote_addr)
            .collect();
        assert!(paired_remotes.contains(&remote1));
        assert!(paired_remotes.contains(&remote2));

        // Verify pairs are sorted by priority (highest first)
        for i in 1..state.candidate_pairs.len() {
            assert!(
                state.candidate_pairs[i - 1].priority >= state.candidate_pairs[i].priority,
                "Pairs should be sorted by priority"
            );
        }

        // Add another local candidate
        let local_addr2 = SocketAddr::from(([192, 168, 1, 20], 5001));
        state.add_local_candidate(local_addr2, CandidateSource::Local, now);

        // Should now have 4 pairs (2 local × 2 remote)
        assert_eq!(state.candidate_pairs.len(), 4);
    }

    #[test]
    fn test_incremental_pair_generation_remote() {
        // Test that add_pairs_for_remote_candidate produces correct results
        let mut state = create_test_state();
        let now = Instant::now();

        // Add two local candidates first
        let local1 = SocketAddr::from(([192, 168, 1, 10], 5000));
        let local2 = SocketAddr::from(([192, 168, 1, 20], 5001));
        state.add_local_candidate(local1, CandidateSource::Local, now);
        state.add_local_candidate(local2, CandidateSource::Local, now);

        // Pairs are empty initially (no remote candidates)
        assert_eq!(state.candidate_pairs.len(), 0);

        // Add a remote candidate - this triggers incremental pair generation
        let remote_addr = SocketAddr::from(([93, 184, 215, 1], 6000));
        state
            .add_remote_candidate(VarInt::from_u32(1), remote_addr, VarInt::from_u32(100), now)
            .expect("add remote candidate should succeed");

        // Should have 2 pairs (2 local × 1 remote)
        assert_eq!(state.candidate_pairs.len(), 2);

        // Verify both local candidates are paired with the remote
        let paired_locals: Vec<_> = state.candidate_pairs.iter().map(|p| p.local_addr).collect();
        assert!(paired_locals.contains(&local1));
        assert!(paired_locals.contains(&local2));
    }

    #[test]
    fn test_pair_index_highest_priority_wins() {
        // Test that pair_index correctly stores the highest priority pair
        // when multiple pairs share the same remote_addr
        let mut state = create_test_state();
        let now = Instant::now();

        // Add two local candidates with different priorities
        // (Local candidates get different local preference based on address)
        let local_high_prio = SocketAddr::from(([8, 8, 8, 8], 5000)); // Public IP = higher prio
        let local_low_prio = SocketAddr::from(([127, 0, 0, 1], 5001)); // Loopback = lower prio
        state.add_local_candidate(local_high_prio, CandidateSource::Local, now);
        state.add_local_candidate(local_low_prio, CandidateSource::Local, now);

        // Add one remote candidate (both local candidates will pair with it)
        let remote_addr = SocketAddr::from(([93, 184, 215, 1], 6000));
        state
            .add_remote_candidate(VarInt::from_u32(1), remote_addr, VarInt::from_u32(100), now)
            .expect("add remote candidate should succeed");

        // Should have 2 pairs with the same remote_addr
        assert_eq!(state.candidate_pairs.len(), 2);

        // The pair_index should point to the HIGHEST priority pair for this remote_addr
        let indexed_pair_idx = state
            .pair_index
            .get(&remote_addr)
            .expect("index should exist");
        let indexed_pair = &state.candidate_pairs[*indexed_pair_idx];

        // Verify pairs are sorted by priority
        assert!(
            state.candidate_pairs[0].priority >= state.candidate_pairs[1].priority,
            "Pairs should be sorted highest priority first"
        );

        // The indexed pair should be at index 0 (highest priority)
        assert_eq!(
            *indexed_pair_idx, 0,
            "Index should point to highest priority pair (index 0)"
        );

        // The indexed pair should have the highest priority
        assert_eq!(
            indexed_pair.priority, state.candidate_pairs[0].priority,
            "Indexed pair should have highest priority"
        );
    }

    #[test]
    fn test_incremental_vs_full_generation_consistency() {
        // Test that incremental generation produces same results as full regeneration
        let now = Instant::now();

        // Create state and add candidates incrementally
        let mut state_incremental = create_test_state();
        let local1 = SocketAddr::from(([192, 168, 1, 10], 5000));
        let local2 = SocketAddr::from(([192, 168, 1, 20], 5001));
        let remote1 = SocketAddr::from(([93, 184, 215, 1], 6000));
        let remote2 = SocketAddr::from(([93, 184, 215, 2], 7000));

        // Add incrementally (each add generates pairs incrementally)
        state_incremental.add_local_candidate(local1, CandidateSource::Local, now);
        state_incremental.add_local_candidate(local2, CandidateSource::Local, now);
        state_incremental
            .add_remote_candidate(VarInt::from_u32(1), remote1, VarInt::from_u32(100), now)
            .unwrap();
        state_incremental
            .add_remote_candidate(VarInt::from_u32(2), remote2, VarInt::from_u32(200), now)
            .unwrap();

        // Create another state and do full regeneration
        let mut state_full = create_test_state();
        state_full.add_local_candidate(local1, CandidateSource::Local, now);
        state_full.add_local_candidate(local2, CandidateSource::Local, now);
        state_full
            .add_remote_candidate(VarInt::from_u32(1), remote1, VarInt::from_u32(100), now)
            .unwrap();
        state_full
            .add_remote_candidate(VarInt::from_u32(2), remote2, VarInt::from_u32(200), now)
            .unwrap();
        // Force full regeneration
        state_full.generate_candidate_pairs(now);

        // Both should have same number of pairs
        assert_eq!(
            state_incremental.candidate_pairs.len(),
            state_full.candidate_pairs.len(),
            "Incremental and full generation should produce same pair count"
        );

        // Both should have pairs sorted by priority
        for state in [&state_incremental, &state_full] {
            for i in 1..state.candidate_pairs.len() {
                assert!(
                    state.candidate_pairs[i - 1].priority >= state.candidate_pairs[i].priority,
                    "Pairs should be sorted by priority"
                );
            }
        }

        // Verify same (local_addr, remote_addr) pairs exist in both
        let pairs_inc: std::collections::HashSet<_> = state_incremental
            .candidate_pairs
            .iter()
            .map(|p| (p.local_addr, p.remote_addr))
            .collect();
        let pairs_full: std::collections::HashSet<_> = state_full
            .candidate_pairs
            .iter()
            .map(|p| (p.local_addr, p.remote_addr))
            .collect();
        assert_eq!(
            pairs_inc, pairs_full,
            "Both methods should produce same (local, remote) pairs"
        );
    }

    #[test]
    fn test_max_candidate_pairs_limit() {
        // Test that incremental generation respects max_candidate_pairs limit
        let mut state = NatTraversalState::new(
            100, // max_candidates (high enough to not limit)
            Duration::from_secs(30),
        );
        let now = Instant::now();

        // The default max_candidate_pairs is 200
        // Add enough candidates to exceed the limit
        // With 15 local × 15 remote = 225 pairs (exceeds 200)
        for i in 0..15u8 {
            let local = SocketAddr::from(([192, 168, 1, i], 5000 + i as u16));
            state.add_local_candidate(local, CandidateSource::Local, now);
        }

        for i in 0..15u32 {
            let remote = SocketAddr::from(([93, 184, 215, i as u8], 6000 + i as u16));
            let _ =
                state.add_remote_candidate(VarInt::from_u32(i), remote, VarInt::from_u32(100), now);
        }

        // Should be capped at max_candidate_pairs (200)
        // Note: max_candidate_pairs default is defined in ResourceManagementConfig::new()
        // at src/connection/nat_traversal.rs line ~1269
        assert!(
            state.candidate_pairs.len() <= 200,
            "Pairs should not exceed max_candidate_pairs limit: got {}",
            state.candidate_pairs.len()
        );
    }

    #[test]
    fn test_add_pairs_at_exact_limit() {
        // Test behavior when exactly at the limit
        let mut state = NatTraversalState::new(100, Duration::from_secs(30));
        let now = Instant::now();

        // Add candidates to get close to limit (14 × 14 = 196 pairs)
        for i in 0..14u8 {
            let local = SocketAddr::from(([192, 168, 1, i], 5000 + i as u16));
            state.add_local_candidate(local, CandidateSource::Local, now);
        }
        for i in 0..14u32 {
            let remote = SocketAddr::from(([93, 184, 215, i as u8], 6000 + i as u16));
            let _ =
                state.add_remote_candidate(VarInt::from_u32(i), remote, VarInt::from_u32(100), now);
        }

        let pairs_at_limit = state.candidate_pairs.len();
        assert!(pairs_at_limit <= 200, "Should be at or under limit");

        // Add one more local candidate - should generate at most 4 more pairs
        // (or fewer if limit reached)
        let extra_local = SocketAddr::from(([192, 168, 1, 100], 9000));
        state.add_local_candidate(extra_local, CandidateSource::Local, now);

        assert!(
            state.candidate_pairs.len() <= 200,
            "Should not exceed limit after adding more candidates"
        );
    }

    #[test]
    fn test_sort_and_reindex_with_duplicate_remote_addrs() {
        // Test that sort_and_reindex_pairs correctly handles multiple pairs
        // with the same remote_addr (different local_addr)
        let mut state = create_test_state();
        let now = Instant::now();

        // Add three local candidates
        let local1 = SocketAddr::from(([192, 168, 1, 1], 5001));
        let local2 = SocketAddr::from(([192, 168, 1, 2], 5002));
        let local3 = SocketAddr::from(([192, 168, 1, 3], 5003));
        state.add_local_candidate(local1, CandidateSource::Local, now);
        state.add_local_candidate(local2, CandidateSource::Local, now);
        state.add_local_candidate(local3, CandidateSource::Local, now);

        // Add one remote - creates 3 pairs with same remote_addr
        let remote = SocketAddr::from(([93, 184, 215, 1], 6000));
        state
            .add_remote_candidate(VarInt::from_u32(1), remote, VarInt::from_u32(100), now)
            .unwrap();

        // Should have 3 pairs
        assert_eq!(state.candidate_pairs.len(), 3);

        // All pairs should have the same remote_addr
        for pair in &state.candidate_pairs {
            assert_eq!(pair.remote_addr, remote);
        }

        // pair_index should have exactly one entry for this remote_addr
        assert!(state.pair_index.contains_key(&remote));

        // The indexed pair should be the highest priority one (index 0)
        let indexed_idx = *state.pair_index.get(&remote).unwrap();
        assert_eq!(
            indexed_idx, 0,
            "Index should point to highest priority pair"
        );

        // Verify the indexed pair has the highest priority
        let indexed_priority = state.candidate_pairs[indexed_idx].priority;
        for pair in &state.candidate_pairs {
            assert!(
                indexed_priority >= pair.priority,
                "Indexed pair should have highest or equal priority"
            );
        }
    }

    #[test]
    fn test_incremental_add_with_zero_remaining_capacity() {
        // Test that incremental add gracefully handles zero capacity
        let mut state = NatTraversalState::new(100, Duration::from_secs(30));
        let now = Instant::now();

        // Fill up to the limit
        for i in 0..15u8 {
            let local = SocketAddr::from(([192, 168, 1, i], 5000 + i as u16));
            state.add_local_candidate(local, CandidateSource::Local, now);
        }
        for i in 0..14u32 {
            let remote = SocketAddr::from(([93, 184, 215, i as u8], 6000 + i as u16));
            let _ =
                state.add_remote_candidate(VarInt::from_u32(i), remote, VarInt::from_u32(100), now);
        }

        // Record count at limit
        let _count_at_limit = state.candidate_pairs.len();

        // Try to add more when at or near limit
        let extra_remote = SocketAddr::from(([93, 184, 215, 200], 9000));
        let _ = state.add_remote_candidate(
            VarInt::from_u32(100),
            extra_remote,
            VarInt::from_u32(100),
            now,
        );

        // Should not panic, and count should not exceed limit
        assert!(
            state.candidate_pairs.len() <= 200,
            "Should handle limit gracefully without panic"
        );
    }
}