ant-node 0.24.0

Pure quantum-proof network node for the Autonomi decentralized network
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
//! ADR-0015 WebRTC Direct browser transport.
//!
//! The listener uses Saorsa's signaling-free WebRTC Direct transport for ICE,
//! DTLS, SCTP, and reliable ordered `DataChannels`. A shared application layer
//! in `saorsa_transport::webrtc` uses ML-KEM-768, ML-DSA-65, and ChaCha20-Poly1305 to bind
//! the node identity and protect every browser RPC without libp2p or Noise.

mod certificate;
mod errors;

use crate::ant_protocol::{
    ChunkMessage, ChunkMessageBody, ChunkPutRequest, ChunkPutResponse, ChunkQuoteRequest,
    ChunkQuoteResponse, MAX_CHUNK_SIZE,
};
use crate::browser::{browser_payment_network, BrowserEndpoint, BrowserPaymentNetwork};
use crate::codec::{encode_exact, ExactEncodeError};
use crate::config::WebRtcDirectConfig;
use crate::error::{Error, Result};
use crate::logging::{debug, info, warn};
use crate::payment::{serialize_single_node_proof, PaymentProof};
use crate::storage::AntProtocol;
use certificate::load_or_generate_certificate;
use errors::{error_response, public_error, sanitize_response};
use evmlib::common::{Amount, TxHash};
use evmlib::{EncodedPeerId, PaymentQuote, ProofOfPayment, RewardsAddress};
use futures::{stream::FuturesUnordered, StreamExt};
use parking_lot::{Mutex, RwLock};
use saorsa_core::identity::NodeIdentity;
use saorsa_core::{AddressType, DHTNode, MultiAddr, P2PNode, PeerId};
use saorsa_transport::upnp::{UpnpConfig, UpnpMappingService, UpnpState, UpnpStateRx};
use saorsa_transport::webrtc::{
    accept_pq_session, decode_pq_frame, encode_response_frame, parse_request_header,
    pq_frame_length, source_ip_bucket, BrowserCommitmentArtifact, BrowserNode,
    BrowserQuoteArtifact, BrowserRequest as Request, BrowserRequestBody as RequestBody,
    BrowserResponse as Response, BrowserResponseBody as ResponseBody,
    BrowserResponseStatus as ResponseStatus, PqSession, TransferDeadline, BROWSER_PROTOCOL_NAME,
    BROWSER_PROTOCOL_VERSION, MAX_BROWSER_FRAME_BYTES, MAX_BROWSER_HEADER_BYTES,
    PQ_CLIENT_HELLO_BYTES, PQ_ENCRYPTED_OVERHEAD_BYTES, PQ_FRAME_PREFIX_BYTES,
    WEBRTC_DIRECT_DATA_CHANNEL, WEBRTC_WRITE_CHUNK_BYTES,
};
use saorsa_transport::webrtc_direct::{
    WebRtcAdmissionLimits, WebRtcDataChannel, WebRtcDiagnostics, WebRtcDiagnosticsSnapshot,
    WebRtcDirectConnection, WebRtcDirectListener,
};
use std::collections::{HashMap, HashSet, VecDeque};
use std::future::Future;
use std::net::{IpAddr, SocketAddr};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
use tokio::sync::{watch, OwnedSemaphorePermit, Semaphore};
use tokio::task::{JoinHandle, JoinSet};
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;

const MAX_FIND_NODE_RESULTS: usize = 20;
// Advertised by HELLO. This is a protocol resource ceiling, not a throughput
// target; clients still obey their global memory/CPU admission budgets.
const MAX_CHANNEL_REQUESTS: usize = 4;
const RPC_MULTIPLEX_CAPABILITY: &str = "rpc-multiplex-4";

/// Advertised when `chunk_protocol` admits pointer reads and paid pointer
/// writes (ADR-0016), so a browser client can tell a node that would refuse
/// them from one that failed.
const POINTER_PROTOCOL_CAPABILITY: &str = "pointer_protocol";
// Browser dials use a 10-second channel-open timeout. Give successful clients
// modest server-side headroom while bounding associations that never open one.
const FIRST_DATA_CHANNEL_TIMEOUT: Duration = Duration::from_secs(15);
const REQUEST_IDLE_TIMEOUT: Duration = Duration::from_mins(1);
const SHUTDOWN_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
const ADDRESS_REFRESH_INTERVAL: Duration = Duration::from_secs(1);
/// Cadence of the `webrtc listener summary (cumulative)` INFO lines (V2-1871).
/// Matches `TRAFFIC_SUMMARY_INTERVAL_SECS` so browser-listener pressure lines
/// up with the replication and chunk-RPC summaries in fleet logs. A `const` so
/// testnets can drop it to 60s; 300s is the production default that keeps log
/// volume negligible.
const WEBRTC_SUMMARY_INTERVAL_SECS: u64 = 300;
const TRACKED_SOURCE_MULTIPLIER: usize = 4;
const MIN_TRACKED_SOURCES: usize = 64;
const CONNECTION_CAPACITY_ERROR: &str = "global connection capacity exhausted";
const SOURCE_CONNECTION_CAPACITY_ERROR: &str = "source connection capacity exhausted";
const FIRST_DATA_CHANNEL_TIMEOUT_ERROR: &str = "DataChannel opening timed out";
const CHANNEL_CAPACITY_ERROR: &str = "global DataChannel capacity exhausted";
const REQUEST_CAPACITY_ERROR: &str = "global request capacity exhausted";
const REQUEST_RATE_ERROR: &str = "request rate limit exceeded";
const GLOBAL_BYTE_CAPACITY_ERROR: &str = "global in-flight byte capacity exhausted";
const SOURCE_BYTE_CAPACITY_ERROR: &str = "source in-flight byte capacity exhausted";

/// Filename containing the node's canonical browser bootstrap address.
///
/// The file is written below the node root directory after the listener has
/// bound and is safe for deployment tooling to copy or print. Its contents are
/// public bootstrap metadata, not key material.
pub const WEBRTC_DIRECT_MULTIADDR_FILENAME: &str = "webrtc-direct.multiaddr";

/// Browser endpoints known to one or more listeners in the same process.
///
/// Only the in-process devnet supplies this catalog. Independently deployed
/// nodes discover endpoints exclusively from authenticated DHT address
/// records.
#[derive(Default)]
pub struct BrowserEndpointCatalog {
    endpoints: RwLock<HashMap<PeerId, BrowserEndpoint>>,
}

impl BrowserEndpointCatalog {
    fn insert(&self, peer_id: PeerId, endpoint: BrowserEndpoint) {
        self.endpoints.write().insert(peer_id, endpoint);
    }

    fn remove(&self, peer_id: &PeerId) {
        self.endpoints.write().remove(peer_id);
    }

    fn get(&self, peer_id: &PeerId) -> Option<BrowserEndpoint> {
        self.endpoints.read().get(peer_id).cloned()
    }
}

/// Fixed-capacity token bucket with a one-second burst allowance.
///
/// The bucket is deliberately constant-space: source churn must not turn the
/// request limiter itself into a memory-exhaustion surface.
struct RequestRateBucket {
    rate_per_second: u128,
    token_units: u128,
    last_refill: Instant,
}

impl RequestRateBucket {
    fn new(rate_per_second: usize) -> Self {
        let rate_per_second = rate_per_second as u128;
        Self {
            rate_per_second,
            token_units: rate_per_second.saturating_mul(1_000_000_000),
            last_refill: Instant::now(),
        }
    }

    fn allow(&mut self, now: Instant) -> bool {
        let elapsed = now.saturating_duration_since(self.last_refill);
        self.last_refill = now;
        let capacity = self.rate_per_second.saturating_mul(1_000_000_000);
        let refill = elapsed.as_nanos().saturating_mul(self.rate_per_second);
        self.token_units = self.token_units.saturating_add(refill).min(capacity);
        if self.token_units < 1_000_000_000 {
            return false;
        }
        self.token_units -= 1_000_000_000;
        true
    }
}

/// Atomic byte budget and an RAII reservation within it.
///
/// A custom counter is used instead of a semaphore because WebRTC frames grow
/// incrementally and the accounting must resize without queueing an unbounded
/// number of waiters.
struct ByteBudget {
    rejections: Arc<AtomicU64>,
    limit: usize,
    in_use: AtomicUsize,
}

impl ByteBudget {
    fn with_rejections(limit: usize, rejections: Arc<AtomicU64>) -> Self {
        Self {
            rejections,
            limit,
            in_use: AtomicUsize::new(0),
        }
    }

    fn try_acquire(
        self: &Arc<Self>,
        amount: usize,
        error: &'static str,
    ) -> ServerResult<ByteReservation> {
        self.in_use
            .try_update(Ordering::AcqRel, Ordering::Acquire, |current| {
                current
                    .checked_add(amount)
                    .filter(|next| *next <= self.limit)
            })
            .map_err(|_| {
                self.rejections.fetch_add(1, Ordering::Relaxed);
                error.to_string()
            })?;
        Ok(ByteReservation {
            budget: Arc::clone(self),
            amount,
            error,
        })
    }

    #[cfg(test)]
    fn in_use(&self) -> usize {
        self.in_use.load(Ordering::Acquire)
    }
}

struct ByteReservation {
    budget: Arc<ByteBudget>,
    amount: usize,
    error: &'static str,
}

impl ByteReservation {
    fn try_grow(&mut self, amount: usize) -> ServerResult<()> {
        self.budget
            .in_use
            .try_update(Ordering::AcqRel, Ordering::Acquire, |current| {
                current
                    .checked_add(amount)
                    .filter(|next| *next <= self.budget.limit)
            })
            .map_err(|_| {
                self.budget.rejections.fetch_add(1, Ordering::Relaxed);
                self.error.to_string()
            })?;
        self.amount += amount;
        Ok(())
    }

    fn shrink(&mut self, amount: usize) {
        let released = amount.min(self.amount);
        self.amount -= released;
        self.budget.in_use.fetch_sub(released, Ordering::AcqRel);
    }
}

impl Drop for ByteReservation {
    fn drop(&mut self) {
        self.budget.in_use.fetch_sub(self.amount, Ordering::AcqRel);
    }
}

struct InFlightByteReservation {
    source: ByteReservation,
    global: ByteReservation,
}

impl InFlightByteReservation {
    fn try_grow(&mut self, amount: usize) -> ServerResult<()> {
        self.source.try_grow(amount)?;
        if let Err(error) = self.global.try_grow(amount) {
            self.source.shrink(amount);
            return Err(error);
        }
        Ok(())
    }

    fn resize(&mut self, amount: usize) -> ServerResult<()> {
        if amount > self.source.amount {
            self.try_grow(amount - self.source.amount)
        } else {
            let released = self.source.amount - amount;
            self.source.shrink(released);
            self.global.shrink(released);
            Ok(())
        }
    }
}

struct TrackedBytes {
    bytes: Vec<u8>,
    reservation: InFlightByteReservation,
}

impl TrackedBytes {
    fn reserve_length(&mut self, length: usize) -> ServerResult<()> {
        self.reservation.resize(length)?;
        if self.bytes.capacity() < length {
            self.bytes.reserve_exact(length - self.bytes.len());
        }
        Ok(())
    }
}

struct SourceQuota {
    bulk_responses: Arc<Semaphore>,
    request_rate: Mutex<RequestRateBucket>,
    bytes: Arc<ByteBudget>,
}

struct SourceEntry {
    active_connections: usize,
    last_seen: Instant,
    quota: Arc<SourceQuota>,
}

#[derive(Default)]
struct SourceAdmissionState {
    sources: HashMap<IpAddr, SourceEntry>,
}

/// Saturating millisecond conversion for the listener's latency counters.
/// Mirrors `replication::audit_metrics::duration_ms`; the crate denies
/// `unwrap_used`, so the overflow case clamps rather than panicking.
fn duration_ms(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

/// Admission and accounting shared by every association on one listener.
struct ListenerResources {
    running: AtomicBool,
    connection_rejections: AtomicU64,
    channel_rejections: AtomicU64,
    request_rejections: AtomicU64,
    rate_rejections: AtomicU64,
    byte_rejections: Arc<AtomicU64>,
    listener_errors: AtomicU64,
    connection_errors: AtomicU64,
    channel_errors: AtomicU64,
    task_failures: AtomicU64,
    /// GETs that reached a response, counted where `get_service_total_ms` is added.
    get_service_count: AtomicU64,
    /// Summed GET service time, including the bulk-slot wait.
    get_service_total_ms: AtomicU64,
    /// Longest single GET service time, including the bulk-slot wait. A
    /// lifetime high-water mark: `fetch_max` only, never reset.
    get_service_max_ms: AtomicU64,
    /// GETs whose processing returned an error instead of a response.
    get_service_failures: AtomicU64,
    /// GETs that acquired both bulk-response permits.
    bulk_wait_count: AtomicU64,
    /// Summed time GETs spent waiting for their bulk-response permits.
    bulk_wait_total_ms: AtomicU64,
    /// Longest single wait for the bulk-response permits. A lifetime
    /// high-water mark: `fetch_max` only, never reset.
    bulk_wait_max_ms: AtomicU64,
    connection_limit: Arc<Semaphore>,
    channel_limit: Arc<Semaphore>,
    request_limit: Arc<Semaphore>,
    bulk_responses: Arc<Semaphore>,
    request_tasks: Mutex<TaskTracker>,
    global_request_rate: Mutex<RequestRateBucket>,
    global_bytes: Arc<ByteBudget>,
    source_state: Mutex<SourceAdmissionState>,
    max_connections_per_ip: usize,
    max_requests_per_second_per_ip: usize,
    max_requests_per_second_per_connection: usize,
    max_in_flight_bytes_per_ip: usize,
    max_tracked_sources: usize,
}

impl ListenerResources {
    fn new(config: &WebRtcDirectConfig) -> Arc<Self> {
        let byte_rejections = Arc::new(AtomicU64::new(0));
        Arc::new(Self {
            running: AtomicBool::new(false),
            connection_rejections: AtomicU64::new(0),
            channel_rejections: AtomicU64::new(0),
            request_rejections: AtomicU64::new(0),
            rate_rejections: AtomicU64::new(0),
            listener_errors: AtomicU64::new(0),
            connection_errors: AtomicU64::new(0),
            channel_errors: AtomicU64::new(0),
            task_failures: AtomicU64::new(0),
            get_service_count: AtomicU64::new(0),
            get_service_total_ms: AtomicU64::new(0),
            get_service_max_ms: AtomicU64::new(0),
            get_service_failures: AtomicU64::new(0),
            bulk_wait_count: AtomicU64::new(0),
            bulk_wait_total_ms: AtomicU64::new(0),
            bulk_wait_max_ms: AtomicU64::new(0),
            byte_rejections: Arc::clone(&byte_rejections),
            connection_limit: Arc::new(Semaphore::new(config.max_connections)),
            channel_limit: Arc::new(Semaphore::new(config.max_channels)),
            request_limit: Arc::new(Semaphore::new(config.max_concurrent_requests)),
            bulk_responses: Arc::new(Semaphore::new(bulk_response_slots(
                config.max_in_flight_bytes,
            ))),
            request_tasks: Mutex::new(TaskTracker::new()),
            global_request_rate: Mutex::new(RequestRateBucket::new(config.max_requests_per_second)),
            global_bytes: Arc::new(ByteBudget::with_rejections(
                config.max_in_flight_bytes,
                byte_rejections,
            )),
            source_state: Mutex::new(SourceAdmissionState::default()),
            max_connections_per_ip: config.max_connections_per_ip,
            max_requests_per_second_per_ip: config.max_requests_per_second_per_ip,
            max_requests_per_second_per_connection: config.max_requests_per_second_per_connection,
            max_in_flight_bytes_per_ip: config.max_in_flight_bytes_per_ip,
            max_tracked_sources: config
                .max_connections
                .saturating_mul(TRACKED_SOURCE_MULTIPLIER)
                .max(MIN_TRACKED_SOURCES),
        })
    }

    fn try_admit_connection(
        self: &Arc<Self>,
        remote_addr: SocketAddr,
    ) -> ServerResult<ConnectionAdmission> {
        self.admit_connection(remote_addr).inspect_err(|_| {
            self.connection_rejections.fetch_add(1, Ordering::Relaxed);
        })
    }

    fn admit_connection(
        self: &Arc<Self>,
        remote_addr: SocketAddr,
    ) -> ServerResult<ConnectionAdmission> {
        let global = Arc::clone(&self.connection_limit)
            .try_acquire_owned()
            .map_err(|_| CONNECTION_CAPACITY_ERROR.to_string())?;
        let ip = source_ip_bucket(remote_addr.ip());
        let source = {
            let mut state = self.source_state.lock();
            if !state.sources.contains_key(&ip) && state.sources.len() >= self.max_tracked_sources {
                let eviction = state
                    .sources
                    .iter()
                    .filter(|(_, entry)| {
                        entry.active_connections == 0
                            && Arc::strong_count(&entry.quota) == 1
                            && entry.quota.bytes.in_use.load(Ordering::Acquire) == 0
                    })
                    .min_by_key(|(_, entry)| entry.last_seen)
                    .map(|(ip, _)| *ip);
                let Some(eviction) = eviction else {
                    return Err(CONNECTION_CAPACITY_ERROR.to_string());
                };
                state.sources.remove(&eviction);
            }

            let entry = state.sources.entry(ip).or_insert_with(|| SourceEntry {
                active_connections: 0,
                last_seen: Instant::now(),
                quota: Arc::new(SourceQuota {
                    bulk_responses: Arc::new(Semaphore::new(bulk_response_slots(
                        self.max_in_flight_bytes_per_ip,
                    ))),
                    request_rate: Mutex::new(RequestRateBucket::new(
                        self.max_requests_per_second_per_ip,
                    )),
                    bytes: Arc::new(ByteBudget::with_rejections(
                        self.max_in_flight_bytes_per_ip,
                        Arc::clone(&self.byte_rejections),
                    )),
                }),
            });
            if entry.active_connections >= self.max_connections_per_ip {
                return Err(SOURCE_CONNECTION_CAPACITY_ERROR.to_string());
            }
            entry.active_connections += 1;
            entry.last_seen = Instant::now();
            Arc::clone(&entry.quota)
        };
        let context = Arc::new(ConnectionResources {
            listener: Arc::clone(self),
            source,
            request_rate: Mutex::new(RequestRateBucket::new(
                self.max_requests_per_second_per_connection,
            )),
        });
        Ok(ConnectionAdmission {
            listener: Arc::clone(self),
            ip,
            context,
            _global: global,
        })
    }

    fn release_connection(&self, ip: IpAddr) {
        let mut state = self.source_state.lock();
        if let Some(entry) = state.sources.get_mut(&ip) {
            entry.active_connections = entry.active_connections.saturating_sub(1);
            entry.last_seen = Instant::now();
        }
    }

    /// Record how long one GET waited for both bulk-response permits.
    fn record_bulk_wait(&self, waited: Duration) {
        let waited = duration_ms(waited);
        self.bulk_wait_count.fetch_add(1, Ordering::Relaxed);
        self.bulk_wait_total_ms.fetch_add(waited, Ordering::Relaxed);
        self.bulk_wait_max_ms.fetch_max(waited, Ordering::Relaxed);
    }

    /// Record one GET's service time: from the spawned request worker starting
    /// to its response being prepared. Includes the bulk-slot wait recorded by
    /// [`Self::record_bulk_wait`], and excludes admission, frame assembly and
    /// decryption, which all finish before the worker is spawned.
    fn record_get_service(&self, served: Duration) {
        let served = duration_ms(served);
        self.get_service_count.fetch_add(1, Ordering::Relaxed);
        self.get_service_total_ms
            .fetch_add(served, Ordering::Relaxed);
        self.get_service_max_ms.fetch_max(served, Ordering::Relaxed);
    }

    fn spawn_request<F>(&self, work: F) -> ServerResult<JoinHandle<F::Output>>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        // TaskTracker::close alone does not prevent spawning. Serialize these
        // steps so a channel still unwinding after abort cannot register work
        // after shutdown observed an empty tracker and returned.
        let tracker = self.request_tasks.lock();
        if tracker.is_closed() {
            return Err("browser listener is shutting down".to_string());
        }
        Ok(tracker.spawn(work))
    }

    async fn drain_requests(&self) {
        let tracker = {
            let tracker = self.request_tasks.lock();
            tracker.close();
            tracker.clone()
        };
        tracker.wait().await;
    }
}

struct ConnectionResources {
    listener: Arc<ListenerResources>,
    source: Arc<SourceQuota>,
    request_rate: Mutex<RequestRateBucket>,
}

impl ConnectionResources {
    fn try_admit_request(&self) -> ServerResult<OwnedSemaphorePermit> {
        let permit = Arc::clone(&self.listener.request_limit)
            .try_acquire_owned()
            .map_err(|_| {
                self.listener
                    .request_rejections
                    .fetch_add(1, Ordering::Relaxed);
                REQUEST_CAPACITY_ERROR.to_string()
            })?;
        let now = Instant::now();
        if !self.source.request_rate.lock().allow(now)
            || !self.request_rate.lock().allow(now)
            || !self.listener.global_request_rate.lock().allow(now)
        {
            self.listener
                .rate_rejections
                .fetch_add(1, Ordering::Relaxed);
            return Err(REQUEST_RATE_ERROR.to_string());
        }
        Ok(permit)
    }

    fn try_reserve_bytes(&self, amount: usize) -> ServerResult<InFlightByteReservation> {
        let source = self
            .source
            .bytes
            .try_acquire(amount, SOURCE_BYTE_CAPACITY_ERROR)?;
        let global = self
            .listener
            .global_bytes
            .try_acquire(amount, GLOBAL_BYTE_CAPACITY_ERROR)?;
        Ok(InFlightByteReservation { source, global })
    }
}

struct ConnectionAdmission {
    listener: Arc<ListenerResources>,
    ip: IpAddr,
    context: Arc<ConnectionResources>,
    _global: OwnedSemaphorePermit,
}

impl Drop for ConnectionAdmission {
    fn drop(&mut self) {
        self.listener.release_connection(self.ip);
    }
}

/// Internal browser-listener diagnostics, sampled without network I/O.
#[derive(Clone, Debug)]
pub struct WebRtcServerSnapshot {
    /// Bound local UDP socket.
    pub local_addr: SocketAddr,
    /// Both accept loop and UDP driver are alive; no external probe is implied.
    pub running: bool,
    /// Transport connection lifecycle and `DataChannel` traffic counters.
    pub transport: WebRtcDiagnosticsSnapshot,
    /// Application connection slots currently held, including setup.
    pub active_connections: usize,
    /// Configured application connection capacity.
    pub max_connections: usize,
    /// `DataChannel` handler slots currently held.
    pub active_channels: usize,
    /// Configured `DataChannel` handler capacity.
    pub max_channels: usize,
    /// Request permits held during frame assembly, processing and response sends.
    /// Includes started requests whose browser has disconnected.
    pub active_requests: usize,
    /// Configured concurrent request capacity.
    pub max_concurrent_requests: usize,
    /// Request and response bytes reserved, including disconnected disk work.
    pub in_flight_bytes: usize,
    /// Configured frame-memory capacity.
    pub max_in_flight_bytes: usize,
    /// Global bulk-response preparation slots currently held by GETs.
    pub bulk_slots_in_use: usize,
    /// Global bulk-response preparation slots derived from `max_in_flight_bytes`.
    pub bulk_slots_max: usize,
    /// Application connection admissions denied by capacity policy.
    pub connection_rejections: u64,
    /// `DataChannels` rejected by global or per-connection capacity policy.
    pub channel_rejections: u64,
    /// Requests rejected because all worker permits are in use.
    pub request_rejections: u64,
    /// Requests rejected by a global, source, or association rate limit.
    pub rate_rejections: u64,
    /// Failed frame-memory reservations, including buffer growth.
    pub byte_rejections: u64,
    /// Transport accept errors observed by the application listener.
    pub listener_errors: u64,
    /// Connection handlers that returned an error.
    pub connection_errors: u64,
    /// `DataChannel` handlers that returned an error, including PQ setup failures.
    pub channel_errors: u64,
    /// Connection or `DataChannel` tasks that panicked or were unexpectedly cancelled.
    pub task_failures: u64,
    /// GETs served to a response, the denominator for `get_service_total_ms`.
    pub get_service_count: u64,
    /// Summed GET service time, measured from the spawned request worker
    /// starting to its response being prepared. Includes the bulk-response
    /// slot wait; excludes admission, frame assembly and decryption, which
    /// complete before the worker is spawned.
    pub get_service_total_ms: u64,
    /// Longest single GET service time, including the bulk-response slot
    /// wait. A lifetime high-water mark: never reset, so it only rises. Do
    /// not diff it — use the mean from `get_service_total_ms` over
    /// `get_service_count` to see a window's latency.
    pub get_service_max_ms: u64,
    /// GETs whose processing returned an error instead of a response. They are
    /// excluded from `get_service_count` and the service-time totals.
    pub get_service_failures: u64,
    /// GETs that acquired both bulk-response permits, the denominator for
    /// `bulk_wait_total_ms`.
    pub bulk_wait_count: u64,
    /// Summed time GETs spent waiting for their source and global
    /// bulk-response permits.
    pub bulk_wait_total_ms: u64,
    /// Longest single wait for the bulk-response permits. A lifetime
    /// high-water mark like `get_service_max_ms`, with the same caveat.
    pub bulk_wait_max_ms: u64,
}

/// Cloneable diagnostics handle for a running or stopped browser listener.
#[derive(Clone)]
pub struct WebRtcServerDiagnostics {
    local_addr: SocketAddr,
    transport: WebRtcDiagnostics,
    resources: Arc<ListenerResources>,
    config: WebRtcDirectConfig,
}

impl WebRtcServerDiagnostics {
    /// Sample listener state, lifecycle counts, traffic, and resource pressure.
    pub fn snapshot(&self) -> WebRtcServerSnapshot {
        let resources = &self.resources;
        let transport = self.transport.snapshot();
        WebRtcServerSnapshot {
            local_addr: self.local_addr,
            running: resources.running.load(Ordering::Acquire) && transport.running,
            transport,
            active_connections: self
                .config
                .max_connections
                .saturating_sub(resources.connection_limit.available_permits()),
            max_connections: self.config.max_connections,
            active_channels: self
                .config
                .max_channels
                .saturating_sub(resources.channel_limit.available_permits()),
            max_channels: self.config.max_channels,
            active_requests: self
                .config
                .max_concurrent_requests
                .saturating_sub(resources.request_limit.available_permits()),
            max_concurrent_requests: self.config.max_concurrent_requests,
            in_flight_bytes: resources.global_bytes.in_use.load(Ordering::Acquire),
            max_in_flight_bytes: self.config.max_in_flight_bytes,
            bulk_slots_in_use: bulk_response_slots(self.config.max_in_flight_bytes)
                .saturating_sub(resources.bulk_responses.available_permits()),
            bulk_slots_max: bulk_response_slots(self.config.max_in_flight_bytes),
            connection_rejections: resources.connection_rejections.load(Ordering::Relaxed),
            channel_rejections: resources.channel_rejections.load(Ordering::Relaxed),
            request_rejections: resources.request_rejections.load(Ordering::Relaxed),
            rate_rejections: resources.rate_rejections.load(Ordering::Relaxed),
            byte_rejections: resources.byte_rejections.load(Ordering::Relaxed),
            listener_errors: resources.listener_errors.load(Ordering::Relaxed),
            connection_errors: resources.connection_errors.load(Ordering::Relaxed),
            channel_errors: resources.channel_errors.load(Ordering::Relaxed),
            task_failures: resources.task_failures.load(Ordering::Relaxed),
            get_service_count: resources.get_service_count.load(Ordering::Relaxed),
            get_service_total_ms: resources.get_service_total_ms.load(Ordering::Relaxed),
            get_service_max_ms: resources.get_service_max_ms.load(Ordering::Relaxed),
            get_service_failures: resources.get_service_failures.load(Ordering::Relaxed),
            bulk_wait_count: resources.bulk_wait_count.load(Ordering::Relaxed),
            bulk_wait_total_ms: resources.bulk_wait_total_ms.load(Ordering::Relaxed),
            bulk_wait_max_ms: resources.bulk_wait_max_ms.load(Ordering::Relaxed),
        }
    }

    /// Emit the browser listener's state as INFO summary lines, target
    /// `ant_node::web_rtc::traffic`, message `webrtc listener summary
    /// (cumulative)`.
    ///
    /// Flat snake-case integer keys like the storage and replication
    /// summaries. Two lines sharing the same target and message, told apart by
    /// `group`: the application listener (`group = 1`) and the WebRTC
    /// transport beneath it (`group = 2`, each key prefixed `transport_`), so
    /// neither line approaches `tracing`'s 32-field cap.
    ///
    /// The fields fall into four classes, and only one of them may be
    /// differenced. Field names are a query contract and are never renamed.
    ///
    /// * **Additive counters**, accumulated since process start: the rejection
    ///   and error counts, `get_service_count`, `get_service_total_ms`,
    ///   `get_service_failures`, `bulk_wait_count`, `bulk_wait_total_ms`, and
    ///   every `transport_` field except the two active/connecting gauges.
    ///   Diff two lines for a rate; mean GET latency over an interval is the
    ///   `get_service_total_ms` diff over the `get_service_count` diff.
    /// * **Instantaneous gauges**, sampled at emission and not cumulative:
    ///   `running`, `active_connections`, `active_channels`,
    ///   `active_requests`, `in_flight_bytes`, `bulk_slots_in_use`,
    ///   `transport_active_connections` and
    ///   `transport_connecting_connections`. Differencing these is
    ///   meaningless; read the level, or average it over the window.
    /// * **Lifetime maxima**: `get_service_max_ms` and `bulk_wait_max_ms` are
    ///   high-water marks that are never reset, so they rise and never fall.
    ///   A diff of either is 0 whenever the window's worst case did not beat
    ///   the all-time worst case, which hides sustained high latency — watch
    ///   the mean from the counters above for that, and read these two as the
    ///   worst case seen since start.
    /// * **Configured capacities**, constant for the process:
    ///   `max_connections`, `max_channels`, `max_concurrent_requests`,
    ///   `max_in_flight_bytes` and `bulk_slots_max`. They are emitted so a
    ///   gauge can be read as a fraction of its limit.
    pub fn log_webrtc_listener_summary(&self) {
        let snapshot = self.snapshot();
        let transport = &snapshot.transport;

        crate::logging::info!(
            target: "ant_node::web_rtc::traffic",
            group = 1,
            running = u64::from(snapshot.running),
            active_connections = snapshot.active_connections as u64,
            max_connections = snapshot.max_connections as u64,
            active_channels = snapshot.active_channels as u64,
            max_channels = snapshot.max_channels as u64,
            active_requests = snapshot.active_requests as u64,
            max_concurrent_requests = snapshot.max_concurrent_requests as u64,
            in_flight_bytes = snapshot.in_flight_bytes as u64,
            max_in_flight_bytes = snapshot.max_in_flight_bytes as u64,
            bulk_slots_in_use = snapshot.bulk_slots_in_use as u64,
            bulk_slots_max = snapshot.bulk_slots_max as u64,
            connection_rejections = snapshot.connection_rejections,
            channel_rejections = snapshot.channel_rejections,
            request_rejections = snapshot.request_rejections,
            rate_rejections = snapshot.rate_rejections,
            byte_rejections = snapshot.byte_rejections,
            listener_errors = snapshot.listener_errors,
            connection_errors = snapshot.connection_errors,
            channel_errors = snapshot.channel_errors,
            task_failures = snapshot.task_failures,
            get_service_count = snapshot.get_service_count,
            get_service_total_ms = snapshot.get_service_total_ms,
            get_service_max_ms = snapshot.get_service_max_ms,
            get_service_failures = snapshot.get_service_failures,
            bulk_wait_count = snapshot.bulk_wait_count,
            bulk_wait_total_ms = snapshot.bulk_wait_total_ms,
            bulk_wait_max_ms = snapshot.bulk_wait_max_ms,
            "webrtc listener summary (cumulative)"
        );

        crate::logging::info!(
            target: "ant_node::web_rtc::traffic",
            group = 2,
            transport_active_connections = transport.active_connections as u64,
            transport_connecting_connections = transport.connecting_connections as u64,
            transport_connection_attempts = transport.connection_attempts,
            transport_successful_connections = transport.successful_connections,
            transport_failed_connections = transport.failed_connections,
            transport_closed_connections = transport.closed_connections,
            transport_disconnections = transport.disconnections,
            transport_rejected_connections = transport.rejected_connections,
            transport_listener_errors = transport.listener_errors,
            transport_bytes_sent = transport.bytes_sent,
            transport_bytes_received = transport.bytes_received,
            "webrtc listener summary (cumulative)"
        );
    }
}

struct ListenerRunGuard(Arc<ListenerResources>);

impl Drop for ListenerRunGuard {
    fn drop(&mut self) {
        self.0.running.store(false, Ordering::Release);
    }
}

/// A running browser listener and the endpoint clients use to reach it.
pub struct WebRtcDirectServer {
    /// Local health, traffic, lifecycle, and admission diagnostics.
    pub diagnostics: WebRtcServerDiagnostics,
    /// Initial endpoint, absent until native address discovery yields a usable IP.
    /// Later updates are published through the DHT and the endpoint file.
    pub endpoint: Option<BrowserEndpoint>,
    /// Listener background task.
    pub task: JoinHandle<()>,
}

/// Start the feature-gated browser listener and return its endpoint and task.
pub async fn spawn(
    config: &WebRtcDirectConfig,
    root_dir: &Path,
    p2p: Arc<P2PNode>,
    ant_protocol: Option<Arc<AntProtocol>>,
    evm_network: &evmlib::Network,
    shutdown: CancellationToken,
    endpoint_catalog: Option<Arc<BrowserEndpointCatalog>>,
) -> Result<WebRtcDirectServer> {
    validate_webrtc_config(config)?;
    let payment = browser_payment_network(evm_network).await?;
    let certificate_path = certificate_path(config, root_dir);
    let certificate = load_or_generate_certificate(&certificate_path).await?;
    let certificate_sha256 = certificate
        .sha256_digest()
        .map_err(|error| Error::Startup(error.to_string()))?;
    let listener = WebRtcDirectListener::bind_with_limits(
        config.bind,
        certificate,
        WebRtcAdmissionLimits {
            max_connections: config.max_connections,
            max_connections_per_ip: config.max_connections_per_ip,
        },
    )
    .await
    .map_err(|error| Error::Startup(format!("failed to bind WebRTC Direct listener: {error}")))?;
    let local_addr = listener.local_addr();
    // Like the native QUIC endpoint, ask the gateway to forward the listener's
    // port. Best effort: without a mapping, publication is unchanged (ADR-0027).
    let upnp = maps_port_with_upnp(config, local_addr, p2p.config().local)
        .then(|| UpnpMappingService::start(local_addr.port(), UpnpConfig::default()));
    let identity = Arc::clone(p2p.transport().node_identity());
    let state = Arc::new(ServerState {
        config: config.clone(),
        identity,
        p2p,
        ant_protocol,
        payment,
        publication: RwLock::new(Publication::default()),
        endpoint_catalog,
        port_mapping: upnp
            .as_ref()
            .map(|service| Box::new(service.subscribe()) as Box<dyn PortMapping>),
    });
    refresh_browser_endpoint(&state, root_dir, local_addr, certificate_sha256).await?;
    let browser_endpoint = state.publication.read().endpoint().cloned();
    if browser_endpoint.is_none() {
        // Do not leave a previous run's socket advertised while discovery is pending.
        remove_persisted_browser_endpoint(root_dir).await?;
    }
    let resources = ListenerResources::new(config);
    let diagnostics = WebRtcServerDiagnostics {
        local_addr,
        transport: listener.diagnostics(),
        resources: Arc::clone(&resources),
        config: config.clone(),
    };
    resources.running.store(true, Ordering::Release);
    let run_guard = ListenerRunGuard(Arc::clone(&resources));
    info!(bind = %local_addr, certificate = %certificate_path.display(),
        "ADR-0015 WebRTC Direct listening");
    let root_dir = root_dir.to_path_buf();
    let summary_diagnostics = diagnostics.clone();
    let task = tokio::spawn(async move {
        // All three futures are owned by the listener task. Neither address
        // publication nor the diagnostics summary can block accepting sessions,
        // and shutdown cancels a pending publication.
        tokio::join!(
            serve_webrtc(
                listener,
                Arc::clone(&state),
                resources,
                shutdown.clone(),
                run_guard
            ),
            refresh_browser_endpoint_loop(
                state,
                root_dir,
                local_addr,
                certificate_sha256,
                shutdown.clone(),
            ),
            log_listener_summaries(summary_diagnostics, shutdown.clone()),
        );
        // Remove the gateway mapping rather than leave it to its lease.
        if let Some(upnp) = upnp {
            upnp.shutdown().await;
        }
    });
    Ok(WebRtcDirectServer {
        diagnostics,
        endpoint: browser_endpoint,
        task,
    })
}

/// Republish the listener's advertised address every
/// `ADDRESS_REFRESH_INTERVAL` until shutdown.
///
/// Owned by the listener task so publication cannot block accepting sessions,
/// and shutdown cancels a pending publication.
async fn refresh_browser_endpoint_loop(
    state: Arc<ServerState>,
    root_dir: PathBuf,
    local_addr: SocketAddr,
    certificate_sha256: [u8; 32],
    shutdown: CancellationToken,
) {
    let refresh = async {
        let mut interval = tokio::time::interval(ADDRESS_REFRESH_INTERVAL);
        loop {
            interval.tick().await;
            if let Err(error) =
                refresh_browser_endpoint(&state, &root_dir, local_addr, certificate_sha256).await
            {
                warn!(%error, "Failed to update WebRTC Direct endpoint");
            }
        }
    };
    tokio::select! {
        () = shutdown.cancelled() => {},
        () = refresh => {},
    }
}

/// Emit the browser listener summary every `WEBRTC_SUMMARY_INTERVAL_SECS`
/// until shutdown.
///
/// Sampling only reads atomics and semaphore permit counts, so this loop never
/// holds a lock across an await and never blocks the accept loop or a request
/// worker.
async fn log_listener_summaries(diagnostics: WebRtcServerDiagnostics, shutdown: CancellationToken) {
    loop {
        tokio::select! {
            () = shutdown.cancelled() => break,
            () = tokio::time::sleep(Duration::from_secs(WEBRTC_SUMMARY_INTERVAL_SECS)) => {
                diagnostics.log_webrtc_listener_summary();
            }
        }
    }
    debug!("WebRTC Direct listener summary loop shut down");
}

async fn refresh_browser_endpoint(
    state: &ServerState,
    root_dir: &Path,
    local_addr: SocketAddr,
    certificate_sha256: [u8; 32],
) -> Result<()> {
    let native = state
        .p2p
        .dht_manager()
        .local_dht_node()
        .await
        .typed_addresses();
    let mapped = state
        .port_mapping
        .as_ref()
        .and_then(|mapping| mapping.external());
    let Some((address, source)) = advertised_addr(&state.config, local_addr, mapped, &native)
    else {
        // As with native publication, keep the last nonempty address set,
        // unless it came from a mapping the gateway no longer holds.
        return withdraw_mapped_endpoint(state, root_dir).await;
    };
    let peer_id = *state.p2p.peer_id();
    let endpoint = BrowserEndpoint::new(address, peer_id.to_bytes(), certificate_sha256)
        .map_err(|error| Error::Config(error.to_string()))?;
    if state.publication.write().reconfirm(&endpoint, source) {
        return Ok(());
    }
    let supplemental = endpoint
        .multiaddr
        .parse()
        .map_err(|error| Error::Startup(format!("invalid WebRTC transport address: {error}")))?;
    persist_browser_endpoint(root_dir, &endpoint).await?;
    if let Some(catalog) = state.endpoint_catalog.as_ref() {
        catalog.insert(peer_id, endpoint.clone());
    }
    *state.publication.write() = Publication::Published { endpoint, source };
    state
        .p2p
        .dht_manager()
        .set_supplemental_self_addresses(vec![supplemental])
        .await;
    Ok(())
}

/// Withdraw an endpoint whose address only a gateway mapping that has ended
/// provided, everywhere it was published: HELLO, the in-process catalog and
/// the DHT address record first, once, then the endpoint file. Any other
/// publication is kept.
///
/// The first three cannot fail, so a file error never keeps the endpoint
/// advertised. It leaves the publication [`Publication::Withdrawing`], and the
/// next call retries only the file.
async fn withdraw_mapped_endpoint(state: &ServerState, root_dir: &Path) -> Result<()> {
    let withdrawn = state.publication.write().begin_withdrawal();
    if let Some(withdrawn) = withdrawn {
        info!(endpoint = %withdrawn.multiaddr,
            "WebRTC Direct endpoint withdrawn: its gateway mapping ended");
        if let Some(catalog) = state.endpoint_catalog.as_ref() {
            catalog.remove(state.p2p.peer_id());
        }
        state
            .p2p
            .dht_manager()
            .set_supplemental_self_addresses(Vec::new())
            .await;
    }
    if *state.publication.read() != Publication::Withdrawing {
        return Ok(());
    }
    remove_persisted_browser_endpoint(root_dir).await?;
    *state.publication.write() = Publication::Unpublished;
    Ok(())
}

async fn remove_persisted_browser_endpoint(root_dir: &Path) -> Result<()> {
    let path = root_dir.join(WEBRTC_DIRECT_MULTIADDR_FILENAME);
    match tokio::fs::remove_file(&path).await {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(Error::Startup(format!(
            "failed to remove WebRTC Direct endpoint {}: {error}",
            path.display()
        ))),
    }
}

async fn persist_browser_endpoint(root_dir: &Path, endpoint: &BrowserEndpoint) -> Result<()> {
    let path = root_dir.join(WEBRTC_DIRECT_MULTIADDR_FILENAME);
    let contents = format!("{}\n", endpoint.multiaddr);
    tokio::fs::write(&path, contents).await.map_err(|error| {
        Error::Startup(format!(
            "failed to write WebRTC Direct endpoint {}: {error}",
            path.display()
        ))
    })
}

fn validate_webrtc_config(config: &WebRtcDirectConfig) -> Result<()> {
    for (name, value) in [
        ("max_connections", config.max_connections),
        ("max_connections_per_ip", config.max_connections_per_ip),
        (
            "max_channels_per_connection",
            config.max_channels_per_connection,
        ),
        ("max_channels", config.max_channels),
        ("max_concurrent_requests", config.max_concurrent_requests),
    ] {
        if value == 0 || value > Semaphore::MAX_PERMITS {
            return Err(Error::Config(format!(
                "webrtc_direct.{name} must be between 1 and {}",
                Semaphore::MAX_PERMITS
            )));
        }
    }
    for (name, value) in [
        ("max_requests_per_second", config.max_requests_per_second),
        (
            "max_requests_per_second_per_ip",
            config.max_requests_per_second_per_ip,
        ),
        (
            "max_requests_per_second_per_connection",
            config.max_requests_per_second_per_connection,
        ),
        ("max_in_flight_bytes", config.max_in_flight_bytes),
        (
            "max_in_flight_bytes_per_ip",
            config.max_in_flight_bytes_per_ip,
        ),
    ] {
        if value == 0 {
            return Err(Error::Config(format!(
                "webrtc_direct.{name} must be greater than zero"
            )));
        }
    }
    if config.max_connections_per_ip >= config.max_connections {
        return Err(Error::Config(
            "webrtc_direct.max_connections_per_ip must be lower than max_connections".to_string(),
        ));
    }
    let source_channel_ceiling = config
        .max_connections_per_ip
        .checked_mul(config.max_channels_per_connection)
        .ok_or_else(|| {
            Error::Config("webrtc_direct per-IP DataChannel ceiling overflows usize".to_string())
        })?;
    if source_channel_ceiling >= config.max_channels {
        return Err(Error::Config(
            "webrtc_direct max_connections_per_ip * max_channels_per_connection must be lower than max_channels"
                .to_string(),
        ));
    }
    if source_channel_ceiling >= config.max_concurrent_requests {
        return Err(Error::Config(
            "webrtc_direct max_connections_per_ip * max_channels_per_connection must be lower than max_concurrent_requests"
                .to_string(),
        ));
    }
    if config.max_requests_per_second_per_connection > config.max_requests_per_second_per_ip {
        return Err(Error::Config(
            "webrtc_direct.max_requests_per_second_per_connection must not exceed max_requests_per_second_per_ip"
                .to_string(),
        ));
    }
    if config.max_requests_per_second_per_ip >= config.max_requests_per_second {
        return Err(Error::Config(
            "webrtc_direct.max_requests_per_second_per_ip must be lower than max_requests_per_second"
                .to_string(),
        ));
    }
    if config.max_in_flight_bytes_per_ip >= config.max_in_flight_bytes {
        return Err(Error::Config(
            "webrtc_direct.max_in_flight_bytes_per_ip must be lower than max_in_flight_bytes"
                .to_string(),
        ));
    }
    if config.advertised_addr.is_some_and(|addr| addr.port() == 0) {
        return Err(Error::Config(
            "webrtc_direct.advertised_addr must not use port zero".to_string(),
        ));
    }
    Ok(())
}

fn certificate_path(config: &WebRtcDirectConfig, root_dir: &Path) -> PathBuf {
    match config.certificate_path.as_ref() {
        Some(path) if path.is_absolute() => path.clone(),
        Some(path) => root_dir.join(path),
        None => root_dir.join("webrtc-direct.pem"),
    }
}

/// Whether the listener chooses its own public address, and so may ask the
/// gateway to forward its port: a wildcard IPv4 listener the operator gave no
/// advertised address, on a node whose native endpoint is not confined to
/// loopback.
///
/// An explicit bind or advertisement is the operator's. A loopback-only
/// (development) node stays off the Internet, and its browsers dial the
/// native loopback view. Gateway mappings are IPv4, which an IPv6 listener
/// would not advertise.
fn maps_port_with_upnp(
    config: &WebRtcDirectConfig,
    local_addr: SocketAddr,
    loopback_only: bool,
) -> bool {
    !loopback_only
        && config.advertised_addr.is_none()
        && local_addr.ip().is_unspecified()
        && local_addr.is_ipv4()
}

/// The gateway's mapping of the listener's port, while it holds one.
trait PortMapping: Send + Sync {
    fn external(&self) -> Option<SocketAddr>;
}

impl PortMapping for UpnpStateRx {
    fn external(&self) -> Option<SocketAddr> {
        match self.current() {
            UpnpState::Mapped { external, .. } => Some(external),
            UpnpState::Probing | UpnpState::Unavailable => None,
        }
    }
}

/// Where an advertised browser address came from, in order of precedence.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AddressSource {
    /// The operator's `advertised_addr`.
    Operator,
    /// An explicit bind address.
    Bind,
    /// The gateway's mapping of the listener's port, which the native view
    /// does not yield. It is valid only while the gateway holds the mapping.
    Mapped,
    /// The native self-address view's IP with the listener's port.
    Native,
}

/// What the listener advertises to browsers.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
enum Publication {
    /// Nothing: no address is known yet, or a mapped endpoint was withdrawn.
    #[default]
    Unpublished,
    /// The endpoint browsers dial, and where its address came from.
    Published {
        endpoint: BrowserEndpoint,
        source: AddressSource,
    },
    /// A mapped endpoint was withdrawn from peers, but its endpoint file is
    /// not removed yet.
    Withdrawing,
}

impl Publication {
    fn endpoint(&self) -> Option<&BrowserEndpoint> {
        match self {
            Self::Published { endpoint, .. } => Some(endpoint),
            Self::Unpublished | Self::Withdrawing => None,
        }
    }

    /// Whether `endpoint` is already published, recording `source` for it if
    /// so: the same address may come from another source than before.
    fn reconfirm(&mut self, endpoint: &BrowserEndpoint, source: AddressSource) -> bool {
        match self {
            Self::Published {
                endpoint: published,
                source: published_source,
            } if published == endpoint => {
                *published_source = source;
                true
            }
            Self::Published { .. } | Self::Unpublished | Self::Withdrawing => false,
        }
    }

    /// Start withdrawing a mapped endpoint, returning it. Any other
    /// publication is kept, and `None` returned.
    fn begin_withdrawal(&mut self) -> Option<BrowserEndpoint> {
        match std::mem::take(self) {
            Self::Published {
                endpoint,
                source: AddressSource::Mapped,
            } => {
                *self = Self::Withdrawing;
                Some(endpoint)
            }
            kept => {
                *self = kept;
                None
            }
        }
    }
}

/// The address browsers dial and its source: the operator's advertisement, an
/// explicit bind, the gateway's mapping of the listener's port (`mapped`), or
/// else the native self-address view's IP with the listener's port.
fn advertised_addr(
    config: &WebRtcDirectConfig,
    local_addr: SocketAddr,
    mapped: Option<SocketAddr>,
    native_addresses: &[(MultiAddr, AddressType)],
) -> Option<(SocketAddr, AddressSource)> {
    if let Some(addr) = config.advertised_addr {
        return Some((addr, AddressSource::Operator));
    }
    if !local_addr.ip().is_unspecified() {
        return Some((local_addr, AddressSource::Bind));
    }
    // The native self-address view already applies observation, scope and
    // priority policy. Relay sockets belong to the relay, not this listener.
    let native = native_addresses
        .iter()
        .filter(|(_, kind)| *kind != AddressType::Relay)
        .filter_map(|(address, _)| address.socket_addr())
        .find(|addr| addr.is_ipv4() == local_addr.is_ipv4())
        .map(|addr| SocketAddr::new(addr.ip(), local_addr.port()));
    // Behind NAT the gateway drops unsolicited traffic to the listener's own
    // port, so the address it forwards is the one browsers can reach. When
    // the native view yields that same address, it does not need the mapping.
    match mapped.filter(|addr| addr.is_ipv4() == local_addr.is_ipv4()) {
        Some(mapped) if native != Some(mapped) => Some((mapped, AddressSource::Mapped)),
        _ => native.map(|addr| (addr, AddressSource::Native)),
    }
}

#[allow(clippy::significant_drop_tightening)]
async fn serve_webrtc(
    mut listener: WebRtcDirectListener,
    state: Arc<ServerState>,
    resources: Arc<ListenerResources>,
    shutdown: CancellationToken,
    _run_guard: ListenerRunGuard,
) {
    let mut connection_tasks = JoinSet::new();
    loop {
        let connection = tokio::select! {
            biased;
            () = shutdown.cancelled() => break,
            completed = connection_tasks.join_next(), if !connection_tasks.is_empty() => {
                if let Some(Err(error)) = completed {
                    resources.task_failures.fetch_add(1, Ordering::Relaxed);
                    warn!(%error, "WebRTC Direct connection task failed");
                }
                continue;
            }
            // Do not perform another ICE/DTLS/SCTP accept while every
            // application connection slot is occupied. The transport's
            // pending-association queue remains bounded, and completed
            // sessions release a permit before this branch becomes eligible.
            connection = listener.accept(), if resources.connection_limit.available_permits() > 0 => connection,
        };
        match connection {
            Ok(connection) => {
                let remote_addr = connection.remote_addr();
                let admission = match resources.try_admit_connection(remote_addr) {
                    Ok(admission) => admission,
                    Err(error) => {
                        debug!(remote = %remote_addr, %error, "Rejected WebRTC Direct connection");
                        if let Err(close_error) = connection.close().await {
                            debug!(remote = %remote_addr, %close_error, "Failed to close rejected connection");
                        }
                        continue;
                    }
                };
                let connection_resources = Arc::clone(&admission.context);
                let connection_state = Arc::clone(&state);
                let connection_shutdown = shutdown.clone();
                let diagnostic_resources = Arc::clone(&resources);
                connection_tasks.spawn(async move {
                    let _admission = admission;
                    if let Err(error) = handle_connection(
                        connection,
                        connection_state,
                        connection_resources,
                        connection_shutdown,
                    )
                    .await
                    {
                        diagnostic_resources
                            .connection_errors
                            .fetch_add(1, Ordering::Relaxed);
                        debug!(remote = %remote_addr, "WebRTC Direct connection ended: {error}");
                    }
                });
            }
            Err(error) => {
                resources.listener_errors.fetch_add(1, Ordering::Relaxed);
                warn!("WebRTC Direct listener error: {error}");
                if matches!(
                    error,
                    saorsa_transport::webrtc_direct::WebRtcDirectError::Closed
                ) {
                    break;
                }
            }
        }
    }
    if let Err(error) = listener.close().await {
        debug!("WebRTC Direct listener close failed: {error}");
    }
    let drained = tokio::time::timeout(SHUTDOWN_DRAIN_TIMEOUT, async {
        while let Some(result) = connection_tasks.join_next().await {
            if let Err(error) = result {
                debug!(%error, "WebRTC Direct connection task failed during shutdown");
            }
        }
    })
    .await;
    if drained.is_err() {
        warn!("WebRTC Direct connection tasks did not drain before shutdown deadline");
        connection_tasks.abort_all();
        while connection_tasks.join_next().await.is_some() {}
    }
    // Connection tasks may be cancelled, but started requests own their permits
    // until the storage/payment handler returns. Never abort these workers: a
    // blocking disk operation can outlive its async caller.
    resources.drain_requests().await;
    info!("ADR-0015 WebRTC Direct stopped");
}

async fn handle_connection(
    mut connection: WebRtcDirectConnection,
    state: Arc<ServerState>,
    resources: Arc<ConnectionResources>,
    shutdown: CancellationToken,
) -> ServerResult<()> {
    let remote_addr = connection.remote_addr();
    let channel_shutdown = shutdown.child_token();
    let mut channel_tasks = JoinSet::new();

    let outcome = 'connection: {
        let first_channel =
            match wait_for_first_data_channel(&shutdown, FIRST_DATA_CHANNEL_TIMEOUT, async {
                connection
                    .accept_data_channel()
                    .await
                    .map_err(|error| format!("DataChannel accept failed: {error}"))
            })
            .await
            {
                Ok(Some(channel)) => channel,
                Ok(None) => break 'connection Ok(()),
                Err(error) => break 'connection Err(error),
            };
        if let Err(error) = start_data_channel_task(
            first_channel,
            &mut channel_tasks,
            &state,
            &resources,
            &channel_shutdown,
            remote_addr,
        )
        .await
        {
            break 'connection Err(error);
        }

        loop {
            let accepted = tokio::select! {
                biased;
                () = shutdown.cancelled() => break Ok(()),
                completed = channel_tasks.join_next(), if !channel_tasks.is_empty() => {
                    if let Some(Err(error)) = completed {
                        resources.listener.task_failures.fetch_add(1, Ordering::Relaxed);
                        debug!(remote = %remote_addr, %error, "WebRTC Direct DataChannel task failed");
                    }
                    // The browser protocol uses persistent channels; it has no channel
                    // reopen/continuation handshake. Once the last channel ends,
                    // close the association promptly instead of retaining a stale
                    // per-IP connection slot while waiting for another channel.
                    if channel_tasks.is_empty() {
                        break Ok(());
                    }
                    continue;
                }
                result = connection.accept_data_channel() => result,
            };
            let channel = match accepted {
                Ok(channel) => channel,
                Err(error) => break Err(format!("DataChannel accept failed: {error}")),
            };
            if let Err(error) = start_data_channel_task(
                channel,
                &mut channel_tasks,
                &state,
                &resources,
                &channel_shutdown,
                remote_addr,
            )
            .await
            {
                break Err(error);
            }
        }
    };

    // Stop channel I/O promptly. Started application requests are owned by the
    // listener's request tracker and keep their storage state and admission
    // until processing finishes, independently of this connection.
    channel_shutdown.cancel();
    if let Err(error) = connection.close().await {
        debug!(remote = %remote_addr, %error, "Failed to close WebRTC Direct connection");
    }
    while let Some(result) = channel_tasks.join_next().await {
        if let Err(error) = result {
            debug!(remote = %remote_addr, %error, "WebRTC Direct DataChannel task failed during shutdown");
        }
    }
    outcome
}

async fn wait_for_first_data_channel<T>(
    shutdown: &CancellationToken,
    timeout: Duration,
    accept: impl Future<Output = ServerResult<T>>,
) -> ServerResult<Option<T>> {
    tokio::select! {
        biased;
        () = shutdown.cancelled() => Ok(None),
        result = tokio::time::timeout(timeout, accept) => result.map_or_else(
            |_| Err(FIRST_DATA_CHANNEL_TIMEOUT_ERROR.to_string()),
            |result| result.map(Some),
        ),
    }
}

async fn start_data_channel_task(
    channel: WebRtcDataChannel,
    channel_tasks: &mut JoinSet<()>,
    state: &Arc<ServerState>,
    resources: &Arc<ConnectionResources>,
    channel_shutdown: &CancellationToken,
    remote_addr: SocketAddr,
) -> ServerResult<()> {
    if channel_tasks.len() >= state.config.max_channels_per_connection {
        resources
            .listener
            .channel_rejections
            .fetch_add(1, Ordering::Relaxed);
        if let Err(error) = channel.close().await {
            debug!(remote = %remote_addr, %error, "Failed to close excess DataChannel");
        }
        // A reset channel's handler may still be scheduled for retirement.
        // Reject only this excess stream, never its healthy sibling association.
        return Ok(());
    }
    let Ok(channel_permit) = Arc::clone(&resources.listener.channel_limit).try_acquire_owned()
    else {
        resources
            .listener
            .channel_rejections
            .fetch_add(1, Ordering::Relaxed);
        if let Err(error) = channel.close().await {
            debug!(remote = %remote_addr, %error, "Failed to close excess DataChannel");
        }
        return Err(CHANNEL_CAPACITY_ERROR.to_string());
    };
    let channel_state = Arc::clone(state);
    let channel_resources = Arc::clone(resources);
    let handler_shutdown = channel_shutdown.clone();
    let diagnostic_resources = Arc::clone(&resources.listener);
    channel_tasks.spawn(async move {
        let _channel_permit = channel_permit;
        if let Err(error) = handle_webrtc_channel(
            &channel,
            channel_state,
            channel_resources,
            handler_shutdown,
        )
        .await
        {
            diagnostic_resources.channel_errors.fetch_add(1, Ordering::Relaxed);
            debug!(remote = %remote_addr, channel = channel.id(), "WebRTC Direct DataChannel ended: {error}");
        }
        if let Err(error) = channel.close().await {
            debug!(remote = %remote_addr, channel = channel.id(), %error, "Failed to close WebRTC Direct DataChannel");
        }
    });
    Ok(())
}

#[allow(clippy::significant_drop_tightening, clippy::too_many_lines)]
async fn handle_webrtc_channel(
    channel: &WebRtcDataChannel,
    state: Arc<ServerState>,
    resources: Arc<ConnectionResources>,
    shutdown: CancellationToken,
) -> ServerResult<()> {
    if channel.label() != WEBRTC_DIRECT_DATA_CHANNEL {
        return Err(format!(
            "unsupported DataChannel label {:?}",
            channel.label()
        ));
    }

    let pq_session = tokio::select! {
        biased;
        () = shutdown.cancelled() => return Ok(()),
        result = establish_pq_session(channel, &state, &resources) => result?,
    };
    // Receiving stays live while application work or response writes are pending.
    // In particular, a channel reset releases its handler slot immediately; the
    // listener's separately tracked storage/payment work retains its charges.
    let session = Mutex::new(pq_session);
    let mut hello_completed = false;
    let mut ids = HashSet::new();
    let mut pending = FuturesUnordered::new();
    let (activity, active_requests) = watch::channel(0usize);
    let mut reading = Box::pin(read_webrtc_request(
        channel,
        &session,
        &resources,
        &active_requests,
    ));
    let mut writing = None;
    let mut ready = VecDeque::<CompletedRequest>::new();
    loop {
        if writing.is_none() {
            if let Some(completed) = ready.pop_front() {
                let id = completed.response.request_id;
                if matches!(completed.response.body, ResponseBody::Hello { .. })
                    && completed.response.status == ResponseStatus::Ok
                {
                    hello_completed = true;
                }
                let session = &session;
                let resources = &resources;
                // Only one complete encrypted frame is written at a time. AEAD
                // sequence numbers follow wire order, not request completion order.
                writing = Some(Box::pin(async move {
                    write_webrtc_response(
                        channel,
                        session,
                        &completed.response,
                        completed.content.as_ref(),
                        resources,
                    )
                    .await?;
                    drop(completed);
                    Ok::<_, String>(id)
                }));
            }
        }
        tokio::select! {
            biased;
            () = shutdown.cancelled() => return Ok(()),
            result = async { match writing.as_mut() { Some(writer) => writer.await, None => std::future::pending().await } }, if writing.is_some() => {
                ids.remove(&result?);
                activity.send_replace(ids.len());
                writing = None;
            }
            result = &mut reading => {
                let admitted = match result {
                    Ok(request) => request,
                    Err(error) if is_quiet_channel_close(&error) => return Ok(()),
                    Err(error) => {
                        if ids.is_empty() {
                            let response = Response::error(0, "invalid_request", error);
                            tokio::select! {
                                () = shutdown.cancelled() => return Ok(()),
                                result = write_webrtc_response(channel, &session, &response, None, &resources) => result?,
                            }
                            return Ok(());
                        }
                        return Err(error);
                    },
                };
                let request = &admitted.request;
                if ids.len() >= MAX_CHANNEL_REQUESTS || !ids.insert(request.request_id) {
                    return Err("duplicate request ID or per-channel RPC capacity exhausted".into());
                }
                activity.send_replace(ids.len());
                let error = if request.version != BROWSER_PROTOCOL_VERSION {
                    Some(Response::error(request.request_id, "unsupported_version",
                        format!("protocol version {} is unsupported; expected {BROWSER_PROTOCOL_VERSION}", request.version)))
                } else if !hello_completed && !matches!(request.body, RequestBody::Hello) {
                    Some(Response::error(request.request_id, "authentication_required",
                        "HELLO must initialize this encrypted WebRTC session first"))
                } else { None };
                let request_state = Arc::clone(&state);
                let request_resources = Arc::clone(&resources);
                pending.push(async move {
                    match error {
                        Some(response) => {
                            let AdmittedRequest { _request_permit: request_permit, _in_flight_bytes: in_flight_bytes, .. } = admitted;
                            Ok(CompletedRequest {
                                _bulk_permits: None,
                                response, content: None,
                                _request_permit: request_permit,
                                _in_flight_bytes: in_flight_bytes,
                                _resources: request_resources,
                            })
                        },
                        None => start_request(admitted, request_state, request_resources).await,
                    }
                });
                reading = Box::pin(read_webrtc_request(channel, &session, &resources, &active_requests));
            }
            completed = pending.next(), if !pending.is_empty() => {
                let Some(completed) = completed else { continue };
                let completed = completed?;
                ready.push_back(completed);
            }
        }
    }
}

fn is_quiet_channel_close(error: &str) -> bool {
    matches!(
        error,
        "DataChannel closed"
            | "request idle timeout"
            | "request frame timed out"
            | REQUEST_CAPACITY_ERROR
            | REQUEST_RATE_ERROR
            | GLOBAL_BYTE_CAPACITY_ERROR
            | SOURCE_BYTE_CAPACITY_ERROR
    ) || error.starts_with("PQ session:")
}

async fn establish_pq_session(
    channel: &WebRtcDataChannel,
    state: &ServerState,
    resources: &ConnectionResources,
) -> ServerResult<PqSession> {
    let first_message = receive_first_message(channel, "PQ client hello idle timeout").await?;
    // The post-quantum handshake is deliberately charged to the same work and
    // rate envelopes as an RPC. Otherwise a source could churn channels and
    // force unmetered ML-KEM/ML-DSA work without ever sending a request.
    let _handshake_permit = resources.try_admit_request()?;
    let client_hello = read_pq_payload_after_first(
        first_message,
        channel,
        PQ_CLIENT_HELLO_BYTES,
        "PQ client hello timed out",
        resources,
    )
    .await?;
    let peer_id = *state.p2p.peer_id().to_bytes();
    let public_key = state.identity.public_key().as_bytes();
    let (server_accept, session) =
        accept_pq_session(&client_hello.bytes, &peer_id, public_key, |transcript| {
            state
                .identity
                .sign(transcript)
                .map(|signature| signature.as_bytes().to_vec())
        })
        .map_err(|error| format!("PQ session: {error}"))?;
    write_pq_payload(channel, &server_accept, resources).await?;
    Ok(session)
}

struct AdmittedRequest {
    request: Request,
    content: Vec<u8>,
    _request_permit: OwnedSemaphorePermit,
    _in_flight_bytes: InFlightByteReservation,
}

struct CompletedRequest {
    // Retain preparation capacity until the response is written or discarded.
    _bulk_permits: Option<(OwnedSemaphorePermit, OwnedSemaphorePermit)>,
    response: Response,
    content: Option<TrackedBytes>,
    _request_permit: OwnedSemaphorePermit,
    _in_flight_bytes: InFlightByteReservation,
    // Prevent source eviction until the response and all its charges are gone.
    _resources: Arc<ConnectionResources>,
}

// A GET may hold record bytes, encoded plaintext and ciphertext together.
// This queue complements exact byte accounting; it never raises those limits.
fn bulk_response_slots(bytes: usize) -> usize {
    (bytes / (3 * ant_protocol::MAX_WIRE_MESSAGE_SIZE + 2 * MAX_BROWSER_HEADER_BYTES)).max(1)
}

fn request_is_get(request: &Request, content: &[u8]) -> bool {
    matches!(request.body, RequestBody::GetChunk { .. })
        || (matches!(request.body, RequestBody::ChunkProtocol)
            // A canonical binary GET is small. Avoid decoding/copying PUTs just
            // to classify scheduling; the ordinary decoder still validates all.
            && content.len() <= 128
            && ChunkMessage::decode(content).is_ok_and(|message| matches!(message.body, ChunkMessageBody::GetRequest(_))))
}

async fn start_request(
    admitted: AdmittedRequest,
    state: Arc<ServerState>,
    resources: Arc<ConnectionResources>,
) -> ServerResult<CompletedRequest> {
    let listener = Arc::clone(&resources.listener);
    let worker = listener.spawn_request(async move {
        // V2-1871: time the worker from the moment it starts, so the GET
        // service time below covers the bulk-slot wait as well as the work.
        // This is deliberately not admission: the request permit, frame
        // assembly and decryption all happen before the worker is spawned, so
        // this clock excludes them.
        let worker_started_at = Instant::now();
        let AdmittedRequest {
            request,
            content,
            _request_permit: request_permit,
            _in_flight_bytes: in_flight_bytes,
        } = admitted;
        let is_get = request_is_get(&request, &content);
        // Reserve enough preparation capacity for one complete response to
        // make progress under the existing byte limits. Acquire source first:
        // queued work from one source cannot occupy every global bulk slot.
        let bulk_permits = if is_get {
            let source = Arc::clone(&resources.source.bulk_responses)
                .acquire_owned()
                .await
                .map_err(|_| "bulk response admission closed".to_string())?;
            let global = Arc::clone(&resources.listener.bulk_responses)
                .acquire_owned()
                .await
                .map_err(|_| "bulk response admission closed".to_string())?;
            resources
                .listener
                .record_bulk_wait(worker_started_at.elapsed());
            Some((source, global))
        } else {
            None
        };
        let (response, content) = match process_request(request, content, &state, &resources).await
        {
            Ok(processed) => processed,
            Err(error) => {
                if is_get {
                    resources
                        .listener
                        .get_service_failures
                        .fetch_add(1, Ordering::Relaxed);
                }
                return Err(error);
            }
        };
        if is_get {
            resources
                .listener
                .record_get_service(worker_started_at.elapsed());
        }
        Ok(CompletedRequest {
            _bulk_permits: bulk_permits,
            response,
            content,
            _request_permit: request_permit,
            _in_flight_bytes: in_flight_bytes,
            _resources: resources,
        })
    })?;
    worker.await.map_err(|error| {
        listener.task_failures.fetch_add(1, Ordering::Relaxed);
        public_error("request_failed", error)
    })?
}

async fn read_webrtc_request(
    channel: &WebRtcDataChannel,
    pq_session: &Mutex<PqSession>,
    resources: &ConnectionResources,
    active_requests: &watch::Receiver<usize>,
) -> ServerResult<AdmittedRequest> {
    let first_message = receive_while_active(
        channel.receive(),
        active_requests.clone(),
        REQUEST_IDLE_TIMEOUT,
    )
    .await?
    .map_err(|error| format!("DataChannel message read failed: {error}"))?;
    if first_message.is_empty() {
        return Err("DataChannel closed".into());
    }
    // Admission happens as soon as a client starts a frame. Idle persistent
    // channels consume neither request-rate tokens nor request worker slots.
    let request_permit = resources.try_admit_request()?;
    let max_plaintext_bytes = MAX_BROWSER_FRAME_BYTES;
    let mut encrypted = read_pq_payload_after_first(
        first_message,
        channel,
        max_plaintext_bytes + PQ_ENCRYPTED_OVERHEAD_BYTES,
        "request frame timed out",
        resources,
    )
    .await?;
    let encrypted_len = encrypted.bytes.len();
    // AEAD opening briefly holds ciphertext and plaintext at once. Reserve the
    // second buffer before asking the cryptographic layer to allocate it.
    encrypted.reservation.try_grow(encrypted_len)?;
    let frame = pq_session
        .lock()
        .open(&encrypted.bytes)
        .map_err(|error| format!("PQ session: {error}"))?;
    let TrackedBytes {
        bytes: encrypted_bytes,
        mut reservation,
    } = encrypted;
    drop(encrypted_bytes);
    reservation.resize(frame.len())?;

    let (request, content_offset) =
        parse_request_header(&frame).map_err(|error| error.to_string())?;
    let content_len = frame.len() - content_offset;
    let accounted_request_bytes = frame.len();
    // serde owns the parsed header and the body copy below owns the content.
    // Account the copy while the complete plaintext frame is still live, then
    // retain one frame-sized reservation for the parsed request's lifetime.
    reservation.try_grow(content_len)?;
    let content = frame[content_offset..].to_vec();
    drop(frame);
    reservation.resize(accounted_request_bytes)?;
    Ok(AdmittedRequest {
        request,
        content,
        _request_permit: request_permit,
        _in_flight_bytes: reservation,
    })
}

// Observe resets even while work is pending. Only an idle channel spends the
// inactivity budget; a slow disk operation or permitted bulk transfer must not
// be interrupted by the request-idle timer. Keep the receive future pinned so
// activity changes never discard a partially polled transport read.
async fn receive_while_active<T>(
    receive: impl Future<Output = T>,
    mut activity: watch::Receiver<usize>,
    idle_timeout: Duration,
) -> ServerResult<T> {
    tokio::pin!(receive);
    loop {
        let idle = *activity.borrow_and_update() == 0;
        tokio::select! {
            biased;
            result = &mut receive => return Ok(result),
            changed = activity.changed() => {
                changed.map_err(|_| "channel activity closed".to_string())?;
            }
            () = tokio::time::sleep(idle_timeout), if idle => return Err("request idle timeout".into()),
        }
    }
}

async fn receive_first_message(
    channel: &WebRtcDataChannel,
    idle_timeout_message: &str,
) -> ServerResult<Vec<u8>> {
    let message = tokio::time::timeout(REQUEST_IDLE_TIMEOUT, channel.receive())
        .await
        .map_err(|_| idle_timeout_message.to_string())?
        .map_err(|error| format!("DataChannel message read failed: {error}"))?;
    if message.is_empty() {
        return Err("DataChannel closed".to_string());
    }
    Ok(message)
}

async fn read_pq_payload_after_first(
    first_message: Vec<u8>,
    channel: &WebRtcDataChannel,
    max_payload_bytes: usize,
    frame_timeout_message: &str,
    resources: &ConnectionResources,
) -> ServerResult<TrackedBytes> {
    let mut frame_deadline = TransferDeadline::for_frame(PQ_FRAME_PREFIX_BYTES);
    let mut frame = TrackedBytes {
        reservation: resources.try_reserve_bytes(first_message.len())?,
        bytes: first_message,
    };
    let mut expected_length = None;
    let max_frame_bytes = 4usize
        .checked_add(max_payload_bytes)
        .ok_or_else(|| "PQ frame limit overflow".to_string())?;
    loop {
        if frame.bytes.len() > max_frame_bytes {
            return Err(format!(
                "request exceeds the {max_frame_bytes}-byte frame limit"
            ));
        }

        if expected_length.is_none() {
            expected_length = pq_frame_length(&frame.bytes, max_payload_bytes)
                .map_err(|error| format!("PQ session: {error}"))?;
            if let Some(length) = expected_length {
                if frame.bytes.len() > length {
                    return Err("PQ frame contains bytes after its declared payload".to_string());
                }
                // Reserve the complete declared frame before accepting a slow
                // body. A sender cannot make many partial 4 MiB frames consume
                // unaccounted memory during their transfer windows.
                frame.reserve_length(length)?;
                frame_deadline.extend_for_frame(length);
            }
        }

        if let Some(length) = expected_length {
            if frame.bytes.len() == length {
                let payload_len = length - PQ_FRAME_PREFIX_BYTES;
                frame.reservation.try_grow(payload_len)?;
                let payload = decode_pq_frame(&frame.bytes, max_payload_bytes)
                    .map_err(|error| format!("PQ session: {error}"))?;
                let TrackedBytes {
                    bytes: encoded_frame,
                    mut reservation,
                } = frame;
                drop(encoded_frame);
                reservation.resize(payload.len())?;
                return Ok(TrackedBytes {
                    bytes: payload,
                    reservation,
                });
            }
        }

        if frame_deadline.remaining().is_zero() {
            return Err(frame_timeout_message.to_string());
        }
        let message = tokio::time::timeout(frame_deadline.remaining(), channel.receive())
            .await
            .map_err(|_| frame_timeout_message.to_string())?
            .map_err(|error| format!("DataChannel message read failed: {error}"))?;
        if message.is_empty() {
            return Err("DataChannel closed".to_string());
        }
        let next_length = frame
            .bytes
            .len()
            .checked_add(message.len())
            .ok_or_else(|| "PQ frame length overflow".to_string())?;
        if next_length > max_frame_bytes
            || expected_length.is_some_and(|length| next_length > length)
        {
            return Err("PQ frame contains bytes after its declared payload".to_string());
        }
        if expected_length.is_none() {
            frame.reserve_length(next_length)?;
        }
        frame.bytes.extend_from_slice(&message);
    }
}

async fn write_webrtc_response(
    channel: &WebRtcDataChannel,
    pq_session: &Mutex<PqSession>,
    response: &Response,
    content: Option<&TrackedBytes>,
    resources: &ConnectionResources,
) -> ServerResult<()> {
    // GET content carries its own reservation from before the storage read.
    // This reservation accounts only the new header, plaintext, and ciphertext
    // allocations made while encoding the response.
    let content = content.map_or(&[][..], |tracked| tracked.bytes.as_slice());
    let encode_reservation = 4usize
        .checked_add(MAX_BROWSER_HEADER_BYTES.saturating_mul(2))
        .and_then(|length| length.checked_add(content.len()))
        .ok_or_else(|| "response frame length overflow".to_string())?;
    let mut reservation = resources.try_reserve_bytes(encode_reservation)?;
    let plaintext = encode_response_frame(response, content).map_err(|error| error.to_string())?;
    reservation.resize(plaintext.len())?;
    let encrypted_len = plaintext
        .len()
        .checked_add(PQ_ENCRYPTED_OVERHEAD_BYTES)
        .ok_or_else(|| "encrypted response length overflow".to_string())?;
    reservation.try_grow(encrypted_len)?;
    let encrypted = pq_session
        .lock()
        .seal(&plaintext)
        .map_err(|error| format!("PQ session: {error}"))?;
    drop(plaintext);
    reservation.resize(content.len() + encrypted.len())?;
    write_framed_pq_payload(channel, &encrypted).await
}

async fn write_pq_payload(
    channel: &WebRtcDataChannel,
    payload: &[u8],
    resources: &ConnectionResources,
) -> ServerResult<()> {
    let _reservation = resources.try_reserve_bytes(payload.len())?;
    write_framed_pq_payload(channel, payload).await
}

async fn write_framed_pq_payload(channel: &WebRtcDataChannel, payload: &[u8]) -> ServerResult<()> {
    let payload_len = u32::try_from(payload.len())
        .map_err(|_| "PQ session: payload length does not fit u32".to_string())?;
    let framed_len = PQ_FRAME_PREFIX_BYTES
        .checked_add(payload.len())
        .ok_or_else(|| "PQ response frame length overflow".to_string())?;
    let deadline = TransferDeadline::for_frame(framed_len);
    tokio::time::timeout(
        deadline.remaining(),
        channel.send(&payload_len.to_be_bytes()),
    )
    .await
    .map_err(|_| "response frame timed out".to_string())?
    .map_err(|error| format!("response message write failed: {error}"))?;
    for chunk in payload.chunks(WEBRTC_WRITE_CHUNK_BYTES) {
        if deadline.remaining().is_zero() {
            return Err("response frame timed out".to_string());
        }
        tokio::time::timeout(deadline.remaining(), channel.send(chunk))
            .await
            .map_err(|_| "response frame timed out".to_string())?
            .map_err(|error| format!("response message write failed: {error}"))?;
    }
    Ok(())
}

async fn process_request(
    request: Request,
    content: Vec<u8>,
    state: &ServerState,
    resources: &ConnectionResources,
) -> ServerResult<(Response, Option<TrackedBytes>)> {
    if !matches!(
        &request.body,
        RequestBody::PutChunk { .. } | RequestBody::ChunkProtocol
    ) && !content.is_empty()
    {
        return Ok((
            Response::error(
                request.request_id,
                "unexpected_content",
                "only put_chunk and chunk_protocol accept binary request content".to_string(),
            ),
            None,
        ));
    }
    match request.body {
        RequestBody::ChunkProtocol => {
            let Some(protocol) = state.ant_protocol.as_ref() else {
                return Ok((
                    Response::error(
                        request.request_id,
                        "storage_disabled",
                        "chunk storage is disabled".to_string(),
                    ),
                    None,
                ));
            };
            // The admitted frame remains charged for the whole request. Charge
            // decoding before it copies the input, then retain that allowance
            // for the PUT handler's disk buffer after dropping the wire buffer.
            let mut reservation = resources.try_reserve_bytes(content.len())?;
            let message = ChunkMessage::decode(&content)
                .map_err(|error| public_error("invalid_request", error))?;
            drop(content);
            let response_limit = binary_response_limit(&message.body)?;
            reservation.resize(reservation.source.amount.max(2 * response_limit))?;
            let response = handle_ant_message(protocol, message).await?;
            let bytes = encode_binary_response(&response, response_limit)?;
            drop(response);
            reservation.resize(bytes.len())?;
            Ok((
                Response::ok(request.request_id, ResponseBody::ChunkProtocol, bytes.len()),
                Some(TrackedBytes { bytes, reservation }),
            ))
        }
        RequestBody::Hello => Ok((hello_response(request.request_id, state), None)),
        RequestBody::FindNode {
            target,
            count,
            with_address_records,
        } => {
            process_find_node(
                request.request_id,
                target,
                count,
                with_address_records,
                state,
                resources,
            )
            .await
        }
        RequestBody::GetChunk { address } => {
            process_get_chunk(request.request_id, address, state, resources).await
        }
        RequestBody::QuoteChunk { address, size } => {
            Ok(process_quote_chunk(request.request_id, address, size, state).await)
        }
        RequestBody::PutChunk {
            address,
            quote,
            transaction_hash,
        } => Ok(process_put_chunk(
            request.request_id,
            address,
            *quote,
            transaction_hash,
            content,
            state,
        )
        .await),
    }
}

// PUT acknowledgements and signed quotes contain no chunk payload. 64 KiB
// covers the ML-DSA public key/signature, quote and signed commitment, including
// worst-case MessagePack integer encoding. GET alone needs a full wire buffer.
//
// A pointer read returns one record of `POINTER_WIRE_LEN` bytes, so it is small
// too and needs no bulk slot (see `request_is_get`).
const SMALL_BINARY_RESPONSE_BYTES: usize = 64 * 1024;
const _: () = assert!(
    ant_protocol::pointer::POINTER_WIRE_LEN < SMALL_BINARY_RESPONSE_BYTES / 2,
    "a pointer read must fit the small response bound with room for its envelope"
);

fn binary_response_limit(body: &ChunkMessageBody) -> ServerResult<usize> {
    match body {
        ChunkMessageBody::GetRequest(_) => Ok(ant_protocol::MAX_WIRE_MESSAGE_SIZE),
        ChunkMessageBody::PutRequest(_)
        | ChunkMessageBody::QuoteRequest(_)
        | ChunkMessageBody::QuoteRequestV2(_)
        | ChunkMessageBody::MerkleCandidateQuoteRequest(_)
        | ChunkMessageBody::MerkleCandidateQuoteRequestV2(_)
        | ChunkMessageBody::PointerGetRequest(_)
        | ChunkMessageBody::PointerPutRequest(_) => Ok(SMALL_BINARY_RESPONSE_BYTES),
        _ => Err("unsupported chunk protocol request".to_string()),
    }
}

fn encode_binary_response(message: &ChunkMessage, limit: usize) -> ServerResult<Vec<u8>> {
    // Size without allocating, then encode into exactly the charged space.
    encode_exact(message, limit).map_err(|error| match error {
        ExactEncodeError::Serialize(error) => public_error("invalid_response", error),
        ExactEncodeError::TooLarge { .. } => {
            "chunk protocol response exceeds operation limit".to_string()
        }
    })
}

fn hello_response(request_id: u64, state: &ServerState) -> Response {
    let Some(endpoint) = state.publication.read().endpoint().cloned() else {
        return Response::error(
            request_id,
            "endpoint_unavailable",
            "address discovery is pending".to_string(),
        );
    };
    Response::ok(
        request_id,
        ResponseBody::Hello {
            protocol: BROWSER_PROTOCOL_NAME.to_string(),
            peer_id: state.p2p.peer_id().to_hex(),
            max_chunk_size: MAX_CHUNK_SIZE,
            endpoint,
            payment: state.payment.clone(),
            capabilities: hello_capabilities(serves_pointers(state.ant_protocol.as_deref())),
        },
        0,
    )
}

/// Whether requests reach a pointer store. A node without one refuses pointer
/// writes and has none to read, so it must not invite them: a browser could
/// otherwise pay a quote before learning the write goes nowhere.
fn serves_pointers(protocol: Option<&AntProtocol>) -> bool {
    protocol.is_some_and(|protocol| protocol.pointer_service().is_some())
}

fn hello_capabilities(pointers: bool) -> Vec<String> {
    let mut capabilities: Vec<String> = vec![
        "chunk_protocol".into(),
        RPC_MULTIPLEX_CAPABILITY.into(),
        "find_node".into(),
        ant_protocol::transport::ADDRESS_V2_CAPABILITY.into(),
        "get_chunk".into(),
        "quote_chunk".into(),
        "put_chunk".into(),
    ];
    if pointers {
        capabilities.push(POINTER_PROTOCOL_CAPABILITY.into());
    }
    capabilities
}

async fn process_find_node(
    request_id: u64,
    target: String,
    count: Option<usize>,
    with_address_records: bool,
    state: &ServerState,
    resources: &ConnectionResources,
) -> ServerResult<(Response, Option<TrackedBytes>)> {
    let target_bytes = match decode_32_byte_hex(&target) {
        Ok(bytes) => bytes,
        Err(error) => return Ok((Response::error(request_id, "invalid_target", error), None)),
    };
    let count = count
        .unwrap_or(MAX_FIND_NODE_RESULTS)
        .clamp(1, MAX_FIND_NODE_RESULTS);
    let dht = state.p2p.dht_manager();
    let dht_nodes = dht
        .find_closest_nodes_local_with_self(&target_bytes, count)
        .await;
    let mut nodes = Vec::with_capacity(dht_nodes.len());
    let mut proofs = Vec::new();
    let mut reservation = resources.try_reserve_bytes(if with_address_records {
        2 * dht_nodes.len() * (saorsa_core::signed_address::MAX_SIGNED_ADDRESS_BYTES + 4)
    } else {
        0
    })?;
    for node in dht_nodes {
        if with_address_records {
            let Some(proof) = dht.signed_address_record_for_peer(&node.peer_id).await else {
                continue;
            };
            proofs.push(proof);
        }
        let supplemental = dht.supplemental_addresses_for_peer(&node.peer_id).await;
        nodes.push(browser_node_from_dht(
            &node,
            &supplemental,
            state.endpoint_catalog.as_deref(),
        ));
    }
    let bytes = saorsa_core::signed_address::encode_record_bundle(&proofs)?;
    drop(proofs);
    reservation.resize(bytes.len())?;
    Ok((
        Response::ok(
            request_id,
            ResponseBody::Nodes { target, nodes },
            bytes.len(),
        ),
        Some(TrackedBytes { bytes, reservation }),
    ))
}

fn browser_node_from_dht(
    node: &DHTNode,
    supplemental: &[MultiAddr],
    endpoint_catalog: Option<&BrowserEndpointCatalog>,
) -> BrowserNode {
    let addresses = node.addresses_by_priority();
    let discovered_endpoint = supplemental
        .iter()
        .find(|address| {
            address.is_webrtc_direct()
                && address.peer_id().is_some_and(|peer| peer == &node.peer_id)
        })
        .cloned()
        .map(|multiaddr| BrowserEndpoint {
            multiaddr: multiaddr.to_string(),
        });
    BrowserNode {
        address_record: None,
        peer_record: rmp_serde::to_vec_named(node).ok().map(hex::encode),
        webrtc_direct: discovered_endpoint
            .or_else(|| endpoint_catalog.and_then(|catalog| catalog.get(&node.peer_id))),
        peer_id: node.peer_id.to_hex(),
        native_addresses: addresses
            .into_iter()
            .filter(|address| !address.is_webrtc_direct())
            .map(|address| address.to_string())
            .collect(),
        reliability: node.reliability,
    }
}

async fn process_get_chunk(
    request_id: u64,
    address: String,
    state: &ServerState,
    resources: &ConnectionResources,
) -> ServerResult<(Response, Option<TrackedBytes>)> {
    let address_bytes = match decode_32_byte_hex(&address) {
        Ok(bytes) => bytes,
        Err(error) => {
            return Ok((Response::error(request_id, "invalid_address", error), None));
        }
    };
    let Some(ant_protocol) = state.ant_protocol.as_ref() else {
        return Ok((
            Response::error(
                request_id,
                "storage_disabled",
                "chunk storage is disabled on this node".to_string(),
            ),
            None,
        ));
    };

    // The storage API allocates its returned Vec internally, so reserve the
    // largest permitted chunk before awaiting it. This closes the interval in
    // which many concurrent GETs could materialize unaccounted full chunks.
    let mut content_reservation = resources.try_reserve_bytes(MAX_CHUNK_SIZE)?;
    let response = match ant_protocol.storage().get(&address_bytes).await {
        Ok(Some(content)) if content.len() <= MAX_CHUNK_SIZE => {
            let content_length = content.len();
            content_reservation.resize(content_length)?;
            Ok((
                Response::ok(
                    request_id,
                    ResponseBody::Chunk {
                        address,
                        size: content_length,
                    },
                    content_length,
                ),
                Some(TrackedBytes {
                    bytes: content,
                    reservation: content_reservation,
                }),
            ))
        }
        Ok(Some(content)) => Ok((
            Response::error(
                request_id,
                "oversize_chunk",
                format!(
                    "stored content is {} bytes; maximum is {MAX_CHUNK_SIZE}",
                    content.len()
                ),
            ),
            None,
        )),
        Ok(None) => Ok((Response::not_found(request_id, address), None)),
        Err(error) => Ok((error_response(request_id, "storage_error", error), None)),
    };
    response
}

async fn process_quote_chunk(
    request_id: u64,
    address: String,
    size: u64,
    state: &ServerState,
) -> (Response, Option<TrackedBytes>) {
    let address_bytes = match decode_32_byte_hex(&address) {
        Ok(bytes) => bytes,
        Err(error) => return (Response::error(request_id, "invalid_address", error), None),
    };
    if size > MAX_CHUNK_SIZE as u64 {
        return (
            Response::error(
                request_id,
                "oversize_chunk",
                format!("chunk size {size} exceeds {MAX_CHUNK_SIZE}"),
            ),
            None,
        );
    }
    let Some(ant_protocol) = state.ant_protocol.as_ref() else {
        return (
            Response::error(
                request_id,
                "storage_disabled",
                "chunk storage is disabled on this node".to_string(),
            ),
            None,
        );
    };

    let message = ChunkMessage {
        request_id,
        body: ChunkMessageBody::QuoteRequest(ChunkQuoteRequest::new(address_bytes, size)),
    };
    let response = match handle_ant_message(ant_protocol, message).await {
        Ok(response) => response,
        Err(error) => return (error_response(request_id, "quote_failed", error), None),
    };
    match response.body {
        ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Success {
            quote,
            already_stored,
            commitment,
        }) => {
            let quote: PaymentQuote = match rmp_serde::from_slice(&quote) {
                Ok(quote) => quote,
                Err(error) => return (error_response(request_id, "invalid_quote", error), None),
            };
            let artifact = match browser_quote_from_quote(
                state.p2p.peer_id(),
                &quote,
                commitment.as_deref(),
            ) {
                Ok(artifact) => artifact,
                Err(error) => return (error_response(request_id, "invalid_quote", error), None),
            };
            (
                Response::ok(
                    request_id,
                    ResponseBody::StorageQuote {
                        address,
                        already_stored,
                        quote: artifact,
                    },
                    0,
                ),
                None,
            )
        }
        ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Error(error)) => (
            Response::error(request_id, "quote_rejected", error.to_string()),
            None,
        ),
        other => (
            error_response(
                request_id,
                "invalid_quote_response",
                format_args!("{other:?}"),
            ),
            None,
        ),
    }
}

async fn process_put_chunk(
    request_id: u64,
    address: String,
    quote: BrowserQuoteArtifact,
    transaction_hash: String,
    content: Vec<u8>,
    state: &ServerState,
) -> (Response, Option<TrackedBytes>) {
    let address_bytes = match decode_32_byte_hex(&address) {
        Ok(bytes) => bytes,
        Err(error) => return (Response::error(request_id, "invalid_address", error), None),
    };
    let Some(ant_protocol) = state.ant_protocol.as_ref() else {
        return (
            Response::error(
                request_id,
                "storage_disabled",
                "chunk storage is disabled on this node".to_string(),
            ),
            None,
        );
    };
    let proof = match build_payment_proof(address_bytes, quote, &transaction_hash) {
        Ok(proof) => proof,
        Err(error) => {
            return (
                Response::error(request_id, "invalid_payment_proof", error),
                None,
            )
        }
    };

    let message = ChunkMessage {
        request_id,
        body: ChunkMessageBody::PutRequest(ChunkPutRequest::with_payment(
            address_bytes,
            bytes::Bytes::from(content),
            proof,
        )),
    };
    let response = match handle_ant_message(ant_protocol, message).await {
        Ok(response) => response,
        Err(error) => return (error_response(request_id, "put_failed", error), None),
    };
    match response.body {
        ChunkMessageBody::PutResponse(ChunkPutResponse::Success { address }) => (
            Response::ok(
                request_id,
                ResponseBody::ChunkStored {
                    address: hex::encode(address),
                    already_stored: false,
                },
                0,
            ),
            None,
        ),
        ChunkMessageBody::PutResponse(ChunkPutResponse::AlreadyExists { address }) => (
            Response::ok(
                request_id,
                ResponseBody::ChunkStored {
                    address: hex::encode(address),
                    already_stored: true,
                },
                0,
            ),
            None,
        ),
        ChunkMessageBody::PutResponse(ChunkPutResponse::PaymentRequired { message }) => (
            Response::error(request_id, "payment_required", message),
            None,
        ),
        ChunkMessageBody::PutResponse(ChunkPutResponse::Error(error)) => (
            Response::error(request_id, "put_rejected", error.to_string()),
            None,
        ),
        other => (
            error_response(
                request_id,
                "invalid_put_response",
                format_args!("{other:?}"),
            ),
            None,
        ),
    }
}

fn build_payment_proof(
    expected_content: [u8; 32],
    quote: BrowserQuoteArtifact,
    transaction_hash: &str,
) -> ServerResult<Vec<u8>> {
    let (peer_id, payment_quote, commitment) =
        payment_quote_from_browser_quote(quote, expected_content)?;
    let transaction_hash = TxHash::from_str(transaction_hash)
        .map_err(|error| format!("invalid EVM transaction hash: {error}"))?;
    let proof = PaymentProof {
        proof_of_payment: ProofOfPayment {
            peer_quotes: vec![(EncodedPeerId::new(peer_id), payment_quote)],
        },
        tx_hashes: vec![transaction_hash],
        commitment_sidecars: commitment.into_iter().collect(),
    };
    serialize_single_node_proof(&proof)
        .map_err(|error| format!("failed to serialize payment proof: {error}"))
}

async fn handle_ant_message(
    ant_protocol: &AntProtocol,
    message: ChunkMessage,
) -> ServerResult<ChunkMessage> {
    let mut response = ant_protocol
        .try_handle_message(message)
        .await
        .ok_or_else(|| "storage handler returned no response".to_string())?;
    sanitize_response(&mut response)?;
    Ok(response)
}

fn decode_32_byte_hex(value: &str) -> ServerResult<[u8; 32]> {
    let value = value.strip_prefix("0x").unwrap_or(value);
    let bytes = hex::decode(value).map_err(|error| format!("expected hexadecimal: {error}"))?;
    bytes
        .try_into()
        .map_err(|bytes: Vec<u8>| format!("expected 32 bytes, received {}", bytes.len()))
}

type ServerResult<T> = std::result::Result<T, String>;

fn browser_quote_from_quote(
    peer_id: &PeerId,
    quote: &PaymentQuote,
    commitment: Option<&[u8]>,
) -> ServerResult<BrowserQuoteArtifact> {
    let timestamp_secs = quote
        .timestamp
        .duration_since(SystemTime::UNIX_EPOCH)
        .map_err(|error| format!("quote timestamp predates the Unix epoch: {error}"))?
        .as_secs();
    let commitment = commitment.map(browser_commitment_from_bytes).transpose()?;
    Ok(BrowserQuoteArtifact {
        peer_id: peer_id.to_hex(),
        content: hex::encode(quote.content.0),
        timestamp_secs,
        price: quote.price.to_string(),
        rewards_address: format!("{:?}", quote.rewards_address),
        public_key: hex::encode(&quote.pub_key),
        signature: hex::encode(&quote.signature),
        committed_key_count: quote.committed_key_count,
        commitment_pin: quote.commitment_pin.map(hex::encode),
        quote_hash: hex::encode(quote.hash()),
        commitment,
    })
}

fn payment_quote_from_browser_quote(
    artifact: BrowserQuoteArtifact,
    expected_content: [u8; 32],
) -> ServerResult<([u8; 32], PaymentQuote, Option<Vec<u8>>)> {
    let peer_id = decode_32_byte_hex(&artifact.peer_id)?;
    let content = decode_32_byte_hex(&artifact.content)?;
    if content != expected_content {
        return Err("payment quote is for a different chunk address".to_string());
    }
    let price = Amount::from_str(&artifact.price)
        .map_err(|error| format!("payment quote has an invalid price: {error}"))?;
    let rewards_address = RewardsAddress::from_str(&artifact.rewards_address)
        .map_err(|error| format!("payment quote has an invalid rewards address: {error}"))?;
    let public_key = hex::decode(&artifact.public_key)
        .map_err(|error| format!("payment quote public key is not hexadecimal: {error}"))?;
    let signature = hex::decode(&artifact.signature)
        .map_err(|error| format!("payment quote signature is not hexadecimal: {error}"))?;
    let commitment_pin = artifact
        .commitment_pin
        .as_deref()
        .map(decode_32_byte_hex)
        .transpose()?;
    let timestamp = SystemTime::UNIX_EPOCH
        .checked_add(Duration::from_secs(artifact.timestamp_secs))
        .ok_or_else(|| "payment quote timestamp is out of range".to_string())?;
    let quote = PaymentQuote {
        content: xor_name::XorName(content),
        timestamp,
        price,
        rewards_address,
        pub_key: public_key,
        signature,
        committed_key_count: artifact.committed_key_count,
        commitment_pin,
    };
    if hex::encode(quote.hash()) != artifact.quote_hash.to_ascii_lowercase() {
        return Err("payment quote hash does not match its signed fields".to_string());
    }
    let commitment = artifact
        .commitment
        .map(|artifact| {
            hex::decode(artifact.encoded)
                .map_err(|error| format!("commitment is not hexadecimal: {error}"))
        })
        .transpose()?;
    Ok((peer_id, quote, commitment))
}

fn browser_commitment_from_bytes(encoded: &[u8]) -> ServerResult<BrowserCommitmentArtifact> {
    let commitment: ::ant_protocol::payment::commitment::StorageCommitment =
        rmp_serde::from_slice(encoded)
            .map_err(|error| format!("node generated an invalid commitment: {error}"))?;
    Ok(BrowserCommitmentArtifact {
        encoded: hex::encode(encoded),
        root: hex::encode(commitment.root),
        key_count: commitment.key_count,
        sender_peer_id: hex::encode(commitment.sender_peer_id),
        sender_public_key: hex::encode(commitment.sender_public_key),
        signature: hex::encode(commitment.signature),
    })
}

struct ServerState {
    config: WebRtcDirectConfig,
    identity: Arc<NodeIdentity>,
    p2p: Arc<P2PNode>,
    ant_protocol: Option<Arc<AntProtocol>>,
    payment: BrowserPaymentNetwork,
    publication: RwLock<Publication>,
    endpoint_catalog: Option<Arc<BrowserEndpointCatalog>>,
    /// The gateway mapping of the listener's port, when the listener asked for one.
    port_mapping: Option<Box<dyn PortMapping>>,
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::significant_drop_tightening
)]
mod tests {
    use super::*;
    use ant_protocol::chunk::{
        PointerGetRequest, PointerGetResponse, PointerPutRequest, PointerPutResponse,
    };
    use ant_protocol::pointer::POINTER_WIRE_LEN;
    use saorsa_core::NodeConfig as CoreNodeConfig;
    use saorsa_transport::webrtc_direct::WebRtcCertificate;
    use std::net::Ipv4Addr;

    /// Any listener certificate digest, for publication tests.
    const CERTIFICATE_SHA256: [u8; 32] = [7; 32];
    /// Arbitrum Sepolia, a payment network that needs no RPC.
    const ARBITRUM_SEPOLIA_CHAIN_ID: u64 = 421_614;

    #[test]
    fn diagnostics_report_capacity_rate_and_byte_pressure_without_leaking_slots() {
        let config = WebRtcDirectConfig {
            max_connections: 2,
            max_connections_per_ip: 1,
            max_concurrent_requests: 1,
            max_requests_per_second_per_connection: 1,
            max_in_flight_bytes: 8,
            max_in_flight_bytes_per_ip: 8,
            ..WebRtcDirectConfig::default()
        };
        let resources = ListenerResources::new(&config);
        let diagnostics = WebRtcServerDiagnostics {
            local_addr: "127.0.0.1:1234".parse().unwrap(),
            transport: WebRtcDiagnostics::default(),
            resources: Arc::clone(&resources),
            config,
        };
        let fresh = diagnostics.snapshot();
        assert_eq!(fresh.get_service_count, 0);
        assert_eq!(fresh.get_service_total_ms, 0);
        assert_eq!(fresh.get_service_max_ms, 0);
        assert_eq!(fresh.get_service_failures, 0);
        assert_eq!(fresh.bulk_wait_count, 0);
        assert_eq!(fresh.bulk_wait_total_ms, 0);
        assert_eq!(fresh.bulk_wait_max_ms, 0);
        assert_eq!(fresh.bulk_slots_in_use, 0);
        // This config's 8-byte frame budget floors the bulk queue at one slot.
        assert_eq!(fresh.bulk_slots_max, 1);
        let first = resources
            .try_admit_connection("192.0.2.1:1000".parse().unwrap())
            .unwrap();
        assert!(resources
            .try_admit_connection("192.0.2.1:1001".parse().unwrap())
            .is_err());
        let second = resources
            .try_admit_connection("192.0.2.2:1000".parse().unwrap())
            .unwrap();
        assert!(resources
            .try_admit_connection("192.0.2.3:1000".parse().unwrap())
            .is_err());
        let permit = first.context.try_admit_request().unwrap();
        assert!(second.context.try_admit_request().is_err());
        assert_eq!(diagnostics.snapshot().active_requests, 1);
        drop(permit);
        assert!(first.context.try_admit_request().is_err());
        let mut bytes = first.context.try_reserve_bytes(6).unwrap();
        assert!(second.context.try_reserve_bytes(3).is_err());
        assert!(bytes.try_grow(3).is_err());
        let busy = diagnostics.snapshot();
        assert_eq!(busy.active_connections, 2);
        assert_eq!(busy.connection_rejections, 2);
        assert_eq!(busy.request_rejections, 1);
        assert_eq!(busy.rate_rejections, 1);
        assert_eq!(busy.byte_rejections, 2);
        assert_eq!(busy.in_flight_bytes, 6);
        assert_eq!(busy.active_requests, 0);
        drop((bytes, first, second));
        let idle = diagnostics.snapshot();
        assert_eq!(idle.in_flight_bytes, 0);
        assert_eq!(idle.active_connections, 0);
        assert_eq!(idle.byte_rejections, 2);
    }

    #[test]
    fn latency_counters_accumulate_and_the_summary_logs_the_snapshot() {
        let config = WebRtcDirectConfig::default();
        let resources = ListenerResources::new(&config);
        let diagnostics = WebRtcServerDiagnostics {
            local_addr: "127.0.0.1:1234".parse().unwrap(),
            transport: WebRtcDiagnostics::default(),
            resources: Arc::clone(&resources),
            config,
        };
        resources.record_bulk_wait(Duration::from_millis(5));
        resources.record_bulk_wait(Duration::from_millis(11));
        resources.record_get_service(Duration::from_millis(40));
        resources.record_get_service(Duration::from_millis(17));
        let snapshot = diagnostics.snapshot();
        assert_eq!(snapshot.bulk_wait_count, 2);
        assert_eq!(snapshot.bulk_wait_total_ms, 16);
        assert_eq!(snapshot.bulk_wait_max_ms, 11);
        assert_eq!(snapshot.get_service_count, 2);
        assert_eq!(snapshot.get_service_total_ms, 57);
        assert_eq!(snapshot.get_service_max_ms, 40);
        // The four global bulk slots whose queueing V2-1795 could not observe.
        assert_eq!(snapshot.bulk_slots_max, 4);
        assert_eq!(snapshot.bulk_slots_in_use, 0);
        diagnostics.log_webrtc_listener_summary();
    }

    /// A `ServerState` with storage disabled: enough for the real request
    /// worker to serve one GET without a node or a chunk store.
    async fn storage_disabled_state() -> Arc<ServerState> {
        let p2p = Arc::new(
            P2PNode::new(
                CoreNodeConfig::builder()
                    .local(true)
                    .ipv6(false)
                    .build()
                    .expect("core config"),
            )
            .await
            .expect("P2P node"),
        );
        Arc::new(ServerState {
            config: WebRtcDirectConfig::default(),
            identity: Arc::clone(p2p.transport().node_identity()),
            p2p,
            ant_protocol: None,
            payment: BrowserPaymentNetwork {
                chain_id: ARBITRUM_SEPOLIA_CHAIN_ID,
                payment_token_address: String::new(),
                payment_vault_address: String::new(),
            },
            publication: RwLock::new(Publication::default()),
            endpoint_catalog: None,
            port_mapping: None,
        })
    }

    #[tokio::test]
    async fn one_get_records_a_bulk_wait_and_a_service_time() {
        let config = WebRtcDirectConfig::default();
        let resources = ListenerResources::new(&config);
        let state = storage_disabled_state().await;
        let connection = resources
            .try_admit_connection("192.0.2.1:1000".parse().expect("source"))
            .expect("connection");
        let admitted = AdmittedRequest {
            request: Request::new(
                1,
                RequestBody::GetChunk {
                    address: hex::encode([7_u8; 32]),
                },
                0,
            ),
            content: Vec::new(),
            _request_permit: connection
                .context
                .try_admit_request()
                .expect("request slot"),
            _in_flight_bytes: connection.context.try_reserve_bytes(1024).expect("bytes"),
        };
        let completed = start_request(admitted, state, Arc::clone(&connection.context))
            .await
            .expect("GET completed");
        let slots = bulk_response_slots(config.max_in_flight_bytes);
        assert_eq!(
            resources.bulk_responses.available_permits(),
            slots - 1,
            "the prepared response still holds its bulk-response slot"
        );
        assert_eq!(resources.bulk_wait_count.load(Ordering::Relaxed), 1);
        assert_eq!(resources.get_service_count.load(Ordering::Relaxed), 1);
        assert_eq!(resources.get_service_failures.load(Ordering::Relaxed), 0);
        drop(completed);
        assert_eq!(resources.bulk_responses.available_permits(), slots);
    }

    #[tokio::test]
    async fn aborting_listener_task_clears_running_status() {
        let resources = ListenerResources::new(&WebRtcDirectConfig::default());
        resources.running.store(true, Ordering::Release);
        let guard = ListenerRunGuard(Arc::clone(&resources));
        let task = tokio::spawn(async move {
            let _guard = guard;
            std::future::pending::<()>().await;
        });
        task.abort();
        assert!(task.await.unwrap_err().is_cancelled());
        assert!(!resources.running.load(Ordering::Acquire));
    }

    #[test]
    fn default_resource_limits_preserve_headroom_for_other_sources() {
        let config = WebRtcDirectConfig::default();
        validate_webrtc_config(&config).expect("default resource limits");

        let source_channel_ceiling =
            config.max_connections_per_ip * config.max_channels_per_connection;
        assert!(config.max_connections_per_ip < config.max_connections);
        assert!(source_channel_ceiling < config.max_channels);
        assert!(source_channel_ceiling < config.max_concurrent_requests);
        assert!(config.max_requests_per_second_per_ip < config.max_requests_per_second);
        assert!(config.max_in_flight_bytes_per_ip < config.max_in_flight_bytes);
    }

    #[test]
    fn rejects_resource_limits_that_let_one_ip_exhaust_a_global_pool() {
        let mut config = WebRtcDirectConfig::default();
        config.max_connections_per_ip = config.max_connections;
        assert!(validate_webrtc_config(&config).is_err());

        let mut config = WebRtcDirectConfig::default();
        config.max_channels = config.max_connections_per_ip * config.max_channels_per_connection;
        assert!(validate_webrtc_config(&config).is_err());

        let mut config = WebRtcDirectConfig::default();
        config.max_in_flight_bytes_per_ip = config.max_in_flight_bytes;
        assert!(validate_webrtc_config(&config).is_err());
    }

    #[tokio::test]
    async fn first_data_channel_wait_times_out_and_scoped_admission_is_released() {
        let config = WebRtcDirectConfig::default();
        let resources = ListenerResources::new(&config);
        let remote_addr: SocketAddr = "198.51.100.1:1000".parse().expect("remote address");
        let shutdown = CancellationToken::new();

        let result = {
            let _admission = resources
                .try_admit_connection(remote_addr)
                .expect("connection admission");
            assert_eq!(
                resources.connection_limit.available_permits(),
                config.max_connections - 1
            );
            wait_for_first_data_channel(
                &shutdown,
                Duration::from_millis(10),
                std::future::pending::<ServerResult<()>>(),
            )
            .await
        };

        assert_eq!(
            result.err().as_deref(),
            Some(FIRST_DATA_CHANNEL_TIMEOUT_ERROR)
        );
        assert_eq!(
            resources.connection_limit.available_permits(),
            config.max_connections
        );
        assert_eq!(
            resources
                .source_state
                .lock()
                .sources
                .get(&remote_addr.ip())
                .expect("tracked source")
                .active_connections,
            0
        );
    }

    #[test]
    fn per_ip_connection_limit_cannot_starve_another_source() {
        let config = WebRtcDirectConfig::default();
        let resources = ListenerResources::new(&config);
        let attacker: SocketAddr = "198.51.100.1:1000".parse().expect("attacker address");
        let honest: SocketAddr = "203.0.113.2:2000".parse().expect("honest address");
        let mut attacker_admissions = Vec::new();

        for port in 0..config.max_connections_per_ip {
            let mut address = attacker;
            address.set_port(u16::try_from(port + 1).expect("test port"));
            attacker_admissions.push(
                resources
                    .try_admit_connection(address)
                    .expect("source share remains"),
            );
        }
        assert_eq!(attacker_admissions.len(), config.max_connections_per_ip);
        assert_eq!(
            resources.try_admit_connection(attacker).err().as_deref(),
            Some(SOURCE_CONNECTION_CAPACITY_ERROR)
        );
        let honest_admission = resources
            .try_admit_connection(honest)
            .expect("another source retains listener headroom");

        drop(attacker_admissions.pop());
        resources
            .try_admit_connection(attacker)
            .expect("released source slot is reusable");
        drop(honest_admission);
    }

    #[test]
    fn ipv4_mapped_ipv6_cannot_bypass_source_accounting() {
        let config = WebRtcDirectConfig::default();
        let resources = ListenerResources::new(&config);
        let v4: SocketAddr = "192.0.2.44:1000".parse().expect("IPv4 address");
        let mapped: SocketAddr = "[::ffff:192.0.2.44]:2000".parse().expect("mapped address");
        let mut admissions = vec![resources
            .try_admit_connection(v4)
            .expect("first connection")];
        for _ in 1..config.max_connections_per_ip {
            admissions.push(
                resources
                    .try_admit_connection(mapped)
                    .expect("mapped source share"),
            );
        }
        assert_eq!(admissions.len(), config.max_connections_per_ip);
        assert_eq!(
            resources.try_admit_connection(mapped).err().as_deref(),
            Some(SOURCE_CONNECTION_CAPACITY_ERROR)
        );
    }

    #[test]
    fn ipv6_hosts_share_connection_rate_and_byte_budgets_by_prefix() {
        let config = WebRtcDirectConfig::default();
        let resources = ListenerResources::new(&config);
        let mut admissions = Vec::new();
        for host in 1..=config.max_connections_per_ip {
            let addr = format!("[2001:db8:1234:5678::{host:x}]:1000")
                .parse()
                .expect("IPv6 host");
            admissions.push(resources.try_admit_connection(addr).expect("prefix share"));
        }
        assert!(Arc::ptr_eq(
            &admissions[0].context.source,
            &admissions[1].context.source
        ));
        let same_prefix = "[2001:db8:1234:5678::ffff]:2000"
            .parse()
            .expect("same prefix");
        assert_eq!(
            resources.try_admit_connection(same_prefix).err().as_deref(),
            Some(SOURCE_CONNECTION_CAPACITY_ERROR)
        );
        let other_prefix = "[2001:db8:1234:5679::1]:2000"
            .parse()
            .expect("other prefix");
        resources
            .try_admit_connection(other_prefix)
            .expect("independent prefix");
        drop(admissions.pop());
        resources
            .try_admit_connection(same_prefix)
            .expect("released prefix slot");
    }

    #[tokio::test]
    async fn active_requests_suspend_idle_timeout_but_not_channel_closure() {
        let (activity, receiver) = watch::channel(1usize);
        let (closed, receive) = tokio::sync::oneshot::channel::<()>();
        let mut waiting = Box::pin(receive_while_active(
            receive,
            receiver,
            Duration::from_millis(15),
        ));
        assert!(
            tokio::time::timeout(Duration::from_millis(40), &mut waiting)
                .await
                .is_err()
        );
        closed.send(()).unwrap();
        assert!(waiting.await.unwrap().is_ok());
        drop(activity);
    }

    #[tokio::test]
    async fn idle_budget_starts_after_the_last_active_response() {
        let (activity, receiver) = watch::channel(1usize);
        let waiting = receive_while_active(
            std::future::pending::<()>(),
            receiver,
            Duration::from_millis(15),
        );
        tokio::pin!(waiting);
        assert!(
            tokio::time::timeout(Duration::from_millis(30), &mut waiting)
                .await
                .is_err()
        );
        activity.send_replace(0);
        assert_eq!(waiting.await.unwrap_err(), "request idle timeout");
    }

    #[test]
    fn request_token_bucket_refills_without_growing_state() {
        let mut bucket = RequestRateBucket::new(2);
        let start = bucket.last_refill;
        assert!(bucket.allow(start));
        assert!(bucket.allow(start));
        assert!(!bucket.allow(start));
        assert!(bucket.allow(start + Duration::from_millis(500)));
        assert!(!bucket.allow(start + Duration::from_millis(500)));
        assert!(bucket.allow(start + Duration::from_secs(1)));
    }

    #[test]
    fn per_ip_request_rate_leaves_other_sources_admissible() {
        let config = WebRtcDirectConfig {
            max_requests_per_second: 4,
            max_requests_per_second_per_ip: 2,
            max_requests_per_second_per_connection: 2,
            ..WebRtcDirectConfig::default()
        };
        let resources = ListenerResources::new(&config);
        let attacker = resources
            .try_admit_connection("198.51.100.1:1000".parse().expect("attacker"))
            .expect("attacker connection");
        let honest = resources
            .try_admit_connection("203.0.113.2:2000".parse().expect("honest"))
            .expect("honest connection");

        assert!(attacker.context.try_admit_request().is_ok());
        assert!(attacker.context.try_admit_request().is_ok());
        assert_eq!(
            attacker.context.try_admit_request().err().as_deref(),
            Some(REQUEST_RATE_ERROR)
        );
        assert!(honest.context.try_admit_request().is_ok());
    }

    #[test]
    fn reconnecting_does_not_reset_the_source_request_bucket() {
        let config = WebRtcDirectConfig {
            max_requests_per_second: 100,
            max_requests_per_second_per_ip: 1,
            max_requests_per_second_per_connection: 1,
            ..WebRtcDirectConfig::default()
        };
        let resources = ListenerResources::new(&config);
        let address = "198.51.100.1:1000".parse().expect("source");
        let first = resources
            .try_admit_connection(address)
            .expect("first connection");
        assert!(first.context.try_admit_request().is_ok());
        drop(first);

        let replacement = resources
            .try_admit_connection(address)
            .expect("replacement connection");
        assert_eq!(
            replacement.context.try_admit_request().err().as_deref(),
            Some(REQUEST_RATE_ERROR)
        );
    }

    #[test]
    fn inactive_source_rate_state_has_a_hard_bound() {
        let config = WebRtcDirectConfig::default();
        let resources = ListenerResources::new(&config);
        for index in 0..resources.max_tracked_sources + 10 {
            let third = u8::try_from(index / 254).expect("third octet");
            let host = u8::try_from(index % 254 + 1).expect("host octet");
            let address = SocketAddr::from((Ipv4Addr::new(198, 51, third, host), 1000));
            drop(
                resources
                    .try_admit_connection(address)
                    .expect("sequential source"),
            );
        }
        assert_eq!(
            resources.source_state.lock().sources.len(),
            resources.max_tracked_sources
        );
    }

    #[test]
    fn source_churn_cannot_evict_disconnected_work_or_reset_its_budget() {
        let resources = ListenerResources::new(&WebRtcDirectConfig::default());
        let address = "192.0.2.1:1000".parse().expect("source");
        let connection = resources.try_admit_connection(address).expect("connection");
        let worker_resources = Arc::clone(&connection.context);
        let reservation = worker_resources
            .try_reserve_bytes(resources.max_in_flight_bytes_per_ip)
            .expect("budget");
        drop(connection);
        for index in 0..resources.max_tracked_sources + 10 {
            let third = u8::try_from(index / 254).expect("third octet");
            let host = u8::try_from(index % 254 + 1).expect("host octet");
            let other = SocketAddr::from((Ipv4Addr::new(198, 51, third, host), 1000));
            drop(resources.try_admit_connection(other).expect("source churn"));
        }
        let reconnect = resources.try_admit_connection(address).expect("reconnect");
        assert!(Arc::ptr_eq(
            &worker_resources.source,
            &reconnect.context.source
        ));
        assert_eq!(
            reconnect.context.try_reserve_bytes(1).err().as_deref(),
            Some(SOURCE_BYTE_CAPACITY_ERROR)
        );
        drop(reservation);
        assert!(reconnect.context.try_reserve_bytes(1).is_ok());
    }

    #[tokio::test]
    async fn request_drain_keeps_started_work_and_rejects_late_registration() {
        let config = WebRtcDirectConfig::default();
        let resources = ListenerResources::new(&config);
        let connection = resources
            .try_admit_connection("192.0.2.1:1000".parse().expect("source"))
            .expect("connection");
        let request_permit = connection
            .context
            .try_admit_request()
            .expect("request slot");
        let bytes = connection.context.try_reserve_bytes(1024).expect("bytes");
        let (finish, finished) = tokio::sync::oneshot::channel::<()>();
        // Dropping the awaiter's handle must leave the actual work charged.
        drop(
            resources
                .spawn_request(async move {
                    let _request_permit = request_permit;
                    let _bytes = bytes;
                    finished.await.expect("finish signal");
                })
                .expect("started request"),
        );
        drop(connection);
        assert!(
            tokio::time::timeout(Duration::from_millis(10), resources.drain_requests())
                .await
                .is_err()
        );
        assert_eq!(resources.global_bytes.in_use(), 1024);
        assert_eq!(
            resources.request_limit.available_permits(),
            config.max_concurrent_requests - 1
        );
        assert!(
            resources.spawn_request(async {}).is_err(),
            "closed admission rejects a late channel"
        );
        finish.send(()).expect("finish work");
        tokio::time::timeout(Duration::from_secs(1), resources.drain_requests())
            .await
            .expect("drained");
        assert_eq!(resources.global_bytes.in_use(), 0);
        assert_eq!(
            resources.request_limit.available_permits(),
            config.max_concurrent_requests
        );
    }

    #[test]
    fn signed_quotes_and_commitments_fit_the_small_binary_response_bound() {
        use ant_protocol::payment::commitment::StorageCommitment;
        use ant_protocol::MerkleCandidateQuoteResponse;
        use evmlib::merkle_payments::MerklePaymentCandidateNode;
        use saorsa_pqc::api::sig::MlDsaVariant;

        // 0xff maximizes MessagePack's integer-array encoding. Use the actual
        // signature profile so an upstream size change exercises this bound.
        let public_key = vec![0xff; MlDsaVariant::MlDsa65.public_key_size()];
        let signature = vec![0xff; MlDsaVariant::MlDsa65.signature_size()];
        let commitment = rmp_serde::to_vec(&StorageCommitment {
            root: [0xff; 32],
            key_count: u32::MAX,
            sender_peer_id: [0xff; 32],
            sender_public_key: public_key.clone(),
            signature: signature.clone(),
        })
        .expect("commitment");
        let quote = PaymentQuote {
            content: xor_name::XorName([0xff; 32]),
            timestamp: SystemTime::UNIX_EPOCH + Duration::from_secs(u32::MAX.into()),
            price: Amount::MAX,
            rewards_address: RewardsAddress::new([0xff; 20]),
            pub_key: public_key.clone(),
            signature: signature.clone(),
            committed_key_count: u32::MAX,
            commitment_pin: Some([0xff; 32]),
        };
        let candidate = MerklePaymentCandidateNode {
            pub_key: public_key,
            price: Amount::MAX,
            reward_address: RewardsAddress::new([0xff; 20]),
            merkle_payment_timestamp: u64::MAX,
            signature,
            committed_key_count: u32::MAX,
            commitment_pin: Some([0xff; 32]),
        };
        for body in [
            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Success {
                quote: rmp_serde::to_vec(&quote).expect("quote"),
                already_stored: false,
                commitment: Some(commitment.clone()),
            }),
            ChunkMessageBody::MerkleCandidateQuoteResponse(MerkleCandidateQuoteResponse::Success {
                candidate_node: rmp_serde::to_vec(&candidate).expect("candidate"),
                commitment: Some(commitment),
            }),
        ] {
            let message = ChunkMessage {
                request_id: u64::MAX,
                body,
            };
            let bytes = encode_binary_response(&message, SMALL_BINARY_RESPONSE_BYTES)
                .expect("bounded quote");
            assert_eq!(bytes, message.encode().expect("shared wire encoding"));
            assert_eq!(bytes.capacity(), bytes.len());
        }
    }

    /// Pointers are advertised only by a node that serves them.
    #[test]
    fn only_a_node_that_serves_pointers_advertises_them() {
        let advertises = |caps: &[String]| caps.iter().any(|c| c == POINTER_PROTOCOL_CAPABILITY);
        assert!(advertises(&hello_capabilities(true)));
        assert!(!advertises(&hello_capabilities(false)));
        assert!(!serves_pointers(None), "no storage, no pointers");
    }

    /// Pointer reads and paid pointer writes are admitted (ADR-0016), and a
    /// full record fits the small bound they are given.
    #[test]
    fn pointer_requests_are_admitted_and_a_full_record_fits() {
        let get = ChunkMessageBody::PointerGetRequest(PointerGetRequest::new([0xff; 32]));
        let put = ChunkMessageBody::PointerPutRequest(PointerPutRequest::with_payment(
            vec![0xff; POINTER_WIRE_LEN].into(),
            vec![0xff; 16 * 1024],
        ));
        assert_eq!(
            binary_response_limit(&get).expect("pointer GET admitted"),
            SMALL_BINARY_RESPONSE_BYTES
        );
        assert_eq!(
            binary_response_limit(&put).expect("pointer PUT admitted"),
            SMALL_BINARY_RESPONSE_BYTES
        );

        let record = ChunkMessage {
            request_id: u64::MAX,
            body: ChunkMessageBody::PointerGetResponse(PointerGetResponse::Success {
                record: vec![0xff; POINTER_WIRE_LEN].into(),
            }),
        };
        let bytes = encode_binary_response(&record, SMALL_BINARY_RESPONSE_BYTES)
            .expect("a full record fits");
        assert_eq!(bytes, record.encode().expect("shared wire encoding"));

        let stored = ChunkMessage {
            request_id: u64::MAX,
            body: ChunkMessageBody::PointerPutResponse(PointerPutResponse::Success {
                address: [0xff; 32],
                state_id: [0xff; 32],
            }),
        };
        assert!(encode_binary_response(&stored, SMALL_BINARY_RESPONSE_BYTES).is_ok());

        // Replies are never admitted as requests.
        assert!(binary_response_limit(&record.body).is_err());
        assert!(binary_response_limit(&stored.body).is_err());
    }

    #[test]
    fn maximum_binary_get_fits_and_oversized_responses_are_rejected() {
        let request = ChunkMessageBody::GetRequest(ant_protocol::ChunkGetRequest::new([0xff; 32]));
        let response = ChunkMessage {
            request_id: u64::MAX,
            body: ChunkMessageBody::GetResponse(ant_protocol::ChunkGetResponse::Success {
                address: [0xff; 32],
                content: vec![0xff; MAX_CHUNK_SIZE],
            }),
        };
        let bytes = encode_binary_response(
            &response,
            binary_response_limit(&request).expect("GET bound"),
        )
        .expect("maximum GET");
        assert_eq!(bytes, response.encode().expect("shared wire encoding"));
        assert!(encode_binary_response(&response, SMALL_BINARY_RESPONSE_BYTES).is_err());
        assert!(binary_response_limit(&response.body).is_err());
    }

    #[test]
    fn byte_reservations_are_per_source_global_and_raii_released() {
        let config = WebRtcDirectConfig {
            max_in_flight_bytes: 256,
            max_in_flight_bytes_per_ip: 128,
            ..WebRtcDirectConfig::default()
        };
        let resources = ListenerResources::new(&config);
        let attacker = resources
            .try_admit_connection("198.51.100.1:1000".parse().expect("attacker"))
            .expect("attacker connection");
        let honest = resources
            .try_admit_connection("203.0.113.2:2000".parse().expect("honest"))
            .expect("honest connection");

        let attacker_bytes = attacker
            .context
            .try_reserve_bytes(128)
            .expect("attacker source budget");
        assert_eq!(resources.global_bytes.in_use(), 128);
        assert_eq!(
            attacker.context.try_reserve_bytes(1).err().as_deref(),
            Some(SOURCE_BYTE_CAPACITY_ERROR)
        );
        let honest_bytes = honest
            .context
            .try_reserve_bytes(64)
            .expect("another source retains byte headroom");
        assert_eq!(resources.global_bytes.in_use(), 192);

        drop(attacker_bytes);
        drop(honest_bytes);
        assert_eq!(resources.global_bytes.in_use(), 0);
        assert_eq!(attacker.context.source.bytes.in_use(), 0);
        assert_eq!(honest.context.source.bytes.in_use(), 0);
    }

    #[test]
    fn global_byte_rejection_rolls_back_the_source_reservation() {
        let config = WebRtcDirectConfig {
            max_in_flight_bytes: 100,
            max_in_flight_bytes_per_ip: 90,
            ..WebRtcDirectConfig::default()
        };
        let resources = ListenerResources::new(&config);
        let first = resources
            .try_admit_connection("198.51.100.1:1000".parse().expect("first"))
            .expect("first connection");
        let second = resources
            .try_admit_connection("203.0.113.2:2000".parse().expect("second"))
            .expect("second connection");
        let _first_bytes = first
            .context
            .try_reserve_bytes(60)
            .expect("first reservation");

        assert_eq!(
            second.context.try_reserve_bytes(50).err().as_deref(),
            Some(GLOBAL_BYTE_CAPACITY_ERROR)
        );
        assert_eq!(second.context.source.bytes.in_use(), 0);
        assert_eq!(resources.global_bytes.in_use(), 60);
    }

    #[test]
    fn wildcard_publication_waits_for_native_discovery_and_excludes_relays() {
        let config = WebRtcDirectConfig::default();
        let local = "0.0.0.0:43210".parse().expect("bound listener");
        assert_eq!(advertised_addr(&config, local, None, &[]), None);
        let addresses = vec![
            (
                MultiAddr::quic("203.0.113.1:1000".parse().expect("relay")),
                AddressType::Relay,
            ),
            (
                MultiAddr::quic("[2001:db8::1]:1000".parse().expect("IPv6")),
                AddressType::Direct,
            ),
        ];
        assert_eq!(advertised_addr(&config, local, None, &addresses), None);
        let mut addresses = addresses;
        addresses.push((
            MultiAddr::quic("198.51.100.2:1000".parse().expect("observed")),
            AddressType::Unverified,
        ));
        assert_eq!(
            advertised_addr(&config, local, None, &addresses),
            Some((
                "198.51.100.2:43210".parse().expect("WebRTC"),
                AddressSource::Native
            ))
        );
        addresses[2].0 = MultiAddr::quic("198.51.100.3:2000".parse().expect("new observed"));
        assert_eq!(
            advertised_addr(&config, local, None, &addresses),
            Some((
                "198.51.100.3:43210".parse().expect("updated WebRTC"),
                AddressSource::Native
            ))
        );
    }

    #[tokio::test]
    async fn automatic_port_is_os_assigned_and_explicit_advertisement_is_independent() {
        let certificate = WebRtcCertificate::generate().expect("certificate");
        let listener =
            WebRtcDirectListener::bind("127.0.0.1:0".parse().expect("bind"), certificate)
                .await
                .expect("ephemeral listener");
        let local = listener.local_addr();
        assert_ne!(local.port(), 0);
        assert_eq!(
            advertised_addr(&WebRtcDirectConfig::default(), local, None, &[]),
            Some((local, AddressSource::Bind))
        );
        let config = WebRtcDirectConfig {
            advertised_addr: Some("198.51.100.4:11000".parse().expect("advertised")),
            ..WebRtcDirectConfig::default()
        };
        assert_eq!(
            advertised_addr(&config, local, None, &[]),
            config
                .advertised_addr
                .map(|addr| (addr, AddressSource::Operator))
        );
        listener.close().await.expect("close listener");
    }

    #[test]
    fn only_a_listener_choosing_its_own_address_maps_its_port() {
        let wildcard = "0.0.0.0:43210".parse().expect("wildcard listener");
        let explicit = "192.0.2.7:43210".parse().expect("explicit listener");
        let default = WebRtcDirectConfig::default();
        assert!(maps_port_with_upnp(&default, wildcard, false));
        assert!(!maps_port_with_upnp(&default, explicit, false));
        let advertised = WebRtcDirectConfig {
            advertised_addr: Some("198.51.100.4:11000".parse().expect("advertised")),
            ..WebRtcDirectConfig::default()
        };
        assert!(!maps_port_with_upnp(&advertised, wildcard, false));
    }

    #[test]
    fn a_development_node_does_not_map_its_port() {
        let wildcard = "0.0.0.0:43210".parse().expect("wildcard listener");
        assert!(!maps_port_with_upnp(
            &WebRtcDirectConfig::default(),
            wildcard,
            true
        ));
    }

    #[test]
    fn an_ipv6_listener_does_not_map_its_port() {
        // Gateway mappings are IPv4, which an IPv6 listener never advertises.
        let wildcard = "[::]:43210".parse().expect("IPv6 wildcard listener");
        assert!(!maps_port_with_upnp(
            &WebRtcDirectConfig::default(),
            wildcard,
            false
        ));
    }

    #[test]
    fn a_gateway_mapping_is_advertised_before_the_native_view() {
        let local = "0.0.0.0:43210".parse().expect("wildcard listener");
        let native = vec![(
            MultiAddr::quic("198.51.100.2:1000".parse().expect("observed")),
            AddressType::Direct,
        )];
        let mapped: SocketAddr = "198.51.100.2:51000".parse().expect("mapped");
        let native_view: SocketAddr = "198.51.100.2:43210".parse().expect("native view");
        let default = WebRtcDirectConfig::default();
        // The gateway may forward another external port than the listener's.
        assert_eq!(
            advertised_addr(&default, local, Some(mapped), &native),
            Some((mapped, AddressSource::Mapped))
        );
        // A mapping needs no native discovery to be published.
        assert_eq!(
            advertised_addr(&default, local, Some(mapped), &[]),
            Some((mapped, AddressSource::Mapped))
        );
        // A mapping in the other address family cannot reach this listener.
        let mapped_v6 = "[2001:db8::2]:51000".parse().expect("IPv6 mapping");
        assert_eq!(
            advertised_addr(&default, local, Some(mapped_v6), &native),
            Some((native_view, AddressSource::Native))
        );
        // Losing the mapping falls back to the native view.
        assert_eq!(
            advertised_addr(&default, local, None, &native),
            Some((native_view, AddressSource::Native))
        );
        // An operator's advertisement still wins.
        let advertised = WebRtcDirectConfig {
            advertised_addr: Some("198.51.100.4:11000".parse().expect("advertised")),
            ..WebRtcDirectConfig::default()
        };
        assert_eq!(
            advertised_addr(&advertised, local, Some(mapped), &native),
            advertised
                .advertised_addr
                .map(|addr| (addr, AddressSource::Operator))
        );
    }

    #[test]
    fn a_mapping_the_native_view_also_yields_comes_from_the_native_view() {
        let local = "0.0.0.0:43210".parse().expect("wildcard listener");
        let native = vec![(
            MultiAddr::quic("198.51.100.2:1000".parse().expect("observed")),
            AddressType::Direct,
        )];
        // The gateway kept the listener's port, so the native view yields the
        // same address, which stays published without the mapping, as before.
        let kept: SocketAddr = "198.51.100.2:43210".parse().expect("mapped");
        assert_eq!(
            advertised_addr(&WebRtcDirectConfig::default(), local, Some(kept), &native),
            Some((kept, AddressSource::Native))
        );
    }

    /// A mapping the test can grant and take away.
    struct TestMapping(Arc<Mutex<Option<SocketAddr>>>);

    impl PortMapping for TestMapping {
        fn external(&self) -> Option<SocketAddr> {
            *self.0.lock()
        }
    }

    /// A wildcard listener whose only publishable address is a gateway
    /// mapping the test controls: a node that has not started has no native
    /// self-address.
    struct MappedOnlyListener {
        p2p: Arc<P2PNode>,
        mapping: Arc<Mutex<Option<SocketAddr>>>,
        catalog: Arc<BrowserEndpointCatalog>,
        state: ServerState,
        root: tempfile::TempDir,
        local: SocketAddr,
    }

    impl MappedOnlyListener {
        async fn new() -> Self {
            let p2p = Arc::new(
                P2PNode::new(
                    CoreNodeConfig::builder()
                        .local(true)
                        .ipv6(false)
                        .build()
                        .expect("core config"),
                )
                .await
                .expect("P2P node"),
            );
            let mapping = Arc::new(Mutex::new(Some(
                "198.51.100.2:51000".parse().expect("mapped"),
            )));
            let catalog = Arc::new(BrowserEndpointCatalog::default());
            let state = ServerState {
                config: WebRtcDirectConfig::default(),
                identity: Arc::clone(p2p.transport().node_identity()),
                p2p: Arc::clone(&p2p),
                ant_protocol: None,
                payment: BrowserPaymentNetwork {
                    chain_id: ARBITRUM_SEPOLIA_CHAIN_ID,
                    payment_token_address: String::new(),
                    payment_vault_address: String::new(),
                },
                publication: RwLock::new(Publication::default()),
                endpoint_catalog: Some(Arc::clone(&catalog)),
                port_mapping: Some(Box::new(TestMapping(Arc::clone(&mapping)))),
            };
            Self {
                p2p,
                mapping,
                catalog,
                state,
                root: tempfile::tempdir().expect("root directory"),
                local: "0.0.0.0:43210".parse().expect("wildcard listener"),
            }
        }

        async fn refresh(&self) -> Result<()> {
            refresh_browser_endpoint(
                &self.state,
                self.root.path(),
                self.local,
                CERTIFICATE_SHA256,
            )
            .await
        }

        fn file(&self) -> PathBuf {
            self.root.path().join(WEBRTC_DIRECT_MULTIADDR_FILENAME)
        }

        fn peer_id(&self) -> PeerId {
            *self.p2p.peer_id()
        }

        fn publication(&self) -> Publication {
            self.state.publication.read().clone()
        }

        async fn supplemental(&self) -> Vec<MultiAddr> {
            self.p2p
                .dht_manager()
                .supplemental_addresses_for_peer(&self.peer_id())
                .await
        }

        /// Assert that peers and browsers no longer see the endpoint.
        async fn assert_unpublished(&self) {
            assert_eq!(self.publication().endpoint(), None);
            assert_eq!(self.catalog.get(&self.peer_id()), None);
            assert_eq!(self.supplemental().await, Vec::<MultiAddr>::new());
        }
    }

    #[tokio::test]
    async fn an_endpoint_only_its_mapping_reached_is_withdrawn_when_the_mapping_ends() {
        let listener = MappedOnlyListener::new().await;

        listener.refresh().await.expect("publish the mapping");
        let published = listener
            .publication()
            .endpoint()
            .cloned()
            .expect("published endpoint");
        assert_eq!(
            listener.publication(),
            Publication::Published {
                endpoint: published.clone(),
                source: AddressSource::Mapped
            }
        );
        assert!(published.multiaddr.contains("/198.51.100.2/udp/51000/"));
        assert!(tokio::fs::read_to_string(listener.file())
            .await
            .expect("endpoint file")
            .contains(&published.multiaddr));
        assert_eq!(listener.catalog.get(&listener.peer_id()), Some(published));
        assert_eq!(listener.supplemental().await.len(), 1);

        *listener.mapping.lock() = None;
        listener.refresh().await.expect("withdraw the mapping");
        listener.assert_unpublished().await;
        assert!(!listener.file().exists());

        // With nothing published, a later refresh without a mapping is a no-op.
        listener.refresh().await.expect("nothing to withdraw");
        assert_eq!(listener.publication(), Publication::Unpublished);
    }

    #[tokio::test]
    async fn a_withdrawal_the_endpoint_file_blocks_still_unpublishes_and_is_retried() {
        let listener = MappedOnlyListener::new().await;
        listener.refresh().await.expect("publish the mapping");

        // A directory in the file's place makes removing it fail.
        tokio::fs::remove_file(listener.file())
            .await
            .expect("remove the endpoint file");
        tokio::fs::create_dir(listener.file())
            .await
            .expect("block the endpoint file");
        *listener.mapping.lock() = None;
        listener
            .refresh()
            .await
            .expect_err("the endpoint file cannot be removed");
        listener.assert_unpublished().await;
        assert_eq!(listener.publication(), Publication::Withdrawing);

        // Once the file can be removed, the next refresh finishes the withdrawal.
        tokio::fs::remove_dir(listener.file())
            .await
            .expect("unblock the endpoint file");
        tokio::fs::write(listener.file(), "stale endpoint\n")
            .await
            .expect("stale endpoint file");
        listener.refresh().await.expect("finish the withdrawal");
        assert!(!listener.file().exists());
        listener.assert_unpublished().await;
        assert_eq!(listener.publication(), Publication::Unpublished);
    }

    #[test]
    fn only_a_mapped_publication_is_withdrawn() {
        let endpoint = BrowserEndpoint::new(
            "198.51.100.2:43210".parse().expect("socket address"),
            PeerId::from_bytes([0x42; 32]).to_bytes(),
            CERTIFICATE_SHA256,
        )
        .expect("browser endpoint");
        for source in [
            AddressSource::Operator,
            AddressSource::Bind,
            AddressSource::Native,
        ] {
            let kept = Publication::Published {
                endpoint: endpoint.clone(),
                source,
            };
            let mut publication = kept.clone();
            assert_eq!(publication.begin_withdrawal(), None);
            assert_eq!(publication, kept);
        }
        let mut mapped = Publication::Published {
            endpoint: endpoint.clone(),
            source: AddressSource::Mapped,
        };
        assert_eq!(mapped.begin_withdrawal(), Some(endpoint));
        assert_eq!(mapped, Publication::Withdrawing);
        // A withdrawal already under way has nothing left to take.
        assert_eq!(mapped.begin_withdrawal(), None);
        assert_eq!(mapped, Publication::Withdrawing);
    }

    #[test]
    fn parses_versioned_requests() {
        let request: Request = serde_json::from_str(
            r#"{"version":5,"request_id":7,"content_length":0,"type":"find_node","target":"0000000000000000000000000000000000000000000000000000000000000000","count":20}"#,
        )
        .expect("valid request");

        assert_eq!(request.version, BROWSER_PROTOCOL_VERSION);
        assert_eq!(request.request_id, 7);
        assert!(matches!(request.body, RequestBody::FindNode { .. }));
    }

    #[test]
    fn validates_fixed_width_hex() {
        assert_eq!(
            decode_32_byte_hex(&"ab".repeat(32)).expect("32 bytes"),
            [0xab; 32]
        );
        assert!(decode_32_byte_hex("abcd").is_err());
        assert!(decode_32_byte_hex(&"zz".repeat(32)).is_err());
    }

    #[test]
    fn payment_quote_hash_vector_uses_evm_keccak256() {
        // Shared with ant-client-web's paymentQuoteHash test. ANT addresses use
        // BLAKE3, but the quote hash paid to the EVM vault is evmlib Keccak-256.
        assert_eq!(
            hex::encode(evmlib::cryptography::hash([0_u8, 1, 2, 3])),
            "d98f2e8134922f73748703c8e7084d42f13d2fa1439936ef5a3abcf5646fe83f"
        );
    }

    #[test]
    fn largest_paid_upload_header_fits_fixed_protocol_limit() {
        // 0xff maximizes MessagePack's integer-array encoding. Exercise the
        // actual native commitment serializer, including the JSON duplication
        // of the commitment's public key and signature.
        let commitment = ::ant_protocol::payment::commitment::StorageCommitment {
            root: [0xff; 32],
            key_count: u32::MAX,
            sender_peer_id: [0xff; 32],
            sender_public_key: vec![0xff; 1952],
            signature: vec![0xff; 3309],
        };
        let encoded = rmp_serde::to_vec(&commitment).expect("serialize commitment");
        let quote = BrowserQuoteArtifact {
            peer_id: "ff".repeat(32),
            content: "ff".repeat(32),
            timestamp_secs: u64::MAX,
            price: "9".repeat(78), // decimal U256 width
            rewards_address: format!("0x{}", "ff".repeat(20)),
            public_key: "ff".repeat(1952),
            signature: "ff".repeat(3309),
            committed_key_count: u32::MAX,
            commitment_pin: Some("ff".repeat(32)),
            quote_hash: "ff".repeat(32),
            commitment: Some(browser_commitment_from_bytes(&encoded).expect("commitment artifact")),
        };
        let request = Request::new(
            u64::MAX,
            RequestBody::PutChunk {
                address: "ff".repeat(32),
                quote: Box::new(quote),
                transaction_hash: format!("0x{}", "ff".repeat(32)),
            },
            MAX_CHUNK_SIZE,
        );
        let header = serde_json::to_vec(&request).expect("serialize paid request");
        assert!(
            header.len() < MAX_BROWSER_HEADER_BYTES,
            "{} bytes",
            header.len()
        );
        let content = vec![0xff; MAX_CHUNK_SIZE];
        let frame = saorsa_transport::webrtc::encode_request_frame(&request, &content)
            .expect("largest paid upload fits");
        assert_eq!(
            parse_request_header(&frame).expect("parse upload").0,
            request
        );
    }

    #[test]
    fn response_header_declares_raw_content_length() {
        let response = Response::ok(
            42,
            ResponseBody::Chunk {
                address: "11".repeat(32),
                size: 3,
            },
            3,
        );
        let value = serde_json::to_value(response).expect("serialize response");
        assert_eq!(value["version"], BROWSER_PROTOCOL_VERSION);
        assert_eq!(value["request_id"], 42);
        assert_eq!(value["status"], "ok");
        assert_eq!(value["content_length"], 3);
        assert_eq!(value["type"], "chunk");
    }

    #[test]
    fn derives_ipv6_advertised_address() {
        let config = WebRtcDirectConfig::default();
        let (addr, source) =
            advertised_addr(&config, "[::1]:23456".parse().expect("socket"), None, &[])
                .expect("advertised address");
        assert_eq!(addr, "[::1]:23456".parse().expect("socket"));
        assert_eq!(source, AddressSource::Bind);
    }

    #[tokio::test]
    async fn dtls_certificate_is_stable_across_reloads() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let path = directory.path().join("webrtc-direct.pem");
        let first = load_or_generate_certificate(&path)
            .await
            .expect("generate certificate");
        let second = load_or_generate_certificate(&path)
            .await
            .expect("reload certificate");

        assert_eq!(
            first.sha256_digest().expect("first fingerprint"),
            second.sha256_digest().expect("second fingerprint")
        );
        assert!(path.exists());
    }

    #[tokio::test]
    async fn persists_canonical_browser_bootstrap_address() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let peer_id = PeerId::from_bytes([0x42; 32]);
        let endpoint = BrowserEndpoint::new(
            "203.0.113.7:11000".parse().expect("socket address"),
            peer_id.to_bytes(),
            [0x24; 32],
        )
        .expect("browser endpoint");

        persist_browser_endpoint(directory.path(), &endpoint)
            .await
            .expect("persist endpoint");

        let contents =
            tokio::fs::read_to_string(directory.path().join(WEBRTC_DIRECT_MULTIADDR_FILENAME))
                .await
                .expect("read endpoint file");
        assert_eq!(contents, format!("{}\n", endpoint.multiaddr));
    }

    #[test]
    fn find_node_exposes_propagated_webrtc_endpoint_separately() {
        let peer_id = PeerId::from_bytes([0x31; 32]);
        let endpoint = BrowserEndpoint::new(
            "203.0.113.9:42768".parse().expect("socket address"),
            peer_id.to_bytes(),
            [0x52; 32],
        )
        .expect("browser endpoint");
        let native = "/ip4/203.0.113.9/udp/10000/quic"
            .parse()
            .expect("native multiaddress");
        let node = DHTNode {
            peer_id,
            addresses: vec![native],
            address_types: Vec::new(),
            distance: None,
            reliability: 0.75,
            address_authority: None,
        };

        let supplemental = endpoint
            .multiaddr
            .parse()
            .expect("WebRTC Direct multiaddress");
        let browser_node = browser_node_from_dht(&node, std::slice::from_ref(&supplemental), None);

        assert_eq!(browser_node.webrtc_direct, Some(endpoint));
        assert_eq!(
            browser_node.native_addresses,
            vec!["/ip4/203.0.113.9/udp/10000/quic"]
        );
    }

    #[test]
    fn production_find_node_does_not_use_dev_endpoint_catalog() {
        let peer_id = PeerId::from_bytes([0x32; 32]);
        let endpoint = BrowserEndpoint::new(
            "203.0.113.10:42768".parse().expect("socket address"),
            peer_id.to_bytes(),
            [0x53; 32],
        )
        .expect("browser endpoint");
        let node = DHTNode {
            peer_id,
            addresses: Vec::new(),
            address_types: Vec::new(),
            distance: None,
            reliability: 0.75,
            address_authority: None,
        };
        let catalog = BrowserEndpointCatalog::default();
        catalog.insert(peer_id, endpoint.clone());

        let browser_node = browser_node_from_dht(&node, &[], None);

        assert!(browser_node.webrtc_direct.is_none());

        let devnet_node = browser_node_from_dht(&node, &[], Some(&catalog));
        assert_eq!(devnet_node.webrtc_direct, Some(endpoint));
    }
}