ant-node 0.22.0

Pure quantum-proof network node for the Autonomi decentralized network
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
//! ANT protocol handler for autonomi protocol messages.
//!
//! This handler processes chunk PUT/GET requests with optional payment verification,
//! storing chunks to LMDB and using the DHT for network-wide retrieval.
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────┐
//! │                    AntProtocol                        │
//! ├─────────────────────────────────────────────────────────┤
//! │  protocol_id() = "autonomi.ant.chunk.v1"                  │
//! │                                                         │
//! │  try_handle_request(data) ──▶ decode ChunkMessage  │
//! │                                   │                     │
//! │         ┌─────────────────────────┼─────────────────┐  │
//! │         ▼                         ▼                 ▼  │
//! │   ChunkQuoteRequest           ChunkPutRequest    ChunkGetRequest
//! │         │                         │                 │  │
//! │         ▼                         ▼                 ▼  │
//! │   QuoteGenerator          PaymentVerifier    ChunkStore│
//! │         │                         │                 │  │
//! │         └─────────────────────────┴─────────────────┘  │
//! │                           │                             │
//! │           return Ok(Some(response_bytes))              │
//! │           return Ok(None) for response messages       │
//! └─────────────────────────────────────────────────────────┘
//! ```

use crate::ant_protocol::DATA_TYPE_CHUNK;
use crate::ant_protocol::{
    settlement_compatibility, ChunkGetRequest, ChunkGetResponse, ChunkMessage, ChunkMessageBody,
    ChunkPutRequest, ChunkPutResponse, ChunkQuoteRequest, ChunkQuoteRequestV2, ChunkQuoteResponse,
    MerkleCandidateQuoteRequest, MerkleCandidateQuoteRequestV2, MerkleCandidateQuoteResponse,
    ProtocolError, SettlementCompatibility, XorName, CHUNK_PROTOCOL_ID, CURRENT_SETTLEMENT_VERSION,
    MAX_CHUNK_SIZE, MIN_SUPPORTED_SETTLEMENT_VERSION,
};
use crate::client::compute_address;
use crate::error::{Error, Result};
use crate::logging::{debug, info, warn};
use crate::payment::{PaymentVerifier, QuoteGenerator, VerificationContext};
use crate::pointer::PointerService;
use crate::replication::admission;
use crate::replication::config::K_BUCKET_SIZE;
use crate::replication::fresh::FreshWriteEvent;
use crate::storage::traffic::{self, ChunkRequestKind, ChunkResponseKey};
use crate::storage::ChunkStore;
use ant_protocol::chunk::{PointerGetResponse, PointerPutResponse};
use bytes::Bytes;
use parking_lot::RwLock;
use saorsa_core::P2PNode;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::mpsc;

/// Width of the self-closeness gate on client PUTs (ADR-0003): a node accepts
/// a PUT only when it is within its own local `SELF_CLOSENESS_GATE_WIDTH`
/// closest peers to the address.
///
/// Set to the client's PUT fallback ceiling (`K_BUCKET_SIZE`), wider than the
/// storage-admission width, so a client routing past full close-group members
/// onto further peers (ADR-0002) is still accepted here, while a genuinely far
/// node — which could only mis-attribute fresh-replication failures — is
/// turned away.
pub const SELF_CLOSENESS_GATE_WIDTH: usize = K_BUCKET_SIZE;

fn duration_ms(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

/// Receipt context supplied by the authenticated P2P event router.
///
/// This is deliberately process-local metadata: it is never encoded or sent on
/// the wire. The receipt instant spans semaphore queueing, storage, response
/// encoding, and the response hand-off to the transport.
pub struct ChunkRequestContext {
    source_peer: String,
    received_at: Instant,
    queue_wait_ms: u64,
}

impl ChunkRequestContext {
    #[must_use]
    pub(crate) fn new(source_peer: String, received_at: Instant, queue_wait: Duration) -> Self {
        Self {
            source_peer,
            received_at,
            queue_wait_ms: duration_ms(queue_wait),
        }
    }
}

/// A decoded protocol request and, for GETs, its pending one-shot telemetry.
///
/// Keeping the handler result and telemetry together lets the router record the
/// event only after response hand-off, while preserving the existing handler
/// error and response behaviour.
pub struct HandledChunkRequest {
    pub(crate) response: Result<Option<Bytes>>,
    pub(crate) get_telemetry: Option<GetRequestTelemetry>,
    /// Kind × outcome of the encoded response, so the router can attribute
    /// the bytes once the send is confirmed (V2-834).
    pub(crate) traffic_key: Option<ChunkResponseKey>,
}

/// Bounded stage timings for one decoded chunk GET.
///
/// `finish_send` emits the sole `get_rpc` event. If the routing task is cancelled
/// after handling but before response hand-off completes, `Drop` emits the same
/// event with `cancelled` outcomes so the request does not disappear silently.
#[cfg_attr(not(feature = "logging"), allow(dead_code))]
pub struct GetRequestTelemetry {
    source_peer: String,
    request_id: u64,
    chunk_address: String,
    received_at: Instant,
    queue_wait_ms: u64,
    storage_read_ms: u64,
    storage_outcome: &'static str,
    storage_error_category: &'static str,
    response_encode_ms: u64,
    finished: bool,
}

impl GetRequestTelemetry {
    fn from_response(
        context: ChunkRequestContext,
        request_id: u64,
        chunk_address: String,
        storage_read_ms: u64,
        response: &ChunkGetResponse,
    ) -> Self {
        let (storage_outcome, storage_error_category) = match response {
            ChunkGetResponse::Success { .. } => ("success", "none"),
            ChunkGetResponse::NotFound { .. } => ("not_found", "none"),
            ChunkGetResponse::Error(ProtocolError::StorageFailed(_)) => ("error", "storage"),
            ChunkGetResponse::Error(_) => ("error", "protocol"),
            _ => ("unknown", "unknown"),
        };
        Self {
            source_peer: context.source_peer,
            request_id,
            chunk_address,
            received_at: context.received_at,
            queue_wait_ms: context.queue_wait_ms,
            storage_read_ms,
            storage_outcome,
            storage_error_category,
            response_encode_ms: 0,
            finished: false,
        }
    }

    fn set_response_encode_ms(&mut self, elapsed: Duration) {
        self.response_encode_ms = duration_ms(elapsed);
    }

    /// Record the single completed GET event after response hand-off.
    pub(crate) fn finish_send(mut self, response_send: Duration, send_succeeded: bool) {
        let (send_outcome, overall_outcome) = if send_succeeded {
            let overall = match self.storage_outcome {
                "success" => "success",
                "not_found" => "not_found",
                "error" => "storage_error",
                _ => "unknown",
            };
            ("success", overall)
        } else {
            ("error", "send_error")
        };
        self.emit(response_send, send_outcome, overall_outcome);
        self.finished = true;
    }

    /// Record a GET which could not reach the response hand-off stage.
    pub(crate) fn finish_without_send(mut self, overall_outcome: &'static str) {
        self.emit(Duration::ZERO, "not_attempted", overall_outcome);
        self.finished = true;
    }

    fn emit(
        &self,
        response_send: Duration,
        send_outcome: &'static str,
        overall_outcome: &'static str,
    ) {
        let response_send_ms = duration_ms(response_send);
        let duration_ms = duration_ms(self.received_at.elapsed());
        info!(
            target: "ant_node::storage::rpc_latency",
            source_peer = %self.source_peer,
            request_id = self.request_id,
            chunk_address = %self.chunk_address,
            addr = %self.chunk_address,
            queue_wait_ms = self.queue_wait_ms,
            storage_read_ms = self.storage_read_ms,
            storage_outcome = self.storage_outcome,
            storage_error_category = self.storage_error_category,
            response_encode_ms = self.response_encode_ms,
            response_send_ms,
            send_outcome,
            duration_ms,
            outcome = overall_outcome,
            "get_rpc"
        );
    }
}

impl Drop for GetRequestTelemetry {
    fn drop(&mut self) {
        if !self.finished {
            self.emit(Duration::ZERO, "cancelled", "cancelled");
            self.finished = true;
        }
    }
}

/// One latency event per pointer PUT, on the target the chunk `put_rpc` uses,
/// so the same store-latency dashboards cover both kinds.
fn log_pointer_put_rpc(elapsed: Duration, record_size: usize, response: &PointerPutResponse) {
    let duration_ms = duration_ms(elapsed);
    let (outcome, address): (&'static str, Option<&XorName>) = match response {
        PointerPutResponse::Success { address, .. } => ("success", Some(address)),
        PointerPutResponse::Unchanged { address, .. } => ("unchanged", Some(address)),
        PointerPutResponse::Stale { address, .. } => ("stale", Some(address)),
        PointerPutResponse::PaymentRequired { .. } => ("payment_required", None),
        PointerPutResponse::Error(_) => ("error", None),
    };
    let addr = address.map(hex::encode).unwrap_or_default();
    info!(
        target: "ant_node::storage::rpc_latency",
        duration_ms,
        record_size,
        outcome,
        addr = %addr,
        "pointer_put_rpc"
    );
}

/// One latency event per pointer GET, beside the chunk `get_rpc`.
fn log_pointer_get_rpc(elapsed: Duration, address: &XorName, response: &PointerGetResponse) {
    let duration_ms = duration_ms(elapsed);
    let outcome: &'static str = match response {
        PointerGetResponse::Success { .. } => "success",
        PointerGetResponse::NotFound { .. } => "not_found",
        PointerGetResponse::Error(_) => "error",
    };
    let addr = hex::encode(address);
    info!(
        target: "ant_node::storage::rpc_latency",
        duration_ms,
        outcome,
        addr = %addr,
        "pointer_get_rpc"
    );
}

/// How many unversioned quote requests to receive between adoption log lines.
///
/// One line per request would drown the log at production quote rates, and one
/// line total would say nothing about the trend. A running count emitted every
/// `N` gives the shape of client adoption, which is the number that decides
/// when unversioned requests can start being refused outright.
const UNVERSIONED_QUOTE_LOG_INTERVAL: u64 = 1_000;

/// Unversioned quote requests received since start, by path.
///
/// Counted on arrival, before the quote is generated, because the question
/// this answers is how many clients still cannot declare a version. A request
/// this node then refuses for an unrelated reason still came from such a
/// client, and would still break if the unversioned path were retired.
///
/// Indices are `[single_node, merkle]`. A plain counter rather than a metric
/// because the only consumer is the rollout decision, and that reads logs.
static UNVERSIONED_QUOTE_REQUESTS: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)];

/// Refuse a quote when the requesting client settles under rules this node no
/// longer accepts. `None` means the request may proceed.
///
/// This is the whole point of the settlement version. A merkle batch pays
/// on-chain **before** any storer sees a PUT, so refusing the *payment* is
/// refusing something already spent and unrefundable. Refusing the *quote*
/// costs the client nothing: no quote means no pool commitment, which means no
/// payment.
///
/// A version NEWER than this node understands is refused too, as
/// `StorerUpdateRequired`. Quoting it would promise to accept a payment whose
/// rules this build does not know, and that promise can only be broken at PUT
/// time, once the client has settled on-chain. The client is told to use a
/// different storer rather than to upgrade, because it is this node that is
/// behind.
fn settlement_gate(client_settlement_version: u32, path: &str) -> Option<ProtocolError> {
    match settlement_compatibility(client_settlement_version) {
        SettlementCompatibility::Compatible => None,
        SettlementCompatibility::ClientTooOld => {
            warn!(
                target: "ant_node::quote::settlement",
                "Refusing {path} quote: client settlement version {client_settlement_version} \
                 is below the minimum {MIN_SUPPORTED_SETTLEMENT_VERSION}. No quote issued, \
                 so the client has not been charged.",
            );
            Some(ProtocolError::ClientUpdateRequired {
                client_settlement_version,
                min_settlement_version: MIN_SUPPORTED_SETTLEMENT_VERSION,
            })
        }
        // This node is the old one. Quoting would promise to accept a payment
        // whose rules it does not know, and a promise broken at PUT time is
        // broken after the client has settled on-chain. Refusing sends the
        // client to a peer that can actually honour the quote, at no cost.
        SettlementCompatibility::NodeTooOld => {
            warn!(
                target: "ant_node::quote::settlement",
                "Refusing {path} quote: client settles under version \
                 {client_settlement_version}, newer than this node's \
                 {CURRENT_SETTLEMENT_VERSION}. This node needs upgrading; the client \
                 has not been charged.",
            );
            Some(ProtocolError::StorerUpdateRequired {
                client_settlement_version,
                node_settlement_version: CURRENT_SETTLEMENT_VERSION,
            })
        }
    }
}

/// ANT protocol handler.
///
/// Handles chunk PUT/GET/Quote requests using LMDB storage for persistence
/// and optional payment verification.
pub struct AntProtocol {
    /// LMDB storage for chunk persistence.
    storage: Arc<ChunkStore>,
    /// Payment verifier for checking payments.
    payment_verifier: Arc<PaymentVerifier>,
    /// Quote generator for creating storage quotes.
    /// Also handles merkle candidate quote signing via ML-DSA-65.
    quote_generator: Arc<QuoteGenerator>,
    /// Channel for notifying the replication engine about newly-stored chunks.
    fresh_write_tx: Option<mpsc::UnboundedSender<FreshWriteEvent>>,
    /// The node's P2P handle, attached post-construction via
    /// `attach_p2p_node`. Drives the self-closeness gate on client PUTs;
    /// `None` in unit tests that never attach a node.
    p2p_node: RwLock<Option<Arc<P2PNode>>>,
    /// Serves pointer requests, when the node has a pointer store.
    ///
    /// `None` on a node built without one, so a peer that sends a pointer
    /// message to a node that does not keep pointers gets a clean refusal
    /// rather than a silent drop.
    pointers: Option<PointerService>,
}

impl AntProtocol {
    /// Create a new ANT protocol handler.
    ///
    /// # Arguments
    ///
    /// * `storage` - LMDB storage for chunk persistence
    /// * `payment_verifier` - Payment verifier for validating payments
    /// * `quote_generator` - Quote generator for creating storage quotes
    #[must_use]
    pub fn new(
        storage: Arc<ChunkStore>,
        payment_verifier: Arc<PaymentVerifier>,
        quote_generator: Arc<QuoteGenerator>,
    ) -> Self {
        // Wire the PaymentVerifier to the same authoritative store used by this
        // protocol handler. Historically the verifier read `current_chunks()`
        // for the paid-quote price floor; ADR-0004 retired that gate (price is
        // bound to the live storage commitment, not the local record count), so
        // the store is no longer consulted for pricing. The attachment is kept
        // so any future store-backed verifier check reads the same record count
        // this handler serves, for every AntProtocol construction path.
        //
        // ADR-0004: the QuoteGenerator no longer prices off `current_chunks()`
        // — its price is bound to the live storage commitment (see
        // `attach_commitment_source`, wired by the node once the replication
        // engine exists), or baseline when none — so it is NOT attached to the
        // store here.
        payment_verifier.attach_storage(Arc::clone(&storage));

        Self {
            storage,
            payment_verifier,
            quote_generator,
            fresh_write_tx: None,
            p2p_node: RwLock::new(None),
            pointers: None,
        }
    }

    /// Serve pointer requests from `pointers`.
    ///
    /// Opt-in rather than built in: a node with no pointer store refuses
    /// pointer messages cleanly instead of pretending to hold them.
    #[must_use]
    pub fn with_pointer_service(mut self, pointers: PointerService) -> Self {
        self.pointers = Some(pointers);
        self
    }

    /// The pointer service, if this node serves pointers.
    #[must_use]
    pub const fn pointer_service(&self) -> Option<&PointerService> {
        self.pointers.as_ref()
    }

    /// Attach the node's P2P handle for payment live-DHT checks.
    ///
    /// Wires the handle into the payment verifier so payment-proof closeness
    /// checks can use the live routing view. Idempotent: calling twice
    /// replaces the verifier handle.
    pub fn attach_p2p_node(&self, node: Arc<P2PNode>) {
        *self.p2p_node.write() = Some(Arc::clone(&node));
        if let Some(pointers) = &self.pointers {
            // Pointers take the same self-closeness gate as chunks, judged at
            // the pointer address because that is what the network routes on.
            pointers.attach_p2p_node(Arc::clone(&node));
        }
        self.payment_verifier.attach_p2p_node(node);
        debug!("AntProtocol: P2PNode attached for payment live-DHT checks and self-closeness gate");
    }

    /// Set the channel sender for fresh-write replication events.
    ///
    /// When set, successful chunk PUTs will notify the replication engine
    /// so it can fan out fresh offers to the close group.
    pub fn set_fresh_write_sender(&mut self, tx: mpsc::UnboundedSender<FreshWriteEvent>) {
        self.fresh_write_tx = Some(tx);
    }

    /// The fresh-write sender, if one was set. Lets tests drive the
    /// replication engine's fresh-write pipeline exactly as a PUT would.
    #[cfg(any(test, feature = "test-utils"))]
    pub fn fresh_write_sender(&self) -> Option<mpsc::UnboundedSender<FreshWriteEvent>> {
        self.fresh_write_tx.clone()
    }

    /// Get the protocol identifier.
    #[must_use]
    pub fn protocol_id(&self) -> &'static str {
        CHUNK_PROTOCOL_ID
    }

    /// Get a reference to the underlying LMDB storage.
    #[must_use]
    pub fn storage(&self) -> Arc<ChunkStore> {
        Arc::clone(&self.storage)
    }

    /// Test-only: the record count the quote generator currently prices on.
    /// Used to assert that quote-time resync tracks records actually held.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn priced_records_stored(&self) -> usize {
        self.quote_generator.records_stored()
    }

    /// Get a shared reference to the payment verifier.
    #[must_use]
    pub fn payment_verifier_arc(&self) -> Arc<PaymentVerifier> {
        Arc::clone(&self.payment_verifier)
    }

    /// ADR-0004: attach the replication engine's commitment state as the quote
    /// generator's commitment source, so quotes force their price from the live
    /// storage commitment and refresh its answerability on issuance.
    ///
    /// Called once, after both the protocol and the replication engine exist
    /// (the engine owns the [`ResponderCommitmentState`](crate::replication::commitment_state::ResponderCommitmentState)).
    /// Until this is wired, the quote generator has no commitment source and
    /// falls back to baseline (no-pin) pricing.
    ///
    /// The same source is forwarded to the payment verifier's price-floor
    /// policy (read-only snapshot), so this node's quotes and its floor are
    /// priced from one commitment by construction.
    pub fn attach_commitment_source(
        &self,
        source: Arc<dyn crate::payment::quote::CommitmentSource>,
    ) {
        self.quote_generator
            .attach_commitment_source(Arc::clone(&source));
        self.payment_verifier.attach_local_commitment_source(source);
    }

    /// ADR-0004: return the proof with any commitment sidecars stripped, so a
    /// replicated/persisted receipt carries only the pin and count (stored
    /// proofs do not grow). Handles BOTH proof types — single-node and
    /// merkle-batch — since both now carry sidecars. An unknown-tagged or
    /// unparseable proof is returned unchanged. Best-effort: any
    /// deserialize/reserialize failure returns the original bytes rather than
    /// corrupting the proof.
    fn strip_commitment_sidecars(proof: Vec<u8>) -> Vec<u8> {
        use crate::payment::proof::{
            deserialize_merkle_proof, deserialize_single_node_proof, detect_proof_type,
            serialize_merkle_proof, serialize_single_node_proof, ProofType,
        };
        match detect_proof_type(&proof) {
            Some(ProofType::SingleNode) => match deserialize_single_node_proof(&proof) {
                Ok(mut parsed) if !parsed.commitment_sidecars.is_empty() => {
                    parsed.commitment_sidecars.clear();
                    serialize_single_node_proof(&parsed).unwrap_or(proof)
                }
                _ => proof, // already sidecar-free, or unparseable: leave as-is
            },
            Some(ProofType::Merkle) => match deserialize_merkle_proof(&proof) {
                Ok(mut parsed) if !parsed.commitment_sidecars.is_empty() => {
                    parsed.commitment_sidecars.clear();
                    serialize_merkle_proof(&parsed).unwrap_or(proof)
                }
                _ => proof,
            },
            _ => proof, // unknown tag: nothing to strip
        }
    }

    /// Handle an incoming request and produce a response.
    ///
    /// Decodes the raw message, processes it if it is a request variant,
    /// and returns the encoded response bytes.  Returns `Ok(None)` for
    /// response messages (which are meant for client subscribers, not for
    /// the protocol handler).
    ///
    /// # Errors
    ///
    /// Returns an error if message decoding, handling, or encoding fails.
    pub async fn try_handle_request(&self, data: &[u8]) -> Result<Option<Bytes>> {
        self.try_handle_request_with_context(data, None)
            .await
            .response
    }

    /// Handle a request while carrying authenticated receipt context through a
    /// GET response hand-off. The context is local-only observability metadata.
    pub(crate) async fn try_handle_request_with_context(
        &self,
        data: &[u8],
        context: Option<ChunkRequestContext>,
    ) -> HandledChunkRequest {
        let message = match ChunkMessage::decode(data) {
            Ok(message) => message,
            Err(e) => {
                traffic::record_rx(ChunkRequestKind::DecodeError, data.len());
                return HandledChunkRequest {
                    response: Err(Error::Protocol(format!("Failed to decode message: {e}"))),
                    get_telemetry: None,
                    traffic_key: None,
                };
            }
        };

        // V2-834: attribute inbound bytes by request kind at the decode
        // choke point. Only this entry point has the wire length; the browser
        // adapter below is handed an already-decoded message.
        traffic::record_rx(ChunkRequestKind::of(&message.body), data.len());

        let (response, mut get_telemetry, traffic_key) =
            self.handle_message_with_context(message, context).await;
        let encode_started = Instant::now();
        let encoded = response
            .map(|response| {
                response
                    .encode()
                    .map(Bytes::from)
                    .map_err(|e| Error::Protocol(format!("Failed to encode response: {e}")))
            })
            .transpose();
        if let Some(telemetry) = &mut get_telemetry {
            telemetry.set_response_encode_ms(encode_started.elapsed());
        }

        HandledChunkRequest {
            response: encoded,
            get_telemetry,
            traffic_key,
        }
    }

    /// Dispatch an already decoded request without copying its chunk buffer.
    /// The wire adapter and browser adapter share all storage and payment checks.
    #[cfg(any(feature = "webrtc-direct", test))]
    pub(crate) async fn try_handle_message(&self, message: ChunkMessage) -> Option<ChunkMessage> {
        self.handle_message_with_context(message, None).await.0
    }

    async fn handle_message_with_context(
        &self,
        message: ChunkMessage,
        context: Option<ChunkRequestContext>,
    ) -> (
        Option<ChunkMessage>,
        Option<GetRequestTelemetry>,
        Option<ChunkResponseKey>,
    ) {
        let request_id = message.request_id;
        let mut get_telemetry = None;

        // Each arm yields the response body and its V2-834 traffic key.
        let (response_body, traffic_key) = match message.body {
            ChunkMessageBody::PutRequest(req) => {
                let response = self.handle_put(req).await;
                let key = ChunkResponseKey::of_put(&response);
                (ChunkMessageBody::PutResponse(response), key)
            }
            ChunkMessageBody::GetRequest(req) => {
                let chunk_address = hex::encode(req.address);
                let storage_started = Instant::now();
                let response = self.handle_get_inner(req).await;
                let storage_read_ms = duration_ms(storage_started.elapsed());
                let key = ChunkResponseKey::of_get(&response);
                if let Some(context) = context {
                    get_telemetry = Some(GetRequestTelemetry::from_response(
                        context,
                        request_id,
                        chunk_address,
                        storage_read_ms,
                        &response,
                    ));
                }
                (ChunkMessageBody::GetResponse(response), key)
            }
            ChunkMessageBody::QuoteRequest(ref req) => {
                Self::note_unversioned_quote("single_node");
                (
                    ChunkMessageBody::QuoteResponse(self.handle_quote(req)),
                    ChunkResponseKey::Quote,
                )
            }
            ChunkMessageBody::MerkleCandidateQuoteRequest(ref req) => {
                Self::note_unversioned_quote("merkle");
                (
                    ChunkMessageBody::MerkleCandidateQuoteResponse(
                        self.handle_merkle_candidate_quote(req),
                    ),
                    ChunkResponseKey::MerkleQuote,
                )
            }
            ChunkMessageBody::QuoteRequestV2(ref req) => (
                ChunkMessageBody::QuoteResponse(self.handle_quote_v2(req)),
                ChunkResponseKey::QuoteV2,
            ),
            ChunkMessageBody::MerkleCandidateQuoteRequestV2(ref req) => (
                ChunkMessageBody::MerkleCandidateQuoteResponse(
                    self.handle_merkle_candidate_quote_v2(req),
                ),
                ChunkResponseKey::MerkleQuoteV2,
            ),
            ChunkMessageBody::PointerPutRequest(req) => {
                let started = Instant::now();
                let record_size = req.record.len();
                let response = match &self.pointers {
                    Some(service) => service.handle_put(req).await,
                    None => PointerPutResponse::Error(ProtocolError::StorageFailed(
                        "this node does not store pointers".to_string(),
                    )),
                };
                log_pointer_put_rpc(started.elapsed(), record_size, &response);
                let key = ChunkResponseKey::of_pointer_put(&response);
                (ChunkMessageBody::PointerPutResponse(response), key)
            }
            ChunkMessageBody::PointerGetRequest(req) => {
                let started = Instant::now();
                let address = req.address;
                let response = match &self.pointers {
                    Some(service) => service.handle_get(req).await,
                    None => PointerGetResponse::NotFound { address },
                };
                log_pointer_get_rpc(started.elapsed(), &address, &response);
                let key = ChunkResponseKey::of_pointer_get(&response);
                (ChunkMessageBody::PointerGetResponse(response), key)
            }
            // Anything else — response messages are handled by client
            // subscribers (e.g. send_and_await_chunk_response), not by the
            // protocol handler. Returning None prevents the caller from
            // sending a reply, which would create an infinite ping-pong
            // loop.
            //
            // `ChunkMessageBody` is `#[non_exhaustive]` in ant-protocol, so
            // a future wire variant added on a protocol minor bump also
            // lands here and is dropped. The CHUNK_PROTOCOL_ID multistream-
            // select handshake version-gates peers, so this arm should
            // only be reached by a misconfigured peer.
            _ => {
                return (None, None, None);
            }
        };

        (
            Some(ChunkMessage {
                request_id,
                body: response_body,
            }),
            get_telemetry,
            Some(traffic_key),
        )
    }

    /// Handle a PUT request.
    ///
    /// Wraps `handle_put_inner` to emit a single structured tracing event per
    /// PUT RPC at every exit path, including early-return validation paths.
    /// The event uses `target: "ant_node::storage::rpc_latency"` so that
    /// Elasticsearch / Kibana can build p50/p95/p99 store-RPC latency
    /// histograms from the existing telegraf log forwarding.
    async fn handle_put(&self, request: ChunkPutRequest) -> ChunkPutResponse {
        let start = std::time::Instant::now();
        let addr_hex = hex::encode(request.address);
        let chunk_size = request.content.len();
        let response = self.handle_put_inner(request).await;
        let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
        let outcome: &'static str = match &response {
            ChunkPutResponse::Success { .. } => "success",
            ChunkPutResponse::AlreadyExists { .. } => "already_exists",
            ChunkPutResponse::PaymentRequired { .. } => "payment_required",
            ChunkPutResponse::Error(_) => "error",
            _ => "unknown",
        };
        info!(
            target: "ant_node::storage::rpc_latency",
            duration_ms,
            chunk_size,
            outcome,
            addr = %addr_hex,
            "put_rpc"
        );
        response
    }

    /// Inner body of `handle_put` — see the wrapper for the per-RPC latency log.
    async fn handle_put_inner(&self, request: ChunkPutRequest) -> ChunkPutResponse {
        let address = request.address;
        let addr_hex = hex::encode(address);
        debug!("Handling PUT request for {addr_hex}");

        // 1. Validate chunk size
        if request.content.len() > MAX_CHUNK_SIZE {
            return ChunkPutResponse::Error(ProtocolError::ChunkTooLarge {
                size: request.content.len(),
                max_size: MAX_CHUNK_SIZE,
            });
        }

        // 2. Verify content address matches BLAKE3(content)
        let computed = compute_address(&request.content);
        if computed != address {
            return ChunkPutResponse::Error(ProtocolError::AddressMismatch {
                expected: address,
                actual: computed,
            });
        }

        // 2b. Refuse a chunk whose address a pointer already occupies.
        //
        // The mirror of the check the pointer path makes. Both kinds draw
        // addresses from the same 32-byte range, and a collision — however
        // infeasible — must not be resolved by whichever kind arrived second,
        // because that silently destroys the other's data.
        if let Some(pointers) = &self.pointers {
            if pointers.store().contains(&address) {
                warn!("Refusing chunk {addr_hex}: a pointer already occupies that address");
                return ChunkPutResponse::Error(ProtocolError::StorageFailed(format!(
                    "address {addr_hex} is already occupied by a pointer; refusing to \
                     store a chunk over it"
                )));
            }
        }

        // 3. Check if already exists (idempotent success)
        //
        // Verified against the offered bytes, not answered from the name. A name can
        // outlive the bytes under it, and acknowledging a good copy of a chunk this node
        // holds only a damaged version of throws that copy away and does not get offered
        // another. Reached only when this node already has the chunk, and the content
        // address was checked in step 2, so a damaged copy is repaired from these bytes
        // rather than the offer being refused.
        if self
            .storage
            .holds_verified(&address, &request.content)
            .await
        {
            debug!("Chunk {addr_hex} already exists");
            return ChunkPutResponse::AlreadyExists { address };
        }

        // 4. Cheap disk-space pre-check — runs BEFORE the expensive payment
        //    verification path (ML-DSA pool checks, a Kademlia closeness
        //    lookup, and an on-chain Arbitrum RPC). A disk-full node can never
        //    satisfy this PUT, so reject it here rather than burning that work
        //    only to fail the reserve check inside `storage.put` (V2-411). The
        //    check caches passing results, so it is free per-PUT on a healthy
        //    node; a disk-full node re-runs a cheap `available_space` syscall
        //    each PUT (still negligible next to the verification it avoids) and
        //    so detects freed space promptly. The store path keeps its own
        //    check as defence-in-depth.
        if let Err(e) = self.storage.check_capacity() {
            info!(
                target: "ant_node::storage::disk_precheck",
                addr = %addr_hex,
                "Rejecting PUT before payment verification: {e}"
            );
            return ChunkPutResponse::Error(ProtocolError::StorageFailed(e.to_string()));
        }

        // Self-closeness gate (ADR-0003): accept a client PUT only when this
        // node is within its own local closest view of the address, so the
        // fresh replication it triggers is legitimate and cannot mis-penalise
        // honest peers. The width is the client's PUT fallback ceiling
        // (`SELF_CLOSENESS_GATE_WIDTH`), so a client routing past full
        // close-group members onto further peers is still accepted here.
        // Skipped when no P2P handle is attached (unit tests). Bind the handle
        // out of the lock first so no guard is held across the `.await`.
        let attached = self.p2p_node.read().as_ref().map(Arc::clone);
        if let Some(p2p) = attached {
            let self_id = *p2p.peer_id();
            if !admission::is_responsible(&self_id, &address, &p2p, SELF_CLOSENESS_GATE_WIDTH).await
            {
                debug!("Rejecting PUT for {addr_hex}: not within local closest peers");
                return ChunkPutResponse::Error(ProtocolError::StorageFailed(
                    "node is not within its local closest peers for this address".to_string(),
                ));
            }
        }

        // 5. Verify payment. The ClientPut context applies the store-strength
        //    payment cache and verifies live proofs.
        let payment_result = self
            .payment_verifier
            .verify_payment(
                &address,
                request.payment_proof.as_deref(),
                VerificationContext::ClientPut,
            )
            .await;

        match payment_result {
            Ok(status) if status.can_store() => {
                // Payment verified or cached
            }
            Ok(_) => {
                return ChunkPutResponse::PaymentRequired {
                    message: "Payment required for new chunk".to_string(),
                };
            }
            Err(e) => {
                return ChunkPutResponse::Error(ProtocolError::PaymentFailed(e.to_string()));
            }
        }

        // 6. Store chunk
        match self.storage.put(&address, &request.content).await {
            Ok(_) => {
                let content_len = request.content.len();
                info!("Stored chunk {addr_hex} ({content_len} bytes)");
                // Bump the in-memory fallback record counter. Under ADR-0004
                // neither pricing nor the receiver-side price floor reads this
                // counter: both are bound to the live storage commitment
                // (committed responsible key count), pricing via the quote
                // generator's commitment source and the floor via the
                // verifier's non-mutating snapshot of the same commitment. The
                // counter only matters as a warm fallback surface when no
                // commitment source is attached (unit tests / pre-replication
                // startup).
                self.quote_generator.record_store();

                // 7. Notify replication engine for fresh fan-out.
                //    Only emit when a real proof is present — cached-as-verified
                //    PUTs have no proof to forward, and the chunk would have
                //    already replicated on the original write that carried one.
                if let (Some(ref tx), Some(proof)) = (&self.fresh_write_tx, request.payment_proof) {
                    // ADR-0004: strip any commitment sidecars before forwarding
                    // to replication — the ADR specifies persisted/replicated
                    // receipts "keep only the pin and count, so stored proofs do
                    // not grow." The sidecars were already consumed by this
                    // node's client-put cross-check; replicas resolve pins via
                    // gossip/fetch (their context is Replication, which skips the
                    // cross-check anyway). Best-effort: if sanitisation fails,
                    // fall back to the original proof rather than dropping the
                    // replication entirely.
                    let proof = Self::strip_commitment_sidecars(proof);
                    // Storage has already accepted the chunk on this path, so
                    // the event carries only the key; the offer dispatcher
                    // reads the chunk back when it is ready to send it.
                    let event = FreshWriteEvent {
                        key: address,
                        payment_proof: proof,
                    };
                    if tx.send(event).is_err() {
                        debug!("Fresh-write channel closed, skipping replication for {addr_hex}");
                    }
                }

                ChunkPutResponse::Success { address }
            }
            Err(e) => {
                warn!("Failed to store chunk {addr_hex}: {e}");
                ChunkPutResponse::Error(ProtocolError::StorageFailed(e.to_string()))
            }
        }
    }

    /// Read a chunk from local storage for a GET request.
    async fn handle_get_inner(&self, request: ChunkGetRequest) -> ChunkGetResponse {
        let address = request.address;
        let addr_hex = hex::encode(address);
        debug!("Handling GET request for {addr_hex}");

        match self.storage.get(&address).await {
            Ok(Some(content)) => {
                let content_len = content.len();
                debug!("Retrieved chunk {addr_hex} ({content_len} bytes)");
                ChunkGetResponse::Success { address, content }
            }
            Ok(None) => {
                debug!("Chunk {addr_hex} not found");
                ChunkGetResponse::NotFound { address }
            }
            Err(e) => {
                warn!("Failed to retrieve chunk {addr_hex}: {e}");
                ChunkGetResponse::Error(ProtocolError::StorageFailed(e.to_string()))
            }
        }
    }

    /// Resync the quoting metric to the authoritative count of records the node
    /// actually holds.
    ///
    /// The quote price is driven by `QuoteGenerator::records_stored()`. Reading
    /// the live LMDB entry count (an O(1) B-tree page-header read) right before
    /// pricing makes the metric deletion-aware: any chunk removed by
    /// [`ChunkStore::delete`] or by the replication prune pass is reflected
    /// immediately, with no risk of missing a delete path.
    ///
    /// On a storage read error — or a count that does not fit `usize` — the
    /// previous metric value is left untouched so a transient LMDB error never
    /// disrupts quote generation.
    fn resync_quote_metric(&self) {
        match self.storage.current_chunks() {
            // Saturating an overflowing count to usize::MAX would jump the
            // metric to the maximum possible price driver; keep the previous
            // value instead, as for a read error.
            Ok(count) => usize::try_from(count).map_or_else(
                |_| {
                    warn!(
                        "current_chunks() count {count} overflows usize; keeping previous quote \
                         metric"
                    );
                },
                |records| self.quote_generator.resync_records(records),
            ),
            Err(e) => {
                warn!("Failed to read current_chunks() for quote metric resync: {e}");
            }
        }
    }

    /// Handle a quote request.
    fn handle_quote(&self, request: &ChunkQuoteRequest) -> ChunkQuoteResponse {
        let addr_hex = hex::encode(request.address);
        let data_size = request.data_size;
        debug!("Handling quote request for {addr_hex} (size: {data_size})");

        // Price on records ACTUALLY HELD, not a monotonic store counter.
        self.resync_quote_metric();

        // Check if the chunk is already stored so we can tell the client
        // to skip payment (already_stored = true).
        //
        // Only chunks: this reads the chunk store, so asking it about any other
        // kind answers a question about the wrong address space. A pointer
        // quote names a state, not content, and every pointer state — creation
        // or update — is paid for, so it is never already stored.
        //
        // The match intentionally logs the error when the `logging` feature is
        // active. Clippy suggests `unwrap_or_default()` when logging is compiled
        // out, but keeping the explicit match preserves the diagnostic intent.
        #[allow(clippy::manual_unwrap_or_default)]
        let already_stored = request.data_type == DATA_TYPE_CHUNK
            && match self.storage.exists(&request.address) {
                Ok(exists) => exists,
                Err(e) => {
                    warn!("Storage check failed for {addr_hex}: {e}");
                    false // Assume not stored on error — generate a normal quote.
                }
            };

        if already_stored {
            debug!("Chunk {addr_hex} already stored — returning quote with already_stored=true");
        }

        // Validate data size - data_size is u64, cast carefully and reject overflow
        let Ok(data_size_usize) = usize::try_from(request.data_size) else {
            return ChunkQuoteResponse::Error(ProtocolError::ChunkTooLarge {
                size: MAX_CHUNK_SIZE + 1,
                max_size: MAX_CHUNK_SIZE,
            });
        };
        if data_size_usize > MAX_CHUNK_SIZE {
            return ChunkQuoteResponse::Error(ProtocolError::ChunkTooLarge {
                size: data_size_usize,
                max_size: MAX_CHUNK_SIZE,
            });
        }

        match self
            .quote_generator
            .create_quote(request.address, data_size_usize, request.data_type)
        {
            Ok(quote) => {
                // ADR-0004: ship the signed commitment the price was bound to
                // alongside the quote ("the commitment arrived with the quote"),
                // so the client can verify the binding before paying and forward
                // it as a sidecar in the PUT bundle. Only a commitment-bound
                // quote pins anything; a baseline `(0, None)` quote carries no
                // commitment. A pin that has rotated out resolves to `None` and
                // the client falls back to gossip/fetch.
                let commitment = quote
                    .commitment_pin
                    .and_then(|pin| self.quote_generator.commitment_blob_for_pin(pin));
                // Serialize the quote
                match rmp_serde::to_vec(&quote) {
                    Ok(quote_bytes) => ChunkQuoteResponse::Success {
                        quote: quote_bytes,
                        already_stored,
                        commitment,
                    },
                    Err(e) => ChunkQuoteResponse::Error(ProtocolError::QuoteFailed(format!(
                        "Failed to serialize quote: {e}"
                    ))),
                }
            }
            Err(e) => ChunkQuoteResponse::Error(ProtocolError::QuoteFailed(e.to_string())),
        }
    }

    /// Handle a version-declaring storage quote request.
    ///
    /// Refuse first, then fall through to the existing unversioned handler
    /// with the same request. The gate is the only difference between the two
    /// paths, so nothing else is duplicated and the two cannot drift.
    fn handle_quote_v2(&self, request: &ChunkQuoteRequestV2) -> ChunkQuoteResponse {
        if let Some(refusal) = settlement_gate(request.settlement_version, "single_node") {
            return ChunkQuoteResponse::Error(refusal);
        }
        self.handle_quote(&ChunkQuoteRequest {
            address: request.address,
            data_size: request.data_size,
            data_type: request.data_type,
        })
    }

    /// Handle a version-declaring merkle candidate quote request.
    ///
    /// The gate matters most here: a merkle batch settles on-chain before any
    /// storer sees a PUT, so this is the last point at which refusing costs
    /// the client nothing.
    fn handle_merkle_candidate_quote_v2(
        &self,
        request: &MerkleCandidateQuoteRequestV2,
    ) -> MerkleCandidateQuoteResponse {
        if let Some(refusal) = settlement_gate(request.settlement_version, "merkle") {
            return MerkleCandidateQuoteResponse::Error(refusal);
        }
        self.handle_merkle_candidate_quote(&MerkleCandidateQuoteRequest {
            address: request.address,
            data_type: request.data_type,
            data_size: request.data_size,
            merkle_payment_timestamp: request.merkle_payment_timestamp,
        })
    }

    /// Record that a client asked for a quote without declaring a settlement
    /// version, and periodically report the running count.
    ///
    /// Unversioned requests are still served. A node cannot tell a client that
    /// settles correctly but predates the version field from one that does
    /// not, and refusing both would break clients that are behaving. What the
    /// count buys is the evidence for flipping that policy later: once
    /// unversioned traffic has decayed, refusing it stops turning away only
    /// the clients that were already going to lose their money.
    fn note_unversioned_quote(path: &str) {
        let slot = usize::from(path == "merkle");
        let Some(counter) = UNVERSIONED_QUOTE_REQUESTS.get(slot) else {
            return;
        };
        let seen = counter.fetch_add(1, Ordering::Relaxed).saturating_add(1);
        if seen % UNVERSIONED_QUOTE_LOG_INTERVAL == 0 {
            info!(
                target: "ant_node::quote::settlement",
                "Received {seen} {path} quote requests from clients that declare no \
                 settlement version. These clients cannot be told to upgrade before \
                 they pay.",
            );
        }
    }

    /// Handle a merkle candidate quote request.
    fn handle_merkle_candidate_quote(
        &self,
        request: &MerkleCandidateQuoteRequest,
    ) -> MerkleCandidateQuoteResponse {
        let addr_hex = hex::encode(request.address);
        let data_size = request.data_size;
        debug!(
            "Handling merkle candidate quote request for {addr_hex} (size: {data_size}, ts: {})",
            request.merkle_payment_timestamp
        );

        // Price on records ACTUALLY HELD, not a monotonic store counter.
        self.resync_quote_metric();

        let Ok(data_size_usize) = usize::try_from(request.data_size) else {
            return MerkleCandidateQuoteResponse::Error(ProtocolError::QuoteFailed(format!(
                "data_size {} overflows usize",
                request.data_size
            )));
        };
        if data_size_usize > MAX_CHUNK_SIZE {
            return MerkleCandidateQuoteResponse::Error(ProtocolError::ChunkTooLarge {
                size: data_size_usize,
                max_size: MAX_CHUNK_SIZE,
            });
        }

        match self.quote_generator.create_merkle_candidate_quote(
            data_size_usize,
            request.data_type,
            request.merkle_payment_timestamp,
        ) {
            Ok(candidate_node) => {
                // ADR-0004: ship the signed commitment this candidate priced
                // against, so the client can verify the binding before paying
                // and forward it as a sidecar. Baseline candidates ship none.
                let commitment = candidate_node
                    .commitment_pin
                    .and_then(|pin| self.quote_generator.commitment_blob_for_pin(pin));
                match rmp_serde::to_vec(&candidate_node) {
                    Ok(bytes) => MerkleCandidateQuoteResponse::Success {
                        candidate_node: bytes,
                        commitment,
                    },
                    Err(e) => MerkleCandidateQuoteResponse::Error(ProtocolError::QuoteFailed(
                        format!("Failed to serialize merkle candidate node: {e}"),
                    )),
                }
            }
            Err(e) => {
                MerkleCandidateQuoteResponse::Error(ProtocolError::QuoteFailed(e.to_string()))
            }
        }
    }

    /// Get storage statistics.
    #[must_use]
    pub fn storage_stats(&self) -> crate::storage::StorageStats {
        self.storage.stats()
    }

    /// Get payment cache statistics.
    #[must_use]
    pub fn payment_cache_stats(&self) -> crate::payment::CacheStats {
        self.payment_verifier.cache_stats()
    }

    /// Get a reference to the payment verifier.
    ///
    /// Exposed for **test harnesses only** — production code should not call
    /// this directly. Use `cache_insert()` on the returned verifier to
    /// pre-populate the payment cache in test setups.
    #[cfg(any(test, feature = "test-utils"))]
    #[must_use]
    pub fn payment_verifier(&self) -> &PaymentVerifier {
        &self.payment_verifier
    }

    /// Check if a chunk exists locally.
    ///
    /// # Errors
    ///
    /// Returns an error if the storage read fails.
    pub fn exists(&self, address: &[u8; 32]) -> Result<bool> {
        self.storage.exists(address)
    }

    /// Get a chunk directly from local storage.
    ///
    /// # Errors
    ///
    /// Returns an error if storage access fails.
    pub async fn get_local(&self, address: &[u8; 32]) -> Result<Option<Vec<u8>>> {
        self.storage.get(address).await
    }

    /// Store a chunk directly to local storage (bypasses payment verification).
    ///
    /// TEST ONLY - This method bypasses payment verification and should only be used in tests.
    ///
    /// # Errors
    ///
    /// Returns an error if storage fails or content doesn't match address.
    #[cfg(test)]
    pub async fn put_local(&self, address: &[u8; 32], content: &[u8]) -> Result<bool> {
        self.storage.put(address, content).await
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use crate::payment::metrics::QuotingMetricsTracker;
    use crate::payment::{EvmVerifierConfig, PaymentVerifierConfig};
    use crate::pointer::{DATA_TYPE_POINTER, POINTER_WIRE_LEN};
    use crate::storage::ChunkStoreConfig;
    use evmlib::RewardsAddress;
    use saorsa_core::identity::NodeIdentity;
    use saorsa_core::MlDsa65;
    use saorsa_pqc::pqc::types::MlDsaSecretKey;
    use tempfile::TempDir;

    async fn create_test_protocol() -> (AntProtocol, TempDir) {
        // `test_default()` sets `disk_reserve: 0`, so the disk pre-check always
        // passes for the regular tests.
        create_test_protocol_with_reserve(0).await
    }

    /// Build a test protocol whose storage enforces the given disk reserve.
    ///
    /// A very large reserve (e.g. `u64::MAX`) makes `available < reserve`
    /// always true, so the disk-space pre-check in `handle_put_inner` fails —
    /// used to exercise the V2-411 early-return path.
    async fn create_test_protocol_with_reserve(disk_reserve: u64) -> (AntProtocol, TempDir) {
        let temp_dir = TempDir::new().expect("create temp dir");

        let storage_config = ChunkStoreConfig {
            root_dir: temp_dir.path().to_path_buf(),
            disk_reserve,
            ..ChunkStoreConfig::test_default()
        };
        let storage = Arc::new(
            ChunkStore::new(storage_config)
                .await
                .expect("create storage"),
        );

        let rewards_address = RewardsAddress::new([1u8; 20]);
        let payment_config = PaymentVerifierConfig {
            evm: EvmVerifierConfig::default(),
            cache_capacity: 100_000,
            close_group_size: crate::ant_protocol::CLOSE_GROUP_SIZE,
            local_rewards_address: rewards_address,
            price_floor: crate::payment::PriceFloorConfig::default(),
        };
        let payment_verifier = Arc::new(PaymentVerifier::new(payment_config));
        let metrics_tracker = QuotingMetricsTracker::new(100);
        let mut quote_generator = QuoteGenerator::new(rewards_address, metrics_tracker);

        // Wire ML-DSA-65 signing so quote requests succeed
        let identity = NodeIdentity::generate().expect("generate identity");
        let pub_key_bytes = identity.public_key().as_bytes().to_vec();
        let sk_bytes = identity.secret_key_bytes().to_vec();
        let sk = MlDsaSecretKey::from_bytes(&sk_bytes).expect("deserialize secret key");
        quote_generator.set_signer(pub_key_bytes, move |msg| {
            use saorsa_pqc::pqc::MlDsaOperations;
            let ml_dsa = MlDsa65::new();
            ml_dsa
                .sign(&sk, msg)
                .map_or_else(|_| vec![], |sig| sig.as_bytes().to_vec())
        });

        let protocol = AntProtocol::new(storage, payment_verifier, Arc::new(quote_generator));
        (protocol, temp_dir)
    }

    #[tokio::test]
    async fn test_put_and_get_chunk() {
        let (protocol, _temp) = create_test_protocol().await;

        let content = b"hello world";
        let address = ChunkStore::compute_address(content);

        // Pre-populate payment cache so EVM verification is bypassed
        protocol.payment_verifier().cache_insert(address);

        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
        let put_msg = ChunkMessage {
            request_id: 1,
            body: ChunkMessageBody::PutRequest(put_request),
        };
        let put_bytes = put_msg.encode().expect("encode put");

        // Handle PUT
        let response_bytes = protocol
            .try_handle_request(&put_bytes)
            .await
            .expect("handle put")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        assert_eq!(response.request_id, 1);
        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Success { address: addr }) =
            response.body
        {
            assert_eq!(addr, address);
        } else {
            panic!("expected PutResponse::Success, got: {response:?}");
        }

        // Create GET request
        let get_request = ChunkGetRequest::new(address);
        let get_msg = ChunkMessage {
            request_id: 2,
            body: ChunkMessageBody::GetRequest(get_request),
        };
        let get_bytes = get_msg.encode().expect("encode get");

        // Handle GET with the same local context the authenticated router adds.
        let handled = protocol
            .try_handle_request_with_context(
                &get_bytes,
                Some(ChunkRequestContext::new(
                    "peer-success".to_string(),
                    Instant::now(),
                    Duration::from_millis(4),
                )),
            )
            .await;
        let telemetry = handled.get_telemetry.expect("GET telemetry");
        assert_eq!(telemetry.source_peer, "peer-success");
        assert_eq!(telemetry.request_id, 2);
        assert_eq!(telemetry.chunk_address, hex::encode(address));
        assert_eq!(telemetry.queue_wait_ms, 4);
        assert_eq!(telemetry.storage_outcome, "success");
        assert_eq!(telemetry.storage_error_category, "none");

        let response_bytes = handled
            .response
            .expect("handle get")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        assert_eq!(response.request_id, 2);
        if let ChunkMessageBody::GetResponse(ChunkGetResponse::Success {
            address: addr,
            content: data,
        }) = response.body
        {
            assert_eq!(addr, address);
            assert_eq!(data, content.to_vec());
        } else {
            panic!("expected GetResponse::Success");
        }
        telemetry.finish_send(Duration::from_millis(2), true);
    }

    #[tokio::test]
    async fn typed_put_preserves_native_validation_and_storage() {
        let (protocol, _temp) = create_test_protocol().await;
        let content = Bytes::from(vec![0x5a; MAX_CHUNK_SIZE]);
        let address = ChunkStore::compute_address(&content);

        // Typed callers still encounter content, size, and payment admission.
        for (request_id, request) in [
            (1, ChunkPutRequest::new([0; 32], content.clone())),
            (
                2,
                ChunkPutRequest::new(address, Bytes::from(vec![0; MAX_CHUNK_SIZE + 1])),
            ),
            (3, ChunkPutRequest::new(address, content.clone())),
        ] {
            let message = ChunkMessage {
                request_id,
                body: ChunkMessageBody::PutRequest(request),
            };
            let wire = message.encode().expect("encode request");
            let typed = protocol
                .try_handle_message(message)
                .await
                .expect("response");
            let native = protocol
                .try_handle_request(&wire)
                .await
                .expect("native request")
                .expect("native response");
            assert_eq!(typed.encode().expect("encode response"), native.as_ref());
            assert!(matches!(
                typed.body,
                ChunkMessageBody::PutResponse(
                    ChunkPutResponse::Error(_) | ChunkPutResponse::PaymentRequired { .. }
                )
            ));
        }
        assert!(protocol
            .storage()
            .get(&address)
            .await
            .expect("read")
            .is_none());

        protocol.payment_verifier().cache_insert(address);
        let response = protocol
            .try_handle_message(ChunkMessage {
                request_id: 4,
                body: ChunkMessageBody::PutRequest(ChunkPutRequest::new(address, content.clone())),
            })
            .await
            .expect("paid response");
        assert_eq!(response.request_id, 4);
        assert!(matches!(
            response.body,
            ChunkMessageBody::PutResponse(ChunkPutResponse::Success { .. })
        ));
        assert_eq!(
            protocol
                .storage()
                .get(&address)
                .await
                .expect("read")
                .expect("stored"),
            content.as_ref()
        );
        assert!(protocol.try_handle_message(response).await.is_none());
    }

    #[tokio::test]
    async fn test_get_not_found() {
        let (protocol, _temp) = create_test_protocol().await;

        let address = [0xAB; 32];
        let get_request = ChunkGetRequest::new(address);
        let get_msg = ChunkMessage {
            request_id: 10,
            body: ChunkMessageBody::GetRequest(get_request),
        };
        let get_bytes = get_msg.encode().expect("encode get");

        let response_bytes = protocol
            .try_handle_request(&get_bytes)
            .await
            .expect("handle get")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        assert_eq!(response.request_id, 10);
        if let ChunkMessageBody::GetResponse(ChunkGetResponse::NotFound { address: addr }) =
            response.body
        {
            assert_eq!(addr, address);
        } else {
            panic!("expected GetResponse::NotFound");
        }
    }

    #[tokio::test]
    async fn test_get_telemetry_preserves_join_fields_and_response() {
        let (protocol, _temp) = create_test_protocol().await;

        let address = [0xCD; 32];
        let request_id = 995;
        let get_msg = ChunkMessage {
            request_id,
            body: ChunkMessageBody::GetRequest(ChunkGetRequest::new(address)),
        };
        let get_bytes = get_msg.encode().expect("encode get");
        let received_at = Instant::now();
        let handled = protocol
            .try_handle_request_with_context(
                &get_bytes,
                Some(ChunkRequestContext::new(
                    "peer-v2-995".to_string(),
                    received_at,
                    Duration::from_millis(17),
                )),
            )
            .await;

        let telemetry = handled.get_telemetry.expect("GET telemetry");
        assert_eq!(telemetry.source_peer, "peer-v2-995");
        assert_eq!(telemetry.request_id, request_id);
        assert_eq!(telemetry.chunk_address, hex::encode(address));
        assert_eq!(telemetry.queue_wait_ms, 17);
        assert_eq!(telemetry.storage_outcome, "not_found");
        assert_eq!(telemetry.storage_error_category, "none");

        let response_bytes = handled
            .response
            .expect("handle get")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
        assert_eq!(response.request_id, request_id);
        assert!(matches!(
            response.body,
            ChunkMessageBody::GetResponse(ChunkGetResponse::NotFound { address: found })
                if found == address
        ));

        telemetry.finish_send(Duration::from_millis(3), true);
    }

    #[tokio::test]
    async fn test_put_address_mismatch() {
        let (protocol, _temp) = create_test_protocol().await;

        let content = b"test content";
        let wrong_address = [0xFF; 32]; // Wrong address

        // Pre-populate cache for the wrong address so we test address mismatch, not payment
        protocol.payment_verifier().cache_insert(wrong_address);

        let put_request = ChunkPutRequest::new(wrong_address, Bytes::copy_from_slice(content));
        let put_msg = ChunkMessage {
            request_id: 20,
            body: ChunkMessageBody::PutRequest(put_request),
        };
        let put_bytes = put_msg.encode().expect("encode put");

        let response_bytes = protocol
            .try_handle_request(&put_bytes)
            .await
            .expect("handle put")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        assert_eq!(response.request_id, 20);
        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Error(
            ProtocolError::AddressMismatch { .. },
        )) = response.body
        {
            // Expected
        } else {
            panic!("expected AddressMismatch error, got: {response:?}");
        }
    }

    #[tokio::test]
    async fn test_put_chunk_too_large() {
        let (protocol, _temp) = create_test_protocol().await;

        // Create oversized content
        let content = vec![0u8; MAX_CHUNK_SIZE + 1];
        let address = ChunkStore::compute_address(&content);

        let put_request = ChunkPutRequest::new(address, Bytes::from(content));
        let put_msg = ChunkMessage {
            request_id: 30,
            body: ChunkMessageBody::PutRequest(put_request),
        };
        let put_bytes = put_msg.encode().expect("encode put");

        let response_bytes = protocol
            .try_handle_request(&put_bytes)
            .await
            .expect("handle put")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        assert_eq!(response.request_id, 30);
        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Error(
            ProtocolError::ChunkTooLarge { .. },
        )) = response.body
        {
            // Expected
        } else {
            panic!("expected ChunkTooLarge error");
        }
    }

    /// A node that is genuinely full must reject a PUT with the disk-space
    /// error *before* running payment verification (`V2-411`).
    ///
    /// "Full" now means both halves of the predicate: the volume is below the
    /// reserve **and** the store has no reusable space. A freshly created store
    /// has no freed pages, so both hold and the pre-check short-circuits, as it
    /// always did. The companion cases in `storage::lmdb::tests` cover the half
    /// that changed, where pruning has left reusable pages and the node must be
    /// admitted rather than refused on `statvfs` alone.
    ///
    /// The chunk is intentionally **not** cache-inserted, so if the handler
    /// reached `verify_payment` it would return `PaymentFailed` (an uncached
    /// chunk with no proof). Observing the `StorageFailed` disk error instead
    /// proves the pre-check short-circuited ahead of verification.
    #[tokio::test]
    async fn test_put_rejected_on_insufficient_capacity_before_verification() {
        // u64::MAX reserve guarantees `available < reserve`, and a fresh store
        // has no reusable pages, so the node is full on both halves.
        let (protocol, _temp) = create_test_protocol_with_reserve(u64::MAX).await;

        let content = b"chunk for a disk-full node";
        let address = ChunkStore::compute_address(content);

        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
        let put_msg = ChunkMessage {
            request_id: 41,
            body: ChunkMessageBody::PutRequest(put_request),
        };
        let put_bytes = put_msg.encode().expect("encode put");

        let response_bytes = protocol
            .try_handle_request(&put_bytes)
            .await
            .expect("handle put")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        assert_eq!(response.request_id, 41);
        match response.body {
            ChunkMessageBody::PutResponse(ChunkPutResponse::Error(
                ProtocolError::StorageFailed(msg),
            )) => {
                assert!(
                    msg.contains("Insufficient disk space"),
                    "expected disk-space error, got: {msg}"
                );
            }
            other => {
                panic!("expected StorageFailed disk error before verification, got: {other:?}")
            }
        }

        // And nothing was stored.
        assert!(!protocol.exists(&address).expect("exists check"));
    }

    #[tokio::test]
    async fn test_put_already_exists() {
        let (protocol, _temp) = create_test_protocol().await;

        let content = b"duplicate content";
        let address = ChunkStore::compute_address(content);

        // Pre-populate cache so EVM verification is bypassed
        protocol.payment_verifier().cache_insert(address);

        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
        let put_msg = ChunkMessage {
            request_id: 40,
            body: ChunkMessageBody::PutRequest(put_request),
        };
        let put_bytes = put_msg.encode().expect("encode put");

        let _ = protocol
            .try_handle_request(&put_bytes)
            .await
            .expect("handle put");

        // Store again - should return AlreadyExists
        let response_bytes = protocol
            .try_handle_request(&put_bytes)
            .await
            .expect("handle put 2")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        assert_eq!(response.request_id, 40);
        if let ChunkMessageBody::PutResponse(ChunkPutResponse::AlreadyExists { address: addr }) =
            response.body
        {
            assert_eq!(addr, address);
        } else {
            panic!("expected AlreadyExists");
        }
    }

    #[tokio::test]
    async fn test_protocol_id() {
        let (protocol, _temp) = create_test_protocol().await;
        assert_eq!(protocol.protocol_id(), CHUNK_PROTOCOL_ID);
    }

    #[tokio::test]
    async fn test_exists_and_local_access() {
        let (protocol, _temp) = create_test_protocol().await;

        let content = b"local access test";
        let address = ChunkStore::compute_address(content);

        assert!(!protocol.exists(&address).expect("exists check"));

        protocol
            .put_local(&address, content)
            .await
            .expect("put local");

        assert!(protocol.exists(&address).expect("exists check"));

        let retrieved = protocol.get_local(&address).await.expect("get local");
        assert_eq!(retrieved, Some(content.to_vec()));
    }

    #[tokio::test]
    async fn test_cache_insert_is_visible() {
        let (protocol, _temp) = create_test_protocol().await;

        let content = b"cache test content";
        let address = ChunkStore::compute_address(content);

        // Before insert: cache should be empty
        let stats_before = protocol.payment_cache_stats();
        assert_eq!(stats_before.additions, 0);

        // Pre-populate cache
        protocol.payment_verifier().cache_insert(address);

        // After insert: cache should have the xorname
        let stats_after = protocol.payment_cache_stats();
        assert_eq!(stats_after.additions, 1);

        // PUT should succeed (cache hit)
        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
        let put_msg = ChunkMessage {
            request_id: 100,
            body: ChunkMessageBody::PutRequest(put_request),
        };
        let put_bytes = put_msg.encode().expect("encode put");
        let response_bytes = protocol
            .try_handle_request(&put_bytes)
            .await
            .expect("handle put")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode");

        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Success { .. }) = response.body {
            // expected
        } else {
            panic!("expected success, got: {response:?}");
        }
    }

    #[tokio::test]
    async fn test_put_same_chunk_twice_hits_cache() {
        let (protocol, _temp) = create_test_protocol().await;

        let content = b"duplicate cache test";
        let address = ChunkStore::compute_address(content);

        // Pre-populate cache for first PUT
        protocol.payment_verifier().cache_insert(address);

        // First PUT
        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
        let put_msg = ChunkMessage {
            request_id: 110,
            body: ChunkMessageBody::PutRequest(put_request),
        };
        let put_bytes = put_msg.encode().expect("encode put");
        let _ = protocol
            .try_handle_request(&put_bytes)
            .await
            .expect("handle put 1");

        // Second PUT should return AlreadyExists from the storage idempotency check.
        let response_bytes = protocol
            .try_handle_request(&put_bytes)
            .await
            .expect("handle put 2")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode");

        if let ChunkMessageBody::PutResponse(ChunkPutResponse::AlreadyExists { .. }) = response.body
        {
            // expected
        } else {
            panic!("expected AlreadyExists, got: {response:?}");
        }
    }

    #[tokio::test]
    async fn test_payment_cache_stats_returns_correct_values() {
        let (protocol, _temp) = create_test_protocol().await;

        let stats = protocol.payment_cache_stats();
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 0);
        assert_eq!(stats.additions, 0);

        // Pre-populate cache, then store a chunk to test stats
        let content = b"stats test";
        let address = ChunkStore::compute_address(content);
        protocol.payment_verifier().cache_insert(address);

        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
        let put_msg = ChunkMessage {
            request_id: 120,
            body: ChunkMessageBody::PutRequest(put_request),
        };
        let put_bytes = put_msg.encode().expect("encode put");
        let _ = protocol
            .try_handle_request(&put_bytes)
            .await
            .expect("handle put");

        let stats = protocol.payment_cache_stats();
        // Should have 1 addition (from cache_insert) + 1 hit (payment verification found cache)
        assert_eq!(stats.additions, 1);
        assert_eq!(stats.hits, 1);
    }

    #[tokio::test]
    async fn test_storage_stats() {
        let (protocol, _temp) = create_test_protocol().await;
        let stats = protocol.storage_stats();
        assert_eq!(stats.chunks_stored, 0);
    }

    #[tokio::test]
    async fn test_merkle_candidate_quote_request() {
        use ant_protocol::payment::verify::verify_merkle_candidate_signature;
        use evmlib::merkle_payments::MerklePaymentCandidateNode;

        // create_test_protocol already wires ML-DSA-65 signing
        let (protocol, _temp) = create_test_protocol().await;

        let address = [0x77; 32];
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system time")
            .as_secs();

        let request = MerkleCandidateQuoteRequest {
            address,
            data_type: DATA_TYPE_CHUNK,
            data_size: 4096,
            merkle_payment_timestamp: timestamp,
        };
        let msg = ChunkMessage {
            request_id: 600,
            body: ChunkMessageBody::MerkleCandidateQuoteRequest(request),
        };
        let msg_bytes = msg.encode().expect("encode request");

        let response_bytes = protocol
            .try_handle_request(&msg_bytes)
            .await
            .expect("handle merkle candidate quote")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        assert_eq!(response.request_id, 600);
        match response.body {
            ChunkMessageBody::MerkleCandidateQuoteResponse(
                MerkleCandidateQuoteResponse::Success { candidate_node, .. },
            ) => {
                let candidate: MerklePaymentCandidateNode =
                    rmp_serde::from_slice(&candidate_node).expect("deserialize candidate node");

                // Verify ML-DSA-65 signature
                assert!(
                    verify_merkle_candidate_signature(&candidate),
                    "ML-DSA-65 candidate signature must be valid"
                );

                assert_eq!(candidate.merkle_payment_timestamp, timestamp);
                // Node-calculated price based on records stored
                assert!(candidate.price >= evmlib::common::Amount::ZERO);
            }
            other => panic!("expected MerkleCandidateQuoteResponse::Success, got: {other:?}"),
        }
    }

    /// A current client gets a quote through the versioned request, exactly as
    /// it would through the legacy one. The gate must be invisible to clients
    /// that can pay.
    #[tokio::test]
    async fn v2_merkle_quote_is_served_at_the_current_settlement_version() {
        let (protocol, _temp) = create_test_protocol().await;
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system time")
            .as_secs();

        let msg = ChunkMessage {
            request_id: 700,
            body: ChunkMessageBody::MerkleCandidateQuoteRequestV2(
                MerkleCandidateQuoteRequestV2::new([0x88; 32], 4096, timestamp),
            ),
        };
        let response_bytes = protocol
            .try_handle_request(&msg.encode().expect("encode request"))
            .await
            .expect("handle v2 merkle candidate quote")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        assert_eq!(response.request_id, 700);
        match response.body {
            ChunkMessageBody::MerkleCandidateQuoteResponse(
                MerkleCandidateQuoteResponse::Success { .. },
            ) => {}
            other => panic!("expected Success, got: {other:?}"),
        }
    }

    /// The point of the whole change: a client that cannot settle correctly is
    /// turned away at quote time, so it never reaches the on-chain payment it
    /// would not be able to spend.
    #[tokio::test]
    async fn v2_merkle_quote_is_refused_below_the_minimum_settlement_version() {
        let (protocol, _temp) = create_test_protocol().await;
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system time")
            .as_secs();

        let stale = MIN_SUPPORTED_SETTLEMENT_VERSION.saturating_sub(1);
        let mut request = MerkleCandidateQuoteRequestV2::new([0x99; 32], 4096, timestamp);
        request.settlement_version = stale;

        let msg = ChunkMessage {
            request_id: 701,
            body: ChunkMessageBody::MerkleCandidateQuoteRequestV2(request),
        };
        let response_bytes = protocol
            .try_handle_request(&msg.encode().expect("encode request"))
            .await
            .expect("handle v2 merkle candidate quote")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        match response.body {
            ChunkMessageBody::MerkleCandidateQuoteResponse(
                MerkleCandidateQuoteResponse::Error(ProtocolError::ClientUpdateRequired {
                    client_settlement_version,
                    min_settlement_version,
                }),
            ) => {
                assert_eq!(client_settlement_version, stale);
                assert_eq!(min_settlement_version, MIN_SUPPORTED_SETTLEMENT_VERSION);
                // The refusal has to be actionable, not just correct.
                let rendered = ProtocolError::ClientUpdateRequired {
                    client_settlement_version,
                    min_settlement_version,
                }
                .to_string();
                assert!(rendered.contains("ant update"), "{rendered}");
            }
            other => panic!("expected ClientUpdateRequired, got: {other:?}"),
        }
    }

    /// Same gate on the single-node path, so a refused merkle client cannot
    /// simply fall back to per-chunk quotes and burn money that way instead.
    #[tokio::test]
    async fn v2_single_node_quote_is_refused_below_the_minimum_settlement_version() {
        let (protocol, _temp) = create_test_protocol().await;

        let mut request = ChunkQuoteRequestV2::new([0xAA; 32], 4096);
        request.settlement_version = MIN_SUPPORTED_SETTLEMENT_VERSION.saturating_sub(1);

        let msg = ChunkMessage {
            request_id: 702,
            body: ChunkMessageBody::QuoteRequestV2(request),
        };
        let response_bytes = protocol
            .try_handle_request(&msg.encode().expect("encode request"))
            .await
            .expect("handle v2 quote")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        match response.body {
            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Error(
                ProtocolError::ClientUpdateRequired { .. },
            )) => {}
            other => panic!("expected ClientUpdateRequired, got: {other:?}"),
        }
    }

    /// A settlement version this node has never heard of is refused, because
    /// quoting it would promise to accept a payment whose rules the verifier
    /// does not know. That promise would be broken at PUT time, which is after
    /// the client has settled on-chain and can no longer be refunded.
    ///
    /// It must be refused as `StorerUpdateRequired`, not `ClientUpdateRequired`.
    /// The client is fine; this node is behind. Telling an up-to-date user to
    /// upgrade would be wrong, and during a client-first rollout it would be
    /// wrong for most of the fleet at once.
    #[tokio::test]
    async fn a_newer_settlement_version_is_refused_as_this_nodes_fault() {
        let (protocol, _temp) = create_test_protocol().await;

        let mut request = ChunkQuoteRequestV2::new([0xBB; 32], 4096);
        request.settlement_version = CURRENT_SETTLEMENT_VERSION.saturating_add(1);

        let msg = ChunkMessage {
            request_id: 703,
            body: ChunkMessageBody::QuoteRequestV2(request),
        };
        let response_bytes = protocol
            .try_handle_request(&msg.encode().expect("encode request"))
            .await
            .expect("handle v2 quote")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        match response.body {
            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Error(
                ProtocolError::StorerUpdateRequired {
                    client_settlement_version,
                    node_settlement_version,
                },
            )) => {
                assert_eq!(
                    client_settlement_version,
                    CURRENT_SETTLEMENT_VERSION.saturating_add(1)
                );
                assert_eq!(node_settlement_version, CURRENT_SETTLEMENT_VERSION);
            }
            other => panic!("expected StorerUpdateRequired, got: {other:?}"),
        }
    }

    /// Legacy requests keep working. A node cannot tell a client that settles
    /// correctly but predates the version field from one that does not, so
    /// refusing both would break clients that are behaving.
    #[tokio::test]
    async fn unversioned_requests_are_still_served() {
        let (protocol, _temp) = create_test_protocol().await;
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system time")
            .as_secs();

        let msg = ChunkMessage {
            request_id: 704,
            body: ChunkMessageBody::MerkleCandidateQuoteRequest(MerkleCandidateQuoteRequest {
                address: [0xCC; 32],
                data_type: DATA_TYPE_CHUNK,
                data_size: 4096,
                merkle_payment_timestamp: timestamp,
            }),
        };
        let response_bytes = protocol
            .try_handle_request(&msg.encode().expect("encode request"))
            .await
            .expect("handle legacy merkle candidate quote")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode response");

        match response.body {
            ChunkMessageBody::MerkleCandidateQuoteResponse(
                MerkleCandidateQuoteResponse::Success { .. },
            ) => {}
            other => panic!("expected Success for a legacy request, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_handle_unexpected_response_message() {
        let (protocol, _temp) = create_test_protocol().await;

        // Send a PutResponse as if it were a request — should return None
        let msg = ChunkMessage {
            request_id: 200,
            body: ChunkMessageBody::PutResponse(ChunkPutResponse::Success { address: [0u8; 32] }),
        };
        let msg_bytes = msg.encode().expect("encode");

        let result = protocol
            .try_handle_request(&msg_bytes)
            .await
            .expect("handle msg");

        assert!(
            result.is_none(),
            "expected None for response message, got: {result:?}"
        );
    }

    #[tokio::test]
    async fn a_stored_chunk_does_not_suppress_a_pointer_quote() {
        // A pointer quote names a state, not content. If a chunk sitting at
        // that address could set `already_stored`, a majority of nodes would
        // tell the client to skip payment and the write would then be refused
        // as unpaid. Only chunks may answer from the chunk store.
        let (protocol, _temp) = create_test_protocol().await;

        let content = b"a chunk that shares a pointer state address";
        let address = ChunkStore::compute_address(content);
        protocol.payment_verifier().cache_insert(address);
        let put_msg = ChunkMessage {
            request_id: 320,
            body: ChunkMessageBody::PutRequest(ChunkPutRequest::new(
                address,
                Bytes::copy_from_slice(content),
            )),
        };
        let put_bytes = put_msg.encode().expect("encode put");
        let _ = protocol
            .try_handle_request(&put_bytes)
            .await
            .expect("handle put");

        let quote_msg = ChunkMessage {
            request_id: 321,
            body: ChunkMessageBody::QuoteRequest(ChunkQuoteRequest {
                address,
                data_size: POINTER_WIRE_LEN as u64,
                data_type: DATA_TYPE_POINTER,
            }),
        };
        let quote_bytes = quote_msg.encode().expect("encode quote");
        let response_bytes = protocol
            .try_handle_request(&quote_bytes)
            .await
            .expect("handle quote")
            .expect("expected response");

        match ChunkMessage::decode(&response_bytes).expect("decode").body {
            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Success {
                already_stored, ..
            }) => assert!(
                !already_stored,
                "a chunk must not answer for a pointer state"
            ),
            other => panic!("expected a quote, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_quote_already_stored_flag() {
        let (protocol, _temp) = create_test_protocol().await;

        let content = b"already stored quote test";
        let address = ChunkStore::compute_address(content);

        // Store the chunk first
        protocol.payment_verifier().cache_insert(address);
        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
        let put_msg = ChunkMessage {
            request_id: 300,
            body: ChunkMessageBody::PutRequest(put_request),
        };
        let put_bytes = put_msg.encode().expect("encode put");
        let _ = protocol
            .try_handle_request(&put_bytes)
            .await
            .expect("handle put");

        // Now request a quote for the same address — already_stored should be true
        let quote_request = ChunkQuoteRequest {
            address,
            data_size: content.len() as u64,
            data_type: DATA_TYPE_CHUNK,
        };
        let quote_msg = ChunkMessage {
            request_id: 301,
            body: ChunkMessageBody::QuoteRequest(quote_request),
        };
        let quote_bytes = quote_msg.encode().expect("encode quote");
        let response_bytes = protocol
            .try_handle_request(&quote_bytes)
            .await
            .expect("handle quote")
            .expect("expected response");
        let response = ChunkMessage::decode(&response_bytes).expect("decode");

        match response.body {
            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Success {
                already_stored, ..
            }) => {
                assert!(
                    already_stored,
                    "already_stored should be true for existing chunk"
                );
            }
            other => panic!("expected Success with already_stored, got: {other:?}"),
        }

        // Request a quote for a chunk that does NOT exist — already_stored should be false
        let new_address = [0xFFu8; 32];
        let quote_request2 = ChunkQuoteRequest {
            address: new_address,
            data_size: 100,
            data_type: DATA_TYPE_CHUNK,
        };
        let quote_msg2 = ChunkMessage {
            request_id: 302,
            body: ChunkMessageBody::QuoteRequest(quote_request2),
        };
        let quote_bytes2 = quote_msg2.encode().expect("encode quote2");
        let response_bytes2 = protocol
            .try_handle_request(&quote_bytes2)
            .await
            .expect("handle quote2")
            .expect("expected response");
        let response2 = ChunkMessage::decode(&response_bytes2).expect("decode2");

        match response2.body {
            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Success {
                already_stored, ..
            }) => {
                assert!(
                    !already_stored,
                    "already_stored should be false for new chunk"
                );
            }
            other => panic!("expected Success with already_stored=false, got: {other:?}"),
        }
    }

    /// Drive the real quote handler, then read the record count it priced on.
    /// The handler calls `resync_quote_metric` first, so this reflects records
    /// ACTUALLY HELD.
    fn priced_records_after_quote(protocol: &AntProtocol) -> usize {
        let quote_request = ChunkQuoteRequest {
            address: [0xAAu8; 32], // a quote-only probe, not one of the stored chunks
            data_size: 100,
            data_type: DATA_TYPE_CHUNK,
        };
        let _ = protocol.handle_quote(&quote_request);
        protocol.priced_records_stored()
    }

    /// The quote price must track records ACTUALLY HELD: deleting stored chunks
    /// must lower the priced record count, not keep quoting as if the data were
    /// still held. Exercises the storage-driven resync in `resync_quote_metric`.
    #[tokio::test]
    async fn test_quote_metric_reflects_deletions() {
        let (protocol, _temp) = create_test_protocol().await;

        // Distinct content -> distinct content-addressed keys.
        let contents: Vec<Vec<u8>> = (0u8..5).map(|i| vec![i; 64]).collect();
        let mut addresses = Vec::new();
        for content in &contents {
            let addr = ChunkStore::compute_address(content);
            protocol.put_local(&addr, content).await.expect("put_local");
            addresses.push(addr);
        }

        // 5 records held -> priced count 5.
        assert_eq!(priced_records_after_quote(&protocol), 5);

        // Delete 2 chunks the node was holding.
        for addr in addresses.iter().take(2) {
            assert!(protocol.storage().delete(addr).await.expect("delete"));
        }
        assert_eq!(priced_records_after_quote(&protocol), 3);

        // Delete the rest; priced count floors at 0, never underflows.
        for addr in addresses.iter().skip(2) {
            assert!(protocol.storage().delete(addr).await.expect("delete"));
        }
        assert_eq!(priced_records_after_quote(&protocol), 0);
    }

    /// Stronger, externally-observable proof: the actual quote PRICE returned
    /// to a client must drop after the node deletes data it held. A monotonic
    /// store counter would keep the price elevated; the resync ties price to
    /// records actually held.
    /// FLIPS IF: `resync_quote_metric` is removed — the price would stay at the
    /// 10-record level even after deletions (`record_store` only ever increments).
    #[tokio::test]
    async fn test_quote_price_drops_after_deletion() {
        use crate::payment::pricing::calculate_price;

        let (protocol, _temp) = create_test_protocol().await;
        let contents: Vec<Vec<u8>> = (0u8..10).map(|i| vec![i; 64]).collect();
        let mut addresses = Vec::new();
        for content in &contents {
            let addr = ChunkStore::compute_address(content);
            protocol.put_local(&addr, content).await.expect("put_local");
            addresses.push(addr);
        }

        // Drive a real quote; the priced count must equal records held (10),
        // and the price must equal calculate_price(10) — the externally
        // observable contract.
        assert_eq!(priced_records_after_quote(&protocol), 10);
        let price_full = calculate_price(10);

        // Delete 8 of 10 held chunks.
        for addr in addresses.iter().take(8) {
            assert!(protocol.storage().delete(addr).await.expect("delete"));
        }
        // The next quote must price on 2 records, and the price must be the
        // calculate_price(2) value — strictly different from the 10-record
        // price (price is monotonic non-decreasing in records_stored).
        assert_eq!(priced_records_after_quote(&protocol), 2);
        let price_after = calculate_price(2);
        assert!(
            price_after < price_full,
            "deleting data must lower the observable quote price \
             (full={price_full:?}, after={price_after:?})"
        );
    }

    /// ADR-0004: `strip_commitment_sidecars` removes sidecars from a single-node
    /// proof before replication/persistence (stored proofs do not grow), and is
    /// a no-op on a sidecar-free proof.
    #[test]
    fn strip_commitment_sidecars_clears_single_node_sidecars() {
        use crate::payment::proof::{
            deserialize_single_node_proof, serialize_single_node_proof, PaymentProof,
        };
        use evmlib::ProofOfPayment;

        let with_sidecars = PaymentProof {
            proof_of_payment: ProofOfPayment {
                peer_quotes: vec![],
            },
            tx_hashes: vec![],
            commitment_sidecars: vec![vec![1u8; 16], vec![2u8; 16]],
        };
        let bytes = serialize_single_node_proof(&with_sidecars).expect("serialize");
        let stripped = AntProtocol::strip_commitment_sidecars(bytes);
        let parsed = deserialize_single_node_proof(&stripped).expect("deserialize stripped");
        assert!(
            parsed.commitment_sidecars.is_empty(),
            "sidecars must be stripped before replication"
        );

        // Idempotent: stripping an already-sidecar-free proof returns it intact.
        let again = AntProtocol::strip_commitment_sidecars(stripped.clone());
        assert_eq!(again, stripped, "stripping a sidecar-free proof is a no-op");
    }
}