rns-net 0.5.5

Network interfaces and node driver for the Reticulum Network Stack
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
//! Link manager: wires rns-core LinkEngine + Channel + Resource into the driver.
//!
//! Manages multiple concurrent links, link destination registration,
//! request/response handling, resource transfers, and full lifecycle
//! (handshake → active → teardown).
//!
//! Python reference: Link.py, RequestReceipt.py, Resource.py

use std::collections::HashMap;

use super::compressor::Bzip2Compressor;
use rns_core::channel::{Channel, Sequence};
use rns_core::constants;
use rns_core::link::types::{LinkId, LinkState, TeardownReason};
use rns_core::link::{LinkAction, LinkEngine, LinkMode};
use rns_core::packet::{PacketFlags, RawPacket};
use rns_core::resource::{ResourceAction, ResourceReceiver, ResourceSender};
use rns_crypto::ed25519::Ed25519PrivateKey;
use rns_crypto::Rng;

use super::time;

/// Resource acceptance strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResourceStrategy {
    /// Reject all incoming resources.
    AcceptNone,
    /// Accept all incoming resources automatically.
    AcceptAll,
    /// Query the application callback for each resource.
    AcceptApp,
}

impl Default for ResourceStrategy {
    fn default() -> Self {
        ResourceStrategy::AcceptNone
    }
}

/// A managed link wrapping LinkEngine + optional Channel + resources.
struct ManagedLink {
    engine: LinkEngine,
    channel: Option<Channel>,
    pending_channel_packets: HashMap<[u8; 32], Sequence>,
    channel_send_ok: u64,
    channel_send_not_ready: u64,
    channel_send_too_big: u64,
    channel_send_other_error: u64,
    channel_messages_received: u64,
    channel_proofs_sent: u64,
    channel_proofs_received: u64,
    /// Destination hash this link belongs to.
    dest_hash: [u8; 16],
    /// Remote identity (hash, public_key) once identified.
    remote_identity: Option<([u8; 16], [u8; 64])>,
    /// Destination's Ed25519 signing public key (for initiator to verify LRPROOF).
    dest_sig_pub_bytes: Option<[u8; 32]>,
    /// Active incoming resource transfers.
    incoming_resources: Vec<ResourceReceiver>,
    /// Active outgoing resource transfers.
    outgoing_resources: Vec<ResourceSender>,
    /// Resource acceptance strategy.
    resource_strategy: ResourceStrategy,
}

/// A registered link destination that can accept incoming LINKREQUEST.
struct LinkDestination {
    sig_prv: Ed25519PrivateKey,
    sig_pub_bytes: [u8; 32],
    resource_strategy: ResourceStrategy,
}

/// A registered request handler for a path.
struct RequestHandlerEntry {
    /// The path this handler serves (e.g. "/status").
    path: String,
    /// The truncated hash of the path (first 16 bytes of SHA-256).
    path_hash: [u8; 16],
    /// Access control: None means allow all, Some(list) means allow only listed identities.
    allowed_list: Option<Vec<[u8; 16]>>,
    /// Handler function: (link_id, path, request_id, data, remote_identity) -> Option<response_data>.
    handler:
        Box<dyn Fn(LinkId, &str, &[u8], Option<&([u8; 16], [u8; 64])>) -> Option<Vec<u8>> + Send>,
}

/// Actions produced by LinkManager for the driver to dispatch.
#[derive(Debug)]
pub enum LinkManagerAction {
    /// Send a packet via the transport engine outbound path.
    SendPacket {
        raw: Vec<u8>,
        dest_type: u8,
        attached_interface: Option<rns_core::transport::types::InterfaceId>,
    },
    /// Link established — notify callbacks.
    LinkEstablished {
        link_id: LinkId,
        dest_hash: [u8; 16],
        rtt: f64,
        is_initiator: bool,
    },
    /// Link closed — notify callbacks.
    LinkClosed {
        link_id: LinkId,
        reason: Option<TeardownReason>,
    },
    /// Remote peer identified — notify callbacks.
    RemoteIdentified {
        link_id: LinkId,
        identity_hash: [u8; 16],
        public_key: [u8; 64],
    },
    /// Register a link_id as local destination in transport (for receiving link data).
    RegisterLinkDest { link_id: LinkId },
    /// Deregister a link_id from transport local destinations.
    DeregisterLinkDest { link_id: LinkId },
    /// A management request that needs to be handled by the driver.
    /// The driver has access to engine state needed to build the response.
    ManagementRequest {
        link_id: LinkId,
        path_hash: [u8; 16],
        /// The request data (msgpack-encoded Value from the request array).
        data: Vec<u8>,
        /// The request_id (truncated hash of the packed request).
        request_id: [u8; 16],
        remote_identity: Option<([u8; 16], [u8; 64])>,
    },
    /// Resource data fully received and assembled.
    ResourceReceived {
        link_id: LinkId,
        data: Vec<u8>,
        metadata: Option<Vec<u8>>,
    },
    /// Resource transfer completed (proof validated on sender side).
    ResourceCompleted { link_id: LinkId },
    /// Resource transfer failed.
    ResourceFailed { link_id: LinkId, error: String },
    /// Resource transfer progress update.
    ResourceProgress {
        link_id: LinkId,
        received: usize,
        total: usize,
    },
    /// Query application whether to accept an incoming resource (for AcceptApp strategy).
    ResourceAcceptQuery {
        link_id: LinkId,
        resource_hash: Vec<u8>,
        transfer_size: u64,
        has_metadata: bool,
    },
    /// Channel message received on a link.
    ChannelMessageReceived {
        link_id: LinkId,
        msgtype: u16,
        payload: Vec<u8>,
    },
    /// Generic link data received (CONTEXT_NONE).
    LinkDataReceived {
        link_id: LinkId,
        context: u8,
        data: Vec<u8>,
    },
    /// Response received on a link.
    ResponseReceived {
        link_id: LinkId,
        request_id: [u8; 16],
        data: Vec<u8>,
    },
    /// A link request was received (for hook notification).
    LinkRequestReceived {
        link_id: LinkId,
        receiving_interface: rns_core::transport::types::InterfaceId,
    },
}

/// Manages multiple links, link destinations, and request/response.
pub struct LinkManager {
    links: HashMap<LinkId, ManagedLink>,
    link_destinations: HashMap<[u8; 16], LinkDestination>,
    request_handlers: Vec<RequestHandlerEntry>,
    /// Path hashes that should be handled externally (by the driver) rather than
    /// by registered handler closures. Used for management destinations.
    management_paths: Vec<[u8; 16]>,
}

impl LinkManager {
    /// Create a new empty link manager.
    pub fn new() -> Self {
        LinkManager {
            links: HashMap::new(),
            link_destinations: HashMap::new(),
            request_handlers: Vec::new(),
            management_paths: Vec::new(),
        }
    }

    /// Register a path hash as a management path.
    /// Management requests are returned as ManagementRequest actions
    /// for the driver to handle (since they need access to engine state).
    pub fn register_management_path(&mut self, path_hash: [u8; 16]) {
        if !self.management_paths.contains(&path_hash) {
            self.management_paths.push(path_hash);
        }
    }

    /// Get the derived session key for a link (needed for hole-punch token derivation).
    pub fn get_derived_key(&self, link_id: &LinkId) -> Option<Vec<u8>> {
        self.links
            .get(link_id)
            .and_then(|link| link.engine.derived_key().map(|dk| dk.to_vec()))
    }

    /// Register a destination that can accept incoming links.
    pub fn register_link_destination(
        &mut self,
        dest_hash: [u8; 16],
        sig_prv: Ed25519PrivateKey,
        sig_pub_bytes: [u8; 32],
        resource_strategy: ResourceStrategy,
    ) {
        self.link_destinations.insert(
            dest_hash,
            LinkDestination {
                sig_prv,
                sig_pub_bytes,
                resource_strategy,
            },
        );
    }

    /// Deregister a link destination.
    pub fn deregister_link_destination(&mut self, dest_hash: &[u8; 16]) {
        self.link_destinations.remove(dest_hash);
    }

    /// Register a request handler for a given path.
    ///
    /// `path`: the request path string (e.g. "/status")
    /// `allowed_list`: None = allow all, Some(list) = restrict to these identity hashes
    /// `handler`: called with (link_id, path, request_data, remote_identity) -> Option<response>
    pub fn register_request_handler<F>(
        &mut self,
        path: &str,
        allowed_list: Option<Vec<[u8; 16]>>,
        handler: F,
    ) where
        F: Fn(LinkId, &str, &[u8], Option<&([u8; 16], [u8; 64])>) -> Option<Vec<u8>>
            + Send
            + 'static,
    {
        let path_hash = compute_path_hash(path);
        self.request_handlers.push(RequestHandlerEntry {
            path: path.to_string(),
            path_hash,
            allowed_list,
            handler: Box::new(handler),
        });
    }

    /// Create an outbound link to a destination.
    ///
    /// `dest_sig_pub_bytes` is the destination's Ed25519 signing public key
    /// (needed to verify LRPROOF). In Python this comes from the Destination's Identity.
    ///
    /// Returns `(link_id, actions)`. The first action will be a SendPacket with
    /// the LINKREQUEST.
    pub fn create_link(
        &mut self,
        dest_hash: &[u8; 16],
        dest_sig_pub_bytes: &[u8; 32],
        hops: u8,
        mtu: u32,
        rng: &mut dyn Rng,
    ) -> (LinkId, Vec<LinkManagerAction>) {
        let mode = LinkMode::Aes256Cbc;
        let (mut engine, request_data) =
            LinkEngine::new_initiator(dest_hash, hops, mode, Some(mtu), time::now(), rng);

        // Build the LINKREQUEST packet to compute link_id
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_SINGLE,
            packet_type: constants::PACKET_TYPE_LINKREQUEST,
        };

        let packet = match RawPacket::pack(
            flags,
            0,
            dest_hash,
            None,
            constants::CONTEXT_NONE,
            &request_data,
        ) {
            Ok(p) => p,
            Err(_) => {
                // Should not happen with valid data
                return ([0u8; 16], Vec::new());
            }
        };

        engine.set_link_id_from_hashable(&packet.get_hashable_part(), request_data.len());
        let link_id = *engine.link_id();

        let managed = ManagedLink {
            engine,
            channel: None,
            pending_channel_packets: HashMap::new(),
            channel_send_ok: 0,
            channel_send_not_ready: 0,
            channel_send_too_big: 0,
            channel_send_other_error: 0,
            channel_messages_received: 0,
            channel_proofs_sent: 0,
            channel_proofs_received: 0,
            dest_hash: *dest_hash,
            remote_identity: None,
            dest_sig_pub_bytes: Some(*dest_sig_pub_bytes),
            incoming_resources: Vec::new(),
            outgoing_resources: Vec::new(),
            resource_strategy: ResourceStrategy::default(),
        };
        self.links.insert(link_id, managed);

        let mut actions = Vec::new();
        // Register the link_id as a local destination so we can receive LRPROOF
        actions.push(LinkManagerAction::RegisterLinkDest { link_id });
        // Send the LINKREQUEST packet
        actions.push(LinkManagerAction::SendPacket {
            raw: packet.raw,
            dest_type: constants::DESTINATION_LINK,
            attached_interface: None,
        });

        (link_id, actions)
    }

    /// Handle a packet delivered locally (via DeliverLocal).
    ///
    /// Returns actions for the driver to dispatch. The `dest_hash` is the
    /// packet's destination_hash field. `raw` is the full packet bytes.
    /// `packet_hash` is the SHA-256 hash.
    pub fn handle_local_delivery(
        &mut self,
        dest_hash: [u8; 16],
        raw: &[u8],
        packet_hash: [u8; 32],
        receiving_interface: rns_core::transport::types::InterfaceId,
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        let packet = match RawPacket::unpack(raw) {
            Ok(p) => p,
            Err(_) => return Vec::new(),
        };

        match packet.flags.packet_type {
            constants::PACKET_TYPE_LINKREQUEST => {
                self.handle_linkrequest(&dest_hash, &packet, receiving_interface, rng)
            }
            constants::PACKET_TYPE_PROOF if packet.context == constants::CONTEXT_LRPROOF => {
                // LRPROOF: dest_hash is the link_id
                self.handle_lrproof(&dest_hash, &packet, rng)
            }
            constants::PACKET_TYPE_PROOF => self.handle_link_proof(&dest_hash, &packet, rng),
            constants::PACKET_TYPE_DATA => {
                self.handle_link_data(&dest_hash, &packet, packet_hash, rng)
            }
            _ => Vec::new(),
        }
    }

    /// Handle an incoming LINKREQUEST packet.
    fn handle_linkrequest(
        &mut self,
        dest_hash: &[u8; 16],
        packet: &RawPacket,
        receiving_interface: rns_core::transport::types::InterfaceId,
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        // Look up the link destination
        let ld = match self.link_destinations.get(dest_hash) {
            Some(ld) => ld,
            None => return Vec::new(),
        };

        let hashable = packet.get_hashable_part();
        let now = time::now();

        // Create responder engine
        let (engine, lrproof_data) = match LinkEngine::new_responder(
            &ld.sig_prv,
            &ld.sig_pub_bytes,
            &packet.data,
            &hashable,
            dest_hash,
            packet.hops,
            now,
            rng,
        ) {
            Ok(r) => r,
            Err(e) => {
                log::debug!("LINKREQUEST rejected: {}", e);
                return Vec::new();
            }
        };

        let link_id = *engine.link_id();

        let managed = ManagedLink {
            engine,
            channel: None,
            pending_channel_packets: HashMap::new(),
            channel_send_ok: 0,
            channel_send_not_ready: 0,
            channel_send_too_big: 0,
            channel_send_other_error: 0,
            channel_messages_received: 0,
            channel_proofs_sent: 0,
            channel_proofs_received: 0,
            dest_hash: *dest_hash,
            remote_identity: None,
            dest_sig_pub_bytes: None,
            incoming_resources: Vec::new(),
            outgoing_resources: Vec::new(),
            resource_strategy: ld.resource_strategy,
        };
        self.links.insert(link_id, managed);

        // Build LRPROOF packet: type=PROOF, context=LRPROOF, dest=link_id
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_LINK,
            packet_type: constants::PACKET_TYPE_PROOF,
        };

        let mut actions = Vec::new();

        // Register link_id as local destination so we receive link data
        actions.push(LinkManagerAction::RegisterLinkDest { link_id });

        if let Ok(pkt) = RawPacket::pack(
            flags,
            0,
            &link_id,
            None,
            constants::CONTEXT_LRPROOF,
            &lrproof_data,
        ) {
            actions.push(LinkManagerAction::SendPacket {
                raw: pkt.raw,
                dest_type: constants::DESTINATION_LINK,
                attached_interface: None,
            });
        }

        // Notify hook system about the incoming link request
        actions.push(LinkManagerAction::LinkRequestReceived {
            link_id,
            receiving_interface,
        });

        actions
    }

    fn handle_link_proof(
        &mut self,
        link_id: &LinkId,
        packet: &RawPacket,
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        if packet.data.len() < 32 {
            return Vec::new();
        }

        let mut tracked_hash = [0u8; 32];
        tracked_hash.copy_from_slice(&packet.data[..32]);

        let Some(link) = self.links.get_mut(link_id) else {
            return Vec::new();
        };
        let Some(sequence) = link.pending_channel_packets.remove(&tracked_hash) else {
            return Vec::new();
        };
        link.channel_proofs_received += 1;
        let Some(channel) = link.channel.as_mut() else {
            return Vec::new();
        };

        let chan_actions = channel.packet_delivered(sequence);
        let _ = channel;
        let _ = link;
        self.process_channel_actions(link_id, chan_actions, rng)
    }

    fn build_link_packet_proof(
        &mut self,
        link_id: &LinkId,
        packet_hash: &[u8; 32],
    ) -> Vec<LinkManagerAction> {
        let dest_hash = match self.links.get(link_id) {
            Some(link) => link.dest_hash,
            None => return Vec::new(),
        };
        let Some(ld) = self.link_destinations.get(&dest_hash) else {
            return Vec::new();
        };
        if let Some(link) = self.links.get_mut(link_id) {
            link.channel_proofs_sent += 1;
        }

        let signature = ld.sig_prv.sign(packet_hash);
        let mut proof_data = Vec::with_capacity(96);
        proof_data.extend_from_slice(packet_hash);
        proof_data.extend_from_slice(&signature);

        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_LINK,
            packet_type: constants::PACKET_TYPE_PROOF,
        };
        if let Ok(pkt) = RawPacket::pack(
            flags,
            0,
            link_id,
            None,
            constants::CONTEXT_NONE,
            &proof_data,
        ) {
            vec![LinkManagerAction::SendPacket {
                raw: pkt.raw,
                dest_type: constants::DESTINATION_LINK,
                attached_interface: None,
            }]
        } else {
            Vec::new()
        }
    }

    /// Handle an incoming LRPROOF packet (initiator side).
    fn handle_lrproof(
        &mut self,
        link_id_bytes: &[u8; 16],
        packet: &RawPacket,
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        let link = match self.links.get_mut(link_id_bytes) {
            Some(l) => l,
            None => return Vec::new(),
        };

        if link.engine.state() != LinkState::Pending || !link.engine.is_initiator() {
            return Vec::new();
        }

        // The destination's signing pub key was stored when create_link was called
        let dest_sig_pub_bytes = match link.dest_sig_pub_bytes {
            Some(b) => b,
            None => {
                log::debug!("LRPROOF: no destination signing key available");
                return Vec::new();
            }
        };

        let now = time::now();
        let (lrrtt_encrypted, link_actions) =
            match link
                .engine
                .handle_lrproof(&packet.data, &dest_sig_pub_bytes, now, rng)
            {
                Ok(r) => r,
                Err(e) => {
                    log::debug!("LRPROOF validation failed: {}", e);
                    return Vec::new();
                }
            };

        let link_id = *link.engine.link_id();
        let mut actions = Vec::new();

        // Process link actions (StateChanged, LinkEstablished)
        actions.extend(self.process_link_actions(&link_id, &link_actions));

        // Send LRRTT: type=DATA, context=LRRTT, dest=link_id
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_LINK,
            packet_type: constants::PACKET_TYPE_DATA,
        };

        if let Ok(pkt) = RawPacket::pack(
            flags,
            0,
            &link_id,
            None,
            constants::CONTEXT_LRRTT,
            &lrrtt_encrypted,
        ) {
            actions.push(LinkManagerAction::SendPacket {
                raw: pkt.raw,
                dest_type: constants::DESTINATION_LINK,
                attached_interface: None,
            });
        }

        // Initialize channel now that link is active
        if let Some(link) = self.links.get_mut(&link_id) {
            if link.engine.state() == LinkState::Active {
                let rtt = link.engine.rtt().unwrap_or(1.0);
                link.channel = Some(Channel::new(rtt));
            }
        }

        actions
    }

    /// Handle DATA packets on an established link.
    ///
    /// Structured to avoid borrow checker issues: we perform engine operations
    /// on the link, collect intermediate results, drop the mutable borrow, then
    /// call self methods that need immutable access.
    fn handle_link_data(
        &mut self,
        link_id_bytes: &[u8; 16],
        packet: &RawPacket,
        packet_hash: [u8; 32],
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        // First pass: perform engine operations, collect results
        enum LinkDataResult {
            Lrrtt {
                link_id: LinkId,
                link_actions: Vec<LinkAction>,
            },
            Identify {
                link_id: LinkId,
                link_actions: Vec<LinkAction>,
            },
            Keepalive {
                link_id: LinkId,
                inbound_actions: Vec<LinkAction>,
            },
            LinkClose {
                link_id: LinkId,
                teardown_actions: Vec<LinkAction>,
            },
            Channel {
                link_id: LinkId,
                inbound_actions: Vec<LinkAction>,
                plaintext: Vec<u8>,
                packet_hash: [u8; 32],
            },
            Request {
                link_id: LinkId,
                inbound_actions: Vec<LinkAction>,
                plaintext: Vec<u8>,
                packet_hash: [u8; 32],
            },
            Response {
                link_id: LinkId,
                inbound_actions: Vec<LinkAction>,
                plaintext: Vec<u8>,
            },
            Generic {
                link_id: LinkId,
                inbound_actions: Vec<LinkAction>,
                plaintext: Vec<u8>,
                context: u8,
                packet_hash: [u8; 32],
            },
            /// Resource advertisement (link-decrypted).
            ResourceAdv {
                link_id: LinkId,
                inbound_actions: Vec<LinkAction>,
                plaintext: Vec<u8>,
            },
            /// Resource part request (link-decrypted).
            ResourceReq {
                link_id: LinkId,
                inbound_actions: Vec<LinkAction>,
                plaintext: Vec<u8>,
            },
            /// Resource hashmap update (link-decrypted).
            ResourceHmu {
                link_id: LinkId,
                inbound_actions: Vec<LinkAction>,
                plaintext: Vec<u8>,
            },
            /// Resource part data (NOT link-decrypted; parts are pre-encrypted by ResourceSender).
            ResourcePart {
                link_id: LinkId,
                inbound_actions: Vec<LinkAction>,
                raw_data: Vec<u8>,
            },
            /// Resource proof (feed to sender).
            ResourcePrf {
                link_id: LinkId,
                inbound_actions: Vec<LinkAction>,
                plaintext: Vec<u8>,
            },
            /// Resource cancel from initiator (link-decrypted).
            ResourceIcl {
                link_id: LinkId,
                inbound_actions: Vec<LinkAction>,
            },
            /// Resource cancel from receiver (link-decrypted).
            ResourceRcl {
                link_id: LinkId,
                inbound_actions: Vec<LinkAction>,
            },
            Error,
        }

        let result = {
            let link = match self.links.get_mut(link_id_bytes) {
                Some(l) => l,
                None => return Vec::new(),
            };

            match packet.context {
                constants::CONTEXT_LRRTT => {
                    match link.engine.handle_lrrtt(&packet.data, time::now()) {
                        Ok(link_actions) => {
                            let link_id = *link.engine.link_id();
                            LinkDataResult::Lrrtt {
                                link_id,
                                link_actions,
                            }
                        }
                        Err(e) => {
                            log::debug!("LRRTT handling failed: {}", e);
                            LinkDataResult::Error
                        }
                    }
                }
                constants::CONTEXT_LINKIDENTIFY => {
                    match link.engine.handle_identify(&packet.data) {
                        Ok(link_actions) => {
                            let link_id = *link.engine.link_id();
                            link.remote_identity = link.engine.remote_identity().cloned();
                            LinkDataResult::Identify {
                                link_id,
                                link_actions,
                            }
                        }
                        Err(e) => {
                            log::debug!("LINKIDENTIFY failed: {}", e);
                            LinkDataResult::Error
                        }
                    }
                }
                constants::CONTEXT_KEEPALIVE => {
                    let inbound_actions = link.engine.record_inbound(time::now());
                    let link_id = *link.engine.link_id();
                    LinkDataResult::Keepalive {
                        link_id,
                        inbound_actions,
                    }
                }
                constants::CONTEXT_LINKCLOSE => {
                    let teardown_actions = link.engine.handle_teardown();
                    let link_id = *link.engine.link_id();
                    LinkDataResult::LinkClose {
                        link_id,
                        teardown_actions,
                    }
                }
                constants::CONTEXT_CHANNEL => match link.engine.decrypt(&packet.data) {
                    Ok(plaintext) => {
                        let inbound_actions = link.engine.record_inbound(time::now());
                        let link_id = *link.engine.link_id();
                        LinkDataResult::Channel {
                            link_id,
                            inbound_actions,
                            plaintext,
                            packet_hash,
                        }
                    }
                    Err(_) => LinkDataResult::Error,
                },
                constants::CONTEXT_REQUEST => match link.engine.decrypt(&packet.data) {
                    Ok(plaintext) => {
                        let inbound_actions = link.engine.record_inbound(time::now());
                        let link_id = *link.engine.link_id();
                        LinkDataResult::Request {
                            link_id,
                            inbound_actions,
                            plaintext,
                            packet_hash,
                        }
                    }
                    Err(_) => LinkDataResult::Error,
                },
                constants::CONTEXT_RESPONSE => match link.engine.decrypt(&packet.data) {
                    Ok(plaintext) => {
                        let inbound_actions = link.engine.record_inbound(time::now());
                        let link_id = *link.engine.link_id();
                        LinkDataResult::Response {
                            link_id,
                            inbound_actions,
                            plaintext,
                        }
                    }
                    Err(_) => LinkDataResult::Error,
                },
                // --- Resource contexts ---
                constants::CONTEXT_RESOURCE_ADV => match link.engine.decrypt(&packet.data) {
                    Ok(plaintext) => {
                        let inbound_actions = link.engine.record_inbound(time::now());
                        let link_id = *link.engine.link_id();
                        LinkDataResult::ResourceAdv {
                            link_id,
                            inbound_actions,
                            plaintext,
                        }
                    }
                    Err(_) => LinkDataResult::Error,
                },
                constants::CONTEXT_RESOURCE_REQ => match link.engine.decrypt(&packet.data) {
                    Ok(plaintext) => {
                        let inbound_actions = link.engine.record_inbound(time::now());
                        let link_id = *link.engine.link_id();
                        LinkDataResult::ResourceReq {
                            link_id,
                            inbound_actions,
                            plaintext,
                        }
                    }
                    Err(_) => LinkDataResult::Error,
                },
                constants::CONTEXT_RESOURCE_HMU => match link.engine.decrypt(&packet.data) {
                    Ok(plaintext) => {
                        let inbound_actions = link.engine.record_inbound(time::now());
                        let link_id = *link.engine.link_id();
                        LinkDataResult::ResourceHmu {
                            link_id,
                            inbound_actions,
                            plaintext,
                        }
                    }
                    Err(_) => LinkDataResult::Error,
                },
                constants::CONTEXT_RESOURCE => {
                    // Resource parts are NOT link-decrypted — they're pre-encrypted by ResourceSender
                    let inbound_actions = link.engine.record_inbound(time::now());
                    let link_id = *link.engine.link_id();
                    LinkDataResult::ResourcePart {
                        link_id,
                        inbound_actions,
                        raw_data: packet.data.clone(),
                    }
                }
                constants::CONTEXT_RESOURCE_PRF => match link.engine.decrypt(&packet.data) {
                    Ok(plaintext) => {
                        let inbound_actions = link.engine.record_inbound(time::now());
                        let link_id = *link.engine.link_id();
                        LinkDataResult::ResourcePrf {
                            link_id,
                            inbound_actions,
                            plaintext,
                        }
                    }
                    Err(_) => LinkDataResult::Error,
                },
                constants::CONTEXT_RESOURCE_ICL => {
                    let _ = link.engine.decrypt(&packet.data); // decrypt to validate
                    let inbound_actions = link.engine.record_inbound(time::now());
                    let link_id = *link.engine.link_id();
                    LinkDataResult::ResourceIcl {
                        link_id,
                        inbound_actions,
                    }
                }
                constants::CONTEXT_RESOURCE_RCL => {
                    let _ = link.engine.decrypt(&packet.data); // decrypt to validate
                    let inbound_actions = link.engine.record_inbound(time::now());
                    let link_id = *link.engine.link_id();
                    LinkDataResult::ResourceRcl {
                        link_id,
                        inbound_actions,
                    }
                }
                _ => match link.engine.decrypt(&packet.data) {
                    Ok(plaintext) => {
                        let inbound_actions = link.engine.record_inbound(time::now());
                        let link_id = *link.engine.link_id();
                        LinkDataResult::Generic {
                            link_id,
                            inbound_actions,
                            plaintext,
                            context: packet.context,
                            packet_hash,
                        }
                    }
                    Err(_) => LinkDataResult::Error,
                },
            }
        }; // mutable borrow of self.links dropped here

        // Second pass: process results using self methods
        let mut actions = Vec::new();
        match result {
            LinkDataResult::Lrrtt {
                link_id,
                link_actions,
            } => {
                actions.extend(self.process_link_actions(&link_id, &link_actions));
                // Initialize channel
                if let Some(link) = self.links.get_mut(&link_id) {
                    if link.engine.state() == LinkState::Active {
                        let rtt = link.engine.rtt().unwrap_or(1.0);
                        link.channel = Some(Channel::new(rtt));
                    }
                }
            }
            LinkDataResult::Identify {
                link_id,
                link_actions,
            } => {
                actions.extend(self.process_link_actions(&link_id, &link_actions));
            }
            LinkDataResult::Keepalive {
                link_id,
                inbound_actions,
            } => {
                actions.extend(self.process_link_actions(&link_id, &inbound_actions));
                // record_inbound() already updated last_inbound, so the link
                // won't go stale.  The regular tick() keepalive mechanism will
                // send keepalives when needs_keepalive() returns true.
                // Do NOT reply here — unconditional replies create an infinite
                // ping-pong loop between the two link endpoints.
            }
            LinkDataResult::LinkClose {
                link_id,
                teardown_actions,
            } => {
                actions.extend(self.process_link_actions(&link_id, &teardown_actions));
            }
            LinkDataResult::Channel {
                link_id,
                inbound_actions,
                plaintext,
                packet_hash,
            } => {
                actions.extend(self.process_link_actions(&link_id, &inbound_actions));
                // Feed plaintext to channel
                if let Some(link) = self.links.get_mut(&link_id) {
                    if let Some(ref mut channel) = link.channel {
                        let chan_actions = channel.receive(&plaintext, time::now());
                        link.channel_messages_received += chan_actions
                            .iter()
                            .filter(|action| {
                                matches!(
                                    action,
                                    rns_core::channel::ChannelAction::MessageReceived { .. }
                                )
                            })
                            .count()
                            as u64;
                        // process_channel_actions needs immutable self, so collect first
                        let _ = link;
                        actions.extend(self.process_channel_actions(&link_id, chan_actions, rng));
                    }
                }
                actions.extend(self.build_link_packet_proof(&link_id, &packet_hash));
            }
            LinkDataResult::Request {
                link_id,
                inbound_actions,
                plaintext,
                packet_hash,
            } => {
                actions.extend(self.process_link_actions(&link_id, &inbound_actions));
                actions.extend(self.handle_request(&link_id, &plaintext, packet_hash, rng));
            }
            LinkDataResult::Response {
                link_id,
                inbound_actions,
                plaintext,
            } => {
                actions.extend(self.process_link_actions(&link_id, &inbound_actions));
                // Unpack msgpack response: [Bin(request_id), response_value]
                actions.extend(self.handle_response(&link_id, &plaintext));
            }
            LinkDataResult::Generic {
                link_id,
                inbound_actions,
                plaintext,
                context,
                packet_hash,
            } => {
                actions.extend(self.process_link_actions(&link_id, &inbound_actions));
                actions.push(LinkManagerAction::LinkDataReceived {
                    link_id,
                    context,
                    data: plaintext,
                });

                actions.extend(self.build_link_packet_proof(&link_id, &packet_hash));
            }
            LinkDataResult::ResourceAdv {
                link_id,
                inbound_actions,
                plaintext,
            } => {
                actions.extend(self.process_link_actions(&link_id, &inbound_actions));
                actions.extend(self.handle_resource_adv(&link_id, &plaintext, rng));
            }
            LinkDataResult::ResourceReq {
                link_id,
                inbound_actions,
                plaintext,
            } => {
                actions.extend(self.process_link_actions(&link_id, &inbound_actions));
                actions.extend(self.handle_resource_req(&link_id, &plaintext, rng));
            }
            LinkDataResult::ResourceHmu {
                link_id,
                inbound_actions,
                plaintext,
            } => {
                actions.extend(self.process_link_actions(&link_id, &inbound_actions));
                actions.extend(self.handle_resource_hmu(&link_id, &plaintext, rng));
            }
            LinkDataResult::ResourcePart {
                link_id,
                inbound_actions,
                raw_data,
            } => {
                actions.extend(self.process_link_actions(&link_id, &inbound_actions));
                actions.extend(self.handle_resource_part(&link_id, &raw_data, rng));
            }
            LinkDataResult::ResourcePrf {
                link_id,
                inbound_actions,
                plaintext,
            } => {
                actions.extend(self.process_link_actions(&link_id, &inbound_actions));
                actions.extend(self.handle_resource_prf(&link_id, &plaintext));
            }
            LinkDataResult::ResourceIcl {
                link_id,
                inbound_actions,
            } => {
                actions.extend(self.process_link_actions(&link_id, &inbound_actions));
                actions.extend(self.handle_resource_icl(&link_id));
            }
            LinkDataResult::ResourceRcl {
                link_id,
                inbound_actions,
            } => {
                actions.extend(self.process_link_actions(&link_id, &inbound_actions));
                actions.extend(self.handle_resource_rcl(&link_id));
            }
            LinkDataResult::Error => {}
        }

        actions
    }

    /// Handle a request on a link.
    fn handle_request(
        &mut self,
        link_id: &LinkId,
        plaintext: &[u8],
        packet_hash: [u8; 32],
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        use rns_core::msgpack::{self, Value};

        // Python-compatible format: msgpack([timestamp, Bin(path_hash), data_value])
        let arr = match msgpack::unpack_exact(plaintext) {
            Ok(Value::Array(arr)) if arr.len() >= 3 => arr,
            _ => return Vec::new(),
        };

        let path_hash_bytes = match &arr[1] {
            Value::Bin(b) if b.len() == 16 => b,
            _ => return Vec::new(),
        };
        let mut path_hash = [0u8; 16];
        path_hash.copy_from_slice(path_hash_bytes);

        // Python-compatible request_id: Packet.getTruncatedHash(), i.e.
        // first 16 bytes of the full packet hash computed from hashable part.
        //
        // IMPORTANT: This is *not* truncated_hash(plaintext). Using plaintext
        // here causes interop failures with Python clients (eg. MeshChat),
        // because they match responses by packet-truncated-hash request IDs.
        let request_id = {
            let mut id = [0u8; 16];
            id.copy_from_slice(&packet_hash[..16]);
            id
        };

        // Re-encode the data element for the handler
        let request_data = msgpack::pack(&arr[2]);

        // Check if this is a management path (handled by the driver)
        if self.management_paths.contains(&path_hash) {
            let remote_identity = self
                .links
                .get(link_id)
                .and_then(|l| l.remote_identity)
                .map(|(h, k)| (h, k));
            return vec![LinkManagerAction::ManagementRequest {
                link_id: *link_id,
                path_hash,
                data: request_data,
                request_id,
                remote_identity,
            }];
        }

        // Look up handler by path_hash
        let handler_idx = self
            .request_handlers
            .iter()
            .position(|h| h.path_hash == path_hash);
        let handler_idx = match handler_idx {
            Some(i) => i,
            None => return Vec::new(),
        };

        // Check ACL
        let remote_identity = self
            .links
            .get(link_id)
            .and_then(|l| l.remote_identity.as_ref());
        let handler = &self.request_handlers[handler_idx];
        if let Some(ref allowed) = handler.allowed_list {
            match remote_identity {
                Some((identity_hash, _)) => {
                    if !allowed.contains(identity_hash) {
                        log::debug!("Request denied: identity not in allowed list");
                        return Vec::new();
                    }
                }
                None => {
                    log::debug!("Request denied: peer not identified");
                    return Vec::new();
                }
            }
        }

        // Call handler
        let path = handler.path.clone();
        let response = (handler.handler)(*link_id, &path, &request_data, remote_identity);

        let mut actions = Vec::new();
        if let Some(response_data) = response {
            actions.extend(self.build_response_packet(link_id, &request_id, &response_data, rng));
        }

        actions
    }

    /// Build a response packet for a request.
    /// `response_data` is the msgpack-encoded response value.
    fn build_response_packet(
        &self,
        link_id: &LinkId,
        request_id: &[u8; 16],
        response_data: &[u8],
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        use rns_core::msgpack::{self, Value};

        // Python-compatible response: msgpack([Bin(request_id), response_value])
        let response_value = msgpack::unpack_exact(response_data)
            .unwrap_or_else(|_| Value::Bin(response_data.to_vec()));

        let response_array = Value::Array(vec![Value::Bin(request_id.to_vec()), response_value]);
        let response_plaintext = msgpack::pack(&response_array);

        let mut actions = Vec::new();
        if let Some(link) = self.links.get(link_id) {
            if let Ok(encrypted) = link.engine.encrypt(&response_plaintext, rng) {
                let flags = PacketFlags {
                    header_type: constants::HEADER_1,
                    context_flag: constants::FLAG_UNSET,
                    transport_type: constants::TRANSPORT_BROADCAST,
                    destination_type: constants::DESTINATION_LINK,
                    packet_type: constants::PACKET_TYPE_DATA,
                };
                if let Ok(pkt) = RawPacket::pack(
                    flags,
                    0,
                    link_id,
                    None,
                    constants::CONTEXT_RESPONSE,
                    &encrypted,
                ) {
                    actions.push(LinkManagerAction::SendPacket {
                        raw: pkt.raw,
                        dest_type: constants::DESTINATION_LINK,
                        attached_interface: None,
                    });
                }
            }
        }
        actions
    }

    /// Send a management response on a link.
    /// Called by the driver after building the response for a ManagementRequest.
    pub fn send_management_response(
        &self,
        link_id: &LinkId,
        request_id: &[u8; 16],
        response_data: &[u8],
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        self.build_response_packet(link_id, request_id, response_data, rng)
    }

    /// Send a request on a link.
    ///
    /// `data` is the msgpack-encoded request data value (e.g. msgpack([True]) for /status).
    ///
    /// Uses Python-compatible format: plaintext = msgpack([timestamp, path_hash_bytes, data_value]).
    /// Returns actions (the encrypted request packet). The response will arrive
    /// later via handle_local_delivery with CONTEXT_RESPONSE.
    pub fn send_request(
        &self,
        link_id: &LinkId,
        path: &str,
        data: &[u8],
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        use rns_core::msgpack::{self, Value};

        let link = match self.links.get(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        if link.engine.state() != LinkState::Active {
            return Vec::new();
        }

        let path_hash = compute_path_hash(path);

        // Decode data bytes to msgpack Value (or use Bin if can't decode)
        let data_value = msgpack::unpack_exact(data).unwrap_or_else(|_| Value::Bin(data.to_vec()));

        // Python-compatible format: msgpack([timestamp, Bin(path_hash), data_value])
        let request_array = Value::Array(vec![
            Value::Float(time::now()),
            Value::Bin(path_hash.to_vec()),
            data_value,
        ]);
        let plaintext = msgpack::pack(&request_array);

        let encrypted = match link.engine.encrypt(&plaintext, rng) {
            Ok(e) => e,
            Err(_) => return Vec::new(),
        };

        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_LINK,
            packet_type: constants::PACKET_TYPE_DATA,
        };

        let mut actions = Vec::new();
        if let Ok(pkt) = RawPacket::pack(
            flags,
            0,
            link_id,
            None,
            constants::CONTEXT_REQUEST,
            &encrypted,
        ) {
            actions.push(LinkManagerAction::SendPacket {
                raw: pkt.raw,
                dest_type: constants::DESTINATION_LINK,
                attached_interface: None,
            });
        }
        actions
    }

    /// Send encrypted data on a link with a given context.
    pub fn send_on_link(
        &self,
        link_id: &LinkId,
        plaintext: &[u8],
        context: u8,
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        let link = match self.links.get(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        if link.engine.state() != LinkState::Active {
            return Vec::new();
        }

        let encrypted = match link.engine.encrypt(plaintext, rng) {
            Ok(e) => e,
            Err(_) => return Vec::new(),
        };

        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_LINK,
            packet_type: constants::PACKET_TYPE_DATA,
        };

        let mut actions = Vec::new();
        if let Ok(pkt) = RawPacket::pack(flags, 0, link_id, None, context, &encrypted) {
            actions.push(LinkManagerAction::SendPacket {
                raw: pkt.raw,
                dest_type: constants::DESTINATION_LINK,
                attached_interface: None,
            });
        }
        actions
    }

    /// Send an identify message on a link (initiator reveals identity to responder).
    pub fn identify(
        &self,
        link_id: &LinkId,
        identity: &rns_crypto::identity::Identity,
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        let link = match self.links.get(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        let encrypted = match link.engine.build_identify(identity, rng) {
            Ok(e) => e,
            Err(_) => return Vec::new(),
        };

        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_LINK,
            packet_type: constants::PACKET_TYPE_DATA,
        };

        let mut actions = Vec::new();
        if let Ok(pkt) = RawPacket::pack(
            flags,
            0,
            link_id,
            None,
            constants::CONTEXT_LINKIDENTIFY,
            &encrypted,
        ) {
            actions.push(LinkManagerAction::SendPacket {
                raw: pkt.raw,
                dest_type: constants::DESTINATION_LINK,
                attached_interface: None,
            });
        }
        actions
    }

    /// Tear down a link.
    pub fn teardown_link(&mut self, link_id: &LinkId) -> Vec<LinkManagerAction> {
        let link = match self.links.get_mut(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        let teardown_actions = link.engine.teardown();
        if let Some(ref mut channel) = link.channel {
            channel.shutdown();
        }

        let mut actions = self.process_link_actions(link_id, &teardown_actions);

        // Send LINKCLOSE packet
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_LINK,
            packet_type: constants::PACKET_TYPE_DATA,
        };
        if let Ok(pkt) = RawPacket::pack(flags, 0, link_id, None, constants::CONTEXT_LINKCLOSE, &[])
        {
            actions.push(LinkManagerAction::SendPacket {
                raw: pkt.raw,
                dest_type: constants::DESTINATION_LINK,
                attached_interface: None,
            });
        }

        actions
    }

    /// Tear down all managed links.
    pub fn teardown_all_links(&mut self) -> Vec<LinkManagerAction> {
        let link_ids: Vec<LinkId> = self.links.keys().copied().collect();
        let mut actions = Vec::new();
        for link_id in link_ids {
            actions.extend(self.teardown_link(&link_id));
        }
        actions
    }

    /// Handle a response on a link.
    fn handle_response(&self, link_id: &LinkId, plaintext: &[u8]) -> Vec<LinkManagerAction> {
        use rns_core::msgpack;

        // Python-compatible response: msgpack([Bin(request_id), response_value])
        let arr = match msgpack::unpack_exact(plaintext) {
            Ok(msgpack::Value::Array(arr)) if arr.len() >= 2 => arr,
            _ => return Vec::new(),
        };

        let request_id_bytes = match &arr[0] {
            msgpack::Value::Bin(b) if b.len() == 16 => b,
            _ => return Vec::new(),
        };
        let mut request_id = [0u8; 16];
        request_id.copy_from_slice(request_id_bytes);

        let response_data = msgpack::pack(&arr[1]);

        vec![LinkManagerAction::ResponseReceived {
            link_id: *link_id,
            request_id,
            data: response_data,
        }]
    }

    /// Handle resource advertisement (CONTEXT_RESOURCE_ADV).
    fn handle_resource_adv(
        &mut self,
        link_id: &LinkId,
        adv_plaintext: &[u8],
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        let link = match self.links.get_mut(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        let link_rtt = link.engine.rtt().unwrap_or(1.0);
        let now = time::now();

        let receiver = match ResourceReceiver::from_advertisement(
            adv_plaintext,
            constants::RESOURCE_SDU,
            link_rtt,
            now,
            None,
            None,
        ) {
            Ok(r) => r,
            Err(e) => {
                log::debug!("Resource ADV rejected: {}", e);
                return Vec::new();
            }
        };

        let strategy = link.resource_strategy;
        let resource_hash = receiver.resource_hash.clone();
        let transfer_size = receiver.transfer_size;
        let has_metadata = receiver.has_metadata;

        match strategy {
            ResourceStrategy::AcceptNone => {
                // Reject: send RCL
                let reject_actions = {
                    let mut r = receiver;
                    r.reject()
                };
                self.process_resource_actions(link_id, reject_actions, rng)
            }
            ResourceStrategy::AcceptAll => {
                link.incoming_resources.push(receiver);
                let idx = link.incoming_resources.len() - 1;
                let resource_actions = link.incoming_resources[idx].accept(now);
                let _ = link;
                self.process_resource_actions(link_id, resource_actions, rng)
            }
            ResourceStrategy::AcceptApp => {
                link.incoming_resources.push(receiver);
                // Query application callback
                vec![LinkManagerAction::ResourceAcceptQuery {
                    link_id: *link_id,
                    resource_hash,
                    transfer_size,
                    has_metadata,
                }]
            }
        }
    }

    /// Accept or reject a pending resource (for AcceptApp strategy).
    pub fn accept_resource(
        &mut self,
        link_id: &LinkId,
        resource_hash: &[u8],
        accept: bool,
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        let link = match self.links.get_mut(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        let now = time::now();
        let idx = link
            .incoming_resources
            .iter()
            .position(|r| r.resource_hash == resource_hash);
        let idx = match idx {
            Some(i) => i,
            None => return Vec::new(),
        };

        let resource_actions = if accept {
            link.incoming_resources[idx].accept(now)
        } else {
            link.incoming_resources[idx].reject()
        };

        let _ = link;
        self.process_resource_actions(link_id, resource_actions, rng)
    }

    /// Handle resource request (CONTEXT_RESOURCE_REQ) — feed to sender.
    fn handle_resource_req(
        &mut self,
        link_id: &LinkId,
        plaintext: &[u8],
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        let link = match self.links.get_mut(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        let now = time::now();
        let mut all_actions = Vec::new();
        for sender in &mut link.outgoing_resources {
            let resource_actions = sender.handle_request(plaintext, now);
            if !resource_actions.is_empty() {
                all_actions.extend(resource_actions);
                break;
            }
        }

        let _ = link;
        self.process_resource_actions(link_id, all_actions, rng)
    }

    /// Handle resource HMU (CONTEXT_RESOURCE_HMU) — feed to receiver.
    fn handle_resource_hmu(
        &mut self,
        link_id: &LinkId,
        plaintext: &[u8],
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        let link = match self.links.get_mut(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        let now = time::now();
        let mut all_actions = Vec::new();
        for receiver in &mut link.incoming_resources {
            let resource_actions = receiver.handle_hashmap_update(plaintext, now);
            if !resource_actions.is_empty() {
                all_actions.extend(resource_actions);
                break;
            }
        }

        let _ = link;
        self.process_resource_actions(link_id, all_actions, rng)
    }

    /// Handle resource part (CONTEXT_RESOURCE) — feed raw to receiver.
    fn handle_resource_part(
        &mut self,
        link_id: &LinkId,
        raw_data: &[u8],
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        let link = match self.links.get_mut(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        let now = time::now();
        let mut all_actions = Vec::new();
        let mut assemble_idx = None;

        for (idx, receiver) in link.incoming_resources.iter_mut().enumerate() {
            let resource_actions = receiver.receive_part(raw_data, now);
            if !resource_actions.is_empty() {
                // Check if all parts received (triggers assembly)
                if receiver.received_count == receiver.total_parts {
                    assemble_idx = Some(idx);
                }
                all_actions.extend(resource_actions);
                break;
            }
        }

        // Assemble if all parts received
        if let Some(idx) = assemble_idx {
            let decrypt_fn = |ciphertext: &[u8]| -> Result<Vec<u8>, ()> {
                link.engine.decrypt(ciphertext).map_err(|_| ())
            };
            let assemble_actions =
                link.incoming_resources[idx].assemble(&decrypt_fn, &Bzip2Compressor);
            all_actions.extend(assemble_actions);
        }

        let _ = link;
        self.process_resource_actions(link_id, all_actions, rng)
    }

    /// Handle resource proof (CONTEXT_RESOURCE_PRF) — feed to sender.
    fn handle_resource_prf(
        &mut self,
        link_id: &LinkId,
        plaintext: &[u8],
    ) -> Vec<LinkManagerAction> {
        let link = match self.links.get_mut(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        let now = time::now();
        let mut result_actions = Vec::new();
        for sender in &mut link.outgoing_resources {
            let resource_actions = sender.handle_proof(plaintext, now);
            if !resource_actions.is_empty() {
                result_actions.extend(resource_actions);
                break;
            }
        }

        // Convert to LinkManagerActions
        let mut actions = Vec::new();
        for ra in result_actions {
            match ra {
                ResourceAction::Completed => {
                    actions.push(LinkManagerAction::ResourceCompleted { link_id: *link_id });
                }
                ResourceAction::Failed(e) => {
                    actions.push(LinkManagerAction::ResourceFailed {
                        link_id: *link_id,
                        error: format!("{}", e),
                    });
                }
                _ => {}
            }
        }

        // Clean up completed/failed senders
        link.outgoing_resources
            .retain(|s| s.status < rns_core::resource::ResourceStatus::Complete);

        actions
    }

    /// Handle cancel from initiator (CONTEXT_RESOURCE_ICL).
    fn handle_resource_icl(&mut self, link_id: &LinkId) -> Vec<LinkManagerAction> {
        let link = match self.links.get_mut(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        let mut actions = Vec::new();
        for receiver in &mut link.incoming_resources {
            let ra = receiver.handle_cancel();
            for a in ra {
                if let ResourceAction::Failed(ref e) = a {
                    actions.push(LinkManagerAction::ResourceFailed {
                        link_id: *link_id,
                        error: format!("{}", e),
                    });
                }
            }
        }
        link.incoming_resources
            .retain(|r| r.status < rns_core::resource::ResourceStatus::Complete);
        actions
    }

    /// Handle cancel from receiver (CONTEXT_RESOURCE_RCL).
    fn handle_resource_rcl(&mut self, link_id: &LinkId) -> Vec<LinkManagerAction> {
        let link = match self.links.get_mut(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        let mut actions = Vec::new();
        for sender in &mut link.outgoing_resources {
            let ra = sender.handle_reject();
            for a in ra {
                if let ResourceAction::Failed(ref e) = a {
                    actions.push(LinkManagerAction::ResourceFailed {
                        link_id: *link_id,
                        error: format!("{}", e),
                    });
                }
            }
        }
        link.outgoing_resources
            .retain(|s| s.status < rns_core::resource::ResourceStatus::Complete);
        actions
    }

    /// Convert ResourceActions to LinkManagerActions.
    fn process_resource_actions(
        &self,
        link_id: &LinkId,
        actions: Vec<ResourceAction>,
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        let link = match self.links.get(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        let mut result = Vec::new();
        for action in actions {
            match action {
                ResourceAction::SendAdvertisement(data) => {
                    // Link-encrypt and send as CONTEXT_RESOURCE_ADV
                    if let Ok(encrypted) = link.engine.encrypt(&data, rng) {
                        result.extend(self.build_link_packet(
                            link_id,
                            constants::CONTEXT_RESOURCE_ADV,
                            &encrypted,
                        ));
                    }
                }
                ResourceAction::SendPart(data) => {
                    // Parts are NOT link-encrypted — send raw as CONTEXT_RESOURCE
                    result.extend(self.build_link_packet(
                        link_id,
                        constants::CONTEXT_RESOURCE,
                        &data,
                    ));
                }
                ResourceAction::SendRequest(data) => {
                    if let Ok(encrypted) = link.engine.encrypt(&data, rng) {
                        result.extend(self.build_link_packet(
                            link_id,
                            constants::CONTEXT_RESOURCE_REQ,
                            &encrypted,
                        ));
                    }
                }
                ResourceAction::SendHmu(data) => {
                    if let Ok(encrypted) = link.engine.encrypt(&data, rng) {
                        result.extend(self.build_link_packet(
                            link_id,
                            constants::CONTEXT_RESOURCE_HMU,
                            &encrypted,
                        ));
                    }
                }
                ResourceAction::SendProof(data) => {
                    if let Ok(encrypted) = link.engine.encrypt(&data, rng) {
                        result.extend(self.build_link_packet(
                            link_id,
                            constants::CONTEXT_RESOURCE_PRF,
                            &encrypted,
                        ));
                    }
                }
                ResourceAction::SendCancelInitiator(data) => {
                    if let Ok(encrypted) = link.engine.encrypt(&data, rng) {
                        result.extend(self.build_link_packet(
                            link_id,
                            constants::CONTEXT_RESOURCE_ICL,
                            &encrypted,
                        ));
                    }
                }
                ResourceAction::SendCancelReceiver(data) => {
                    if let Ok(encrypted) = link.engine.encrypt(&data, rng) {
                        result.extend(self.build_link_packet(
                            link_id,
                            constants::CONTEXT_RESOURCE_RCL,
                            &encrypted,
                        ));
                    }
                }
                ResourceAction::DataReceived { data, metadata } => {
                    result.push(LinkManagerAction::ResourceReceived {
                        link_id: *link_id,
                        data,
                        metadata,
                    });
                }
                ResourceAction::Completed => {
                    result.push(LinkManagerAction::ResourceCompleted { link_id: *link_id });
                }
                ResourceAction::Failed(e) => {
                    result.push(LinkManagerAction::ResourceFailed {
                        link_id: *link_id,
                        error: format!("{}", e),
                    });
                }
                ResourceAction::ProgressUpdate { received, total } => {
                    result.push(LinkManagerAction::ResourceProgress {
                        link_id: *link_id,
                        received,
                        total,
                    });
                }
            }
        }
        result
    }

    /// Build a link DATA packet with a given context and data.
    fn build_link_packet(
        &self,
        link_id: &LinkId,
        context: u8,
        data: &[u8],
    ) -> Vec<LinkManagerAction> {
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_LINK,
            packet_type: constants::PACKET_TYPE_DATA,
        };
        let mut actions = Vec::new();
        if let Ok(pkt) = RawPacket::pack(flags, 0, link_id, None, context, data) {
            actions.push(LinkManagerAction::SendPacket {
                raw: pkt.raw,
                dest_type: constants::DESTINATION_LINK,
                attached_interface: None,
            });
        }
        actions
    }

    /// Start sending a resource on a link.
    pub fn send_resource(
        &mut self,
        link_id: &LinkId,
        data: &[u8],
        metadata: Option<&[u8]>,
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        let link = match self.links.get_mut(link_id) {
            Some(l) => l,
            None => return Vec::new(),
        };

        if link.engine.state() != LinkState::Active {
            return Vec::new();
        }

        let link_rtt = link.engine.rtt().unwrap_or(1.0);
        let now = time::now();

        // Use RefCell for interior mutability since ResourceSender::new expects &dyn Fn (not FnMut)
        // but link.engine.encrypt needs &mut dyn Rng
        let enc_rng = std::cell::RefCell::new(rns_crypto::OsRng);
        let encrypt_fn = |plaintext: &[u8]| -> Vec<u8> {
            link.engine
                .encrypt(plaintext, &mut *enc_rng.borrow_mut())
                .unwrap_or_else(|_| plaintext.to_vec())
        };

        let sender = match ResourceSender::new(
            data,
            metadata,
            constants::RESOURCE_SDU,
            &encrypt_fn,
            &Bzip2Compressor,
            rng,
            now,
            true,  // auto_compress
            false, // is_response
            None,  // request_id
            1,     // segment_index
            1,     // total_segments
            None,  // original_hash
            link_rtt,
            6.0, // traffic_timeout_factor
        ) {
            Ok(s) => s,
            Err(e) => {
                log::debug!("Failed to create ResourceSender: {}", e);
                return Vec::new();
            }
        };

        let mut sender = sender;
        let adv_actions = sender.advertise(now);
        link.outgoing_resources.push(sender);

        let _ = link;
        self.process_resource_actions(link_id, adv_actions, rng)
    }

    /// Set the resource acceptance strategy for a link.
    pub fn set_resource_strategy(&mut self, link_id: &LinkId, strategy: ResourceStrategy) {
        if let Some(link) = self.links.get_mut(link_id) {
            link.resource_strategy = strategy;
        }
    }

    /// Flush the channel TX ring for a link, clearing outstanding messages.
    /// Called after holepunch completion where signaling messages are fire-and-forget.
    pub fn flush_channel_tx(&mut self, link_id: &LinkId) {
        if let Some(link) = self.links.get_mut(link_id) {
            if let Some(ref mut channel) = link.channel {
                channel.flush_tx();
            }
        }
    }

    /// Send a channel message on a link.
    pub fn send_channel_message(
        &mut self,
        link_id: &LinkId,
        msgtype: u16,
        payload: &[u8],
        rng: &mut dyn Rng,
    ) -> Result<Vec<LinkManagerAction>, String> {
        let link = match self.links.get_mut(link_id) {
            Some(l) => l,
            None => return Err("unknown link".to_string()),
        };

        let channel = match link.channel {
            Some(ref mut ch) => ch,
            None => return Err("link has no active channel".to_string()),
        };

        let link_mdu = link.engine.mdu();
        let now = time::now();
        let chan_actions = match channel.send(msgtype, payload, now, link_mdu) {
            Ok(a) => {
                link.channel_send_ok += 1;
                a
            }
            Err(e) => {
                log::debug!("Channel send failed: {:?}", e);
                match e {
                    rns_core::channel::ChannelError::NotReady => link.channel_send_not_ready += 1,
                    rns_core::channel::ChannelError::MessageTooBig => {
                        link.channel_send_too_big += 1;
                    }
                    rns_core::channel::ChannelError::InvalidEnvelope => {
                        link.channel_send_other_error += 1;
                    }
                }
                return Err(e.to_string());
            }
        };

        let _ = link;
        Ok(self.process_channel_actions(link_id, chan_actions, rng))
    }

    /// Periodic tick: check keepalive, stale, timeouts for all links.
    pub fn tick(&mut self, rng: &mut dyn Rng) -> Vec<LinkManagerAction> {
        let now = time::now();
        let mut all_actions = Vec::new();

        // Collect link_ids to avoid borrow issues
        let link_ids: Vec<LinkId> = self.links.keys().copied().collect();

        for link_id in &link_ids {
            let link = match self.links.get_mut(link_id) {
                Some(l) => l,
                None => continue,
            };

            // Tick the engine
            let tick_actions = link.engine.tick(now);
            all_actions.extend(self.process_link_actions(link_id, &tick_actions));

            // Check if keepalive is needed
            let link = match self.links.get_mut(link_id) {
                Some(l) => l,
                None => continue,
            };
            if link.engine.needs_keepalive(now) {
                // Send keepalive packet (empty data with CONTEXT_KEEPALIVE)
                let flags = PacketFlags {
                    header_type: constants::HEADER_1,
                    context_flag: constants::FLAG_UNSET,
                    transport_type: constants::TRANSPORT_BROADCAST,
                    destination_type: constants::DESTINATION_LINK,
                    packet_type: constants::PACKET_TYPE_DATA,
                };
                if let Ok(pkt) =
                    RawPacket::pack(flags, 0, link_id, None, constants::CONTEXT_KEEPALIVE, &[])
                {
                    all_actions.push(LinkManagerAction::SendPacket {
                        raw: pkt.raw,
                        dest_type: constants::DESTINATION_LINK,
                        attached_interface: None,
                    });
                    link.engine.record_outbound(now, true);
                }
            }

            if let Some(channel) = link.channel.as_mut() {
                let chan_actions = channel.tick(now);
                let _ = channel;
                let _ = link;
                all_actions.extend(self.process_channel_actions(link_id, chan_actions, rng));
            }
        }

        // Tick resource senders and receivers
        for link_id in &link_ids {
            let link = match self.links.get_mut(link_id) {
                Some(l) => l,
                None => continue,
            };

            // Tick outgoing resources (senders)
            let mut sender_actions = Vec::new();
            for sender in &mut link.outgoing_resources {
                sender_actions.extend(sender.tick(now));
            }

            // Tick incoming resources (receivers)
            let mut receiver_actions = Vec::new();
            for receiver in &mut link.incoming_resources {
                let decrypt_fn = |ciphertext: &[u8]| -> Result<Vec<u8>, ()> {
                    link.engine.decrypt(ciphertext).map_err(|_| ())
                };
                receiver_actions.extend(receiver.tick(now, &decrypt_fn, &Bzip2Compressor));
            }

            // Clean up completed/failed resources
            link.outgoing_resources
                .retain(|s| s.status < rns_core::resource::ResourceStatus::Complete);
            link.incoming_resources
                .retain(|r| r.status < rns_core::resource::ResourceStatus::Assembling);

            let _ = link;
            all_actions.extend(self.process_resource_actions(link_id, sender_actions, rng));
            all_actions.extend(self.process_resource_actions(link_id, receiver_actions, rng));
        }

        // Clean up closed links
        let closed: Vec<LinkId> = self
            .links
            .iter()
            .filter(|(_, l)| l.engine.state() == LinkState::Closed)
            .map(|(id, _)| *id)
            .collect();
        for id in closed {
            self.links.remove(&id);
            all_actions.push(LinkManagerAction::DeregisterLinkDest { link_id: id });
        }

        all_actions
    }

    /// Check if a destination hash is a known link_id managed by this manager.
    pub fn is_link_destination(&self, dest_hash: &[u8; 16]) -> bool {
        self.links.contains_key(dest_hash) || self.link_destinations.contains_key(dest_hash)
    }

    /// Get the state of a link.
    pub fn link_state(&self, link_id: &LinkId) -> Option<LinkState> {
        self.links.get(link_id).map(|l| l.engine.state())
    }

    /// Get the RTT of a link.
    pub fn link_rtt(&self, link_id: &LinkId) -> Option<f64> {
        self.links.get(link_id).and_then(|l| l.engine.rtt())
    }

    /// Update the RTT of a link (e.g., after path redirect to a direct connection).
    pub fn set_link_rtt(&mut self, link_id: &LinkId, rtt: f64) {
        if let Some(link) = self.links.get_mut(link_id) {
            link.engine.set_rtt(rtt);
        }
    }

    /// Reset the inbound timer for a link (e.g., after path redirect).
    pub fn record_link_inbound(&mut self, link_id: &LinkId) {
        if let Some(link) = self.links.get_mut(link_id) {
            link.engine.record_inbound(time::now());
        }
    }

    /// Update the MTU of a link (e.g., after path redirect to a different interface).
    pub fn set_link_mtu(&mut self, link_id: &LinkId, mtu: u32) {
        if let Some(link) = self.links.get_mut(link_id) {
            link.engine.set_mtu(mtu);
        }
    }

    /// Get the number of active links.
    pub fn link_count(&self) -> usize {
        self.links.len()
    }

    /// Get the number of active resource transfers across all links.
    pub fn resource_transfer_count(&self) -> usize {
        self.links
            .values()
            .map(|managed| managed.incoming_resources.len() + managed.outgoing_resources.len())
            .sum()
    }

    /// Cancel all active resource transfers and return the generated actions.
    pub fn cancel_all_resources(&mut self, rng: &mut dyn Rng) -> Vec<LinkManagerAction> {
        let link_ids: Vec<LinkId> = self.links.keys().copied().collect();
        let mut all_actions = Vec::new();

        for link_id in &link_ids {
            let link = match self.links.get_mut(link_id) {
                Some(l) => l,
                None => continue,
            };

            let mut sender_actions = Vec::new();
            for sender in &mut link.outgoing_resources {
                sender_actions.extend(sender.cancel());
            }

            let mut receiver_actions = Vec::new();
            for receiver in &mut link.incoming_resources {
                receiver_actions.extend(receiver.reject());
            }

            link.outgoing_resources
                .retain(|s| s.status < rns_core::resource::ResourceStatus::Complete);
            link.incoming_resources
                .retain(|r| r.status < rns_core::resource::ResourceStatus::Assembling);

            let _ = link;
            all_actions.extend(self.process_resource_actions(link_id, sender_actions, rng));
            all_actions.extend(self.process_resource_actions(link_id, receiver_actions, rng));
        }

        all_actions
    }

    /// Get information about all active links.
    pub fn link_entries(&self) -> Vec<crate::event::LinkInfoEntry> {
        self.links
            .iter()
            .map(|(link_id, managed)| {
                let state = match managed.engine.state() {
                    LinkState::Pending => "pending",
                    LinkState::Handshake => "handshake",
                    LinkState::Active => "active",
                    LinkState::Stale => "stale",
                    LinkState::Closed => "closed",
                };
                crate::event::LinkInfoEntry {
                    link_id: *link_id,
                    state: state.to_string(),
                    is_initiator: managed.engine.is_initiator(),
                    dest_hash: managed.dest_hash,
                    remote_identity: managed.remote_identity.as_ref().map(|(h, _)| *h),
                    rtt: managed.engine.rtt(),
                    channel_window: managed.channel.as_ref().map(|c| c.window()),
                    channel_outstanding: managed.channel.as_ref().map(|c| c.outstanding()),
                    pending_channel_packets: managed.pending_channel_packets.len(),
                    channel_send_ok: managed.channel_send_ok,
                    channel_send_not_ready: managed.channel_send_not_ready,
                    channel_send_too_big: managed.channel_send_too_big,
                    channel_send_other_error: managed.channel_send_other_error,
                    channel_messages_received: managed.channel_messages_received,
                    channel_proofs_sent: managed.channel_proofs_sent,
                    channel_proofs_received: managed.channel_proofs_received,
                }
            })
            .collect()
    }

    /// Get information about all active resource transfers.
    pub fn resource_entries(&self) -> Vec<crate::event::ResourceInfoEntry> {
        let mut entries = Vec::new();
        for (link_id, managed) in &self.links {
            for recv in &managed.incoming_resources {
                let (received, total) = recv.progress();
                entries.push(crate::event::ResourceInfoEntry {
                    link_id: *link_id,
                    direction: "incoming".to_string(),
                    total_parts: total,
                    transferred_parts: received,
                    complete: received >= total && total > 0,
                });
            }
            for send in &managed.outgoing_resources {
                let total = send.total_parts();
                let sent = send.sent_parts;
                entries.push(crate::event::ResourceInfoEntry {
                    link_id: *link_id,
                    direction: "outgoing".to_string(),
                    total_parts: total,
                    transferred_parts: sent,
                    complete: sent >= total && total > 0,
                });
            }
        }
        entries
    }

    /// Convert LinkActions to LinkManagerActions.
    fn process_link_actions(
        &self,
        link_id: &LinkId,
        actions: &[LinkAction],
    ) -> Vec<LinkManagerAction> {
        let mut result = Vec::new();
        for action in actions {
            match action {
                LinkAction::StateChanged {
                    new_state, reason, ..
                } => match new_state {
                    LinkState::Closed => {
                        result.push(LinkManagerAction::LinkClosed {
                            link_id: *link_id,
                            reason: *reason,
                        });
                    }
                    _ => {}
                },
                LinkAction::LinkEstablished {
                    rtt, is_initiator, ..
                } => {
                    let dest_hash = self
                        .links
                        .get(link_id)
                        .map(|l| l.dest_hash)
                        .unwrap_or([0u8; 16]);
                    result.push(LinkManagerAction::LinkEstablished {
                        link_id: *link_id,
                        dest_hash,
                        rtt: *rtt,
                        is_initiator: *is_initiator,
                    });
                }
                LinkAction::RemoteIdentified {
                    identity_hash,
                    public_key,
                    ..
                } => {
                    result.push(LinkManagerAction::RemoteIdentified {
                        link_id: *link_id,
                        identity_hash: *identity_hash,
                        public_key: *public_key,
                    });
                }
                LinkAction::DataReceived { .. } => {
                    // Data delivery is handled at a higher level
                }
            }
        }
        result
    }

    /// Convert ChannelActions to LinkManagerActions.
    fn process_channel_actions(
        &mut self,
        link_id: &LinkId,
        actions: Vec<rns_core::channel::ChannelAction>,
        rng: &mut dyn Rng,
    ) -> Vec<LinkManagerAction> {
        let mut result = Vec::new();
        for action in actions {
            match action {
                rns_core::channel::ChannelAction::SendOnLink { raw, sequence } => {
                    // Encrypt and send as CHANNEL context
                    let encrypted = match self.links.get(link_id) {
                        Some(link) => match link.engine.encrypt(&raw, rng) {
                            Ok(encrypted) => encrypted,
                            Err(_) => continue,
                        },
                        None => continue,
                    };
                    let flags = PacketFlags {
                        header_type: constants::HEADER_1,
                        context_flag: constants::FLAG_UNSET,
                        transport_type: constants::TRANSPORT_BROADCAST,
                        destination_type: constants::DESTINATION_LINK,
                        packet_type: constants::PACKET_TYPE_DATA,
                    };
                    if let Ok(pkt) = RawPacket::pack(
                        flags,
                        0,
                        link_id,
                        None,
                        constants::CONTEXT_CHANNEL,
                        &encrypted,
                    ) {
                        if let Some(link_mut) = self.links.get_mut(link_id) {
                            link_mut
                                .pending_channel_packets
                                .insert(pkt.packet_hash, sequence);
                        }
                        result.push(LinkManagerAction::SendPacket {
                            raw: pkt.raw,
                            dest_type: constants::DESTINATION_LINK,
                            attached_interface: None,
                        });
                    }
                }
                rns_core::channel::ChannelAction::MessageReceived {
                    msgtype, payload, ..
                } => {
                    result.push(LinkManagerAction::ChannelMessageReceived {
                        link_id: *link_id,
                        msgtype,
                        payload,
                    });
                }
                rns_core::channel::ChannelAction::TeardownLink => {
                    result.push(LinkManagerAction::LinkClosed {
                        link_id: *link_id,
                        reason: Some(TeardownReason::Timeout),
                    });
                }
            }
        }
        result
    }
}

/// Compute a path hash from a path string.
/// Uses truncated SHA-256 (first 16 bytes).
fn compute_path_hash(path: &str) -> [u8; 16] {
    let full = rns_core::hash::full_hash(path.as_bytes());
    let mut result = [0u8; 16];
    result.copy_from_slice(&full[..16]);
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use rns_crypto::identity::Identity;
    use rns_crypto::{FixedRng, OsRng};

    fn make_rng(seed: u8) -> FixedRng {
        FixedRng::new(&[seed; 128])
    }

    fn make_dest_keys(rng: &mut dyn Rng) -> (Ed25519PrivateKey, [u8; 32]) {
        let sig_prv = Ed25519PrivateKey::generate(rng);
        let sig_pub_bytes = sig_prv.public_key().public_bytes();
        (sig_prv, sig_pub_bytes)
    }

    #[test]
    fn test_register_link_destination() {
        let mut mgr = LinkManager::new();
        let mut rng = make_rng(0x01);
        let (sig_prv, sig_pub_bytes) = make_dest_keys(&mut rng);
        let dest_hash = [0xDD; 16];

        mgr.register_link_destination(
            dest_hash,
            sig_prv,
            sig_pub_bytes,
            ResourceStrategy::AcceptNone,
        );
        assert!(mgr.is_link_destination(&dest_hash));

        mgr.deregister_link_destination(&dest_hash);
        assert!(!mgr.is_link_destination(&dest_hash));
    }

    #[test]
    fn test_create_link() {
        let mut mgr = LinkManager::new();
        let mut rng = OsRng;
        let dest_hash = [0xDD; 16];

        let sig_pub_bytes = [0xAA; 32]; // dummy sig pub for test
        let (link_id, actions) = mgr.create_link(
            &dest_hash,
            &sig_pub_bytes,
            1,
            constants::MTU as u32,
            &mut rng,
        );
        assert_ne!(link_id, [0u8; 16]);
        // Should have RegisterLinkDest + SendPacket
        assert_eq!(actions.len(), 2);
        assert!(matches!(
            actions[0],
            LinkManagerAction::RegisterLinkDest { .. }
        ));
        assert!(matches!(actions[1], LinkManagerAction::SendPacket { .. }));

        // Link should be in Pending state
        assert_eq!(mgr.link_state(&link_id), Some(LinkState::Pending));
    }

    #[test]
    fn test_full_handshake_via_manager() {
        let mut rng = OsRng;
        let dest_hash = [0xDD; 16];

        // Setup responder
        let mut responder_mgr = LinkManager::new();
        let (sig_prv, sig_pub_bytes) = make_dest_keys(&mut rng);
        responder_mgr.register_link_destination(
            dest_hash,
            sig_prv,
            sig_pub_bytes,
            ResourceStrategy::AcceptNone,
        );

        // Setup initiator
        let mut initiator_mgr = LinkManager::new();

        // Step 1: Initiator creates link (needs dest signing pub key for LRPROOF verification)
        let (link_id, init_actions) = initiator_mgr.create_link(
            &dest_hash,
            &sig_pub_bytes,
            1,
            constants::MTU as u32,
            &mut rng,
        );
        assert_eq!(init_actions.len(), 2);

        // Extract the LINKREQUEST packet raw bytes
        let linkrequest_raw = match &init_actions[1] {
            LinkManagerAction::SendPacket { raw, .. } => raw.clone(),
            _ => panic!("Expected SendPacket"),
        };

        // Parse to get packet_hash and dest_hash
        let lr_packet = RawPacket::unpack(&linkrequest_raw).unwrap();

        // Step 2: Responder handles LINKREQUEST
        let resp_actions = responder_mgr.handle_local_delivery(
            lr_packet.destination_hash,
            &linkrequest_raw,
            lr_packet.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );
        // Should have RegisterLinkDest + SendPacket(LRPROOF)
        assert!(resp_actions.len() >= 2);
        assert!(matches!(
            resp_actions[0],
            LinkManagerAction::RegisterLinkDest { .. }
        ));

        // Extract LRPROOF packet
        let lrproof_raw = match &resp_actions[1] {
            LinkManagerAction::SendPacket { raw, .. } => raw.clone(),
            _ => panic!("Expected SendPacket for LRPROOF"),
        };

        // Step 3: Initiator handles LRPROOF
        let lrproof_packet = RawPacket::unpack(&lrproof_raw).unwrap();
        let init_actions2 = initiator_mgr.handle_local_delivery(
            lrproof_packet.destination_hash,
            &lrproof_raw,
            lrproof_packet.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );

        // Should have LinkEstablished + SendPacket(LRRTT)
        let has_established = init_actions2
            .iter()
            .any(|a| matches!(a, LinkManagerAction::LinkEstablished { .. }));
        assert!(has_established, "Initiator should emit LinkEstablished");

        // Extract LRRTT
        let lrrtt_raw = init_actions2
            .iter()
            .find_map(|a| match a {
                LinkManagerAction::SendPacket { raw, .. } => Some(raw.clone()),
                _ => None,
            })
            .expect("Should have LRRTT SendPacket");

        // Step 4: Responder handles LRRTT
        let lrrtt_packet = RawPacket::unpack(&lrrtt_raw).unwrap();
        let resp_link_id = lrrtt_packet.destination_hash;
        let resp_actions2 = responder_mgr.handle_local_delivery(
            resp_link_id,
            &lrrtt_raw,
            lrrtt_packet.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );

        let has_established = resp_actions2
            .iter()
            .any(|a| matches!(a, LinkManagerAction::LinkEstablished { .. }));
        assert!(has_established, "Responder should emit LinkEstablished");

        // Both sides should be Active
        assert_eq!(initiator_mgr.link_state(&link_id), Some(LinkState::Active));
        assert_eq!(responder_mgr.link_state(&link_id), Some(LinkState::Active));

        // Both should have RTT
        assert!(initiator_mgr.link_rtt(&link_id).is_some());
        assert!(responder_mgr.link_rtt(&link_id).is_some());
    }

    #[test]
    fn test_encrypted_data_exchange() {
        let mut rng = OsRng;
        let dest_hash = [0xDD; 16];
        let mut resp_mgr = LinkManager::new();
        let (sig_prv, sig_pub_bytes) = make_dest_keys(&mut rng);
        resp_mgr.register_link_destination(
            dest_hash,
            sig_prv,
            sig_pub_bytes,
            ResourceStrategy::AcceptNone,
        );
        let mut init_mgr = LinkManager::new();

        // Handshake
        let (link_id, init_actions) = init_mgr.create_link(
            &dest_hash,
            &sig_pub_bytes,
            1,
            constants::MTU as u32,
            &mut rng,
        );
        let lr_raw = extract_send_packet(&init_actions);
        let lr_pkt = RawPacket::unpack(&lr_raw).unwrap();
        let resp_actions = resp_mgr.handle_local_delivery(
            lr_pkt.destination_hash,
            &lr_raw,
            lr_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );
        let lrproof_raw = extract_send_packet_at(&resp_actions, 1);
        let lrproof_pkt = RawPacket::unpack(&lrproof_raw).unwrap();
        let init_actions2 = init_mgr.handle_local_delivery(
            lrproof_pkt.destination_hash,
            &lrproof_raw,
            lrproof_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );
        let lrrtt_raw = extract_any_send_packet(&init_actions2);
        let lrrtt_pkt = RawPacket::unpack(&lrrtt_raw).unwrap();
        resp_mgr.handle_local_delivery(
            lrrtt_pkt.destination_hash,
            &lrrtt_raw,
            lrrtt_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );

        // Send data from initiator to responder
        let actions =
            init_mgr.send_on_link(&link_id, b"hello link!", constants::CONTEXT_NONE, &mut rng);
        assert_eq!(actions.len(), 1);
        assert!(matches!(actions[0], LinkManagerAction::SendPacket { .. }));
    }

    #[test]
    fn test_request_response() {
        let mut rng = OsRng;
        let dest_hash = [0xDD; 16];
        let mut resp_mgr = LinkManager::new();
        let (sig_prv, sig_pub_bytes) = make_dest_keys(&mut rng);
        resp_mgr.register_link_destination(
            dest_hash,
            sig_prv,
            sig_pub_bytes,
            ResourceStrategy::AcceptNone,
        );

        // Register a request handler
        resp_mgr.register_request_handler("/status", None, |_link_id, _path, _data, _remote| {
            Some(b"OK".to_vec())
        });

        let mut init_mgr = LinkManager::new();

        // Complete handshake
        let (link_id, init_actions) = init_mgr.create_link(
            &dest_hash,
            &sig_pub_bytes,
            1,
            constants::MTU as u32,
            &mut rng,
        );
        let lr_raw = extract_send_packet(&init_actions);
        let lr_pkt = RawPacket::unpack(&lr_raw).unwrap();
        let resp_actions = resp_mgr.handle_local_delivery(
            lr_pkt.destination_hash,
            &lr_raw,
            lr_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );
        let lrproof_raw = extract_send_packet_at(&resp_actions, 1);
        let lrproof_pkt = RawPacket::unpack(&lrproof_raw).unwrap();
        let init_actions2 = init_mgr.handle_local_delivery(
            lrproof_pkt.destination_hash,
            &lrproof_raw,
            lrproof_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );
        let lrrtt_raw = extract_any_send_packet(&init_actions2);
        let lrrtt_pkt = RawPacket::unpack(&lrrtt_raw).unwrap();
        resp_mgr.handle_local_delivery(
            lrrtt_pkt.destination_hash,
            &lrrtt_raw,
            lrrtt_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );

        // Send request from initiator
        let req_actions = init_mgr.send_request(&link_id, "/status", b"query", &mut rng);
        assert_eq!(req_actions.len(), 1);

        // Deliver request to responder
        let req_raw = extract_send_packet_from(&req_actions);
        let req_pkt = RawPacket::unpack(&req_raw).unwrap();
        let resp_actions = resp_mgr.handle_local_delivery(
            req_pkt.destination_hash,
            &req_raw,
            req_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );

        // Should have a response SendPacket
        let has_response = resp_actions
            .iter()
            .any(|a| matches!(a, LinkManagerAction::SendPacket { .. }));
        assert!(has_response, "Handler should produce a response packet");
    }

    #[test]
    fn test_request_acl_deny_unidentified() {
        let mut rng = OsRng;
        let dest_hash = [0xDD; 16];
        let mut resp_mgr = LinkManager::new();
        let (sig_prv, sig_pub_bytes) = make_dest_keys(&mut rng);
        resp_mgr.register_link_destination(
            dest_hash,
            sig_prv,
            sig_pub_bytes,
            ResourceStrategy::AcceptNone,
        );

        // Register handler with ACL (only allow specific identity)
        resp_mgr.register_request_handler(
            "/restricted",
            Some(vec![[0xAA; 16]]),
            |_link_id, _path, _data, _remote| Some(b"secret".to_vec()),
        );

        let mut init_mgr = LinkManager::new();

        // Complete handshake (without identification)
        let (link_id, init_actions) = init_mgr.create_link(
            &dest_hash,
            &sig_pub_bytes,
            1,
            constants::MTU as u32,
            &mut rng,
        );
        let lr_raw = extract_send_packet(&init_actions);
        let lr_pkt = RawPacket::unpack(&lr_raw).unwrap();
        let resp_actions = resp_mgr.handle_local_delivery(
            lr_pkt.destination_hash,
            &lr_raw,
            lr_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );
        let lrproof_raw = extract_send_packet_at(&resp_actions, 1);
        let lrproof_pkt = RawPacket::unpack(&lrproof_raw).unwrap();
        let init_actions2 = init_mgr.handle_local_delivery(
            lrproof_pkt.destination_hash,
            &lrproof_raw,
            lrproof_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );
        let lrrtt_raw = extract_any_send_packet(&init_actions2);
        let lrrtt_pkt = RawPacket::unpack(&lrrtt_raw).unwrap();
        resp_mgr.handle_local_delivery(
            lrrtt_pkt.destination_hash,
            &lrrtt_raw,
            lrrtt_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );

        // Send request without identifying first
        let req_actions = init_mgr.send_request(&link_id, "/restricted", b"query", &mut rng);
        let req_raw = extract_send_packet_from(&req_actions);
        let req_pkt = RawPacket::unpack(&req_raw).unwrap();
        let resp_actions = resp_mgr.handle_local_delivery(
            req_pkt.destination_hash,
            &req_raw,
            req_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );

        // Should be denied — no response packet
        let has_response = resp_actions
            .iter()
            .any(|a| matches!(a, LinkManagerAction::SendPacket { .. }));
        assert!(!has_response, "Unidentified peer should be denied");
    }

    #[test]
    fn test_teardown_link() {
        let mut rng = OsRng;
        let dest_hash = [0xDD; 16];
        let mut mgr = LinkManager::new();

        let dummy_sig = [0xAA; 32];
        let (link_id, _) =
            mgr.create_link(&dest_hash, &dummy_sig, 1, constants::MTU as u32, &mut rng);
        assert_eq!(mgr.link_count(), 1);

        let actions = mgr.teardown_link(&link_id);
        let has_close = actions
            .iter()
            .any(|a| matches!(a, LinkManagerAction::LinkClosed { .. }));
        assert!(has_close);

        // After tick, closed links should be cleaned up
        let tick_actions = mgr.tick(&mut rng);
        let has_deregister = tick_actions
            .iter()
            .any(|a| matches!(a, LinkManagerAction::DeregisterLinkDest { .. }));
        assert!(has_deregister);
        assert_eq!(mgr.link_count(), 0);
    }

    #[test]
    fn test_identify_on_link() {
        let mut rng = OsRng;
        let dest_hash = [0xDD; 16];
        let mut resp_mgr = LinkManager::new();
        let (sig_prv, sig_pub_bytes) = make_dest_keys(&mut rng);
        resp_mgr.register_link_destination(
            dest_hash,
            sig_prv,
            sig_pub_bytes,
            ResourceStrategy::AcceptNone,
        );
        let mut init_mgr = LinkManager::new();

        // Complete handshake
        let (link_id, init_actions) = init_mgr.create_link(
            &dest_hash,
            &sig_pub_bytes,
            1,
            constants::MTU as u32,
            &mut rng,
        );
        let lr_raw = extract_send_packet(&init_actions);
        let lr_pkt = RawPacket::unpack(&lr_raw).unwrap();
        let resp_actions = resp_mgr.handle_local_delivery(
            lr_pkt.destination_hash,
            &lr_raw,
            lr_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );
        let lrproof_raw = extract_send_packet_at(&resp_actions, 1);
        let lrproof_pkt = RawPacket::unpack(&lrproof_raw).unwrap();
        let init_actions2 = init_mgr.handle_local_delivery(
            lrproof_pkt.destination_hash,
            &lrproof_raw,
            lrproof_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );
        let lrrtt_raw = extract_any_send_packet(&init_actions2);
        let lrrtt_pkt = RawPacket::unpack(&lrrtt_raw).unwrap();
        resp_mgr.handle_local_delivery(
            lrrtt_pkt.destination_hash,
            &lrrtt_raw,
            lrrtt_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );

        // Identify initiator to responder
        let identity = Identity::new(&mut rng);
        let id_actions = init_mgr.identify(&link_id, &identity, &mut rng);
        assert_eq!(id_actions.len(), 1);

        // Deliver identify to responder
        let id_raw = extract_send_packet_from(&id_actions);
        let id_pkt = RawPacket::unpack(&id_raw).unwrap();
        let resp_actions = resp_mgr.handle_local_delivery(
            id_pkt.destination_hash,
            &id_raw,
            id_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );

        let has_identified = resp_actions
            .iter()
            .any(|a| matches!(a, LinkManagerAction::RemoteIdentified { .. }));
        assert!(has_identified, "Responder should emit RemoteIdentified");
    }

    #[test]
    fn test_path_hash_computation() {
        let h1 = compute_path_hash("/status");
        let h2 = compute_path_hash("/path");
        assert_ne!(h1, h2);

        // Deterministic
        assert_eq!(h1, compute_path_hash("/status"));
    }

    #[test]
    fn test_link_count() {
        let mut mgr = LinkManager::new();
        let mut rng = OsRng;

        assert_eq!(mgr.link_count(), 0);

        let dummy_sig = [0xAA; 32];
        mgr.create_link(&[0x11; 16], &dummy_sig, 1, constants::MTU as u32, &mut rng);
        assert_eq!(mgr.link_count(), 1);

        mgr.create_link(&[0x22; 16], &dummy_sig, 1, constants::MTU as u32, &mut rng);
        assert_eq!(mgr.link_count(), 2);
    }

    // --- Test helpers ---

    fn extract_send_packet(actions: &[LinkManagerAction]) -> Vec<u8> {
        extract_send_packet_at(actions, actions.len() - 1)
    }

    fn extract_send_packet_at(actions: &[LinkManagerAction], idx: usize) -> Vec<u8> {
        match &actions[idx] {
            LinkManagerAction::SendPacket { raw, .. } => raw.clone(),
            other => panic!("Expected SendPacket at index {}, got {:?}", idx, other),
        }
    }

    fn extract_any_send_packet(actions: &[LinkManagerAction]) -> Vec<u8> {
        actions
            .iter()
            .find_map(|a| match a {
                LinkManagerAction::SendPacket { raw, .. } => Some(raw.clone()),
                _ => None,
            })
            .expect("Expected at least one SendPacket action")
    }

    fn extract_send_packet_from(actions: &[LinkManagerAction]) -> Vec<u8> {
        extract_any_send_packet(actions)
    }

    /// Set up two linked managers with an active link.
    /// Returns (initiator_mgr, responder_mgr, link_id).
    fn setup_active_link() -> (LinkManager, LinkManager, LinkId) {
        let mut rng = OsRng;
        let dest_hash = [0xDD; 16];
        let mut resp_mgr = LinkManager::new();
        let (sig_prv, sig_pub_bytes) = make_dest_keys(&mut rng);
        resp_mgr.register_link_destination(
            dest_hash,
            sig_prv,
            sig_pub_bytes,
            ResourceStrategy::AcceptNone,
        );
        let mut init_mgr = LinkManager::new();

        let (link_id, init_actions) = init_mgr.create_link(
            &dest_hash,
            &sig_pub_bytes,
            1,
            constants::MTU as u32,
            &mut rng,
        );
        let lr_raw = extract_send_packet(&init_actions);
        let lr_pkt = RawPacket::unpack(&lr_raw).unwrap();
        let resp_actions = resp_mgr.handle_local_delivery(
            lr_pkt.destination_hash,
            &lr_raw,
            lr_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );
        let lrproof_raw = extract_send_packet_at(&resp_actions, 1);
        let lrproof_pkt = RawPacket::unpack(&lrproof_raw).unwrap();
        let init_actions2 = init_mgr.handle_local_delivery(
            lrproof_pkt.destination_hash,
            &lrproof_raw,
            lrproof_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );
        let lrrtt_raw = extract_any_send_packet(&init_actions2);
        let lrrtt_pkt = RawPacket::unpack(&lrrtt_raw).unwrap();
        resp_mgr.handle_local_delivery(
            lrrtt_pkt.destination_hash,
            &lrrtt_raw,
            lrrtt_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );

        assert_eq!(init_mgr.link_state(&link_id), Some(LinkState::Active));
        assert_eq!(resp_mgr.link_state(&link_id), Some(LinkState::Active));

        (init_mgr, resp_mgr, link_id)
    }

    // ====================================================================
    // Phase 8a: Resource wiring tests
    // ====================================================================

    #[test]
    fn test_resource_strategy_default() {
        let mut mgr = LinkManager::new();
        let mut rng = OsRng;
        let dummy_sig = [0xAA; 32];
        let (link_id, _) =
            mgr.create_link(&[0x11; 16], &dummy_sig, 1, constants::MTU as u32, &mut rng);

        // Default strategy is AcceptNone
        let link = mgr.links.get(&link_id).unwrap();
        assert_eq!(link.resource_strategy, ResourceStrategy::AcceptNone);
    }

    #[test]
    fn test_set_resource_strategy() {
        let mut mgr = LinkManager::new();
        let mut rng = OsRng;
        let dummy_sig = [0xAA; 32];
        let (link_id, _) =
            mgr.create_link(&[0x11; 16], &dummy_sig, 1, constants::MTU as u32, &mut rng);

        mgr.set_resource_strategy(&link_id, ResourceStrategy::AcceptAll);
        assert_eq!(
            mgr.links.get(&link_id).unwrap().resource_strategy,
            ResourceStrategy::AcceptAll
        );

        mgr.set_resource_strategy(&link_id, ResourceStrategy::AcceptApp);
        assert_eq!(
            mgr.links.get(&link_id).unwrap().resource_strategy,
            ResourceStrategy::AcceptApp
        );
    }

    #[test]
    fn test_send_resource_on_active_link() {
        let (mut init_mgr, _resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        // Send resource data
        let data = vec![0xAB; 100]; // small enough for a single part
        let actions = init_mgr.send_resource(&link_id, &data, None, &mut rng);

        // Should produce at least a SendPacket (advertisement)
        let has_send = actions
            .iter()
            .any(|a| matches!(a, LinkManagerAction::SendPacket { .. }));
        assert!(
            has_send,
            "send_resource should emit advertisement SendPacket"
        );
    }

    #[test]
    fn test_send_resource_on_inactive_link() {
        let mut mgr = LinkManager::new();
        let mut rng = OsRng;
        let dummy_sig = [0xAA; 32];
        let (link_id, _) =
            mgr.create_link(&[0x11; 16], &dummy_sig, 1, constants::MTU as u32, &mut rng);

        // Link is Pending, not Active
        let actions = mgr.send_resource(&link_id, b"data", None, &mut rng);
        assert!(actions.is_empty(), "Cannot send resource on inactive link");
    }

    #[test]
    fn test_resource_adv_rejected_by_accept_none() {
        let (mut init_mgr, mut resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        // Responder uses default AcceptNone strategy
        // Send resource from initiator
        let data = vec![0xCD; 100];
        let adv_actions = init_mgr.send_resource(&link_id, &data, None, &mut rng);

        // Deliver advertisement to responder
        for action in &adv_actions {
            if let LinkManagerAction::SendPacket { raw, .. } = action {
                let pkt = RawPacket::unpack(raw).unwrap();
                let resp_actions = resp_mgr.handle_local_delivery(
                    pkt.destination_hash,
                    raw,
                    pkt.packet_hash,
                    rns_core::transport::types::InterfaceId(0),
                    &mut rng,
                );
                // AcceptNone: should not produce ResourceReceived, may produce SendPacket (RCL)
                let has_resource_received = resp_actions
                    .iter()
                    .any(|a| matches!(a, LinkManagerAction::ResourceReceived { .. }));
                assert!(
                    !has_resource_received,
                    "AcceptNone should not accept resource"
                );
            }
        }
    }

    #[test]
    fn test_resource_adv_accepted_by_accept_all() {
        let (mut init_mgr, mut resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        // Set responder to AcceptAll
        resp_mgr.set_resource_strategy(&link_id, ResourceStrategy::AcceptAll);

        // Send resource from initiator
        let data = vec![0xCD; 100];
        let adv_actions = init_mgr.send_resource(&link_id, &data, None, &mut rng);

        // Deliver advertisement to responder
        for action in &adv_actions {
            if let LinkManagerAction::SendPacket { raw, .. } = action {
                let pkt = RawPacket::unpack(raw).unwrap();
                let resp_actions = resp_mgr.handle_local_delivery(
                    pkt.destination_hash,
                    raw,
                    pkt.packet_hash,
                    rns_core::transport::types::InterfaceId(0),
                    &mut rng,
                );
                // AcceptAll: should accept and produce a SendPacket (request for parts)
                let has_send = resp_actions
                    .iter()
                    .any(|a| matches!(a, LinkManagerAction::SendPacket { .. }));
                assert!(has_send, "AcceptAll should accept and request parts");
            }
        }
    }

    #[test]
    fn test_resource_accept_app_query() {
        let (mut init_mgr, mut resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        // Set responder to AcceptApp
        resp_mgr.set_resource_strategy(&link_id, ResourceStrategy::AcceptApp);

        // Send resource from initiator
        let data = vec![0xCD; 100];
        let adv_actions = init_mgr.send_resource(&link_id, &data, None, &mut rng);

        // Deliver advertisement to responder
        let mut got_query = false;
        for action in &adv_actions {
            if let LinkManagerAction::SendPacket { raw, .. } = action {
                let pkt = RawPacket::unpack(raw).unwrap();
                let resp_actions = resp_mgr.handle_local_delivery(
                    pkt.destination_hash,
                    raw,
                    pkt.packet_hash,
                    rns_core::transport::types::InterfaceId(0),
                    &mut rng,
                );
                for a in &resp_actions {
                    if matches!(a, LinkManagerAction::ResourceAcceptQuery { .. }) {
                        got_query = true;
                    }
                }
            }
        }
        assert!(got_query, "AcceptApp should emit ResourceAcceptQuery");
    }

    #[test]
    fn test_resource_accept_app_accept() {
        let (mut init_mgr, mut resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        resp_mgr.set_resource_strategy(&link_id, ResourceStrategy::AcceptApp);

        let data = vec![0xCD; 100];
        let adv_actions = init_mgr.send_resource(&link_id, &data, None, &mut rng);

        for action in &adv_actions {
            if let LinkManagerAction::SendPacket { raw, .. } = action {
                let pkt = RawPacket::unpack(raw).unwrap();
                let resp_actions = resp_mgr.handle_local_delivery(
                    pkt.destination_hash,
                    raw,
                    pkt.packet_hash,
                    rns_core::transport::types::InterfaceId(0),
                    &mut rng,
                );
                for a in &resp_actions {
                    if let LinkManagerAction::ResourceAcceptQuery {
                        link_id: lid,
                        resource_hash,
                        ..
                    } = a
                    {
                        // Accept the resource
                        let accept_actions =
                            resp_mgr.accept_resource(lid, resource_hash, true, &mut rng);
                        // Should produce a SendPacket (request for parts)
                        let has_send = accept_actions
                            .iter()
                            .any(|a| matches!(a, LinkManagerAction::SendPacket { .. }));
                        assert!(
                            has_send,
                            "Accepting resource should produce request for parts"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn test_resource_accept_app_reject() {
        let (mut init_mgr, mut resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        resp_mgr.set_resource_strategy(&link_id, ResourceStrategy::AcceptApp);

        let data = vec![0xCD; 100];
        let adv_actions = init_mgr.send_resource(&link_id, &data, None, &mut rng);

        for action in &adv_actions {
            if let LinkManagerAction::SendPacket { raw, .. } = action {
                let pkt = RawPacket::unpack(raw).unwrap();
                let resp_actions = resp_mgr.handle_local_delivery(
                    pkt.destination_hash,
                    raw,
                    pkt.packet_hash,
                    rns_core::transport::types::InterfaceId(0),
                    &mut rng,
                );
                for a in &resp_actions {
                    if let LinkManagerAction::ResourceAcceptQuery {
                        link_id: lid,
                        resource_hash,
                        ..
                    } = a
                    {
                        // Reject the resource
                        let reject_actions =
                            resp_mgr.accept_resource(lid, resource_hash, false, &mut rng);
                        // Rejecting should send a cancel and not request parts
                        // No ResourceReceived should appear
                        let has_resource_received = reject_actions
                            .iter()
                            .any(|a| matches!(a, LinkManagerAction::ResourceReceived { .. }));
                        assert!(!has_resource_received);
                    }
                }
            }
        }
    }

    #[test]
    fn test_resource_full_transfer() {
        let (mut init_mgr, mut resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        // Set responder to AcceptAll
        resp_mgr.set_resource_strategy(&link_id, ResourceStrategy::AcceptAll);

        // Small data (fits in single SDU)
        let original_data = b"Hello, Resource Transfer!".to_vec();
        let adv_actions = init_mgr.send_resource(&link_id, &original_data, None, &mut rng);

        // Drive the full transfer protocol between the two managers.
        // Tag each SendPacket with its source ('i' = initiator, 'r' = responder).
        let mut pending: Vec<(char, LinkManagerAction)> =
            adv_actions.into_iter().map(|a| ('i', a)).collect();
        let mut rounds = 0;
        let max_rounds = 50;
        let mut resource_received = false;
        let mut sender_completed = false;

        while !pending.is_empty() && rounds < max_rounds {
            rounds += 1;
            let mut next: Vec<(char, LinkManagerAction)> = Vec::new();

            for (source, action) in pending.drain(..) {
                if let LinkManagerAction::SendPacket { raw, .. } = action {
                    let pkt = RawPacket::unpack(&raw).unwrap();

                    // Deliver only to the OTHER side
                    let target_actions = if source == 'i' {
                        resp_mgr.handle_local_delivery(
                            pkt.destination_hash,
                            &raw,
                            pkt.packet_hash,
                            rns_core::transport::types::InterfaceId(0),
                            &mut rng,
                        )
                    } else {
                        init_mgr.handle_local_delivery(
                            pkt.destination_hash,
                            &raw,
                            pkt.packet_hash,
                            rns_core::transport::types::InterfaceId(0),
                            &mut rng,
                        )
                    };

                    let target_source = if source == 'i' { 'r' } else { 'i' };
                    for a in &target_actions {
                        match a {
                            LinkManagerAction::ResourceReceived { data, .. } => {
                                assert_eq!(*data, original_data);
                                resource_received = true;
                            }
                            LinkManagerAction::ResourceCompleted { .. } => {
                                sender_completed = true;
                            }
                            _ => {}
                        }
                    }
                    next.extend(target_actions.into_iter().map(|a| (target_source, a)));
                }
            }
            pending = next;
        }

        assert!(
            resource_received,
            "Responder should receive resource data (rounds={})",
            rounds
        );
        assert!(
            sender_completed,
            "Sender should get completion proof (rounds={})",
            rounds
        );
    }

    #[test]
    fn test_resource_cancel_icl() {
        let (mut init_mgr, mut resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        resp_mgr.set_resource_strategy(&link_id, ResourceStrategy::AcceptAll);

        // Use large data so transfer is multi-part
        let data = vec![0xAB; 2000];
        let adv_actions = init_mgr.send_resource(&link_id, &data, None, &mut rng);

        // Deliver advertisement — responder accepts and sends request
        for action in &adv_actions {
            if let LinkManagerAction::SendPacket { raw, .. } = action {
                let pkt = RawPacket::unpack(raw).unwrap();
                resp_mgr.handle_local_delivery(
                    pkt.destination_hash,
                    raw,
                    pkt.packet_hash,
                    rns_core::transport::types::InterfaceId(0),
                    &mut rng,
                );
            }
        }

        // Verify there are incoming resources on the responder
        assert!(!resp_mgr
            .links
            .get(&link_id)
            .unwrap()
            .incoming_resources
            .is_empty());

        // Simulate ICL (cancel from initiator side) by calling handle_resource_icl
        let icl_actions = resp_mgr.handle_resource_icl(&link_id);

        // Should have resource failed
        let has_failed = icl_actions
            .iter()
            .any(|a| matches!(a, LinkManagerAction::ResourceFailed { .. }));
        assert!(has_failed, "ICL should produce ResourceFailed");
    }

    #[test]
    fn test_resource_cancel_rcl() {
        let (mut init_mgr, _resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        // Create a resource sender
        let data = vec![0xAB; 2000];
        init_mgr.send_resource(&link_id, &data, None, &mut rng);

        // Verify there are outgoing resources
        assert!(!init_mgr
            .links
            .get(&link_id)
            .unwrap()
            .outgoing_resources
            .is_empty());

        // Simulate RCL (cancel from receiver side)
        let rcl_actions = init_mgr.handle_resource_rcl(&link_id);

        let has_failed = rcl_actions
            .iter()
            .any(|a| matches!(a, LinkManagerAction::ResourceFailed { .. }));
        assert!(has_failed, "RCL should produce ResourceFailed");
    }

    #[test]
    fn test_cancel_all_resources_clears_active_transfers() {
        let (mut init_mgr, _resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        let actions = init_mgr.send_resource(&link_id, b"resource body", None, &mut rng);
        assert!(!actions.is_empty());
        assert_eq!(init_mgr.resource_transfer_count(), 1);

        let cancel_actions = init_mgr.cancel_all_resources(&mut rng);

        assert_eq!(init_mgr.resource_transfer_count(), 0);
        assert!(cancel_actions
            .iter()
            .any(|action| matches!(action, LinkManagerAction::SendPacket { .. })));
    }

    #[test]
    fn test_resource_tick_cleans_up() {
        let (mut init_mgr, _resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        let data = vec![0xAB; 100];
        init_mgr.send_resource(&link_id, &data, None, &mut rng);

        assert!(!init_mgr
            .links
            .get(&link_id)
            .unwrap()
            .outgoing_resources
            .is_empty());

        // Cancel the sender to make it Complete
        init_mgr.handle_resource_rcl(&link_id);

        // Tick should clean up completed resources
        init_mgr.tick(&mut rng);

        assert!(
            init_mgr
                .links
                .get(&link_id)
                .unwrap()
                .outgoing_resources
                .is_empty(),
            "Tick should clean up completed/failed outgoing resources"
        );
    }

    #[test]
    fn test_build_link_packet() {
        let (init_mgr, _resp_mgr, link_id) = setup_active_link();

        let actions =
            init_mgr.build_link_packet(&link_id, constants::CONTEXT_RESOURCE, b"test data");
        assert_eq!(actions.len(), 1);
        if let LinkManagerAction::SendPacket { raw, dest_type, .. } = &actions[0] {
            let pkt = RawPacket::unpack(raw).unwrap();
            assert_eq!(pkt.context, constants::CONTEXT_RESOURCE);
            assert_eq!(*dest_type, constants::DESTINATION_LINK);
        } else {
            panic!("Expected SendPacket");
        }
    }

    // ====================================================================
    // Phase 8b: Channel message & data callback tests
    // ====================================================================

    #[test]
    fn test_channel_message_delivery() {
        let (mut init_mgr, mut resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        // Send channel message from initiator
        let chan_actions = init_mgr
            .send_channel_message(&link_id, 42, b"channel data", &mut rng)
            .expect("active link channel send should succeed");
        assert!(!chan_actions.is_empty());

        // Deliver to responder
        let mut got_channel_msg = false;
        for action in &chan_actions {
            if let LinkManagerAction::SendPacket { raw, .. } = action {
                let pkt = RawPacket::unpack(raw).unwrap();
                let resp_actions = resp_mgr.handle_local_delivery(
                    pkt.destination_hash,
                    raw,
                    pkt.packet_hash,
                    rns_core::transport::types::InterfaceId(0),
                    &mut rng,
                );
                for a in &resp_actions {
                    if let LinkManagerAction::ChannelMessageReceived {
                        msgtype, payload, ..
                    } = a
                    {
                        assert_eq!(*msgtype, 42);
                        assert_eq!(*payload, b"channel data");
                        got_channel_msg = true;
                    }
                }
            }
        }
        assert!(got_channel_msg, "Responder should receive channel message");
    }

    #[test]
    fn test_channel_proof_reopens_send_window() {
        let (mut init_mgr, _resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        init_mgr
            .send_channel_message(&link_id, 42, b"first", &mut rng)
            .expect("first send should succeed");
        init_mgr
            .send_channel_message(&link_id, 42, b"second", &mut rng)
            .expect("second send should succeed");

        let err = init_mgr
            .send_channel_message(&link_id, 42, b"third", &mut rng)
            .expect_err("third send should hit the initial channel window");
        assert_eq!(err, "Channel is not ready to send");

        let queued_packets = init_mgr
            .links
            .get(&link_id)
            .unwrap()
            .pending_channel_packets
            .clone();
        assert_eq!(queued_packets.len(), 2);
        for tracked_hash in queued_packets.keys().take(1) {
            let mut proof_data = Vec::with_capacity(96);
            proof_data.extend_from_slice(tracked_hash);
            proof_data.extend_from_slice(&[0x11; 64]);
            let flags = PacketFlags {
                header_type: constants::HEADER_1,
                context_flag: constants::FLAG_UNSET,
                transport_type: constants::TRANSPORT_BROADCAST,
                destination_type: constants::DESTINATION_LINK,
                packet_type: constants::PACKET_TYPE_PROOF,
            };
            let proof = RawPacket::pack(
                flags,
                0,
                &link_id,
                None,
                constants::CONTEXT_NONE,
                &proof_data,
            )
            .expect("proof packet should pack");
            let ack_actions = init_mgr.handle_local_delivery(
                link_id,
                &proof.raw,
                proof.packet_hash,
                rns_core::transport::types::InterfaceId(0),
                &mut rng,
            );
            assert!(
                ack_actions.is_empty(),
                "proof delivery should only update channel state"
            );
        }

        init_mgr
            .send_channel_message(&link_id, 42, b"third", &mut rng)
            .expect("proof should free one channel slot");
    }

    #[test]
    fn test_generic_link_data_delivery() {
        let (init_mgr, mut resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        // Send generic data with a custom context
        let actions = init_mgr.send_on_link(&link_id, b"raw stuff", 0x42, &mut rng);
        assert_eq!(actions.len(), 1);

        // Deliver to responder
        let raw = extract_any_send_packet(&actions);
        let pkt = RawPacket::unpack(&raw).unwrap();
        let resp_actions = resp_mgr.handle_local_delivery(
            pkt.destination_hash,
            &raw,
            pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );

        let has_data = resp_actions
            .iter()
            .any(|a| matches!(a, LinkManagerAction::LinkDataReceived { context: 0x42, .. }));
        assert!(
            has_data,
            "Responder should receive LinkDataReceived for unknown context"
        );
    }

    #[test]
    fn test_response_delivery() {
        let (mut init_mgr, mut resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        // Register handler on responder
        resp_mgr.register_request_handler("/echo", None, |_link_id, _path, data, _remote| {
            Some(data.to_vec())
        });

        // Send request from initiator
        let req_actions = init_mgr.send_request(&link_id, "/echo", b"\xc0", &mut rng); // msgpack nil
        assert!(!req_actions.is_empty());

        // Deliver request to responder — should produce response
        let req_raw = extract_any_send_packet(&req_actions);
        let req_pkt = RawPacket::unpack(&req_raw).unwrap();
        let resp_actions = resp_mgr.handle_local_delivery(
            req_pkt.destination_hash,
            &req_raw,
            req_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );
        let has_resp_send = resp_actions
            .iter()
            .any(|a| matches!(a, LinkManagerAction::SendPacket { .. }));
        assert!(has_resp_send, "Handler should produce response");

        // Deliver response back to initiator
        let resp_raw = extract_any_send_packet(&resp_actions);
        let resp_pkt = RawPacket::unpack(&resp_raw).unwrap();
        let init_actions = init_mgr.handle_local_delivery(
            resp_pkt.destination_hash,
            &resp_raw,
            resp_pkt.packet_hash,
            rns_core::transport::types::InterfaceId(0),
            &mut rng,
        );

        let has_response_received = init_actions
            .iter()
            .any(|a| matches!(a, LinkManagerAction::ResponseReceived { .. }));
        assert!(
            has_response_received,
            "Initiator should receive ResponseReceived"
        );
    }

    #[test]
    fn test_send_channel_message_on_no_channel() {
        let mut mgr = LinkManager::new();
        let mut rng = OsRng;
        let dummy_sig = [0xAA; 32];
        let (link_id, _) =
            mgr.create_link(&[0x11; 16], &dummy_sig, 1, constants::MTU as u32, &mut rng);

        // Link is Pending (no channel), should return empty
        let err = mgr
            .send_channel_message(&link_id, 1, b"test", &mut rng)
            .expect_err("pending link should reject channel send");
        assert_eq!(err, "link has no active channel");
    }

    #[test]
    fn test_send_on_link_requires_active() {
        let mut mgr = LinkManager::new();
        let mut rng = OsRng;
        let dummy_sig = [0xAA; 32];
        let (link_id, _) =
            mgr.create_link(&[0x11; 16], &dummy_sig, 1, constants::MTU as u32, &mut rng);

        let actions = mgr.send_on_link(&link_id, b"test", constants::CONTEXT_NONE, &mut rng);
        assert!(actions.is_empty(), "Cannot send on pending link");
    }

    #[test]
    fn test_send_on_link_unknown_link() {
        let mgr = LinkManager::new();
        let mut rng = OsRng;

        let actions = mgr.send_on_link(&[0xFF; 16], b"test", constants::CONTEXT_NONE, &mut rng);
        assert!(actions.is_empty());
    }

    #[test]
    fn test_resource_full_transfer_large() {
        let (mut init_mgr, mut resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        resp_mgr.set_resource_strategy(&link_id, ResourceStrategy::AcceptAll);

        // Multi-part data (larger than a single SDU of 464 bytes)
        let original_data: Vec<u8> = (0..2000u32)
            .map(|i| {
                let pos = i as usize;
                (pos ^ (pos >> 8) ^ (pos >> 16)) as u8
            })
            .collect();

        let adv_actions = init_mgr.send_resource(&link_id, &original_data, None, &mut rng);

        let mut pending: Vec<(char, LinkManagerAction)> =
            adv_actions.into_iter().map(|a| ('i', a)).collect();
        let mut rounds = 0;
        let max_rounds = 200;
        let mut resource_received = false;
        let mut sender_completed = false;

        while !pending.is_empty() && rounds < max_rounds {
            rounds += 1;
            let mut next: Vec<(char, LinkManagerAction)> = Vec::new();

            for (source, action) in pending.drain(..) {
                if let LinkManagerAction::SendPacket { raw, .. } = action {
                    let pkt = match RawPacket::unpack(&raw) {
                        Ok(p) => p,
                        Err(_) => continue,
                    };

                    let target_actions = if source == 'i' {
                        resp_mgr.handle_local_delivery(
                            pkt.destination_hash,
                            &raw,
                            pkt.packet_hash,
                            rns_core::transport::types::InterfaceId(0),
                            &mut rng,
                        )
                    } else {
                        init_mgr.handle_local_delivery(
                            pkt.destination_hash,
                            &raw,
                            pkt.packet_hash,
                            rns_core::transport::types::InterfaceId(0),
                            &mut rng,
                        )
                    };

                    let target_source = if source == 'i' { 'r' } else { 'i' };
                    for a in &target_actions {
                        match a {
                            LinkManagerAction::ResourceReceived { data, .. } => {
                                assert_eq!(*data, original_data);
                                resource_received = true;
                            }
                            LinkManagerAction::ResourceCompleted { .. } => {
                                sender_completed = true;
                            }
                            _ => {}
                        }
                    }
                    next.extend(target_actions.into_iter().map(|a| (target_source, a)));
                }
            }
            pending = next;
        }

        assert!(
            resource_received,
            "Should receive large resource (rounds={})",
            rounds
        );
        assert!(
            sender_completed,
            "Sender should complete (rounds={})",
            rounds
        );
    }

    #[test]
    fn test_process_resource_actions_mapping() {
        let (init_mgr, _resp_mgr, link_id) = setup_active_link();
        let mut rng = OsRng;

        // Test that various ResourceActions map to correct LinkManagerActions
        let actions = vec![
            ResourceAction::DataReceived {
                data: vec![1, 2, 3],
                metadata: Some(vec![4, 5]),
            },
            ResourceAction::Completed,
            ResourceAction::Failed(rns_core::resource::ResourceError::Timeout),
            ResourceAction::ProgressUpdate {
                received: 10,
                total: 20,
            },
        ];

        let result = init_mgr.process_resource_actions(&link_id, actions, &mut rng);

        assert!(matches!(
            result[0],
            LinkManagerAction::ResourceReceived { .. }
        ));
        assert!(matches!(
            result[1],
            LinkManagerAction::ResourceCompleted { .. }
        ));
        assert!(matches!(
            result[2],
            LinkManagerAction::ResourceFailed { .. }
        ));
        assert!(matches!(
            result[3],
            LinkManagerAction::ResourceProgress {
                received: 10,
                total: 20,
                ..
            }
        ));
    }

    #[test]
    fn test_link_state_empty() {
        let mgr = LinkManager::new();
        let fake_id = [0xAA; 16];
        assert!(mgr.link_state(&fake_id).is_none());
    }
}