ant-node 0.23.1

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
//! Gossip-triggered contiguous-subtree storage audit (ADR-0002).
//!
//! A node commits to what it stores (a signed Merkle [`StorageCommitment`]
//! gossiped to neighbours). On receiving a peer's changed commitment, a
//! neighbour may audit it: pin the just-gossiped root, send a fresh nonce that
//! deterministically selects one contiguous subtree, and require the peer to
//! prove that subtree (structure + real bytes) within a deadline. This module
//! owns the auditor entry point [`run_subtree_audit`] and the responder handler
//! [`handle_subtree_challenge`]; the pure proof maths live in
//! [`crate::replication::subtree`].

use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::logging::{debug, info, warn};
use bytes::Bytes;
use rand::Rng;

use crate::ant_protocol::XorName;
use crate::pointer::store::{PointerStore, SUPERSEDED_RETENTION};
use crate::replication::commitment::{commitment_hash, pointer_leaf_hash, StorageCommitment};
use crate::replication::commitment_state::ResponderCommitmentState;
use crate::replication::config::{
    ReplicationConfig, MAX_SLICE_OPENINGS, SUBTREE_AUDIT_PROTOCOL_ID,
    SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES, SUBTREE_SESSION_TTL,
};
use crate::replication::protocol::{
    RejectKind, ReplicationMessage, ReplicationMessageBody, SubtreeAuditChallenge,
    SubtreeAuditResponse, SubtreeSliceChallenge, SubtreeSliceItem, SubtreeSliceOpening,
    SubtreeSliceResponse, MAX_POINTER_RECORDS_PER_ITEM,
};
use crate::replication::recent_provers::RecentProvers;
use crate::replication::slice::nonced_block_root;
use crate::replication::subtree::{
    select_subtree_path, subtree_plan, verify_subtree_proof, StructureVerdict, SubtreeLeaf,
    SubtreeProof,
};
use crate::replication::types::{AuditFailureReason, AuditFailureSummary, FailureEvidence};
use crate::storage::ChunkStore;
use ant_protocol::pointer::{Pointer, POINTER_WIRE_LEN};
use saorsa_core::identity::PeerId;
use saorsa_core::P2PNode;
use tokio::sync::RwLock;

// The gossip-triggered auditor shares the engine's [`AuditTickResult`] outcome
// type with the responsible-chunk audit (defined in [`super::audit`]), so the
// engine can dispatch both audits' results through one match.
use crate::replication::audit::AuditTickResult;

// ---------------------------------------------------------------------------
// Auditor side
// ---------------------------------------------------------------------------

/// ADR-0002 round-2 slice challenge samples a SMALL surprise set of the proven
/// leaves (3..=5). Small enough that the responder's honest local-disk read of
/// the original chunks stays well inside the response deadline, which is a
/// liveness bound and nothing more here: the reply is a few KB, so no deadline
/// prices a relay out of fetching it (ADR-0009). Large enough that faking a
/// fraction `x` of leaves survives only `(1 - x)^k`.
const BYTE_SPOTCHECK_MIN: u32 = 3;
const BYTE_SPOTCHECK_MAX: u32 = 5;

// Each sampled leaf produces up to two openings (a fresh-random block plus the
// claimed final block, deduplicated when they coincide), so the opening cap must
// cover twice the leaf sample.
const _: () = assert!(
    2 * BYTE_SPOTCHECK_MAX as usize <= MAX_SLICE_OPENINGS,
    "MAX_SLICE_OPENINGS must cover two openings per sampled leaf"
);

/// ADR-0004 A1: with grace removed, the responder retries a TRANSIENT chunk-read
/// error a few times before rejecting `Transient` (which routes to the timeout
/// lane). A momentary disk blip usually clears within these attempts; only a
/// persistent read failure — the node genuinely cannot serve committed bytes —
/// falls through. Total added latency ((attempts − 1) × backoff) stays well inside the
/// audit response deadline.
const AUDIT_READ_RETRY_ATTEMPTS: u32 = 3;
const AUDIT_READ_RETRY_BACKOFF: Duration = Duration::from_millis(200);

/// Read a committed chunk's bytes, retrying a transient read error up to
/// [`AUDIT_READ_RETRY_ATTEMPTS`] times with [`AUDIT_READ_RETRY_BACKOFF`] between
/// tries. `Ok(None)` (bytes definitively absent — real loss) is NOT retried; only
/// an `Err` (transient IO) is. A persistent `Err` is returned so the caller emits
/// `RejectKind::Transient` (timeout lane).
async fn get_raw_retrying(
    storage: &ChunkStore,
    key: &XorName,
) -> crate::error::Result<Option<Vec<u8>>> {
    let mut attempt = 1u32;
    loop {
        match storage.get_raw(key).await {
            Ok(v) => return Ok(v),
            Err(e) if attempt < AUDIT_READ_RETRY_ATTEMPTS => {
                debug!(
                    "Audit: transient read error for {} (attempt {attempt}/{AUDIT_READ_RETRY_ATTEMPTS}): {e}; retrying",
                    hex::encode(key)
                );
                attempt += 1;
                tokio::time::sleep(AUDIT_READ_RETRY_BACKOFF).await;
            }
            Err(e) => return Err(e),
        }
    }
}

/// How the auditor grades a *responsive* audit rejection (ADR-0004 A1: grace
/// removed). The decision is a pure function of the [`RejectKind`] so it can be
/// unit-tested independently of the P2P/side-effect machinery.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RejectGrade {
    /// Provable misbehaviour → confirmed failure (trust penalty + credit
    /// revocation downstream).
    Confirmed,
    /// Non-response/timeout lane: no trust penalty, but the pinned commitment's
    /// holder credit is revoked (the peer answered but could not prove possession).
    TimeoutLane,
}

/// Grade a responsive rejection. Repudiating a pinned root (`UnknownCommitment`)
/// or an explicit protocol fault is a confirmed failure; a `Transient` read error
/// (already retried by the responder) routes to the timeout lane.
const fn grade_reject(kind: RejectKind) -> RejectGrade {
    match kind {
        RejectKind::UnknownCommitment | RejectKind::Protocol => RejectGrade::Confirmed,
        RejectKind::Transient => RejectGrade::TimeoutLane,
    }
}

/// Holder-eligibility cache the auditor credits on a passing audit.
///
/// Owned by [`crate::replication::ReplicationEngine`]; borrowed here so a
/// passing audit can record `(peer, commitment_hash)` as a proven holder for
/// downstream quorum / paid-list credit.
pub struct AuditCredit<'a> {
    /// Holder-eligibility cache.
    pub recent_provers: &'a Arc<RwLock<RecentProvers>>,
}

/// Local subsystem that launched a storage-commitment audit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubtreeAuditOrigin {
    /// Lottery-gated audit after commitment gossip.
    Gossip,
    /// Deterministic audit after a commitment-backed payment.
    FirstMonetized,
    /// Explicit test or diagnostic request.
    Manual,
}

#[cfg(feature = "logging")]
impl SubtreeAuditOrigin {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Gossip => "gossip",
            Self::FirstMonetized => "first_monetized",
            Self::Manual => "manual",
        }
    }
}

/// The cross-cutting context for verifying one audit response, bundled so the
/// response-dispatch and verification functions stay readable.
struct AuditCtx<'a> {
    p2p_node: &'a Arc<P2PNode>,
    challenged_peer: &'a PeerId,
    challenge_id: u64,
    nonce: [u8; 32],
    expected_commitment_hash: [u8; 32],
    config: &'a ReplicationConfig,
    credit: Option<&'a AuditCredit<'a>>,
    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
    origin: SubtreeAuditOrigin,
}

/// Run one gossip-triggered subtree audit against `challenged_peer`, pinned to
/// the commitment hash the peer just gossiped (`expected_commitment_hash`).
///
/// ADR-0002 two-round audit. The auditor sends a fresh random nonce and runs:
///
/// 1. **Structure** (round 1) — the returned subtree rebuilds to the pinned
///    root, within a size-scaled deadline.
/// 2. **Verified slice** (round 2) — for a 3..=5 FRESHLY-RANDOM sample of the
///    proven leaves (chosen after the proof arrives, not nonce-derived — see
///    `random_spotcheck_leaves`), the auditor opens one random 1 KiB block per
///    leaf (plus its final block) and verifies a Bao slice against the chunk
///    address and a nonced-tree opening against the round-1 `nonced_root`, over
///    the bytes the responder serves. The auditor holds none of the peer's
///    chunks, and possession is the round-1 commitment, not a full-chunk transfer.
/// 3. **Timing** — a response deadline still bounds liveness, but (unlike the old
///    full-byte round 2) it is no longer the possession proof; that is the
///    round-1 `nonced_root` commitment.
///
/// A timeout (either round) is reported as [`AuditFailureReason::Timeout`] (the
/// caller applies the strike/grace policy). Any structural failure, served
/// content that fails a hash, an explicit `Absent` for a committed sampled key,
/// or a rejection of a recently gossiped commitment, is a confirmed failure
/// acted on immediately. On a full pass, records the peer as a proven holder.
pub async fn run_subtree_audit(
    p2p_node: &Arc<P2PNode>,
    config: &ReplicationConfig,
    challenged_peer: &PeerId,
    expected_commitment_hash: [u8; 32],
    key_count: u32,
    credit: Option<&AuditCredit<'_>>,
) -> AuditTickResult {
    run_subtree_audit_with_origin(
        p2p_node,
        config,
        challenged_peer,
        expected_commitment_hash,
        key_count,
        credit,
        SubtreeAuditOrigin::Manual,
    )
    .await
}

/// Run a subtree audit while retaining the local scheduler origin in logs.
pub(crate) async fn run_subtree_audit_with_origin(
    p2p_node: &Arc<P2PNode>,
    config: &ReplicationConfig,
    challenged_peer: &PeerId,
    expected_commitment_hash: [u8; 32],
    key_count: u32,
    credit: Option<&AuditCredit<'_>>,
    origin: SubtreeAuditOrigin,
) -> AuditTickResult {
    let (nonce, challenge_id) = {
        let mut rng = rand::thread_rng();
        (rng.gen::<[u8; 32]>(), rng.gen::<u64>())
    };

    let challenge = SubtreeAuditChallenge {
        challenge_id,
        nonce,
        challenged_peer_id: *challenged_peer.as_bytes(),
        expected_commitment_hash,
    };
    let msg = ReplicationMessage {
        request_id: challenge_id,
        body: ReplicationMessageBody::SubtreeAuditChallenge(challenge),
    };
    let encoded = match msg.encode() {
        Ok(data) => data,
        Err(e) => {
            warn!("Audit: failed to encode subtree challenge for {challenged_peer}: {e}");
            return AuditTickResult::Idle;
        }
    };

    // Size the proof deadline from the ACTUAL selected subtree (its real-leaf
    // count for this nonce + key_count), not a fixed worst-case hint. This keeps
    // the deadline proportional to the work an honest responder actually owes —
    // hashing ~sqrt(N) chunks at local-disk speed — so a slow honest node is not
    // failed for being large. It is not an anti-relay bound: see ADR-0009, the
    // proof is delegable at any deadline. The auditor and responder derive the
    // same selection, so we know the leaf count before the response arrives.
    let subtree_leaves = select_subtree_path(&nonce, key_count).map_or_else(
        || config.subtree_audit_timeout_leaf_hint(),
        |p| p.real_leaf_count() as usize,
    );
    let timeout = config.audit_response_timeout(subtree_leaves);

    info!(
        target: "ant_node::replication::audit_requester",
        event = "started",
        audit_origin = origin.as_str(),
        audit_round = "subtree",
        challenged_peer = %challenged_peer,
        challenge_id,
        work_items = subtree_leaves,
        timeout_ms = timeout.as_millis(),
        "Outbound audit request started"
    );
    let request_started = Instant::now();
    let response = match p2p_node
        .send_request(challenged_peer, SUBTREE_AUDIT_PROTOCOL_ID, encoded, timeout)
        .await
    {
        Ok(resp) => {
            info!(
                target: "ant_node::replication::audit_requester",
                event = "completed",
                audit_origin = origin.as_str(),
                audit_round = "subtree",
                challenged_peer = %challenged_peer,
                challenge_id,
                work_items = subtree_leaves,
                elapsed_ms = request_started.elapsed().as_millis(),
                outcome = "response",
                "Outbound audit request completed"
            );
            resp
        }
        Err(e) => {
            warn!(
                target: "ant_node::replication::audit_requester",
                event = "completed",
                audit_origin = origin.as_str(),
                audit_round = "subtree",
                challenged_peer = %challenged_peer,
                challenge_id,
                work_items = subtree_leaves,
                elapsed_ms = request_started.elapsed().as_millis(),
                outcome = "no_response",
                error = %e,
                "Outbound audit request completed without a response"
            );
            return failed(challenged_peer, challenge_id, AuditFailureReason::Timeout);
        }
    };

    let resp_msg = match ReplicationMessage::decode_subtree_audit_response(&response.data) {
        Ok(m) => m,
        Err(e) => {
            warn!("Audit: failed to decode subtree response from {challenged_peer}: {e}");
            return failed(
                challenged_peer,
                challenge_id,
                AuditFailureReason::MalformedResponse,
            );
        }
    };

    let ctx = AuditCtx {
        p2p_node,
        challenged_peer,
        challenge_id,
        nonce,
        expected_commitment_hash,
        config,
        credit,
        origin,
    };
    dispatch_subtree_response(resp_msg.body, &ctx).await
}

/// Outcome of the round-2 slice challenge round-trip (auditor side).
enum SliceRound {
    /// The responder returned per-opening items (verified by the caller).
    Served(Vec<SubtreeSliceItem>),
    /// The responder rejected the slice challenge (confirmed failure for a
    /// recently pinned commitment).
    Rejected,
    /// The responder rejected with `Transient` (a local read error): routed to
    /// the non-response/timeout lane — no trust penalty, but the pinned
    /// commitment's holder credit is revoked, because the peer answered and
    /// could not prove possession, so it must not keep stale credit.
    ///
    /// This lands in the same place as [`SliceRound::Timeout`] below, which also
    /// revokes commitment-scoped credit without a trust penalty. The two are
    /// kept separate because they say different things about the peer — one
    /// could not read its disk, the other did not reply at all — and only the
    /// reason is logged differently.
    TransientReject,
    /// No response within the slice deadline, or a transport error. Routed to
    /// the non-response/timeout lane: no trust penalty, but the pinned
    /// commitment's holder credit is revoked.
    ///
    /// Silence here is not the same as a silent peer in general. The responder
    /// answered round 1 in this same exchange, so it was live and reachable, and
    /// it saw which blocks were drawn before deciding whether to reply. Leaving
    /// credit in place would make "answer only when the draw is favourable" a
    /// free strategy: an unfavourable sample would cost nothing and the credit
    /// earned from an earlier favourable one would survive. Revoking scopes the
    /// cost to the pinned commitment, so the peer must actually answer a round 2
    /// to hold credit, while an honest node that drops one reply keeps its trust
    /// intact and re-earns credit on its next audit.
    Timeout,
    /// The responder claimed `Bootstrapping` in round 2 after answering a valid
    /// round-1 proof. A node that just produced a signed subtree proof is
    /// provably not bootstrapping, so this responsive contradiction is a
    /// confirmed failure (not a graced timeout): it revokes the peer's holder
    /// credit and takes the trust penalty.
    ///
    /// This classification relies on `is_bootstrapping` being ONE-WAY (true →
    /// false; see `mod.rs`): a round-1 proof implies the snapshot was already
    /// `false`, and a restart drops the single-use round-1 session so round 2 is
    /// answered `Transient` before this branch is ever reached. An honest running
    /// node therefore cannot produce this response; only a malicious, incompatible,
    /// or future broken-state peer can. If a "re-bootstrap" (false → true)
    /// transition is ever added, it MUST clear live sessions or this policy must
    /// be revisited.
    ResponsiveBootstrap,
    /// Malformed / unexpected round-2 response body.
    Malformed,
}

/// Round 2: ask the responder to open `openings` blocks (one 1 KiB block per
/// sampled leaf, at most [`MAX_SLICE_OPENINGS`]) with a Bao verified slice plus a
/// nonced block-tree opening each. The reply is a few KB total, so there is no
/// batching. The responder cannot have predicted which leaves — or which block
/// within each — are opened (fresh post-proof randomness).
#[allow(clippy::too_many_lines)]
async fn request_slice_proof(ctx: &AuditCtx<'_>, openings: &[SubtreeSliceOpening]) -> SliceRound {
    let challenge = SubtreeSliceChallenge {
        challenge_id: ctx.challenge_id,
        nonce: ctx.nonce,
        challenged_peer_id: *ctx.challenged_peer.as_bytes(),
        expected_commitment_hash: ctx.expected_commitment_hash,
        openings: openings.to_vec(),
    };
    let msg = ReplicationMessage {
        request_id: ctx.challenge_id,
        body: ReplicationMessageBody::SubtreeSliceChallenge(challenge),
    };
    let encoded = match msg.encode() {
        Ok(data) => data,
        Err(e) => {
            warn!("Audit: failed to encode slice challenge: {e}");
            return SliceRound::Malformed;
        }
    };

    // Deadline sized to "honest responder reads `openings.len()` full local
    // chunks to build their proofs": generous, because what binds the bytes is
    // the round-1 nonced commitment, not the clock. It is a liveness bound only
    // — the reply is a few KB, so no deadline prices a relay out of it, and the
    // proof is delegable at any deadline (ADR-0009).
    let timeout = ctx.config.slice_audit_response_timeout(openings.len());
    info!(
        target: "ant_node::replication::audit_requester",
        event = "started",
        audit_origin = ctx.origin.as_str(),
        audit_round = "byte",
        challenged_peer = %ctx.challenged_peer,
        challenge_id = ctx.challenge_id,
        work_items = openings.len(),
        timeout_ms = timeout.as_millis(),
        "Outbound audit request started"
    );
    let request_started = Instant::now();
    let response = match ctx
        .p2p_node
        .send_request(
            ctx.challenged_peer,
            SUBTREE_AUDIT_PROTOCOL_ID,
            encoded,
            timeout,
        )
        .await
    {
        Ok(resp) => {
            info!(
                target: "ant_node::replication::audit_requester",
                event = "completed",
                audit_origin = ctx.origin.as_str(),
                audit_round = "byte",
                challenged_peer = %ctx.challenged_peer,
                challenge_id = ctx.challenge_id,
                work_items = openings.len(),
                elapsed_ms = request_started.elapsed().as_millis(),
                outcome = "response",
                "Outbound audit request completed"
            );
            resp
        }
        Err(e) => {
            warn!(
                target: "ant_node::replication::audit_requester",
                event = "completed",
                audit_origin = ctx.origin.as_str(),
                audit_round = "byte",
                challenged_peer = %ctx.challenged_peer,
                challenge_id = ctx.challenge_id,
                work_items = openings.len(),
                elapsed_ms = request_started.elapsed().as_millis(),
                outcome = "no_response",
                error = %e,
                "Outbound audit request completed without a response"
            );
            return SliceRound::Timeout;
        }
    };

    let resp_msg = match ReplicationMessage::decode_subtree_audit_response(&response.data) {
        Ok(m) => m,
        Err(e) => {
            warn!("Audit: failed to decode slice response: {e}");
            return SliceRound::Malformed;
        }
    };

    classify_slice_response(resp_msg.body, ctx.challenge_id, ctx.challenged_peer)
}

/// Classify a decoded round-2 body into a [`SliceRound`].
///
/// Pure over the wire body so the round-2 accounting boundary is testable
/// without a live `P2PNode`; [`request_slice_proof`] calls exactly this on the
/// bytes it decoded.
///
/// Every arm is guarded on `challenge_id`: a body carrying any other id is
/// `Malformed`, so a responder cannot answer a hard challenge with a softer
/// verdict minted for a different one.
fn classify_slice_response(
    body: ReplicationMessageBody,
    challenge_id: u64,
    challenged_peer: &PeerId,
) -> SliceRound {
    match body {
        ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Items {
            challenge_id: id,
            items,
        }) if id == challenge_id => SliceRound::Served(items),
        ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Rejected {
            challenge_id: id,
            kind,
            reason,
        }) if id == challenge_id => {
            // ADR-0004 A1: grace removed. UnknownCommitment/Protocol repudiation
            // of a pinned root is a confirmed failure; a Transient read error
            // routes to the timeout lane (credit revoked, no trust penalty) — the
            // responder retries reads first, so a Transient reaching round 2 means
            // it still could not serve committed bytes.
            match grade_reject(kind) {
                RejectGrade::Confirmed => {
                    warn!(
                        "Audit: {challenged_peer} rejected slice challenge \
                         ({kind:?}; confirmed): {reason}"
                    );
                    SliceRound::Rejected
                }
                RejectGrade::TimeoutLane => {
                    debug!(
                        "Audit: {challenged_peer} returned Transient for slice challenge \
                         (timeout lane): {reason}"
                    );
                    SliceRound::TransientReject
                }
            }
        }
        // A node claiming bootstrap MID-AUDIT (it just answered round 1 with a
        // valid signed proof) is contradicting itself: a bootstrapping node has
        // no committed data to prove. A graced timeout here would let it keep the
        // holder credit it earned earlier while dodging every round-2 possession
        // check, so this is a confirmed failure with credit revocation.
        ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Bootstrapping {
            challenge_id: id,
        }) if id == challenge_id => SliceRound::ResponsiveBootstrap,
        _ => SliceRound::Malformed,
    }
}

/// Whether a round-2 outcome must revoke the holder credit carried by the
/// commitment the auditor pinned.
///
/// True for every outcome that ends round 2 without a completed possession
/// proof but stays in the graced timeout lane — an explicit `Transient` reject
/// and silence alike. Both mean the peer did not prove it still holds the bytes
/// it committed to, so it must not keep standing earned by an earlier audit.
///
/// Silence matters most here. By round 2 the responder has already answered
/// round 1, so it is demonstrably live, and it learns which blocks were drawn
/// before it decides whether to reply. If silence kept credit, replying only to
/// favourable draws would cost nothing: unfavourable samples would be free and
/// credit from an earlier favourable one would persist, so the sampling
/// probability would describe answered passes rather than detection. Revoking
/// makes every unanswered round 2 cost the peer its standing for that
/// commitment, while an honest peer that drops one reply takes no trust penalty
/// and re-earns credit on its next audit.
///
/// The confirmed lanes (`Rejected`, `ResponsiveBootstrap`, `Malformed`) are
/// excluded because they revoke more broadly downstream, via
/// `apply_audit_failure_credit_revocation` → `forget_peer`.
const fn round2_revokes_pinned_credit(round: &SliceRound) -> bool {
    matches!(round, SliceRound::TransientReject | SliceRound::Timeout)
}

/// Map a decoded response body to an audit outcome (auditor side). A response
/// whose `challenge_id` doesn't match, or any non-subtree body, is malformed.
async fn dispatch_subtree_response(
    body: ReplicationMessageBody,
    ctx: &AuditCtx<'_>,
) -> AuditTickResult {
    let challenged_peer = ctx.challenged_peer;
    let challenge_id = ctx.challenge_id;
    let malformed = || {
        failed(
            challenged_peer,
            challenge_id,
            AuditFailureReason::MalformedResponse,
        )
    };
    match body {
        ReplicationMessageBody::SubtreeAuditResponse(SubtreeAuditResponse::Bootstrapping {
            challenge_id: resp_id,
        }) => {
            if resp_id != challenge_id {
                return malformed();
            }
            AuditTickResult::BootstrapClaim {
                peer: *challenged_peer,
            }
        }
        ReplicationMessageBody::SubtreeAuditResponse(SubtreeAuditResponse::Rejected {
            challenge_id: resp_id,
            kind,
            reason,
        }) => {
            if resp_id != challenge_id {
                return malformed();
            }
            // ADR-0004 A1: audit grace is REMOVED. Answerability is now
            // restart-durable (persisted retention) and the auditor only pins
            // in-window roots, so an honest node can always answer a pin it could
            // be challenged on. A responsive rejection is therefore graded on the
            // kind, with no grace:
            match grade_reject(kind) {
                // Repudiating a pinned root the node published (`UnknownCommitment`)
                // or an explicit protocol fault is provable misbehaviour →
                // confirmed failure (trust penalty + credit revocation happen
                // downstream in handle_subtree_failed_audit).
                RejectGrade::Confirmed => {
                    warn!(
                        "Audit: peer {challenged_peer} rejected subtree challenge \
                         ({kind:?}; confirmed — grace removed): {reason}"
                    );
                    failed(challenged_peer, challenge_id, AuditFailureReason::Rejected)
                }
                // A transient local read error (already retried by the responder)
                // is not a provable cheat, but not graced-with-standing either:
                // route it to the non-response/timeout lane — no trust penalty, but
                // revoke the holder credit for THIS pinned commitment so it gains
                // no positive standing (a Transient-spammer profits nothing).
                // Scoped to the commitment hash, not the whole peer, so a stale
                // audit of an old commitment cannot erase credit re-earned for a
                // newer one.
                RejectGrade::TimeoutLane => {
                    if let Some(credit) = ctx.credit {
                        credit
                            .recent_provers
                            .write()
                            .await
                            .forget_commitment(&ctx.expected_commitment_hash);
                    }
                    debug!(
                        "Audit: peer {challenged_peer} returned Transient for subtree challenge \
                         (timeout lane; credit for the pinned commitment revoked): {reason}"
                    );
                    failed(challenged_peer, challenge_id, AuditFailureReason::Timeout)
                }
            }
        }
        ReplicationMessageBody::SubtreeAuditResponse(SubtreeAuditResponse::Proof {
            challenge_id: resp_id,
            commitment,
            proof,
        }) => {
            if resp_id != challenge_id {
                return malformed();
            }
            verify_subtree_response(ctx, &commitment, &proof).await
        }
        _ => {
            warn!("Audit: unexpected response type from {challenged_peer}");
            malformed()
        }
    }
}

/// The pure verdict of evaluating a subtree-audit response, independent of
/// storage/network. Tests call this directly so the SHIPPED gate logic is what
/// gets exercised (no reimplementation that could drift).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AuditVerdict {
    /// All gates passed and at least one leaf was byte-verified.
    Pass {
        /// Number of leaves whose real bytes were verified in round 2.
        checked: usize,
    },
    /// A confirmed failure with this reason (penalizable / acted upon).
    Fail(AuditFailureReason),
}

/// Round-1 structural evaluation of a subtree-audit proof (ADR-0002).
///
/// Runs the cheap gates in fail-fast order: pin / identity / signature →
/// structure (the returned subtree rebuilds to the pinned root). It does **not**
/// prove byte possession — the leaves carry only the public `bytes_hash` (the
/// chunk address), a `content_len`, and a `nonced_root` the responder computed
/// itself. Possession is proven in round 2 ([`verify_slice_response`]), where the
/// auditor opens a freshly-random (post-proof) block per sampled leaf and
/// verifies a Bao slice against the address plus a nonced-tree opening against
/// the round-1 `nonced_root` — over the SERVED bytes, so the auditor never holds
/// the peer's chunks.
///
/// Returns [`StructureVerdict::Valid`] (proceed to round 2) or a confirmed
/// [`AuditFailureReason`] mapped from the failing gate.
pub(crate) fn evaluate_subtree_structure(
    commitment: &StorageCommitment,
    proof: &SubtreeProof,
    nonce: &[u8; 32],
    expected_commitment_hash: &[u8; 32],
    challenged_peer_bytes: &[u8; 32],
) -> Result<(), AuditFailureReason> {
    // -- Pin + identity + signature --
    if &commitment.sender_peer_id != challenged_peer_bytes {
        return Err(AuditFailureReason::Rejected);
    }
    let derived_peer_id = *blake3::hash(&commitment.sender_public_key).as_bytes();
    if derived_peer_id != commitment.sender_peer_id {
        return Err(AuditFailureReason::Rejected);
    }
    match commitment_hash(commitment) {
        Some(h) if &h == expected_commitment_hash => {}
        _ => return Err(AuditFailureReason::Rejected),
    }
    if !crate::replication::commitment::verify_commitment_signature(commitment) {
        return Err(AuditFailureReason::Rejected);
    }

    // -- Structure --
    if let StructureVerdict::Invalid(_) = verify_subtree_proof(proof, nonce, commitment) {
        return Err(AuditFailureReason::DigestMismatch);
    }

    // -- Content-address binding (possession-forgery guard) --
    // The commitment is only sound for CONTENT-ADDRESSED chunks, where the key IS
    // the content hash (`key == BLAKE3(content)`), so an honest leaf is always
    // `(key, key)` (see the commitment builder's `(k, k)` shortcut). The signed
    // Merkle leaf hashes `key ‖ bytes_hash` WITHOUT forcing them equal, yet round 2
    // authenticates the served slice against `bytes_hash` while holder credit is
    // recorded for `key`. A leaf with `bytes_hash != key` would therefore let a peer
    // earn credit for an expensive address `key` by proving possession of an
    // unrelated (e.g. one-byte) chunk hashing to `bytes_hash`. Reject any such leaf:
    // for honest content-addressed data the two are identical, so this never fails
    // an honest holder, and it re-binds Chain 1's `bytes_hash` check to the credited
    // `key`.
    //
    // A pointer (ADR-0016) is the one other honest leaf shape: its address is not
    // a content hash, so it is committed as `(key, pointer_leaf_hash(key))` at the
    // fixed record length, and round 2 proves possession with the whole signed
    // record instead of a slice. Anything else is still rejected.
    if proof
        .leaves
        .iter()
        .any(|l| l.bytes_hash != l.key && !is_pointer_leaf(l))
    {
        return Err(AuditFailureReason::DigestMismatch);
    }
    Ok(())
}

// Round 2 may be owed the record an update replaced after round 1 bound it.
const _: () = assert!(
    SUPERSEDED_RETENTION.as_secs() > SUBTREE_SESSION_TTL.as_secs(),
    "a replaced pointer record must outlive the audit session that may be owed it"
);

/// What round 1 bound for each committed pointer it proved, by address.
///
/// Each is the nonced root round 1 reported over the record it read
/// (ADR-0019). Round 2 is owed that record, whatever the pointer holds by the
/// time it asks.
pub type PointerBindings = HashMap<XorName, [u8; 32]>;

/// The pointer bindings a round-1 response reports. Only a proof reports any.
#[must_use]
pub fn pointer_bindings(response: &SubtreeAuditResponse) -> PointerBindings {
    match response {
        SubtreeAuditResponse::Proof { proof, .. } => proof
            .leaves
            .iter()
            .filter(|leaf| is_pointer_leaf(leaf))
            .map(|leaf| (leaf.key, leaf.nonced_root))
            .collect(),
        _ => PointerBindings::new(),
    }
}

/// Whether a round-1 leaf commits a pointer (ADR-0016): committed under
/// [`pointer_leaf_hash`] of its key, at the fixed record length.
fn is_pointer_leaf(leaf: &SubtreeLeaf) -> bool {
    leaf.bytes_hash == pointer_leaf_hash(&leaf.key)
        && usize::try_from(leaf.content_len).ok() == Some(POINTER_WIRE_LEN)
}

/// Check the round-2 item for a pointer leaf: one of the records served must
/// prove it. An admitted absence is `KeyAbsent`; anything else that does not
/// prove it, including no item at all, is `DigestMismatch`.
fn verify_pointer_item(
    nonce: &[u8; 32],
    challenged_peer_bytes: &[u8; 32],
    leaf: &SubtreeLeaf,
    items: &[SubtreeSliceItem],
) -> Result<(), AuditFailureReason> {
    let served = items.iter().find_map(|it| match it {
        SubtreeSliceItem::PointerRecord { key, records } if key == &leaf.key => {
            Some(Some(records.as_slice()))
        }
        SubtreeSliceItem::Absent { key } if key == &leaf.key => Some(None),
        _ => None,
    });
    match served {
        Some(Some(records))
            if records
                .iter()
                .any(|record| proves_pointer(nonce, challenged_peer_bytes, leaf, record)) =>
        {
            Ok(())
        }
        Some(None) => Err(AuditFailureReason::KeyAbsent),
        _ => Err(AuditFailureReason::DigestMismatch),
    }
}

/// Whether `record` proves the pointer `leaf` commits: its signature verifies,
/// it belongs at the leaf's address, and it is the record round 1 bound the
/// leaf's nonced root over.
fn proves_pointer(
    nonce: &[u8; 32],
    challenged_peer_bytes: &[u8; 32],
    leaf: &SubtreeLeaf,
    record: &[u8],
) -> bool {
    nonced_block_root(nonce, challenged_peer_bytes, &leaf.key, record) == leaf.nonced_root
        && Pointer::from_bytes(record).is_ok_and(|pointer| pointer.address() == leaf.key)
}

/// The auditor's **freshly-randomised** spot-check sample of the round-1 proof:
/// `count` distinct leaves (deduplicated, in increasing-index order) whose
/// original bytes the auditor will demand in round 2.
///
/// CRITICAL (ADR-0002 soundness): the sample MUST NOT be derivable from
/// anything the responder knew when it built the round-1 proof. The structural
/// root check binds only `(key, bytes_hash)` (both public — `bytes_hash` is the
/// chunk's network address), NOT `nonced_root`. So a relay holding only public
/// addresses can fabricate a structurally-valid proof with a bogus `nonced_root`
/// on every leaf and, if it could predict which leaves round 2 opens, fetch
/// only those and pass — earning holder credit for leaves it never held.
///
/// Picking the sample with fresh CSPRNG randomness AFTER the proof is received
/// turns round 1 into a commitment and round 2 into an unpredictable challenge
/// (cut-and-choose): to pass with probability above `(1 - faked_fraction)^count`
/// the responder must have produced a correct `nonced_root` — which requires the
/// real bytes under the fresh nonce — for essentially every leaf at round-1
/// commit time. The auditor still holds none of the peer's chunks. The block
/// index opened within each sampled leaf is likewise drawn fresh
/// ([`random_block_index`]), so no single block can be prepared in advance.
fn random_spotcheck_leaves(
    proof: &SubtreeProof,
    count: u32,
) -> Vec<&crate::replication::subtree::SubtreeLeaf> {
    let n = proof.leaves.len();
    if n == 0 {
        return Vec::new();
    }
    let want = (count as usize).min(n);
    let mut rng = rand::thread_rng();
    let mut picked = std::collections::BTreeSet::new();
    // n >= want, so this terminates quickly; bound the loop defensively against
    // a pathological RNG rather than risk spinning.
    let mut guard = 0u32;
    while picked.len() < want && guard < count.saturating_mul(64).max(64) {
        picked.insert(rng.gen_range(0..n));
        guard = guard.saturating_add(1);
    }
    // Deterministic top-up if the RNG kept colliding (astronomically unlikely):
    // fill the lowest missing indices so the sample is never silently short.
    for idx in 0..n {
        if picked.len() >= want {
            break;
        }
        picked.insert(idx);
    }
    picked
        .into_iter()
        .filter_map(|idx| proof.leaves.get(idx))
        .collect()
}

/// Draw a fresh-random 1 KiB block index in `0..block_count(content_len)`.
///
/// Called AFTER the round-1 proof is in hand, per sampled leaf, so the responder
/// could not have prepared only the opened block (the cut-and-choose property,
/// now at block granularity).
fn random_block_index(content_len: u32) -> u32 {
    let count = crate::replication::slice::block_count(u64::from(content_len));
    if count <= 1 {
        return 0;
    }
    rand::thread_rng().gen_range(0..count)
}

/// The two block indices opened for one sampled leaf: a fresh-random block (the
/// cut-and-choose possession check) and the claimed final block.
///
/// The final block is opened so the auditor's Bao decode reaches EOF, which is
/// where Bao authenticates the encoded length against the address. Without it a
/// responder can forge a *shorter* `content_len` (which is not signed by the
/// round-1 commitment), collapse the challenge space, and pass while storing only
/// the prefix — the length header alone is not bound for a prefix slice that
/// never touches EOF. Opening the final block pins the true length: a forged
/// short length fails the final-block decode against the real address.
///
/// Returns one index when the random draw already lands on the final block (or
/// the chunk is a single block), two otherwise, never more than two.
fn block_indices_for_leaf(content_len: u32) -> Vec<u32> {
    let count = crate::replication::slice::block_count(u64::from(content_len));
    let final_index = count.saturating_sub(1);
    let random = random_block_index(content_len);
    if random == final_index {
        vec![final_index]
    } else {
        vec![random, final_index]
    }
}

/// Round-2 verdict (ADR-0002 / V2-685): the responder opened one 1 KiB block per
/// sampled leaf with a Bao verified slice plus a nonced block-tree opening;
/// verify possession from those.
///
/// `openings` pairs each sampled leaf with the block index the auditor drew for
/// it. `items` is what the responder returned. For each opening the auditor:
///   1. finds the responder's `Present` item for exactly this `(key, block_index)`
///      (a missing, `Absent` or wrong-block item is a provable lie);
///   2. **Chain 1** — decodes the Bao slice against `leaf.bytes_hash` (the chunk
///      address), recovering the verified block bytes. This proves the block is
///      the real content at that offset, without the auditor holding the chunk.
///   3. **Chain 2** — folds the nonced block leaf (recomputed from those verified
///      bytes under the audit nonce/peer/key/index) with the returned siblings to
///      `leaf.nonced_root`. This proves the responder committed a nonced tree
///      over the real content at round-1 time, so it held the bytes then.
///
/// Both chains are over the SAME block bytes and the auditor holds none of the
/// peer's chunks. Every failure here is a confirmed one, split by what the
/// responder actually did so the audit log can tell them apart:
///
/// - an explicit `Absent` for a key committed in round 1 is an admitted loss →
///   [`AuditFailureReason::KeyAbsent`] (`absent_keys`);
/// - a missing item, a wrong block, a slice that fails to decode against the
///   address, or a nonced opening that does not fold to the committed root, is a
///   proof failure → [`AuditFailureReason::DigestMismatch`]
///   (`digest_mismatch_keys`).
///
/// Both reasons take the same trust penalty, clear the bootstrap claim and
/// revoke holder credit, so the split is diagnostic and not an enforcement
/// change. All openings verifying → `Pass { checked }`.
pub(crate) fn verify_slice_response(
    openings: &[(crate::replication::subtree::SubtreeLeaf, u32)],
    nonce: &[u8; 32],
    challenged_peer_bytes: &[u8; 32],
    items: &[SubtreeSliceItem],
) -> AuditVerdict {
    // Validate the response shape before matching. A well-formed response has at
    // most one item per SOLICITED identity; the per-opening `find_map` below
    // returns the FIRST match, so a duplicate `(key, block_index)` `Present`, a
    // key that is both `Present` and `Absent`, a repeated `Absent`, or an
    // UNSOLICITED item would let the responder's item order (or padding) decide
    // the verdict. Bounding `items.len()` to the request count also keeps this
    // check (and the matching below) at O(openings) — a peer cannot pad the
    // response with thousands of unique items to force quadratic validation work.
    if items.len() > openings.len() {
        return AuditVerdict::Fail(AuditFailureReason::MalformedResponse);
    }
    let requested_blocks: HashSet<(XorName, u32)> =
        openings.iter().map(|(leaf, i)| (leaf.key, *i)).collect();
    let requested_keys: HashSet<XorName> = openings.iter().map(|(leaf, _)| leaf.key).collect();
    let mut present: HashSet<(XorName, u32)> = HashSet::new();
    let mut absent: HashSet<XorName> = HashSet::new();
    let mut records: HashSet<XorName> = HashSet::new();
    for it in items {
        let ok = match it {
            SubtreeSliceItem::Present {
                key, block_index, ..
            } => {
                requested_blocks.contains(&(*key, *block_index))
                    && present.insert((*key, *block_index))
                    && !absent.contains(key)
                    && !records.contains(key)
            }
            SubtreeSliceItem::Absent { key } => {
                requested_keys.contains(key)
                    && absent.insert(*key)
                    && !present.iter().any(|(k, _)| k == key)
                    && !records.contains(key)
            }
            SubtreeSliceItem::PointerRecord {
                key,
                records: served,
            } => {
                requested_keys.contains(key)
                    && (1..=MAX_POINTER_RECORDS_PER_ITEM).contains(&served.len())
                    && records.insert(*key)
                    && !absent.contains(key)
                    && !present.iter().any(|(k, _)| k == key)
            }
        };
        if !ok {
            return AuditVerdict::Fail(AuditFailureReason::MalformedResponse);
        }
    }

    let mut checked = 0usize;
    for (leaf, block_index) in openings {
        // A pointer leaf is proved by the whole signed record: it must verify,
        // belong at the committed address, and be the record round 1 bound its
        // nonced root over, which the responder had to read before it knew what
        // would be sampled. An update between the rounds does not fail an
        // honest holder: it serves the record round 1 read (ADR-0019).
        if is_pointer_leaf(leaf) {
            if let Err(reason) = verify_pointer_item(nonce, challenged_peer_bytes, leaf, items) {
                return AuditVerdict::Fail(reason);
            }
            checked += 1;
            continue;
        }
        let block_index = *block_index;
        // Match the responder's item for exactly this (key, block_index). A
        // missing item, an explicit Absent, or a different block is a provable lie.
        let served = items.iter().find_map(|it| match it {
            SubtreeSliceItem::Present {
                key,
                block_index: served_index,
                bao_slice,
                nonced_siblings,
            } if key == &leaf.key && *served_index == block_index => {
                Some(Some((bao_slice.as_slice(), nonced_siblings.as_slice())))
            }
            SubtreeSliceItem::Absent { key } if key == &leaf.key => Some(None),
            _ => None,
        });
        let (bao_slice, nonced_siblings) = match served {
            Some(Some(opening)) => opening,
            // The responder explicitly answered "I do not hold this key", for a
            // key it committed to in round 1. That is an admitted loss, not a
            // broken proof, and it is reported as `KeyAbsent` so the failure log
            // line separates the two: `absent_keys` counts a peer that owned up
            // to missing data, `digest_mismatch_keys` counts one whose proof did
            // not verify. Both are confirmed failures and carry identical trust,
            // bootstrap-claim and holder-credit effects, so this changes what an
            // operator can see, not what the audit enforces.
            Some(None) => return AuditVerdict::Fail(AuditFailureReason::KeyAbsent),
            // No item at all for a solicited opening: the responder neither
            // served the block nor admitted the key is gone, so nothing about
            // possession was established. That stays a proof failure.
            None => return AuditVerdict::Fail(AuditFailureReason::DigestMismatch),
        };

        // Chain 1: authenticate the block against the chunk address.
        let Some(block) = crate::replication::slice::verify_block_slice(
            bao_slice,
            &leaf.bytes_hash,
            u64::from(leaf.content_len),
            block_index,
        ) else {
            return AuditVerdict::Fail(AuditFailureReason::DigestMismatch);
        };

        // Chain 2: prove the block was committed under round 1's fresh nonce,
        // with the sibling chain pinned to the canonical depth for the chunk's
        // block count (bound the claimed tree geometry).
        if !crate::replication::slice::verify_nonced_block(
            nonce,
            challenged_peer_bytes,
            &leaf.key,
            block_index,
            &block,
            nonced_siblings,
            &leaf.nonced_root,
            crate::replication::slice::block_count(u64::from(leaf.content_len)),
        ) {
            return AuditVerdict::Fail(AuditFailureReason::DigestMismatch);
        }
        checked += 1;
    }
    AuditVerdict::Pass { checked }
}

/// Verify a subtree-proof response (auditor side), ADR-0002 two-round audit.
///
/// **Round 1** (this proof): pin + identity + signature + structure. If the
/// proof structurally rebuilds to the pinned root, the tree SHAPE is committed —
/// but not yet that the bytes are held. **Round 2**: the auditor picks a small
/// freshly-random (post-proof) sample of the just-proven leaves, draws a fresh
/// block index for each, and sends a [`SubtreeSliceChallenge`] opening those
/// blocks. It verifies each opened block against the committed `bytes_hash`
/// (Bao slice → content address) and `nonced_root` (nonced block-tree opening →
/// round-1 possession commit). A responder that committed to a chunk it no
/// longer held cannot have committed a correct `nonced_root`, so it fails —
/// regardless of what the auditor holds. On a full pass, credits the peer as a
/// proven holder.
async fn verify_subtree_response(
    ctx: &AuditCtx<'_>,
    commitment: &StorageCommitment,
    proof: &SubtreeProof,
) -> AuditTickResult {
    let challenged_peer = ctx.challenged_peer;
    let challenge_id = ctx.challenge_id;

    // -- Round 1: pin/identity/signature + structure (no bytes). --
    if let Err(reason) = evaluate_subtree_structure(
        commitment,
        proof,
        &ctx.nonce,
        &ctx.expected_commitment_hash,
        challenged_peer.as_bytes(),
    ) {
        warn!("Audit: {challenged_peer} failed subtree structure ({reason:?})");
        return failed(challenged_peer, challenge_id, reason);
    }

    // -- Round 2: surprise slice challenge for a 3..=5 FRESHLY-RANDOM sample. --
    // The sample is chosen now, with CSPRNG randomness, AFTER the round-1 proof
    // is in hand — NOT derived from the round-1 nonce. The responder committed
    // every leaf's `nonced_root` in round 1 without knowing which leaves — or
    // which block within each — we will open, so it could not have prepared only
    // the opened blocks (cut-and-choose). The reply is a few KB per opening (a
    // 1 KiB block plus two short hash chains), so one round-2 message serves the
    // whole sample; no batching.
    let sample_n = ctx
        .config
        .audit_spotcheck_count()
        .clamp(BYTE_SPOTCHECK_MIN, BYTE_SPOTCHECK_MAX);
    let sampled = random_spotcheck_leaves(proof, sample_n);
    if sampled.is_empty() {
        // Cannot happen after a valid structure (subtree is never empty), but
        // guard rather than credit an unproven peer.
        warn!("Audit: {challenged_peer} produced an empty spot-check sample; rejecting");
        return failed(
            challenged_peer,
            challenge_id,
            AuditFailureReason::DigestMismatch,
        );
    }
    // Pair each sampled leaf with up to two block indices: a fresh-random block
    // (possession) and the claimed final block (a length pin — see
    // `block_indices_for_leaf`). Own the leaves so the borrow on `proof` ends
    // before the await. The sample is <= BYTE_SPOTCHECK_MAX and each leaf yields
    // <= 2 openings, so the total is <= 2 * BYTE_SPOTCHECK_MAX <= MAX_SLICE_OPENINGS
    // (statically asserted); `take` is a defensive backstop.
    let openings_with_leaves: Vec<(crate::replication::subtree::SubtreeLeaf, u32)> = sampled
        .iter()
        .flat_map(|leaf| {
            let leaf = (*leaf).clone();
            // A pointer is served whole, so it takes one opening, at block 0.
            let indices = if is_pointer_leaf(&leaf) {
                vec![0]
            } else {
                block_indices_for_leaf(leaf.content_len)
            };
            indices
                .into_iter()
                .map(move |block_index| (leaf.clone(), block_index))
        })
        .take(MAX_SLICE_OPENINGS)
        .collect();
    let openings: Vec<SubtreeSliceOpening> = openings_with_leaves
        .iter()
        .map(|(leaf, block_index)| SubtreeSliceOpening {
            key: leaf.key,
            block_index: *block_index,
        })
        .collect();

    let round = request_slice_proof(ctx, &openings).await;

    // Round 2 ended without a completed possession proof: drop the holder credit
    // this pinned commitment carries, before mapping the outcome to a verdict.
    // Scoped to the commitment hash, so credit the peer re-earned for a newer
    // commitment survives.
    if round2_revokes_pinned_credit(&round) {
        if let Some(credit) = ctx.credit {
            credit
                .recent_provers
                .write()
                .await
                .forget_commitment(&ctx.expected_commitment_hash);
        }
    }

    let verdict = match round {
        // The responder served openings: verify both chains for every one. Any
        // failing chain is a confirmed cheat.
        SliceRound::Served(items) => verify_slice_response(
            &openings_with_leaves,
            &ctx.nonce,
            challenged_peer.as_bytes(),
            &items,
        ),
        // Confirmed round-2 failures. `Rejected`: the responder repudiated the
        // slice challenge for a recently pinned commitment. `ResponsiveBootstrap`:
        // it claimed bootstrap AFTER producing a valid round-1 proof, which is a
        // self-contradiction (a bootstrapping node has no committed data to
        // prove). Both are classified as any other confirmed `Rejected`, which
        // revokes the peer's holder credit and takes the trust penalty downstream
        // (`apply_audit_failure_credit_revocation` → `forget_peer`).
        SliceRound::Rejected | SliceRound::ResponsiveBootstrap => {
            AuditVerdict::Fail(AuditFailureReason::Rejected)
        }
        // Round 2 produced no proof, either as an explicit `Transient` (a local
        // read error) or as silence. Both route to the timeout lane: no trust
        // penalty, the strike policy still graces them, and the credit for the
        // pinned commitment was already revoked above.
        SliceRound::TransientReject | SliceRound::Timeout => {
            AuditVerdict::Fail(AuditFailureReason::Timeout)
        }
        // Malformed/unexpected round-2 body.
        SliceRound::Malformed => AuditVerdict::Fail(AuditFailureReason::MalformedResponse),
    };

    match verdict {
        AuditVerdict::Fail(reason) => {
            warn!("Audit: {challenged_peer} failed subtree audit ({reason:?})");
            failed(challenged_peer, challenge_id, reason)
        }
        AuditVerdict::Pass { checked } => {
            // Closeness (ADR-0002, soft/observe-only) — see observe_closeness.
            observe_closeness(ctx.p2p_node, ctx.config, challenged_peer, proof).await;
            // Credit the peer as a proven holder of its committed keys.
            if let (Some(credit), Some(pin)) = (ctx.credit, commitment_hash(commitment)) {
                let now = std::time::Instant::now();
                let mut provers = credit.recent_provers.write().await;
                for leaf in &proof.leaves {
                    provers.record_proof(leaf.key, *challenged_peer, pin, now);
                }
            }
            info!(
                "Audit: peer {challenged_peer} passed subtree audit ({} leaves, {checked} \
                 block openings verified)",
                proof.leaves.len()
            );
            AuditTickResult::Passed {
                challenged_peer: *challenged_peer,
                keys_checked: checked,
            }
        }
    }
}

/// Soft, density-aware closeness observation (ADR-0002). Logs — never fails —
/// when a suspicious fraction of the proof's leaves are keys the auditor itself
/// is NOT responsible for (a proxy for "implausibly far from the peer").
///
/// Using the auditor's own `SelfInclusiveRT` responsibility as the yardstick
/// makes this density-aware for free: on a small/dense network the auditor is
/// close to nearly every key, so almost nothing reads as far and no honest peer
/// is ever flagged. Enforcement is intentionally deferred until a testnet
/// calibrates the density threshold.
async fn observe_closeness(
    p2p_node: &Arc<P2PNode>,
    config: &ReplicationConfig,
    challenged_peer: &PeerId,
    proof: &SubtreeProof,
) {
    /// Max leaves probed for the closeness estimate (bounds the DHT lookups).
    const CLOSENESS_SAMPLE_CAP: usize = 8;

    // This is an observe-only DEBUG signal (never enforced). The check costs one
    // DHT responsibility lookup per inspected leaf, so (§12): (a) skip it
    // entirely unless debug logging is on — there is no other consumer — and
    // (b) inspect at most a bounded SAMPLE of leaves rather than all ~sqrt(N),
    // which still reveals the "mostly far" padding shape without N lookups.
    if !crate::logging::enabled!(crate::logging::Level::DEBUG) {
        return;
    }

    let self_id = *p2p_node.peer_id();
    let inspected = proof.leaves.len().min(CLOSENESS_SAMPLE_CAP);
    let mut far = 0usize;
    for leaf in proof.leaves.iter().take(inspected) {
        if !crate::replication::admission::is_responsible(
            &self_id,
            &leaf.key,
            p2p_node,
            config.close_group_size,
        )
        .await
        {
            far += 1;
        }
    }
    // Only worth a line when MOST of the inspected sample is far — that's the
    // padding shape. A normal proof on a sparse network has some far keys.
    if inspected > 0 && far * 2 > inspected {
        debug!(
            "Audit: closeness signal — {far}/{inspected} sampled of {challenged_peer}'s proven \
             leaves are keys this auditor is not close to (observe-only; possible padding, not \
             penalized)"
        );
    }
}

/// Build a confirmed-failure result. The auditor pinned a commitment the peer
/// committed to itself, so there is no per-key responsibility to re-confirm:
/// the failure is about the peer's own committed tree.
///
/// The subtree audit fails a peer as a whole (one challenge, one verdict) rather
/// than per-key, so the [`AuditFailureSummary`] is a single-failure rollup
/// mapped from `reason` — enough for the shared audit-failure diagnostics log
/// line (`absent_keys`/`digest_mismatch_keys`) without inventing per-key counts
/// this audit shape does not have.
fn failed(
    challenged_peer: &PeerId,
    challenge_id: u64,
    reason: AuditFailureReason,
) -> AuditTickResult {
    let summary = subtree_failure_summary(&reason);
    AuditTickResult::Failed {
        evidence: FailureEvidence::AuditFailure {
            challenge_id,
            challenged_peer: *challenged_peer,
            confirmed_failed_keys: Vec::new(),
            summary,
            reason,
        },
        no_response_class: None,
    }
}

/// Map a subtree-audit `reason` to a single-failure [`AuditFailureSummary`].
///
/// A `Timeout` is not a confirmed failure (it is the non-response/timeout lane),
/// so it rolls up as zero confirmed failures; every other reason is one confirmed failure,
/// categorised where the category is meaningful (byte/nonce/root mismatch →
/// `digest_mismatch_keys`; explicit absent → `absent_keys`).
fn subtree_failure_summary(reason: &AuditFailureReason) -> AuditFailureSummary {
    let mut summary = AuditFailureSummary {
        challenged_keys: 1,
        ..AuditFailureSummary::default()
    };
    match reason {
        AuditFailureReason::Timeout => {}
        AuditFailureReason::DigestMismatch => {
            summary.failed_keys = 1;
            summary.digest_mismatch_keys = 1;
        }
        AuditFailureReason::KeyAbsent => {
            summary.failed_keys = 1;
            summary.absent_keys = 1;
        }
        AuditFailureReason::MalformedResponse | AuditFailureReason::Rejected => {
            summary.failed_keys = 1;
        }
    }
    summary
}

// ---------------------------------------------------------------------------
// Responder side
// ---------------------------------------------------------------------------

/// Handle an incoming subtree audit challenge (responder side).
///
/// Validates the challenge targets this node, looks up the pinned commitment in
/// the retained (in-window) set, and builds the subtree proof for the
/// nonce-selected branch. If this node is bootstrapping it says so; if it
/// genuinely does not retain the pinned commitment it rejects (which, with audit
/// grace removed, the auditor treats as a confirmed failure for an in-window pin).
pub async fn handle_subtree_challenge(
    challenge: &SubtreeAuditChallenge,
    storage: &ChunkStore,
    self_peer_id: &PeerId,
    is_bootstrapping: bool,
    commitment_state: Option<&Arc<ResponderCommitmentState>>,
) -> SubtreeAuditResponse {
    handle_subtree_challenge_measured(
        challenge,
        storage,
        self_peer_id,
        is_bootstrapping,
        commitment_state,
    )
    .await
    .response
}

/// A round-1 response together with the chunk bytes spent producing it.
pub struct Round1Work {
    /// What to send back.
    pub response: SubtreeAuditResponse,
    /// Chunk content read from the store and hashed BEFORE this response was
    /// produced.
    ///
    /// Counted on the rejecting paths too, which is the point. A subtree is read
    /// leaf by leaf, so a commitment holding one unreadable key still costs a
    /// full run of reads and keyed-BLAKE3 passes over every leaf before it. If
    /// only the `Proof` arm were charged, an attacker who found such a
    /// commitment could replay subtrees over it indefinitely for free — and
    /// since the per-peer cooldown is escapable by rotating identity, the
    /// responder-wide work budget is the only bound that would have caught it.
    pub content_bytes: i64,
    /// Committed chunks whose bytes, read for this proof, no longer hash to
    /// their key.
    ///
    /// The proof still carries what was read, so the auditor's verdict on them
    /// is unchanged. The caller reports them to the chunk store
    /// (`ChunkStore::report_corrupt`), whose recheck worker takes the ones its
    /// bounded queue admits out of service, so the node stops committing a chunk
    /// it cannot prove and replication can repair it, rather than failing every
    /// audit that lands on that key until a fetch of the same key happens to
    /// notice. A key the queue cannot take stays committed, so the next audit
    /// that reads it reports it again. Not done here, so the cleanup never delays
    /// the answer the auditor is waiting for.
    pub corrupt_keys: Vec<XorName>,
}

/// [`handle_subtree_challenge`], additionally reporting the read-and-hash work
/// it performed so the caller can charge it on every exit path.
pub async fn handle_subtree_challenge_measured(
    challenge: &SubtreeAuditChallenge,
    storage: &ChunkStore,
    self_peer_id: &PeerId,
    is_bootstrapping: bool,
    commitment_state: Option<&Arc<ResponderCommitmentState>>,
) -> Round1Work {
    handle_subtree_challenge_measured_with_pointers(
        challenge,
        storage,
        None,
        self_peer_id,
        is_bootstrapping,
        commitment_state,
    )
    .await
}

/// [`handle_subtree_challenge_measured`] for a node that also commits pointers
/// (ADR-0016): committed pointer leaves are answered from `pointers`.
pub async fn handle_subtree_challenge_measured_with_pointers(
    challenge: &SubtreeAuditChallenge,
    storage: &ChunkStore,
    pointers: Option<&PointerStore>,
    self_peer_id: &PeerId,
    is_bootstrapping: bool,
    commitment_state: Option<&Arc<ResponderCommitmentState>>,
) -> Round1Work {
    // The accumulator is threaded in rather than returned per-arm so that every
    // exit reports its work by construction: a new early return cannot forget to
    // account for the reads that already happened.
    let mut content_bytes = 0i64;
    let mut corrupt_keys = Vec::new();
    let response = subtree_challenge_response(
        challenge,
        storage,
        pointers,
        self_peer_id,
        is_bootstrapping,
        commitment_state,
        &mut content_bytes,
        &mut corrupt_keys,
    )
    .await;
    Round1Work {
        response,
        content_bytes,
        corrupt_keys,
    }
}

/// The round-1 responder proper. `content_bytes` accrues the chunk content read
/// and hashed so far, and is meaningful on every return path, not just the
/// successful one. `corrupt_keys` collects the committed chunks whose bytes did
/// not hash to their key (see [`Round1Work::corrupt_keys`]).
#[allow(clippy::too_many_lines, clippy::too_many_arguments)]
async fn subtree_challenge_response(
    challenge: &SubtreeAuditChallenge,
    storage: &ChunkStore,
    pointers: Option<&PointerStore>,
    self_peer_id: &PeerId,
    is_bootstrapping: bool,
    commitment_state: Option<&Arc<ResponderCommitmentState>>,
    content_bytes: &mut i64,
    corrupt_keys: &mut Vec<XorName>,
) -> SubtreeAuditResponse {
    if is_bootstrapping {
        return SubtreeAuditResponse::Bootstrapping {
            challenge_id: challenge.challenge_id,
        };
    }

    if challenge.challenged_peer_id != *self_peer_id.as_bytes() {
        warn!(
            "Subtree audit challenge targeted wrong peer: expected {}, got {}",
            hex::encode(self_peer_id.as_bytes()),
            hex::encode(challenge.challenged_peer_id),
        );
        return SubtreeAuditResponse::Rejected {
            challenge_id: challenge.challenge_id,
            kind: RejectKind::Protocol,
            reason: "challenged_peer_id does not match this node".to_string(),
        };
    }

    let Some(state) = commitment_state else {
        return SubtreeAuditResponse::Rejected {
            challenge_id: challenge.challenge_id,
            kind: RejectKind::Protocol,
            reason: "no commitment state".to_string(),
        };
    };

    // Look up the pinned commitment among the in-window retained set (TTL-bounded
    // answerability with a MAX_RETAINED_GOSSIPED_SLOTS backstop).
    // A miss is `UnknownCommitment`. With audit grace removed (ADR-0004 A1) the
    // auditor treats a responsive miss on an in-window pin as a CONFIRMED failure:
    // answerability is restart-durable and pins are challenged only while in
    // window, so failing to answer is a real repudiation, not benign rotation.
    let Some(built) = state.lookup_by_hash(&challenge.expected_commitment_hash) else {
        return SubtreeAuditResponse::Rejected {
            challenge_id: challenge.challenge_id,
            kind: RejectKind::UnknownCommitment,
            reason: "unknown commitment hash".to_string(),
        };
    };

    // Geometry first (no bytes touched): which leaves to prove + the sibling
    // cut-hashes from the committed tree.
    let plan = match subtree_plan(built.tree(), &challenge.nonce) {
        Ok(p) => p,
        Err(e) => {
            warn!("Subtree audit: failed to plan proof: {e:?}");
            return SubtreeAuditResponse::Rejected {
                challenge_id: challenge.challenge_id,
                kind: RejectKind::Protocol,
                reason: "could not build subtree proof".to_string(),
            };
        }
    };

    // Read chunk bytes one leaf at a time so peak memory is bounded regardless
    // of subtree size, hashing each into its plain + nonced leaf.
    let mut leaves = Vec::with_capacity(plan.leaf_keys.len());
    for (position, key) in plan.leaf_keys.iter().enumerate() {
        // A pointer leaf (ADR-0016) commits no bytes in the tree, since its
        // bytes change with every update. Round 1 binds them here instead: the
        // nonced root over the record held now, which round 2 must reproduce.
        // So a node answers from records it holds, not ones it could fetch once
        // it learns which few are sampled. A loss is admitted exactly as a
        // missing chunk is, and a read error is transient as for a chunk.
        if plan.leaf_is_pointer.get(position).copied().unwrap_or(false) {
            *content_bytes = content_bytes.saturating_add(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES);
            let key_hex = hex::encode(key);
            let read = match pointers {
                Some(store) => store.record_bytes(key).await,
                None => Ok(None),
            };
            let record = match read {
                Ok(Some(record)) => record,
                Ok(None) => {
                    warn!("Subtree audit: committed pointer {key_hex} is not held");
                    return SubtreeAuditResponse::Rejected {
                        challenge_id: challenge.challenge_id,
                        kind: RejectKind::Protocol,
                        reason: format!("missing bytes for committed key: {key_hex}"),
                    };
                }
                Err(e) => {
                    warn!(
                        "Subtree audit: read error for committed pointer {key_hex}: {e} \
                         (rejecting as transient, not a confirmed failure)"
                    );
                    return SubtreeAuditResponse::Rejected {
                        challenge_id: challenge.challenge_id,
                        kind: RejectKind::Transient,
                        reason: format!("transient storage read error: {e}"),
                    };
                }
            };
            // Top up to the record read, as for a chunk.
            let content = i64::try_from(record.len()).unwrap_or(i64::MAX);
            *content_bytes = content_bytes.saturating_add(
                content
                    .saturating_sub(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES)
                    .max(0),
            );
            leaves.push(SubtreeLeaf {
                key: *key,
                bytes_hash: pointer_leaf_hash(key),
                content_len: u32::try_from(POINTER_WIRE_LEN).unwrap_or(u32::MAX),
                nonced_root: nonced_block_root(
                    &challenge.nonce,
                    &challenge.challenged_peer_id,
                    key,
                    &record,
                ),
            });
            continue;
        }
        // Charge the fixed cost of ATTEMPTING a leaf before the read, because
        // it is owed whether or not the read succeeds: the lookup and its
        // retries, and the blocking-task round trip below. Charging only
        // content bytes left both a failing leaf and a tiny one nearly free,
        // and nothing bounds a chunk from below, so a commitment of a million
        // small records could run a full subtree of lookups per audit against
        // almost no budget. The top-up after a successful read makes the total
        // `max(bytes, floor)` rather than a surcharge on honest chunks.
        *content_bytes = content_bytes.saturating_add(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES);
        let bytes = match get_raw_retrying(storage, key).await {
            Ok(Some(bytes)) => bytes,
            // Key is in our committed tree but definitively NOT stored — real
            // storage loss / the classic deleter. For a recently gossiped pin
            // the auditor counts this as a CONFIRMED failure.
            Ok(None) => {
                warn!(
                    "Subtree audit: missing bytes for committed key {}",
                    hex::encode(key)
                );
                return SubtreeAuditResponse::Rejected {
                    challenge_id: challenge.challenge_id,
                    kind: RejectKind::Protocol,
                    reason: format!("missing bytes for committed key: {}", hex::encode(key)),
                };
            }
            // Persistent transient read error after retries — NOT proof of missing
            // data. Reject `Transient`; the auditor routes it to the timeout lane
            // (no confirmed penalty) so a genuinely flaky disk is not branded a
            // deleter, while gaining no positive standing.
            Err(e) => {
                warn!(
                    "Subtree audit: storage read error for committed key {}: {e} \
                     (rejecting as transient, not a confirmed failure)",
                    hex::encode(key)
                );
                return SubtreeAuditResponse::Rejected {
                    challenge_id: challenge.challenge_id,
                    kind: RejectKind::Transient,
                    reason: format!("transient storage read error: {e}"),
                };
            }
        };
        // Top up to the content actually read, above the floor already charged.
        // Charged at the READ, not at the end: the disk read and the
        // keyed-BLAKE3 pass below are both already owed at this point, and
        // every remaining exit from this loop — a later missing key, a
        // persistent read error, a failed hashing task — discards the leaves
        // but not the work. Accruing here is what makes a commitment with one
        // bad key cost the attacker something per replay instead of nothing.
        let content = i64::try_from(bytes.len()).unwrap_or(i64::MAX);
        *content_bytes = content_bytes.saturating_add(
            content
                .saturating_sub(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES)
                .max(0),
        );
        // Hash the leaf (a full keyed-BLAKE3 pass over the chunk) on a blocking
        // thread, not the async worker: a maximal subtree is ~sqrt(N) leaves of up
        // to MAX_CHUNK_SIZE each, so doing this inline would tie up a Tokio worker
        // for the whole proof and let a few round-1 requests starve the runtime.
        // One chunk is resident at a time, so peak memory is bounded.
        let nonce = challenge.nonce;
        let peer = challenge.challenged_peer_id;
        let leaf_key = *key;
        let leaf = match tokio::task::spawn_blocking(move || {
            crate::replication::subtree::subtree_leaf(&nonce, &peer, &leaf_key, &bytes)
        })
        .await
        {
            Ok(leaf) => leaf,
            Err(e) => {
                warn!(
                    "Subtree audit: leaf hashing task failed for key {}: {e}",
                    hex::encode(key)
                );
                return SubtreeAuditResponse::Rejected {
                    challenge_id: challenge.challenge_id,
                    kind: RejectKind::Transient,
                    reason: format!("leaf hashing task error: {e}"),
                };
            }
        };
        // The leaf's plain hash is the content address of what was just read, so a
        // committed chunk whose file no longer matches its name shows up here at no
        // extra cost. See `Round1Work::corrupt_keys` for what happens to it.
        if leaf.bytes_hash != *key {
            warn!(
                "Subtree audit: committed key {} does not hash to its address; \
                 reporting it for a recheck so it can be taken out of service \
                 and repaired",
                hex::encode(key)
            );
            corrupt_keys.push(*key);
        }
        leaves.push(leaf);
    }

    SubtreeAuditResponse::Proof {
        challenge_id: challenge.challenge_id,
        commitment: built.commitment().clone(),
        proof: SubtreeProof {
            leaves,
            sibling_cut_hashes: plan.sibling_cut_hashes,
        },
    }
}

/// Build every requested opening for one committed key from a single hashing
/// pass over its bytes: a Bao verified slice (authenticity against the chunk
/// address) plus a nonced block-tree opening (possession against round 1's
/// `nonced_root`) per block index.
///
/// The Bao outboard and nonced tree each hash the full chunk, so this builds
/// them once (via [`ChunkOpener`]) and serves all `indices` from them rather
/// than re-hashing per opening (V2-685 round-2 amplification fix). `indices` is
/// deduplicated by the caller. CPU-heavy, so callers run it on a blocking thread.
///
/// Returns `Err((kind, reason))` for the terminal cases that abort the whole
/// response: a block index out of range (only a forged/buggy auditor sends one →
/// `Protocol`), or a surprise in-memory Bao extraction error (`Transient`, so an
/// honest holder is not branded a deleter).
fn build_slice_items_for_key(
    nonce: [u8; 32],
    peer: [u8; 32],
    key: XorName,
    bytes: &[u8],
    indices: &[u32],
) -> Result<Vec<SubtreeSliceItem>, (RejectKind, String)> {
    let opener = crate::replication::slice::ChunkOpener::new(&nonce, &peer, &key, bytes);
    let count = opener.block_count();
    let mut items = Vec::with_capacity(indices.len());
    for &block_index in indices {
        if block_index >= count {
            return Err((
                RejectKind::Protocol,
                format!(
                    "block index {block_index} out of range for key {}",
                    hex::encode(key)
                ),
            ));
        }
        let bao_slice = match opener.bao_slice(block_index) {
            Ok(slice) => slice,
            Err(e) => {
                warn!(
                    "Subtree slice audit: bao extraction failed for key {}: {e}",
                    hex::encode(key)
                );
                return Err((RejectKind::Transient, format!("bao extraction error: {e}")));
            }
        };
        // `block_index < count` was just checked, so siblings must exist. A
        // `None` here is an internal proof-building inconsistency, not an honest
        // condition: abort the whole response as `Transient` (routes to the
        // timeout lane) rather than emit an empty-siblings `Present` that would
        // make an honest holder fail its own audit.
        let Some(nonced_siblings) = opener.nonced_siblings(block_index) else {
            warn!(
                "Subtree slice audit: no nonced siblings for in-range block {block_index} of key {}",
                hex::encode(key)
            );
            return Err((
                RejectKind::Transient,
                format!("nonced sibling build inconsistency for block {block_index}"),
            ));
        };
        items.push(SubtreeSliceItem::Present {
            key,
            block_index,
            bao_slice,
            nonced_siblings,
        });
    }
    Ok(items)
}

/// Handle a round-2 slice challenge (responder side), ADR-0002 / V2-685.
///
/// The auditor has already structurally verified this node's round-1 subtree
/// proof and now opens up to two 1 KiB blocks (a fresh-random block plus the
/// final block) of a small freshly-random sample of those leaves. For each
/// opening the responder reads the committed chunk and builds a two-chain
/// opening (a Bao verified slice for authenticity against the chunk address, and
/// a nonced block-tree opening for possession against round 1's `nonced_root`),
/// returning [`SubtreeSliceItem::Present`]. If it committed to the key but can no
/// longer
/// produce the bytes it returns [`SubtreeSliceItem::Absent`], which the auditor
/// counts as a provable failure.
///
/// Openings are authorised against the subtree round 1 actually proved, not
/// merely against the pinned commitment. A challenge naming any key outside that
/// subtree is refused whole, before any chunk is read, so the work this round can
/// cost is bounded by the work the caller already paid for in round 1. An honest
/// auditor cannot trip this: it samples only the leaves round 1 returned, and
/// without that leaf's `nonced_root` and `content_len` it has nothing to verify
/// an answer against.
pub async fn handle_subtree_slice_challenge(
    challenge: &SubtreeSliceChallenge,
    storage: &ChunkStore,
    self_peer_id: &PeerId,
    is_bootstrapping: bool,
    commitment_state: Option<&Arc<ResponderCommitmentState>>,
) -> SubtreeSliceResponse {
    serve_slice_challenge(
        challenge,
        storage,
        None,
        None,
        self_peer_id,
        is_bootstrapping,
        commitment_state,
    )
    .await
}

/// [`handle_subtree_slice_challenge`] for a node that also commits pointers
/// (ADR-0016), without what round 1 bound for them.
///
/// Kept for callers of the earlier signature, and answering as it did: a
/// committed pointer is served as the record held now and the newest one an
/// update replaced, and one no longer held is absent. That fails an honest holder after two updates between
/// the rounds, which is what ADR-0019 fixes; the engine uses
/// [`handle_subtree_slice_challenge_with_pointer_bindings`].
pub async fn handle_subtree_slice_challenge_with_pointers(
    challenge: &SubtreeSliceChallenge,
    storage: &ChunkStore,
    pointers: Option<&PointerStore>,
    self_peer_id: &PeerId,
    is_bootstrapping: bool,
    commitment_state: Option<&Arc<ResponderCommitmentState>>,
) -> SubtreeSliceResponse {
    serve_slice_challenge(
        challenge,
        storage,
        pointers,
        None,
        self_peer_id,
        is_bootstrapping,
        commitment_state,
    )
    .await
}

/// [`handle_subtree_slice_challenge`] for a node that also commits pointers
/// (ADR-0016): a committed pointer is answered with its whole signed record,
/// the one `bound` says round 1 read (ADR-0019).
pub async fn handle_subtree_slice_challenge_with_pointer_bindings(
    challenge: &SubtreeSliceChallenge,
    storage: &ChunkStore,
    pointers: Option<&PointerStore>,
    bound: &PointerBindings,
    self_peer_id: &PeerId,
    is_bootstrapping: bool,
    commitment_state: Option<&Arc<ResponderCommitmentState>>,
) -> SubtreeSliceResponse {
    serve_slice_challenge(
        challenge,
        storage,
        pointers,
        Some(bound),
        self_peer_id,
        is_bootstrapping,
        commitment_state,
    )
    .await
}

/// The body of the slice-challenge handlers. `bound` is `None` for the
/// earlier entry point, which serves pointers as it did before ADR-0019.
#[allow(clippy::too_many_lines, clippy::too_many_arguments)]
async fn serve_slice_challenge(
    challenge: &SubtreeSliceChallenge,
    storage: &ChunkStore,
    pointers: Option<&PointerStore>,
    bound: Option<&PointerBindings>,
    self_peer_id: &PeerId,
    is_bootstrapping: bool,
    commitment_state: Option<&Arc<ResponderCommitmentState>>,
) -> SubtreeSliceResponse {
    if is_bootstrapping {
        return SubtreeSliceResponse::Bootstrapping {
            challenge_id: challenge.challenge_id,
        };
    }

    if challenge.challenged_peer_id != *self_peer_id.as_bytes() {
        return SubtreeSliceResponse::Rejected {
            challenge_id: challenge.challenge_id,
            kind: RejectKind::Protocol,
            reason: "challenged_peer_id does not match this node".to_string(),
        };
    }

    // An honest auditor opens at most MAX_SLICE_OPENINGS blocks per challenge.
    // Reject larger requests up front: each opening forces a full chunk read to
    // build its proof, so an oversized request is a disk-read amplification lever
    // for a forged auditor.
    if challenge.openings.len() > MAX_SLICE_OPENINGS {
        let requested = challenge.openings.len();
        return SubtreeSliceResponse::Rejected {
            challenge_id: challenge.challenge_id,
            kind: RejectKind::Protocol,
            reason: format!(
                "slice challenge requests {requested} openings; max {MAX_SLICE_OPENINGS} per challenge"
            ),
        };
    }

    let Some(state) = commitment_state else {
        return SubtreeSliceResponse::Rejected {
            challenge_id: challenge.challenge_id,
            kind: RejectKind::Protocol,
            reason: "no commitment state".to_string(),
        };
    };
    // Resolve the SAME commitment the auditor pinned in round 1. If we no longer
    // retain it (rotated past it), reject as `UnknownCommitment`. With audit
    // grace removed (ADR-0004 A1) the auditor treats a responsive miss on an
    // in-window pin as a confirmed failure — answerability is restart-durable and
    // pins are challenged only in-window. We open blocks only for keys committed
    // under this pin.
    let Some(built) = state.lookup_by_hash(&challenge.expected_commitment_hash) else {
        return SubtreeSliceResponse::Rejected {
            challenge_id: challenge.challenge_id,
            kind: RejectKind::UnknownCommitment,
            reason: "unknown commitment hash".to_string(),
        };
    };

    // Coalesce openings by key, preserving first-seen order and deduplicating
    // block indices per key, so each committed chunk is read from the store and hashed
    // at most once even when the auditor opens several of its blocks (the normal
    // random + final pair, or a forged duplicate). Without this a ten-opening
    // request could re-read and re-hash the same chunk ten times.
    let mut key_order: Vec<XorName> = Vec::new();
    let mut indices_by_key: HashMap<XorName, Vec<u32>> = HashMap::new();
    for opening in &challenge.openings {
        let entry = indices_by_key.entry(opening.key).or_default();
        if entry.is_empty() {
            key_order.push(opening.key);
        }
        if !entry.contains(&opening.block_index) {
            entry.push(opening.block_index);
        }
    }

    // Coalescing only saves work when keys REPEAT. A forged auditor could still
    // spread its MAX_SLICE_OPENINGS across that many DISTINCT keys to force a
    // full-chunk read each (up to ~40 MiB). An honest auditor samples at most
    // BYTE_SPOTCHECK_MAX leaves, so cap distinct keys to that.
    if key_order.len() > BYTE_SPOTCHECK_MAX as usize {
        let distinct = key_order.len();
        return SubtreeSliceResponse::Rejected {
            challenge_id: challenge.challenge_id,
            kind: RejectKind::Protocol,
            reason: format!(
                "slice challenge spans {distinct} distinct keys; max {BYTE_SPOTCHECK_MAX}"
            ),
        };
    }

    // Round 2 may open ONLY the leaves round 1 actually proved, not the whole
    // pinned commitment. Membership of the pinned tree is the weaker property:
    // it would let a cheap round 1 over small records authorise openings against
    // large records elsewhere in the commitment, so the work this round costs
    // would not be bounded by the work the caller paid for in round 1.
    //
    // The authorised set is recomputed from `(tree, nonce)` rather than carried
    // in the round-1 session. The subtree is a pure function of those two, both
    // of which are already pinned — the nonce was matched against the session
    // before this handler ran — so recomputing costs one tree walk with no chunk
    // reads, while storing the key list would cost up to a full subtree of keys
    // per live session.
    let plan = match subtree_plan(built.tree(), &challenge.nonce) {
        Ok(plan) => plan,
        // The tree is ours and round 1 already walked it, so a failure here is
        // local inconsistency rather than anything the caller did. Transient
        // routes the auditor to the graced timeout lane instead of branding this
        // node with a confirmed failure it did not earn.
        Err(e) => {
            warn!("Subtree slice audit: cannot rebuild the round-1 subtree plan: {e:?}");
            return SubtreeSliceResponse::Rejected {
                challenge_id: challenge.challenge_id,
                kind: RejectKind::Transient,
                reason: "cannot rebuild the audited subtree".to_string(),
            };
        }
    };
    let authorised: HashSet<XorName> = plan.leaf_keys.iter().copied().collect();

    // Refuse the whole challenge before touching storage, matching how an
    // over-broad challenge is handled above. An honest auditor cannot reach this:
    // it samples only the leaves round 1 returned, and it has no `nonced_root` or
    // `content_len` to verify an answer for anything else against, so an opening
    // outside the subtree could not tell it anything even if served.
    if let Some(outside) = key_order.iter().find(|key| !authorised.contains(*key)) {
        return SubtreeSliceResponse::Rejected {
            challenge_id: challenge.challenge_id,
            kind: RejectKind::Protocol,
            reason: format!(
                "slice challenge opens {} which is outside the audited subtree",
                hex::encode(outside)
            ),
        };
    }

    let mut items = Vec::with_capacity(challenge.openings.len());
    for key in key_order {
        let indices = indices_by_key.remove(&key).unwrap_or_default();
        if built.tree().commits_pointer(&key) {
            // The record round 1 read, found by the root it reported over it
            // among what is held now and every record updates have replaced
            // since. The auditor verifies whatever is served, so nothing is
            // verified here.
            let Some(store) = pointers else {
                items.push(SubtreeSliceItem::Absent { key });
                continue;
            };
            let current = match store.record_bytes(&key).await {
                Ok(current) => current,
                Err(e) => {
                    return SubtreeSliceResponse::Rejected {
                        challenge_id: challenge.challenge_id,
                        kind: RejectKind::Transient,
                        reason: format!("pointer read error: {e}"),
                    }
                }
            };
            let Some(bound) = bound else {
                // As before ADR-0019, the record held and the newest one an
                // update replaced; but a node that no longer holds the pointer
                // is absent, whatever replaced records it still keeps.
                match current {
                    Some(current) => {
                        let mut records = vec![current];
                        records.extend(store.superseded(&key));
                        items.push(SubtreeSliceItem::PointerRecord { key, records });
                    }
                    None => items.push(SubtreeSliceItem::Absent { key }),
                }
                continue;
            };
            match pointer_records(
                challenge,
                &key,
                bound.get(&key),
                current,
                store.superseded_all(&key),
            ) {
                PointerServe::Record(record) => {
                    items.push(SubtreeSliceItem::PointerRecord {
                        key,
                        records: vec![record],
                    });
                }
                PointerServe::Absent => items.push(SubtreeSliceItem::Absent { key }),
                PointerServe::Unavailable => {
                    return SubtreeSliceResponse::Rejected {
                        challenge_id: challenge.challenge_id,
                        kind: RejectKind::Transient,
                        reason: format!(
                            "cannot serve the record round 1 read for pointer {}",
                            hex::encode(key)
                        ),
                    }
                }
            }
            continue;
        }
        match serve_committed_key_openings(challenge, storage, key, indices).await {
            KeyServe::Items(mut built_items) => items.append(&mut built_items),
            KeyServe::Absent => items.push(SubtreeSliceItem::Absent { key }),
            KeyServe::Reject(reject) => return reject,
        }
    }

    SubtreeSliceResponse::Items {
        challenge_id: challenge.challenge_id,
        items,
    }
}

/// What round 2 serves for a committed pointer.
enum PointerServe {
    /// The record round 1 read.
    Record(Vec<u8>),
    /// The pointer is no longer held, which is a lost pointer, whatever
    /// replaced records this node still keeps in memory.
    Absent,
    /// The pointer is held, but this node cannot serve the record round 1
    /// read: it has aged out or been evicted to keep memory bounded, or no
    /// root for it was kept, which a session this node opened never lacks. A
    /// local limit, not a lost pointer, so it is reported as one rather than
    /// proved wrong.
    Unavailable,
}

/// Choose what round 2 serves for the pointer at `key` (ADR-0019), from the
/// record held now and the records updates replaced: the one that reproduces
/// the root round 1 reported.
///
/// Without that root nothing is served for a pointer still held. Neither the
/// record held now nor the replaced records kept can show that no update came
/// since round 1 read it, since the kept ones are capped, so serving one would
/// be a guess that fails the node when it is wrong.
fn pointer_records(
    challenge: &SubtreeSliceChallenge,
    key: &XorName,
    bound: Option<&[u8; 32]>,
    current: Option<Vec<u8>>,
    replaced: Vec<Bytes>,
) -> PointerServe {
    // A node that no longer holds the pointer has lost it. Records an update
    // replaced are kept only to prove what round 1 read; they do not make up
    // for the pointer itself being gone.
    let Some(current) = current else {
        return PointerServe::Absent;
    };
    let Some(root) = bound else {
        return PointerServe::Unavailable;
    };
    let reproduces = |record: &[u8]| {
        nonced_block_root(&challenge.nonce, &challenge.challenged_peer_id, key, record) == *root
    };
    if reproduces(&current) {
        return PointerServe::Record(current);
    }
    replaced
        .into_iter()
        .find(|record| reproduces(record))
        .map_or(PointerServe::Unavailable, |record| {
            PointerServe::Record(Vec::from(record))
        })
}

/// Outcome of serving all requested openings for one committed key.
enum KeyServe {
    /// Openings built for this key; append to the response.
    Items(Vec<SubtreeSliceItem>),
    /// Committed but the bytes are gone → provable `Absent`.
    Absent,
    /// A terminal condition (out-of-range index, read/build error) that aborts
    /// the whole response.
    Reject(SubtreeSliceResponse),
}

/// Read a committed key's chunk once and build every requested opening from it.
///
/// The Bao outboard + nonced tree hash the whole chunk, so the CPU-heavy build
/// runs on a blocking thread to keep an audit-responder flood off the Tokio pool.
/// `indices` is already deduplicated by the caller.
async fn serve_committed_key_openings(
    challenge: &SubtreeSliceChallenge,
    storage: &ChunkStore,
    key: XorName,
    indices: Vec<u32>,
) -> KeyServe {
    let reject = |kind, reason| {
        KeyServe::Reject(SubtreeSliceResponse::Rejected {
            challenge_id: challenge.challenge_id,
            kind,
            reason,
        })
    };
    match get_raw_retrying(storage, &key).await {
        Ok(Some(bytes)) => {
            let nonce = challenge.nonce;
            let peer = challenge.challenged_peer_id;
            match tokio::task::spawn_blocking(move || {
                build_slice_items_for_key(nonce, peer, key, &bytes, &indices)
            })
            .await
            {
                Ok(Ok(built_items)) => KeyServe::Items(built_items),
                Ok(Err((kind, reason))) => reject(kind, reason),
                Err(e) => {
                    warn!(
                        "Subtree slice audit: proof build task failed for key {}: {e}",
                        hex::encode(key)
                    );
                    reject(
                        RejectKind::Transient,
                        format!("proof build task error: {e}"),
                    )
                }
            }
        }
        // Committed key, definitively absent → provable failure (§7: a real "I
        // don't hold it" answer, distinct from a read error).
        Ok(None) => {
            warn!(
                "Subtree slice audit: committed key {} requested but bytes absent",
                hex::encode(key)
            );
            KeyServe::Absent
        }
        // Persistent transient read error after retries → do NOT brand the peer a
        // deleter. Reject `Transient`; the auditor routes it to the timeout lane
        // so a flaky read never manufactures a confirmed possession failure
        // on an honest holder (which also gains no credit).
        Err(e) => {
            warn!(
                "Subtree slice audit: storage read error for committed key {}: {e} \
                 (rejecting as transient, not a confirmed failure)",
                hex::encode(key)
            );
            reject(
                RejectKind::Transient,
                format!("transient storage read error: {e}"),
            )
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use crate::replication::commitment_state::BuiltCommitment;
    use crate::replication::subtree::{build_subtree_proof, SubtreeLeaf};
    use saorsa_pqc::api::sig::ml_dsa_65;
    use std::time::Instant;

    /// ADR-0004 A1 grade flip (grace removed): a responsive `UnknownCommitment`
    /// or `Protocol` rejection is a CONFIRMED failure; only `Transient` routes to
    /// the timeout lane. This pure decision backs both audit rounds
    /// (`Confirmed → AuditFailureReason::Rejected` / `SliceRound::Rejected`;
    /// `TimeoutLane → AuditFailureReason::Timeout` + pinned-credit revocation).
    #[test]
    fn grade_reject_removes_grace_for_unknown_commitment() {
        assert_eq!(
            grade_reject(RejectKind::UnknownCommitment),
            RejectGrade::Confirmed,
            "an unanswerable pinned root is now a confirmed failure, not graced"
        );
        assert_eq!(grade_reject(RejectKind::Protocol), RejectGrade::Confirmed);
        assert_eq!(
            grade_reject(RejectKind::Transient),
            RejectGrade::TimeoutLane,
            "a transient read error routes to the timeout lane (no confirmed penalty)"
        );
    }

    /// A peer id for classification tests (never dialled).
    fn classify_peer() -> PeerId {
        PeerId::from_bytes([0x5Au8; 32])
    }

    // A node that answers round 1 with a valid signed proof and then claims
    // `Bootstrapping` in round 2 is contradicting itself: a bootstrapping node
    // has no committed data to prove. Grading that as a graced timeout would be
    // the cheapest possible way to dodge every possession check while KEEPING
    // the holder credit earned in round 1 — so it must be a confirmed failure.
    #[test]
    fn responsive_bootstrap_is_a_confirmed_failure_not_a_graced_timeout() {
        let id = 4242u64;
        let round = classify_slice_response(
            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Bootstrapping {
                challenge_id: id,
            }),
            id,
            &classify_peer(),
        );
        assert!(
            matches!(round, SliceRound::ResponsiveBootstrap),
            "mid-audit Bootstrapping must classify as ResponsiveBootstrap"
        );

        // The production arm maps `ResponsiveBootstrap` alongside `Rejected` to
        // `AuditFailureReason::Rejected`, and THAT reason is what revokes the
        // peer's holder credit wholesale. Pin the policy both ways, since the
        // whole point of the classification is landing on the revoking side.
        assert!(
            super::super::audit_failure_revokes_holder_credit(&AuditFailureReason::Rejected),
            "a confirmed round-2 failure must revoke holder credit"
        );
        assert!(
            !super::super::audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
            "the timeout lane must not revoke credit WHOLESALE — the contrast that \
             makes classifying ResponsiveBootstrap as confirmed load-bearing. The \
             timeout lane still drops the pinned commitment's own credit; see \
             round2_revokes_pinned_credit"
        );
    }

    /// A responder that answered round 1 and then goes quiet must not keep the
    /// holder credit for the commitment under audit.
    ///
    /// Round 2 names the blocks after the roots are committed, so a responder
    /// chooses whether to reply already knowing the draw. If silence kept
    /// credit, answering only favourable draws would be free and standing earned
    /// once would survive every dodged check afterwards. Both no-proof outcomes
    /// therefore drop the pinned credit, while the confirmed lanes are excluded
    /// here because they revoke the peer's credit wholesale downstream.
    #[test]
    fn round2_without_a_proof_drops_the_pinned_commitment_credit() {
        assert!(
            round2_revokes_pinned_credit(&SliceRound::Timeout),
            "silence after a valid round-1 proof must cost the pinned credit"
        );
        assert!(
            round2_revokes_pinned_credit(&SliceRound::TransientReject),
            "a transient reject also ends round 2 with no possession proof"
        );
        assert!(
            !round2_revokes_pinned_credit(&SliceRound::Served(vec![])),
            "a served response is judged on its contents, not here"
        );
        for confirmed in [
            SliceRound::Rejected,
            SliceRound::ResponsiveBootstrap,
            SliceRound::Malformed,
        ] {
            assert!(
                !round2_revokes_pinned_credit(&confirmed),
                "confirmed failures revoke wholesale downstream, not scoped here"
            );
        }
    }

    /// The scoped revocation must not erase credit the peer re-earned under a
    /// different commitment: an unanswered round 2 costs the pin it was about,
    /// not the peer's whole standing.
    #[test]
    fn pinned_credit_revocation_is_scoped_to_the_audited_commitment() {
        let peer = classify_peer();
        let (audited, newer) = ([0x11u8; 32], [0x22u8; 32]);
        let key: XorName = [0xC3u8; 32];
        let now = Instant::now();
        let mut provers = RecentProvers::new();
        provers.record_proof(key, peer, audited, now);
        provers.record_proof(key, peer, newer, now);

        // What `verify_subtree_response` does when round 2 yields no proof.
        provers.forget_commitment(&audited);

        assert!(
            !provers.is_credited_holder(&key, &peer, &audited),
            "credit for the audited pin must be gone after an unanswered round 2"
        );
        assert!(
            provers.is_credited_holder(&key, &peer, &newer),
            "credit re-earned under a newer commitment must survive"
        );
    }

    // Every classification arm is guarded on `challenge_id`. A responder must not
    // be able to answer the challenge it was actually sent with a body minted for
    // a different one — in particular it must not downgrade a live challenge by
    // replaying a `Bootstrapping` or `Transient` body from another exchange.
    #[test]
    fn slice_response_for_another_challenge_is_malformed() {
        let (sent, other) = (7u64, 8u64);
        let peer = classify_peer();
        let bodies = [
            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Bootstrapping {
                challenge_id: other,
            }),
            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Items {
                challenge_id: other,
                items: vec![],
            }),
            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Rejected {
                challenge_id: other,
                kind: RejectKind::Transient,
                reason: String::new(),
            }),
        ];
        for body in bodies {
            assert!(
                matches!(
                    classify_slice_response(body, sent, &peer),
                    SliceRound::Malformed
                ),
                "a body carrying another challenge_id must be malformed"
            );
        }

        // A non-round-2 body on the round-2 path is malformed too.
        assert!(matches!(
            classify_slice_response(
                ReplicationMessageBody::SubtreeAuditResponse(
                    crate::replication::protocol::SubtreeAuditResponse::Bootstrapping {
                        challenge_id: sent,
                    }
                ),
                sent,
                &peer,
            ),
            SliceRound::Malformed
        ));
    }

    // The two-round audit splits into SHIPPED pure functions exercised directly
    // here (no reimplementation that could drift):
    //   - round 1: `evaluate_subtree_structure` (pin/identity/signature +
    //     structural root rebuild),
    //   - sampling: `random_spotcheck_leaves` (3..=5 FRESHLY-RANDOM leaves chosen
    //     after the proof is in hand — see its doc for the soundness argument), and
    //   - round 2: `verify_slice_response` (decode the Bao slice against the chunk
    //     address + fold the nonced opening to the round-1 `nonced_root`, both from
    //     what the RESPONDER served — the auditor holds nothing).

    fn key(i: u32) -> XorName {
        let mut k = [0u8; 32];
        k[..4].copy_from_slice(&i.to_be_bytes());
        k
    }

    // The auditor's per-opening matcher returns the FIRST item with a matching
    // identity, so an oversized, unsolicited, or colliding response must be
    // rejected as malformed BEFORE matching — otherwise item order (or padding)
    // could decide the verdict or force quadratic validation work.
    #[test]
    fn verify_slice_response_rejects_malformed_item_sets() {
        let leaf = |k: XorName| SubtreeLeaf {
            key: k,
            bytes_hash: [0u8; 32],
            content_len: 0,
            nonced_root: [0u8; 32],
        };
        let present = |k: XorName, i: u32| SubtreeSliceItem::Present {
            key: k,
            block_index: i,
            bao_slice: vec![],
            nonced_siblings: vec![],
        };
        let malformed = |verdict| {
            matches!(
                verdict,
                AuditVerdict::Fail(AuditFailureReason::MalformedResponse)
            )
        };
        let nonce = [0u8; 32];
        let peer = [0u8; 32];
        // The auditor requested (key1, block 0), (key1, block 1), (key2, block 0).
        let openings = vec![(leaf(key(1)), 0u32), (leaf(key(1)), 1), (leaf(key(2)), 0)];

        // More items than requested openings.
        let oversized = vec![
            present(key(1), 0),
            present(key(1), 1),
            present(key(2), 0),
            present(key(2), 0),
        ];
        assert!(malformed(verify_slice_response(
            &openings, &nonce, &peer, &oversized
        )));

        // An item that was not requested.
        let unsolicited = vec![present(key(9), 0)];
        assert!(malformed(verify_slice_response(
            &openings,
            &nonce,
            &peer,
            &unsolicited
        )));

        // Duplicate (key, block_index).
        let dup = vec![present(key(1), 0), present(key(1), 0)];
        assert!(malformed(verify_slice_response(
            &openings, &nonce, &peer, &dup
        )));

        // A key that is both Present and Absent.
        let conflict = vec![present(key(1), 0), SubtreeSliceItem::Absent { key: key(1) }];
        assert!(malformed(verify_slice_response(
            &openings, &nonce, &peer, &conflict
        )));

        // A well-formed, unique, solicited response passes the identity guard (the
        // empty proofs then fail verification as DigestMismatch, NOT malformed).
        let ok = vec![present(key(1), 0), present(key(1), 1), present(key(2), 0)];
        assert!(!malformed(verify_slice_response(
            &openings, &nonce, &peer, &ok
        )));
    }
    /// Deterministic chunk content for fixture index `i`. Fixture keys are
    /// CONTENT-ADDRESSED (`ckey(i) == BLAKE3(chunk_bytes(i))`), so a committed
    /// leaf is `(key, key)` exactly as production, and round 2 serves this content.
    fn chunk_bytes(i: u32) -> Vec<u8> {
        let mut v = b"chunk-body".to_vec();
        v.extend_from_slice(&i.to_le_bytes());
        v
    }

    /// Content-addressed key for fixture index `i` (so `bytes_hash == key`).
    fn ckey(i: u32) -> XorName {
        *blake3::hash(&chunk_bytes(i)).as_bytes()
    }

    /// The content behind a committed fixture key (reverse of `ckey`), so round-2
    /// fixtures can serve the real bytes for any sampled leaf.
    fn content_for_key(k: &XorName) -> Vec<u8> {
        (0..16_384u32)
            .find(|&i| &ckey(i) == k)
            .map(chunk_bytes)
            .expect("fixture content for committed key")
    }

    /// Build an honest committed tree of `n` keys + a valid round-1 proof for
    /// `nonce`. Returns `(built, proof, peer_id)`. The auditor pins `built.hash()`.
    fn honest(n: u32, nonce: &[u8; 32]) -> (BuiltCommitment, SubtreeProof, [u8; 32]) {
        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
        let pk_b = pk.to_bytes();
        // Content-addressed: bytes_hash == key, exactly as production commits.
        let entries: Vec<_> = (0..n).map(|i| (ckey(i), ckey(i))).collect();
        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
        let proof =
            build_subtree_proof(built.tree(), nonce, &peer_id, |k| Some(content_for_key(k)))
                .unwrap();
        (built, proof, peer_id)
    }

    /// Round-1 verdict against the pinned commitment.
    fn structure(
        built: &BuiltCommitment,
        proof: &SubtreeProof,
        nonce: &[u8; 32],
        peer: &[u8; 32],
    ) -> Result<(), AuditFailureReason> {
        evaluate_subtree_structure(built.commitment(), proof, nonce, &built.hash(), peer)
    }

    /// The 3..=5 spot-check leaves the auditor would open in round 2. Now
    /// freshly-random (post-proof) rather than nonce-derived; the `_nonce`/
    /// `_key_count` params are kept so existing call sites read unchanged.
    fn sample<'a>(
        proof: &'a SubtreeProof,
        _nonce: &[u8; 32],
        _key_count: u32,
    ) -> Vec<&'a SubtreeLeaf> {
        random_spotcheck_leaves(proof, 8u32.clamp(BYTE_SPOTCHECK_MIN, BYTE_SPOTCHECK_MAX))
    }

    /// Pair each sampled leaf with a block index for round 2. The fixtures use
    /// short (single-block) chunks, so block 0 is the only block; the production
    /// auditor draws a fresh random index via `random_block_index`.
    fn openings_for(sample: &[&SubtreeLeaf]) -> Vec<(SubtreeLeaf, u32)> {
        sample.iter().map(|l| ((*l).clone(), 0u32)).collect()
    }

    /// Honest responder: for each opening build a real Bao slice + nonced opening
    /// from the true chunk content, exactly as `handle_subtree_slice_challenge`
    /// would.
    fn served_honest_items(
        openings: &[(SubtreeLeaf, u32)],
        nonce: &[u8; 32],
        peer: &[u8; 32],
    ) -> Vec<SubtreeSliceItem> {
        openings
            .iter()
            .map(|(leaf, block_index)| {
                let content = content_for_key(&leaf.key);
                let bao_slice =
                    crate::replication::slice::extract_block_slice(&content, *block_index).unwrap();
                let nonced_siblings = crate::replication::slice::nonced_block_siblings(
                    nonce,
                    peer,
                    &leaf.key,
                    &content,
                    *block_index,
                )
                .unwrap();
                SubtreeSliceItem::Present {
                    key: leaf.key,
                    block_index: *block_index,
                    bao_slice,
                    nonced_siblings,
                }
            })
            .collect()
    }

    // ---- round 1: structure --------------------------------------------------

    #[test]
    fn honest_structure_then_bytes_passes() {
        let nonce = [9u8; 32];
        let (built, proof, peer) = honest(400, &nonce);
        // Round 1.
        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
        // Round 2: honest responder opens real slices for the sample.
        let s = sample(&proof, &nonce, built.commitment().key_count);
        assert!(!s.is_empty(), "expected a non-empty sample");
        let openings = openings_for(&s);
        let items = served_honest_items(&openings, &nonce, &peer);
        match verify_slice_response(&openings, &nonce, &peer, &items) {
            AuditVerdict::Pass { checked } => assert!(checked >= 1, "must verify >=1 leaf"),
            other @ AuditVerdict::Fail(_) => panic!("expected Pass, got {other:?}"),
        }
    }

    /// Possession-forgery guard: a peer that signs a commitment whose leaves
    /// decouple the credited `key` from the authenticated content hash
    /// (`bytes_hash != key`) is rejected at round 1 — even though the structural
    /// root still rebuilds from `(key, bytes_hash)`. Without the guard such a peer
    /// could earn holder credit for an expensive address `key` while only proving
    /// possession of an unrelated (e.g. one-byte) chunk hashing to `bytes_hash`.
    #[test]
    fn leaf_with_bytes_hash_decoupled_from_key_is_rejected() {
        let nonce = [5u8; 32];
        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
        let pk_b = pk.to_bytes();
        // Every leaf commits (key, bytes_hash) with bytes_hash != key.
        let entries: Vec<_> = (0..64u32).map(|i| (ckey(i), ckey(i + 10_000))).collect();
        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
        let proof =
            build_subtree_proof(built.tree(), &nonce, &peer_id, |k| Some(content_for_key(k)))
                .unwrap();
        // The structural root rebuilds (it is a genuinely signed tree), so the
        // decoupled-address gate is what must reject it.
        assert_eq!(
            structure(&built, &proof, &nonce, &peer_id),
            Err(AuditFailureReason::DigestMismatch),
            "a leaf whose bytes_hash != key must be rejected at round 1"
        );
    }

    #[test]
    fn commitment_bound_to_another_peer_rejected() {
        let nonce = [3u8; 32];
        let (built, proof, _peer) = honest(200, &nonce);
        let other = [0xAAu8; 32];
        assert_eq!(
            structure(&built, &proof, &nonce, &other),
            Err(AuditFailureReason::Rejected)
        );
    }

    #[test]
    fn wrong_pinned_commitment_rejected() {
        let nonce = [3u8; 32];
        let (built, proof, peer) = honest(200, &nonce);
        let mut wrong_pin = built.hash();
        wrong_pin[0] ^= 0x01;
        assert_eq!(
            evaluate_subtree_structure(built.commitment(), &proof, &nonce, &wrong_pin, &peer),
            Err(AuditFailureReason::Rejected)
        );
    }

    #[test]
    fn tampered_leaf_structure_rejected() {
        let nonce = [3u8; 32];
        let (built, mut proof, peer) = honest(200, &nonce);
        if let Some(first) = proof.leaves.first_mut() {
            first.bytes_hash[0] ^= 0x01; // breaks root reconstruction
        }
        assert_eq!(
            structure(&built, &proof, &nonce, &peer),
            Err(AuditFailureReason::DigestMismatch)
        );
    }

    #[test]
    fn wrong_leaf_count_structure_rejected() {
        let nonce = [3u8; 32];
        let (built, mut proof, peer) = honest(200, &nonce);
        proof.leaves.pop();
        assert_eq!(
            structure(&built, &proof, &nonce, &peer),
            Err(AuditFailureReason::DigestMismatch)
        );
    }

    // ---- round 2: responder-served bytes ------------------------------------

    #[test]
    fn deleter_absent_bytes_is_confirmed_failure() {
        // THE headline fix: a node whose round-1 proof is structurally perfect
        // but which has DELETED a committed chunk cannot serve its bytes. It
        // signals `Absent` for the sampled key → provable lie → confirmed
        // failure, reported as `KeyAbsent` because the peer admitted the loss.
        // Crucially, the auditor holds NONE of the peer's chunks; the
        // verdict depends only on what the responder serves.
        let nonce = [9u8; 32];
        let (built, proof, peer) = honest(400, &nonce);
        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
        let s = sample(&proof, &nonce, built.commitment().key_count);
        let openings = openings_for(&s);
        // Responder returns Absent for the FIRST opening, honest for the rest.
        let victim = openings.first().map(|(l, _)| l.key).unwrap();
        let mut items = served_honest_items(&openings, &nonce, &peer);
        if let Some(slot) = items.first_mut() {
            *slot = SubtreeSliceItem::Absent { key: victim };
        }
        let v = verify_slice_response(&openings, &nonce, &peer, &items);
        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::KeyAbsent));
    }

    #[test]
    fn omitted_committed_key_is_confirmed_failure() {
        // A responder that simply omits a sampled committed opening from its items
        // (neither Present nor Absent) is a confirmed failure just like Absent,
        // but it never admitted the loss, so it is a proof failure rather than
        // `KeyAbsent`. This is the counterpart to
        // `deleter_absent_bytes_is_confirmed_failure`: together they pin that the
        // two reasons stay distinguishable in the audit-failure log line.
        let nonce = [9u8; 32];
        let (built, proof, peer) = honest(400, &nonce);
        let s = sample(&proof, &nonce, built.commitment().key_count);
        let openings = openings_for(&s);
        let mut items = served_honest_items(&openings, &nonce, &peer);
        items.remove(0); // omit the first opening entirely
        let v = verify_slice_response(&openings, &nonce, &peer, &items);
        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
    }

    #[test]
    fn fake_storage_garbage_bytes_is_confirmed_failure() {
        // A "fake-storage" responder claims possession but opens a slice built
        // from garbage content. The garbage slice does not decode against the
        // committed content address (`bytes_hash`), so chain 1 fails → confirmed
        // failure. No auditor holdings involved.
        let nonce = [9u8; 32];
        let (built, proof, peer) = honest(400, &nonce);
        let s = sample(&proof, &nonce, built.commitment().key_count);
        let openings = openings_for(&s);
        let items: Vec<SubtreeSliceItem> = openings
            .iter()
            .map(|(leaf, bi)| {
                let mut garbage = blake3::hash(&leaf.key).as_bytes().to_vec();
                garbage.extend_from_slice(b"adversary-fake-storage");
                let bao_slice =
                    crate::replication::slice::extract_block_slice(&garbage, *bi).unwrap();
                let nonced_siblings = crate::replication::slice::nonced_block_siblings(
                    &nonce, &peer, &leaf.key, &garbage, *bi,
                )
                .unwrap();
                SubtreeSliceItem::Present {
                    key: leaf.key,
                    block_index: *bi,
                    bao_slice,
                    nonced_siblings,
                }
            })
            .collect();
        let v = verify_slice_response(&openings, &nonce, &peer, &items);
        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
    }

    #[test]
    fn correct_content_address_but_stale_nonced_root_fails() {
        // A responder can serve the real block (chain 1, the Bao slice against the
        // address, passes), but if its committed `nonced_root` does not correspond
        // to the audit's nonce over that content, the nonced opening (chain 2)
        // cannot fold to it. We model a leaf whose committed `nonced_root` was
        // built under a DIFFERENT nonce; the honest opening under the audit nonce
        // then fails to match it.
        let nonce = [9u8; 32];
        let (built, mut proof, peer) = honest(400, &nonce);
        let other_nonce = [0xEEu8; 32];
        for leaf in &mut proof.leaves {
            leaf.nonced_root = crate::replication::slice::nonced_block_root(
                &other_nonce,
                &peer,
                &leaf.key,
                &content_for_key(&leaf.key),
            );
        }
        let s = sample(&proof, &nonce, built.commitment().key_count);
        let openings = openings_for(&s);
        let items = served_honest_items(&openings, &nonce, &peer);
        let v = verify_slice_response(&openings, &nonce, &peer, &items);
        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
    }

    #[test]
    fn auditor_holds_nothing_still_catches_deleter() {
        // Explicit contract: the auditor's own storage is irrelevant. A deleter
        // is caught purely from its served (absent) response. (Compare the OLD
        // design, where an auditor holding none of the chunks went Inconclusive
        // and the deleter walked free.)
        let nonce = [0x21u8; 32];
        let (built, proof, peer) = honest(256, &nonce);
        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
        let s = sample(&proof, &nonce, built.commitment().key_count);
        let openings = openings_for(&s);
        // Responder is a total deleter: Absent for every opening.
        let items: Vec<SubtreeSliceItem> = openings
            .iter()
            .map(|(l, _)| SubtreeSliceItem::Absent { key: l.key })
            .collect();
        let v = verify_slice_response(&openings, &nonce, &peer, &items);
        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::KeyAbsent));
    }

    #[test]
    fn admitted_absence_and_failed_proof_are_reported_separately() {
        // ROLLOUT DIAGNOSTICS: the two ways a peer fails round 2 must stay
        // distinguishable in the failure summary, because they mean different
        // things operationally — a peer owning up to lost data versus one whose
        // proof did not verify. Before this was split, both rolled up as
        // `digest_mismatch_keys` and `absent_keys` was always 0, so a fleet-wide
        // audit regression and a fleet-wide data loss looked identical.
        let nonce = [0x33u8; 32];
        let (built, proof, peer) = honest(256, &nonce);
        let s = sample(&proof, &nonce, built.commitment().key_count);
        let openings = openings_for(&s);

        // Admitted loss → KeyAbsent → counted under `absent_keys`.
        let absent_items: Vec<SubtreeSliceItem> = openings
            .iter()
            .map(|(l, _)| SubtreeSliceItem::Absent { key: l.key })
            .collect();
        assert_eq!(
            verify_slice_response(&openings, &nonce, &peer, &absent_items),
            AuditVerdict::Fail(AuditFailureReason::KeyAbsent),
        );
        let absent_summary = subtree_failure_summary(&AuditFailureReason::KeyAbsent);
        assert_eq!(absent_summary.absent_keys, 1);
        assert_eq!(absent_summary.digest_mismatch_keys, 0);

        // Withheld without admission → DigestMismatch → `digest_mismatch_keys`.
        let withheld: Vec<SubtreeSliceItem> = served_honest_items(&openings, &nonce, &peer)
            .into_iter()
            .skip(1)
            .collect();
        assert_eq!(
            verify_slice_response(&openings, &nonce, &peer, &withheld),
            AuditVerdict::Fail(AuditFailureReason::DigestMismatch),
        );
        let mismatch_summary = subtree_failure_summary(&AuditFailureReason::DigestMismatch);
        assert_eq!(mismatch_summary.digest_mismatch_keys, 1);
        assert_eq!(mismatch_summary.absent_keys, 0);

        // Both are confirmed failures with identical enforcement, so the split is
        // diagnostic only: it must not quietly soften what an absent key costs.
        assert_eq!(absent_summary.failed_keys, mismatch_summary.failed_keys);
    }

    #[test]
    fn sample_size_is_in_3_to_5_band() {
        // ADR-0002: round-2 samples a SMALL surprise set (3..=5) of the proven
        // leaves. For a large subtree the sample is capped at 5.
        let nonce = [7u8; 32];
        let (built, proof, _peer) = honest(1024, &nonce);
        let s = sample(&proof, &nonce, built.commitment().key_count);
        assert!(
            (BYTE_SPOTCHECK_MIN as usize..=BYTE_SPOTCHECK_MAX as usize).contains(&s.len()),
            "sample {} must be within 3..=5",
            s.len()
        );
    }

    #[test]
    fn full_pass_requires_every_sampled_leaf() {
        // checked must equal the number of sampled leaves on a pass (no leaf is
        // silently skipped — every sampled, committed key must verify).
        let nonce = [11u8; 32];
        let (built, proof, peer) = honest(400, &nonce);
        let s = sample(&proof, &nonce, built.commitment().key_count);
        let openings = openings_for(&s);
        let items = served_honest_items(&openings, &nonce, &peer);
        match verify_slice_response(&openings, &nonce, &peer, &items) {
            AuditVerdict::Pass { checked } => assert_eq!(checked, openings.len()),
            other @ AuditVerdict::Fail(_) => panic!("expected Pass, got {other:?}"),
        }
    }

    // ---- end-to-end gate composition ----------------------------------------

    #[test]
    fn structure_fail_short_circuits_before_round_2() {
        // A structurally invalid proof is rejected in round 1; the slice challenge
        // is never issued. We assert the round-1 gate returns Err so the auditor
        // (verify_subtree_response) never reaches request_slice_proof.
        let nonce = [5u8; 32];
        let (built, mut proof, peer) = honest(300, &nonce);
        if let Some(first) = proof.leaves.first_mut() {
            first.bytes_hash[0] ^= 0x01;
        }
        assert!(structure(&built, &proof, &nonce, &peer).is_err());
    }

    /// Build an honest committed tree whose keys are content-addressed but biased
    /// to the FAR half of the XOR space (top bit set), so `observe_closeness`
    /// counts them toward `far`. Keys stay content-addressed (`bytes_hash == key`)
    /// so round 2 serves real bytes.
    fn honest_far(n: u32, nonce: &[u8; 32]) -> (BuiltCommitment, SubtreeProof, [u8; 32]) {
        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
        let pk_b = pk.to_bytes();
        let mut entries: Vec<(XorName, [u8; 32])> = Vec::new();
        let mut i = 0u32;
        while entries.len() < n as usize {
            let k = ckey(i);
            if k[0] >= 0x80 {
                entries.push((k, k));
            }
            i = i.saturating_add(1);
        }
        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
        let proof =
            build_subtree_proof(built.tree(), nonce, &peer_id, |k| Some(content_for_key(k)))
                .unwrap();
        (built, proof, peer_id)
    }

    /// ADR-0002 "Closeness" is OBSERVE-ONLY: far-keyed honest proofs verify
    /// exactly like near-keyed ones. The verdict (structure + served bytes) is
    /// closeness-blind, so a "far/padding" shape can never produce a Fail.
    #[test]
    fn closeness_is_observe_only_far_keys_still_pass() {
        let nonce = [9u8; 32];

        let (built_far, proof_far, peer_far) = honest_far(400, &nonce);
        assert!(structure(&built_far, &proof_far, &nonce, &peer_far).is_ok());
        let sf = sample(&proof_far, &nonce, built_far.commitment().key_count);
        let of = openings_for(&sf);
        let v_far = verify_slice_response(
            &of,
            &nonce,
            &peer_far,
            &served_honest_items(&of, &nonce, &peer_far),
        );

        let (built_near, proof_near, peer_near) = honest(400, &nonce);
        assert!(structure(&built_near, &proof_near, &nonce, &peer_near).is_ok());
        let sn = sample(&proof_near, &nonce, built_near.commitment().key_count);
        let on = openings_for(&sn);
        let v_near = verify_slice_response(
            &on,
            &nonce,
            &peer_near,
            &served_honest_items(&on, &nonce, &peer_near),
        );

        match (&v_far, &v_near) {
            (AuditVerdict::Pass { checked: cf }, AuditVerdict::Pass { checked: cn }) => {
                assert!(*cf >= 1 && *cn >= 1);
            }
            other => panic!("both honest proofs must Pass regardless of closeness, got {other:?}"),
        }
        assert!(
            !matches!(v_far, AuditVerdict::Fail(_)),
            "far/padding-shaped honest proof must NEVER fail, got {v_far:?}"
        );
    }

    // Unused-leaf constructor guard: keep SubtreeLeaf import meaningful.
    #[test]
    fn subtree_leaf_is_constructible() {
        let _l = SubtreeLeaf {
            key: key(1),
            bytes_hash: [0u8; 32],
            content_len: 0,
            nonced_root: [0u8; 32],
        };
    }
}

/// Pointers in the storage audit (ADR-0016), driven through the live responders
/// against real stores and judged by the auditor's own checks, so a pass here
/// is a pass on the network.
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod pointer_audit_tests {
    use super::*;
    use crate::replication::commitment::MerkleTree;
    use crate::replication::commitment::MAX_COMMITMENT_KEY_COUNT;
    use crate::replication::commitment_state::BuiltCommitment;
    use crate::replication::subtree::max_subtree_leaves;
    use crate::storage::chunk_store::CHUNKS_DIR_NAME;
    use crate::storage::ChunkStoreConfig;
    use ant_protocol::pointer::{PointerTarget, PointerTargetKind};
    use saorsa_pqc::api::sig::ml_dsa_65;
    use std::path::PathBuf;
    use tempfile::TempDir;
    use tokio_util::sync::CancellationToken;

    const CHALLENGE_ID: u64 = 7;

    /// A one-block chunk, distinct per `i`.
    fn chunk(i: u8) -> Vec<u8> {
        (0..=255u8).cycle().take(1024).map(|b| b ^ i).collect()
    }

    /// `owner`'s pointer at `counter`.
    fn pointer(owner: u8, counter: u64) -> Pointer {
        let (pk, sk) = ml_dsa_65().generate_keypair_from_seed(&[owner; 32]);
        let target = PointerTarget::new(PointerTargetKind::Chunk, [owner; 32]);
        Pointer::sign(&sk, &pk, counter, target).expect("sign")
    }

    /// A responder that holds and has committed to `chunks` chunks and
    /// `pointers` pointers.
    struct Responder {
        storage: ChunkStore,
        pointers: PointerStore,
        state: Arc<ResponderCommitmentState>,
        peer: PeerId,
        peer_bytes: [u8; 32],
        chunk_root: PathBuf,
        _dirs: (TempDir, TempDir),
    }

    impl Responder {
        async fn new(chunks: u8, pointers: u8) -> Self {
            let chunk_dir = TempDir::new().expect("temp dir");
            let storage = ChunkStore::new(ChunkStoreConfig {
                root_dir: chunk_dir.path().to_path_buf(),
                ..ChunkStoreConfig::test_default()
            })
            .await
            .expect("chunk store");
            let pointer_dir = TempDir::new().expect("temp dir");
            let pointer_store = PointerStore::new(pointer_dir.path())
                .await
                .expect("pointer store");

            let mut entries = Vec::new();
            for i in 0..chunks {
                let content = chunk(i);
                let address = ChunkStore::compute_address(&content);
                storage.put(&address, &content).await.expect("put chunk");
                entries.push((address, address));
            }
            for owner in 0..pointers {
                let record = pointer(owner, 1);
                pointer_store
                    .put_bytes(&record.to_bytes())
                    .await
                    .expect("put pointer");
                entries.push((record.address(), pointer_leaf_hash(&record.address())));
            }

            let (pk, sk) = ml_dsa_65().generate_keypair().expect("keypair");
            let peer_bytes = *blake3::hash(&pk.to_bytes()).as_bytes();
            let built =
                BuiltCommitment::build(entries, &peer_bytes, &sk, &pk.to_bytes()).expect("build");
            let state = Arc::new(ResponderCommitmentState::new());
            state.rotate(built);
            Self {
                storage,
                pointers: pointer_store,
                state,
                peer: PeerId::from_bytes(peer_bytes),
                peer_bytes,
                chunk_root: chunk_dir.path().to_path_buf(),
                _dirs: (chunk_dir, pointer_dir),
            }
        }

        /// Where the file store keeps `key`'s bytes, so a test can rot them.
        fn chunk_file(&self, key: &XorName) -> PathBuf {
            self.chunk_root
                .join(CHUNKS_DIR_NAME)
                .join(format!("{:02x}", key.last().copied().unwrap_or(0)))
                .join(hex::encode(key))
        }

        fn committed(&self) -> Arc<BuiltCommitment> {
            self.state.current().expect("a current commitment")
        }

        async fn round1(&self, nonce: [u8; 32]) -> SubtreeAuditResponse {
            self.round1_work(nonce).await.response
        }

        async fn round1_work(&self, nonce: [u8; 32]) -> Round1Work {
            let challenge = SubtreeAuditChallenge {
                challenge_id: CHALLENGE_ID,
                nonce,
                challenged_peer_id: self.peer_bytes,
                expected_commitment_hash: self.committed().hash(),
            };
            handle_subtree_challenge_measured_with_pointers(
                &challenge,
                &self.storage,
                Some(&self.pointers),
                &self.peer,
                false,
                Some(&self.state),
            )
            .await
        }

        /// Round 2 as the engine serves it: with what round 1 bound for each
        /// pointer it opens, as the live session carries it.
        async fn round2(
            &self,
            nonce: [u8; 32],
            openings: &[(SubtreeLeaf, u32)],
        ) -> Vec<SubtreeSliceItem> {
            let bound = openings
                .iter()
                .map(|(leaf, _)| leaf)
                .filter(|leaf| is_pointer_leaf(leaf))
                .map(|leaf| (leaf.key, leaf.nonced_root))
                .collect();
            self.round2_bound(nonce, openings, &bound).await
        }

        async fn round2_bound(
            &self,
            nonce: [u8; 32],
            openings: &[(SubtreeLeaf, u32)],
            bound: &PointerBindings,
        ) -> Vec<SubtreeSliceItem> {
            match self.round2_response(nonce, openings, bound).await {
                SubtreeSliceResponse::Items { items, .. } => items,
                other => panic!("expected items, got {other:?}"),
            }
        }

        async fn round2_response(
            &self,
            nonce: [u8; 32],
            openings: &[(SubtreeLeaf, u32)],
            bound: &PointerBindings,
        ) -> SubtreeSliceResponse {
            let challenge = SubtreeSliceChallenge {
                challenge_id: CHALLENGE_ID,
                nonce,
                challenged_peer_id: self.peer_bytes,
                expected_commitment_hash: self.committed().hash(),
                openings: openings
                    .iter()
                    .map(|(leaf, block_index)| SubtreeSliceOpening {
                        key: leaf.key,
                        block_index: *block_index,
                    })
                    .collect(),
            };
            handle_subtree_slice_challenge_with_pointer_bindings(
                &challenge,
                &self.storage,
                Some(&self.pointers),
                bound,
                &self.peer,
                false,
                Some(&self.state),
            )
            .await
        }

        /// Round 1 as the auditor sees it: the proof, checked against the pin.
        async fn proved_leaves(&self, nonce: [u8; 32]) -> Vec<SubtreeLeaf> {
            let committed = self.committed();
            match self.round1(nonce).await {
                SubtreeAuditResponse::Proof {
                    commitment, proof, ..
                } => {
                    assert_eq!(
                        evaluate_subtree_structure(
                            &commitment,
                            &proof,
                            &nonce,
                            &committed.hash(),
                            &self.peer_bytes,
                        ),
                        Ok(()),
                        "the auditor must accept the round-1 proof"
                    );
                    proof.leaves
                }
                other => panic!("expected a proof, got {other:?}"),
            }
        }
    }

    /// A nonce whose audited subtree holds both a pointer and a chunk.
    fn mixed_nonce(tree: &MerkleTree) -> [u8; 32] {
        (0..=255u8)
            .map(|b| [b; 32])
            .find(|nonce| {
                subtree_plan(tree, nonce).is_ok_and(|plan| {
                    plan.leaf_is_pointer.contains(&true) && plan.leaf_is_pointer.contains(&false)
                })
            })
            .expect("some nonce audits a mixed subtree")
    }

    /// What the auditor opens: every pointer leaf, then chunks, up to the
    /// spot-check cap, with the block indices production draws.
    fn openings(leaves: &[SubtreeLeaf]) -> Vec<(SubtreeLeaf, u32)> {
        let (pointers, chunks): (Vec<_>, Vec<_>) =
            leaves.iter().partition(|leaf| is_pointer_leaf(leaf));
        pointers
            .into_iter()
            .take(3)
            .chain(chunks)
            .take(BYTE_SPOTCHECK_MAX as usize)
            .flat_map(|leaf| {
                let indices = if is_pointer_leaf(leaf) {
                    vec![0]
                } else {
                    block_indices_for_leaf(leaf.content_len)
                };
                indices.into_iter().map(|i| (leaf.clone(), i))
            })
            .collect()
    }

    fn first_pointer(openings: &[(SubtreeLeaf, u32)]) -> XorName {
        openings
            .iter()
            .map(|(leaf, _)| leaf)
            .find(|leaf| is_pointer_leaf(leaf))
            .map(|leaf| leaf.key)
            .expect("a pointer is opened")
    }

    #[tokio::test]
    async fn a_committed_pointer_is_proved_by_its_signed_record() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let leaves = responder.proved_leaves(nonce).await;
        let openings = openings(&leaves);
        let items = responder.round2(nonce, &openings).await;

        assert!(
            items
                .iter()
                .any(|item| matches!(item, SubtreeSliceItem::PointerRecord { .. })),
            "a pointer is proved by its record"
        );
        assert!(
            items
                .iter()
                .any(|item| matches!(item, SubtreeSliceItem::Present { .. })),
            "and the chunks beside it by their slices"
        );
        assert!(
            matches!(
                verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
                AuditVerdict::Pass { .. }
            ),
            "the auditor must pass an honest holder of both"
        );
    }

    /// A record an update replaces is kept for longer than the slowest audit
    /// can take: a round 1 over the largest subtree an auditor waits for,
    /// which may have read the pointer at its start, then the session its
    /// round 2 must arrive within.
    #[test]
    fn a_replaced_record_outlives_the_slowest_audit_by_default() {
        let largest =
            usize::try_from(max_subtree_leaves(MAX_COMMITMENT_KEY_COUNT)).expect("fits a usize");
        let slowest =
            ReplicationConfig::default().audit_response_timeout(largest) + SUBTREE_SESSION_TTL;
        assert!(
            SUPERSEDED_RETENTION > slowest,
            "{SUPERSEDED_RETENTION:?} must outlive {slowest:?}"
        );
    }

    /// The earlier entry point knows nothing of round 1's roots, and answers
    /// as it did before them: an unchanged pointer is served, and passes,
    /// rather than reported as a transient failure.
    #[tokio::test]
    async fn the_earlier_entry_point_still_serves_an_unchanged_pointer() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let openings = openings(&responder.proved_leaves(nonce).await);
        let items = legacy_round2(&responder, nonce, &openings).await;
        assert!(items
            .iter()
            .any(|item| matches!(item, SubtreeSliceItem::PointerRecord { .. })));
        assert!(matches!(
            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
            AuditVerdict::Pass { .. }
        ));
    }

    /// After one update between the rounds, the earlier entry point serves
    /// the record held and the one it replaced, newest first, and passes.
    #[tokio::test]
    async fn the_earlier_entry_point_still_serves_across_one_update() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let openings = openings(&responder.proved_leaves(nonce).await);
        let updated = first_pointer(&openings);
        let owner = (0..24u8)
            .find(|owner| pointer(*owner, 1).address() == updated)
            .expect("the opened pointer is one of ours");
        let replaced = responder
            .pointers
            .record_bytes(&updated)
            .await
            .expect("read")
            .expect("held");
        let newer = pointer(owner, 2).to_bytes();
        responder.pointers.put_bytes(&newer).await.expect("update");

        let items = legacy_round2(&responder, nonce, &openings).await;
        let served = items.iter().find_map(|item| match item {
            SubtreeSliceItem::PointerRecord { key, records } if *key == updated => {
                Some(records.clone())
            }
            _ => None,
        });
        assert_eq!(
            served,
            Some(vec![newer, replaced]),
            "the record held, then the one it replaced"
        );
        assert!(matches!(
            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
            AuditVerdict::Pass { .. }
        ));
    }

    /// Through the earlier entry point too, a pointer updated and then lost
    /// is absent, not proved by the record the update replaced.
    #[tokio::test]
    async fn the_earlier_entry_point_reports_a_lost_pointer_absent() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let openings = openings(&responder.proved_leaves(nonce).await);
        let lost = first_pointer(&openings);
        let owner = (0..24u8)
            .find(|owner| pointer(*owner, 1).address() == lost)
            .expect("the opened pointer is one of ours");
        responder
            .pointers
            .put_bytes(&pointer(owner, 2).to_bytes())
            .await
            .expect("update");
        assert!(responder.pointers.delete(&lost).await.expect("delete"));

        let items = legacy_round2(&responder, nonce, &openings).await;
        assert!(items
            .iter()
            .any(|item| matches!(item, SubtreeSliceItem::Absent { key } if *key == lost)));
        assert_eq!(
            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
            AuditVerdict::Fail(AuditFailureReason::KeyAbsent)
        );
    }

    /// Round 2 through the earlier entry point, which takes no bindings.
    async fn legacy_round2(
        responder: &Responder,
        nonce: [u8; 32],
        openings: &[(SubtreeLeaf, u32)],
    ) -> Vec<SubtreeSliceItem> {
        let challenge = SubtreeSliceChallenge {
            challenge_id: CHALLENGE_ID,
            nonce,
            challenged_peer_id: responder.peer_bytes,
            expected_commitment_hash: responder.committed().hash(),
            openings: openings
                .iter()
                .map(|(leaf, block_index)| SubtreeSliceOpening {
                    key: leaf.key,
                    block_index: *block_index,
                })
                .collect(),
        };
        let response = handle_subtree_slice_challenge_with_pointers(
            &challenge,
            &responder.storage,
            Some(&responder.pointers),
            &responder.peer,
            false,
            Some(&responder.state),
        )
        .await;
        let SubtreeSliceResponse::Items { items, .. } = response else {
            panic!("expected items, got {response:?}");
        };
        items
    }

    /// Round 1 binds each pointer it proves, and nothing else.
    #[tokio::test]
    async fn round_one_binds_exactly_the_pointers_it_proves() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let response = responder.round1(nonce).await;
        let SubtreeAuditResponse::Proof { proof, .. } = &response else {
            panic!("expected a proof, got {response:?}");
        };
        let expected: PointerBindings = proof
            .leaves
            .iter()
            .filter(|leaf| responder.committed().tree().commits_pointer(&leaf.key))
            .map(|leaf| (leaf.key, leaf.nonced_root))
            .collect();
        assert!(!expected.is_empty(), "the subtree holds a pointer");
        assert_eq!(pointer_bindings(&response), expected);
        assert!(
            pointer_bindings(&SubtreeAuditResponse::Bootstrapping {
                challenge_id: CHALLENGE_ID
            })
            .is_empty(),
            "only a proof binds anything"
        );
    }

    /// Without the root round 1 reported, which a session this node opened
    /// never lacks but a direct caller can, a pointer still held is reported
    /// as a transient failure, updated or not: the node cannot show which
    /// record round 1 read, and guessing would risk a confirmed failure it did
    /// not earn.
    #[tokio::test]
    async fn without_the_bound_root_a_pointer_is_unavailable_not_failed() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let openings = openings(&responder.proved_leaves(nonce).await);
        let unavailable = |response: SubtreeSliceResponse| {
            matches!(
                response,
                SubtreeSliceResponse::Rejected {
                    kind: RejectKind::Transient,
                    ..
                }
            )
        };

        assert!(unavailable(
            responder
                .round2_response(nonce, &openings, &PointerBindings::new())
                .await
        ));

        let updated = first_pointer(&openings);
        let owner = (0..24u8)
            .find(|owner| pointer(*owner, 1).address() == updated)
            .expect("the opened pointer is one of ours");
        responder
            .pointers
            .put_bytes(&pointer(owner, 2).to_bytes())
            .await
            .expect("update");
        assert!(unavailable(
            responder
                .round2_response(nonce, &openings, &PointerBindings::new())
                .await
        ));
    }

    /// A root round 1 reported that nothing held now reproduces, as when the
    /// record it read has been evicted to keep memory bounded, is reported as
    /// a transient failure while the pointer is still held, and as absent
    /// once nothing at all is.
    #[tokio::test]
    async fn a_bound_record_no_longer_held_is_unavailable_not_failed() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let openings = openings(&responder.proved_leaves(nonce).await);
        let target = first_pointer(&openings);
        let evicted: PointerBindings = openings
            .iter()
            .map(|(leaf, _)| leaf)
            .filter(|leaf| is_pointer_leaf(leaf))
            .map(|leaf| (leaf.key, [0xEE; 32]))
            .collect();

        assert!(matches!(
            responder.round2_response(nonce, &openings, &evicted).await,
            SubtreeSliceResponse::Rejected {
                kind: RejectKind::Transient,
                ..
            }
        ));

        for (leaf, _) in openings.iter().filter(|(leaf, _)| is_pointer_leaf(leaf)) {
            responder.pointers.delete(&leaf.key).await.expect("delete");
        }
        let items = responder.round2_bound(nonce, &openings, &evicted).await;
        assert!(items
            .iter()
            .any(|item| matches!(item, SubtreeSliceItem::Absent { key } if *key == target)));
        assert_eq!(
            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
            AuditVerdict::Fail(AuditFailureReason::KeyAbsent),
            "a pointer lost outright is still a confirmed failure"
        );
    }

    /// The commitment binds which pointers are held, not their state, so an
    /// owner updating a pointer mid-audit cannot fail the node holding it.
    #[tokio::test]
    async fn an_update_between_the_rounds_does_not_fail_an_honest_holder() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let openings = openings(&responder.proved_leaves(nonce).await);
        let updated = first_pointer(&openings);

        let owner = (0..24u8)
            .find(|owner| pointer(*owner, 1).address() == updated)
            .expect("the opened pointer is one of ours");
        responder
            .pointers
            .put_bytes(&pointer(owner, 2).to_bytes())
            .await
            .expect("update");

        let items = responder.round2(nonce, &openings).await;
        assert!(matches!(
            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
            AuditVerdict::Pass { .. }
        ));
    }

    /// However many paid updates land between the rounds, the record round 1
    /// bound is the one round 2 serves: the owner's activity is not the
    /// holder's failure.
    #[tokio::test]
    async fn several_updates_between_the_rounds_do_not_fail_an_honest_holder() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let openings = openings(&responder.proved_leaves(nonce).await);
        let updated = first_pointer(&openings);

        let owner = (0..24u8)
            .find(|owner| pointer(*owner, 1).address() == updated)
            .expect("the opened pointer is one of ours");
        for counter in 2..=4 {
            responder
                .pointers
                .put_bytes(&pointer(owner, counter).to_bytes())
                .await
                .expect("update");
        }

        let items = responder.round2(nonce, &openings).await;
        assert!(
            matches!(
                verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
                AuditVerdict::Pass { .. }
            ),
            "three updates between the rounds must not fail the holder, got {:?}",
            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items)
        );
        let served = items.iter().find_map(|item| match item {
            SubtreeSliceItem::PointerRecord { key, records } if *key == updated => Some(records),
            _ => None,
        });
        assert_eq!(
            served,
            Some(&vec![pointer_record_bound_in_round_one(&responder, owner)]),
            "exactly the record round 1 read, and nothing else"
        );
    }

    /// The record a responder held for `owner`'s pointer before any update:
    /// counter 1, as [`Responder::new`] stored it.
    fn pointer_record_bound_in_round_one(responder: &Responder, owner: u8) -> Vec<u8> {
        let address = pointer(owner, 1).address();
        responder
            .pointers
            .superseded_all(&address)
            .last()
            .map(|record| record.to_vec())
            .expect("the first record is kept")
    }

    #[tokio::test]
    async fn a_node_that_lost_a_committed_pointer_fails_round_one() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let plan = subtree_plan(responder.committed().tree(), &nonce).expect("plan");
        let lost = plan
            .leaf_keys
            .iter()
            .zip(&plan.leaf_is_pointer)
            .find_map(|(key, is_pointer)| is_pointer.then_some(*key))
            .expect("a pointer in the subtree");
        assert!(responder.pointers.delete(&lost).await.expect("delete"));

        match responder.round1(nonce).await {
            SubtreeAuditResponse::Rejected { kind, .. } => {
                assert_eq!(
                    grade_reject(kind),
                    RejectGrade::Confirmed,
                    "a lost pointer is a confirmed failure, as a lost chunk is"
                );
            }
            other => panic!("expected a rejection, got {other:?}"),
        }
    }

    /// A node that lost the pointer is absent, even while it still keeps in
    /// memory the record an update replaced, and even when that is the very
    /// record round 1 read: the replaced records prove what round 1 read, not
    /// that the node still holds the pointer.
    #[tokio::test]
    async fn a_lost_pointer_is_absent_whatever_replaced_records_remain() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let openings = openings(&responder.proved_leaves(nonce).await);
        let lost = first_pointer(&openings);
        let owner = (0..24u8)
            .find(|owner| pointer(*owner, 1).address() == lost)
            .expect("the opened pointer is one of ours");
        responder
            .pointers
            .put_bytes(&pointer(owner, 2).to_bytes())
            .await
            .expect("update");
        assert!(responder.pointers.delete(&lost).await.expect("delete"));
        assert!(
            !responder.pointers.superseded_all(&lost).is_empty(),
            "the record round 1 read is still kept in memory"
        );

        let items = responder.round2(nonce, &openings).await;
        assert!(items
            .iter()
            .any(|item| matches!(item, SubtreeSliceItem::Absent { key } if *key == lost)));
        assert_eq!(
            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
            AuditVerdict::Fail(AuditFailureReason::KeyAbsent)
        );
    }

    #[tokio::test]
    async fn a_pointer_lost_after_round_one_is_admitted_absent() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let openings = openings(&responder.proved_leaves(nonce).await);
        assert!(responder
            .pointers
            .delete(&first_pointer(&openings))
            .await
            .expect("delete"));

        let items = responder.round2(nonce, &openings).await;
        assert_eq!(
            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
            AuditVerdict::Fail(AuditFailureReason::KeyAbsent)
        );
    }

    /// A node cannot prove it holds one pointer with another, genuinely signed
    /// record: the record must belong at the committed address.
    #[tokio::test]
    async fn another_pointer_is_not_proof_of_the_one_committed() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let openings = openings(&responder.proved_leaves(nonce).await);
        let target = first_pointer(&openings);

        let mut items = responder.round2(nonce, &openings).await;
        replace_records(&mut items, &target, &[pointer(200, 1).to_bytes()]);
        assert_eq!(
            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
            AuditVerdict::Fail(AuditFailureReason::DigestMismatch)
        );
    }

    /// A committed chunk whose file has rotted fails round 1 exactly as before,
    /// but the responder reports it, and the chunk store's recheck worker then
    /// stops the node claiming it, so its next commitment leaves the chunk out
    /// and replication can repair it rather than the node failing every audit
    /// that lands on that key.
    #[tokio::test]
    async fn round_one_takes_a_rotted_committed_chunk_out_of_service() {
        let responder = Responder::new(24, 0).await;
        let committed = responder.committed();
        let nonce = [7u8; 32];
        let plan = subtree_plan(committed.tree(), &nonce).expect("plan");
        let victim = plan.leaf_keys.first().copied().expect("a selected chunk");
        let path = responder.chunk_file(&victim);
        std::fs::write(&path, b"rotted").expect("corrupt the file");

        let work = responder.round1_work(nonce).await;
        assert_eq!(
            work.corrupt_keys,
            vec![victim],
            "the responder reports exactly the rotted chunk"
        );
        match work.response {
            SubtreeAuditResponse::Proof {
                commitment, proof, ..
            } => assert_eq!(
                evaluate_subtree_structure(
                    &commitment,
                    &proof,
                    &nonce,
                    &committed.hash(),
                    &responder.peer_bytes,
                ),
                Err(AuditFailureReason::DigestMismatch),
                "the auditor's verdict on the rotted chunk is unchanged"
            ),
            other => panic!("expected a proof, got {other:?}"),
        }

        // What the replication engine does with the report: queue it for the chunk
        // store's recheck worker. The worker finishes the recheck it is on before it
        // stops, so once it returns the chunk has been dealt with.
        responder.storage.report_corrupt(&work.corrupt_keys);
        let stop = CancellationToken::new();
        let removed = async {
            let deadline = Instant::now() + Duration::from_secs(30);
            while path.exists() && Instant::now() < deadline {
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
            stop.cancel();
        };
        tokio::join!(responder.storage.run_corrupt_rechecks(&stop), removed);
        let keys = responder.storage.all_keys().await.expect("keys");
        assert!(
            !keys.contains(&victim),
            "the rotted chunk leaves the view the next commitment is built from"
        );
        assert!(!path.exists(), "the rotted file is removed");
        assert_eq!(keys.len(), 23, "every intact chunk stays in service");
    }

    /// An honest round 1 over intact chunks takes nothing out of service.
    #[tokio::test]
    async fn round_one_over_intact_chunks_keeps_every_chunk() {
        let responder = Responder::new(24, 0).await;
        for seed in 0..8u8 {
            let corrupt = responder.round1_work([seed; 32]).await.corrupt_keys;
            assert!(
                corrupt.is_empty(),
                "an intact chunk was reported rotted: {corrupt:?}"
            );
            let leaves = responder.proved_leaves([seed; 32]).await;
            assert!(!leaves.is_empty(), "expected round 1 to prove some leaves");
        }
        assert_eq!(responder.storage.all_keys().await.expect("keys").len(), 24);
    }

    fn replace_records(items: &mut [SubtreeSliceItem], target: &XorName, with: &[Vec<u8>]) {
        for item in items {
            if let SubtreeSliceItem::PointerRecord { key, records } = item {
                if key == target {
                    *records = with.to_vec();
                }
            }
        }
    }

    /// A node that holds no pointers cannot pass by fetching the few sampled
    /// records once round 2 names them: round 1 had to bind each record's
    /// bytes under the nonce before anything was sampled, and it had none.
    #[tokio::test]
    async fn a_relay_that_fetches_records_only_in_round_two_fails() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let genuine = responder.proved_leaves(nonce).await;
        let held = openings(&genuine);
        // What a relay can say in round 1 without the bytes.
        let mut leaves = genuine;
        for leaf in leaves.iter_mut().filter(|leaf| is_pointer_leaf(leaf)) {
            leaf.nonced_root = [0u8; 32];
        }
        let openings = openings(&leaves);
        // And in round 2 it serves the genuine records, fetched on demand.
        let items = responder.round2(nonce, &held).await;
        assert_eq!(
            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
            AuditVerdict::Fail(AuditFailureReason::DigestMismatch)
        );
    }

    /// Nor can it pass with another replica's copy of the very state it
    /// committed: every signature is randomised, so each replica's bytes, and
    /// the nonced root over them, are its own.
    #[tokio::test]
    async fn another_replicas_copy_of_the_same_state_is_not_proof() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let openings = openings(&responder.proved_leaves(nonce).await);
        let target = first_pointer(&openings);
        let owner = (0..24u8)
            .find(|owner| pointer(*owner, 1).address() == target)
            .expect("the opened pointer is one of ours");
        let replica = pointer(owner, 1);
        assert_eq!(
            replica.state_id(),
            responder.pointers.state(&target).expect("held").state_id,
            "the same state"
        );

        let mut items = responder.round2(nonce, &openings).await;
        replace_records(&mut items, &target, &[replica.to_bytes()]);
        assert_eq!(
            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
            AuditVerdict::Fail(AuditFailureReason::DigestMismatch)
        );
    }

    /// A pointer item may carry at most two records. This build serves one;
    /// two is what a responder that kept no round-1 roots served (ADR-0016).
    #[tokio::test]
    async fn a_pointer_item_with_more_than_two_records_is_malformed() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let openings = openings(&responder.proved_leaves(nonce).await);
        let target = first_pointer(&openings);
        let mut items = responder.round2(nonce, &openings).await;
        let held = responder
            .pointers
            .record_bytes(&target)
            .await
            .expect("read")
            .expect("held");
        replace_records(&mut items, &target, &[held.clone(), held.clone(), held]);
        assert_eq!(
            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
            AuditVerdict::Fail(AuditFailureReason::MalformedResponse)
        );
    }

    /// The pointer leaf shape is accepted only at a pointer's exact size, so it
    /// cannot stand in for a chunk of another length.
    #[tokio::test]
    async fn a_pointer_leaf_of_any_other_length_is_refused() {
        let responder = Responder::new(24, 24).await;
        let nonce = mixed_nonce(responder.committed().tree());
        let committed = responder.committed();
        let SubtreeAuditResponse::Proof {
            commitment,
            mut proof,
            ..
        } = responder.round1(nonce).await
        else {
            panic!("expected a proof");
        };
        let leaf = proof
            .leaves
            .iter_mut()
            .find(|leaf| is_pointer_leaf(leaf))
            .expect("a pointer leaf");
        leaf.content_len = leaf.content_len.saturating_add(1);

        assert_eq!(
            evaluate_subtree_structure(
                &commitment,
                &proof,
                &nonce,
                &committed.hash(),
                &responder.peer_bytes,
            ),
            Err(AuditFailureReason::DigestMismatch)
        );
    }
}