Skip to main content

ant_node/storage/
handler.rs

1//! ANT protocol handler for autonomi protocol messages.
2//!
3//! This handler processes chunk PUT/GET requests with optional payment verification,
4//! storing chunks on disk and using the DHT for network-wide retrieval.
5//!
6//! # Architecture
7//!
8//! ```text
9//! ┌─────────────────────────────────────────────────────────┐
10//! │                    AntProtocol                        │
11//! ├─────────────────────────────────────────────────────────┤
12//! │  protocol_id() = "autonomi.ant.chunk.v1"                  │
13//! │                                                         │
14//! │  try_handle_request(data) ──▶ decode ChunkMessage  │
15//! │                                   │                     │
16//! │         ┌─────────────────────────┼─────────────────┐  │
17//! │         ▼                         ▼                 ▼  │
18//! │   ChunkQuoteRequest           ChunkPutRequest    ChunkGetRequest
19//! │         │                         │                 │  │
20//! │         ▼                         ▼                 ▼  │
21//! │   QuoteGenerator          PaymentVerifier    ChunkStore│
22//! │         │                         │                 │  │
23//! │         └─────────────────────────┴─────────────────┘  │
24//! │                           │                             │
25//! │           return Ok(Some(response_bytes))              │
26//! │           return Ok(None) for response messages       │
27//! └─────────────────────────────────────────────────────────┘
28//! ```
29
30use crate::ant_protocol::DATA_TYPE_CHUNK;
31use crate::ant_protocol::{
32    settlement_compatibility, ChunkGetOrCloserRequest, ChunkGetOrCloserResponse, ChunkGetRequest,
33    ChunkGetResponse, ChunkMessage, ChunkMessageBody, ChunkPutRequest, ChunkPutResponse,
34    ChunkQuoteRequest, ChunkQuoteRequestV2, ChunkQuoteResponse, MerkleCandidateQuoteRequest,
35    MerkleCandidateQuoteRequestV2, MerkleCandidateQuoteResponse, ProtocolError,
36    SettlementCompatibility, XorName, CHUNK_PROTOCOL_ID, CURRENT_SETTLEMENT_VERSION,
37    MAX_CHUNK_SIZE, MIN_SUPPORTED_SETTLEMENT_VERSION,
38};
39use crate::client::compute_address;
40use crate::error::{Error, Result};
41use crate::logging::{debug, info, warn};
42use crate::payment::{PaymentVerifier, QuoteGenerator, VerificationContext};
43use crate::pointer::PointerService;
44use crate::replication::admission;
45use crate::replication::config::K_BUCKET_SIZE;
46use crate::replication::fresh::FreshWriteEvent;
47use crate::storage::traffic::{self, ChunkRequestKind, ChunkResponseKey};
48use crate::storage::ChunkStore;
49use ant_protocol::chunk::{PointerGetResponse, PointerPutResponse};
50use bytes::Bytes;
51use parking_lot::RwLock;
52use saorsa_core::{P2PNode, PeerId};
53use std::sync::atomic::{AtomicU64, Ordering};
54use std::sync::Arc;
55use std::time::{Duration, Instant};
56use tokio::sync::mpsc;
57
58/// Width of the self-closeness gate on client PUTs (ADR-0003): a node accepts
59/// a PUT only when it is within its own local `SELF_CLOSENESS_GATE_WIDTH`
60/// closest peers to the address.
61///
62/// Set to the client's PUT fallback ceiling (`K_BUCKET_SIZE`), wider than the
63/// storage-admission width, so a client routing past full close-group members
64/// onto further peers (ADR-0002) is still accepted here, while a genuinely far
65/// node — which could only mis-attribute fresh-replication failures — is
66/// turned away.
67pub const SELF_CLOSENESS_GATE_WIDTH: usize = K_BUCKET_SIZE;
68
69fn duration_ms(duration: Duration) -> u64 {
70    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
71}
72
73/// Receipt context supplied by the authenticated P2P event router.
74///
75/// This is deliberately process-local metadata: it is never encoded or sent on
76/// the wire. The receipt instant spans semaphore queueing, storage, response
77/// encoding, and the response hand-off to the transport.
78pub struct ChunkRequestContext {
79    source_peer: String,
80    /// The authenticated sender, when the router knows it.
81    requester: Option<PeerId>,
82    received_at: Instant,
83    queue_wait_ms: u64,
84}
85
86impl ChunkRequestContext {
87    #[must_use]
88    pub(crate) fn new(source_peer: String, received_at: Instant, queue_wait: Duration) -> Self {
89        Self {
90            source_peer,
91            requester: None,
92            received_at,
93            queue_wait_ms: duration_ms(queue_wait),
94        }
95    }
96
97    /// Record the authenticated sender, so a get-or-closer answer can leave
98    /// it out of the closer peers, as a `FIND_NODE` answer does.
99    #[must_use]
100    pub(crate) fn with_requester(mut self, requester: PeerId) -> Self {
101        self.requester = Some(requester);
102        self
103    }
104}
105
106/// A decoded protocol request and, for GETs, its pending one-shot telemetry.
107///
108/// Keeping the handler result and telemetry together lets the router record the
109/// event only after response hand-off, while preserving the existing handler
110/// error and response behaviour.
111pub struct HandledChunkRequest {
112    pub(crate) response: Result<Option<Bytes>>,
113    pub(crate) get_telemetry: Option<GetRequestTelemetry>,
114    /// Kind × outcome of the encoded response, so the router can attribute
115    /// the bytes once the send is confirmed (V2-834).
116    pub(crate) traffic_key: Option<ChunkResponseKey>,
117}
118
119/// Bounded stage timings for one decoded chunk GET.
120///
121/// `finish_send` emits the sole `get_rpc` event. If the routing task is cancelled
122/// after handling but before response hand-off completes, `Drop` emits the same
123/// event with `cancelled` outcomes so the request does not disappear silently.
124#[cfg_attr(not(feature = "logging"), allow(dead_code))]
125pub struct GetRequestTelemetry {
126    /// The read request: `get`, or `get_or_closer` (ADR-0020).
127    request: &'static str,
128    source_peer: String,
129    request_id: u64,
130    chunk_address: String,
131    received_at: Instant,
132    queue_wait_ms: u64,
133    storage_read_ms: u64,
134    storage_outcome: &'static str,
135    storage_error_category: &'static str,
136    response_encode_ms: u64,
137    finished: bool,
138}
139
140impl GetRequestTelemetry {
141    fn from_response(
142        context: ChunkRequestContext,
143        request_id: u64,
144        chunk_address: String,
145        storage_read_ms: u64,
146        response: &ChunkGetResponse,
147    ) -> Self {
148        let storage = match response {
149            ChunkGetResponse::Success { .. } => ("success", "none"),
150            ChunkGetResponse::NotFound { .. } => ("not_found", "none"),
151            ChunkGetResponse::Error(ProtocolError::StorageFailed(_)) => ("error", "storage"),
152            ChunkGetResponse::Error(_) => ("error", "protocol"),
153            _ => ("unknown", "unknown"),
154        };
155        Self::new(
156            "get",
157            context,
158            request_id,
159            chunk_address,
160            storage_read_ms,
161            storage,
162        )
163    }
164
165    /// A get-or-closer read (ADR-0020). Answering with closer peers means the
166    /// chunk was not in storage, so its storage outcome is `not_found`.
167    fn from_get_or_closer_response(
168        context: ChunkRequestContext,
169        request_id: u64,
170        chunk_address: String,
171        storage_read_ms: u64,
172        response: &ChunkGetOrCloserResponse,
173    ) -> Self {
174        let storage = match response {
175            ChunkGetOrCloserResponse::Found { .. } => ("success", "none"),
176            ChunkGetOrCloserResponse::Closer { .. } => ("not_found", "none"),
177            ChunkGetOrCloserResponse::Error(ProtocolError::StorageFailed(_)) => {
178                ("error", "storage")
179            }
180            ChunkGetOrCloserResponse::Error(_) => ("error", "protocol"),
181            _ => ("unknown", "unknown"),
182        };
183        Self::new(
184            "get_or_closer",
185            context,
186            request_id,
187            chunk_address,
188            storage_read_ms,
189            storage,
190        )
191    }
192
193    fn new(
194        request: &'static str,
195        context: ChunkRequestContext,
196        request_id: u64,
197        chunk_address: String,
198        storage_read_ms: u64,
199        (storage_outcome, storage_error_category): (&'static str, &'static str),
200    ) -> Self {
201        Self {
202            request,
203            source_peer: context.source_peer,
204            request_id,
205            chunk_address,
206            received_at: context.received_at,
207            queue_wait_ms: context.queue_wait_ms,
208            storage_read_ms,
209            storage_outcome,
210            storage_error_category,
211            response_encode_ms: 0,
212            finished: false,
213        }
214    }
215
216    fn set_response_encode_ms(&mut self, elapsed: Duration) {
217        self.response_encode_ms = duration_ms(elapsed);
218    }
219
220    /// Record the single completed GET event after response hand-off.
221    pub(crate) fn finish_send(mut self, response_send: Duration, send_succeeded: bool) {
222        let (send_outcome, overall_outcome) = if send_succeeded {
223            let overall = match self.storage_outcome {
224                "success" => "success",
225                "not_found" => "not_found",
226                "error" => "storage_error",
227                _ => "unknown",
228            };
229            ("success", overall)
230        } else {
231            ("error", "send_error")
232        };
233        self.emit(response_send, send_outcome, overall_outcome);
234        self.finished = true;
235    }
236
237    /// Record a GET which could not reach the response hand-off stage.
238    pub(crate) fn finish_without_send(mut self, overall_outcome: &'static str) {
239        self.emit(Duration::ZERO, "not_attempted", overall_outcome);
240        self.finished = true;
241    }
242
243    fn emit(
244        &self,
245        response_send: Duration,
246        send_outcome: &'static str,
247        overall_outcome: &'static str,
248    ) {
249        let response_send_ms = duration_ms(response_send);
250        let duration_ms = duration_ms(self.received_at.elapsed());
251        info!(
252            target: "ant_node::storage::rpc_latency",
253            request = self.request,
254            source_peer = %self.source_peer,
255            request_id = self.request_id,
256            chunk_address = %self.chunk_address,
257            addr = %self.chunk_address,
258            queue_wait_ms = self.queue_wait_ms,
259            storage_read_ms = self.storage_read_ms,
260            storage_outcome = self.storage_outcome,
261            storage_error_category = self.storage_error_category,
262            response_encode_ms = self.response_encode_ms,
263            response_send_ms,
264            send_outcome,
265            duration_ms,
266            outcome = overall_outcome,
267            "get_rpc"
268        );
269    }
270}
271
272impl Drop for GetRequestTelemetry {
273    fn drop(&mut self) {
274        if !self.finished {
275            self.emit(Duration::ZERO, "cancelled", "cancelled");
276            self.finished = true;
277        }
278    }
279}
280
281/// One latency event per pointer PUT, on the target the chunk `put_rpc` uses,
282/// so the same store-latency dashboards cover both kinds.
283fn log_pointer_put_rpc(elapsed: Duration, record_size: usize, response: &PointerPutResponse) {
284    let duration_ms = duration_ms(elapsed);
285    let (outcome, address): (&'static str, Option<&XorName>) = match response {
286        PointerPutResponse::Success { address, .. } => ("success", Some(address)),
287        PointerPutResponse::Unchanged { address, .. } => ("unchanged", Some(address)),
288        PointerPutResponse::Stale { address, .. } => ("stale", Some(address)),
289        PointerPutResponse::PaymentRequired { .. } => ("payment_required", None),
290        PointerPutResponse::Error(_) => ("error", None),
291    };
292    let addr = address.map(hex::encode).unwrap_or_default();
293    info!(
294        target: "ant_node::storage::rpc_latency",
295        duration_ms,
296        record_size,
297        outcome,
298        addr = %addr,
299        "pointer_put_rpc"
300    );
301}
302
303/// One latency event per pointer GET, beside the chunk `get_rpc`.
304fn log_pointer_get_rpc(elapsed: Duration, address: &XorName, response: &PointerGetResponse) {
305    let duration_ms = duration_ms(elapsed);
306    let outcome: &'static str = match response {
307        PointerGetResponse::Success { .. } => "success",
308        PointerGetResponse::NotFound { .. } => "not_found",
309        PointerGetResponse::Error(_) => "error",
310    };
311    let addr = hex::encode(address);
312    info!(
313        target: "ant_node::storage::rpc_latency",
314        duration_ms,
315        outcome,
316        addr = %addr,
317        "pointer_get_rpc"
318    );
319}
320
321/// How many unversioned quote requests to receive between adoption log lines.
322///
323/// One line per request would drown the log at production quote rates, and one
324/// line total would say nothing about the trend. A running count emitted every
325/// `N` gives the shape of client adoption, which is the number that decides
326/// when unversioned requests can start being refused outright.
327const UNVERSIONED_QUOTE_LOG_INTERVAL: u64 = 1_000;
328
329/// Unversioned quote requests received since start, by path.
330///
331/// Counted on arrival, before the quote is generated, because the question
332/// this answers is how many clients still cannot declare a version. A request
333/// this node then refuses for an unrelated reason still came from such a
334/// client, and would still break if the unversioned path were retired.
335///
336/// Indices are `[single_node, merkle]`. A plain counter rather than a metric
337/// because the only consumer is the rollout decision, and that reads logs.
338static UNVERSIONED_QUOTE_REQUESTS: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)];
339
340/// Refuse a quote when the requesting client settles under rules this node no
341/// longer accepts. `None` means the request may proceed.
342///
343/// This is the whole point of the settlement version. A merkle batch pays
344/// on-chain **before** any storer sees a PUT, so refusing the *payment* is
345/// refusing something already spent and unrefundable. Refusing the *quote*
346/// costs the client nothing: no quote means no pool commitment, which means no
347/// payment.
348///
349/// A version NEWER than this node understands is refused too, as
350/// `StorerUpdateRequired`. Quoting it would promise to accept a payment whose
351/// rules this build does not know, and that promise can only be broken at PUT
352/// time, once the client has settled on-chain. The client is told to use a
353/// different storer rather than to upgrade, because it is this node that is
354/// behind.
355fn settlement_gate(client_settlement_version: u32, path: &str) -> Option<ProtocolError> {
356    match settlement_compatibility(client_settlement_version) {
357        SettlementCompatibility::Compatible => None,
358        SettlementCompatibility::ClientTooOld => {
359            warn!(
360                target: "ant_node::quote::settlement",
361                "Refusing {path} quote: client settlement version {client_settlement_version} \
362                 is below the minimum {MIN_SUPPORTED_SETTLEMENT_VERSION}. No quote issued, \
363                 so the client has not been charged.",
364            );
365            Some(ProtocolError::ClientUpdateRequired {
366                client_settlement_version,
367                min_settlement_version: MIN_SUPPORTED_SETTLEMENT_VERSION,
368            })
369        }
370        // This node is the old one. Quoting would promise to accept a payment
371        // whose rules it does not know, and a promise broken at PUT time is
372        // broken after the client has settled on-chain. Refusing sends the
373        // client to a peer that can actually honour the quote, at no cost.
374        SettlementCompatibility::NodeTooOld => {
375            warn!(
376                target: "ant_node::quote::settlement",
377                "Refusing {path} quote: client settles under version \
378                 {client_settlement_version}, newer than this node's \
379                 {CURRENT_SETTLEMENT_VERSION}. This node needs upgrading; the client \
380                 has not been charged.",
381            );
382            Some(ProtocolError::StorerUpdateRequired {
383                client_settlement_version,
384                node_settlement_version: CURRENT_SETTLEMENT_VERSION,
385            })
386        }
387    }
388}
389
390/// ANT protocol handler.
391///
392/// Handles chunk PUT/GET/Quote requests, persisting each chunk as its own file
393/// and optional payment verification.
394pub struct AntProtocol {
395    /// The chunk store.
396    storage: Arc<ChunkStore>,
397    /// Payment verifier for checking payments.
398    payment_verifier: Arc<PaymentVerifier>,
399    /// Quote generator for creating storage quotes.
400    /// Also handles merkle candidate quote signing via ML-DSA-65.
401    quote_generator: Arc<QuoteGenerator>,
402    /// Channel for notifying the replication engine about newly-stored chunks.
403    fresh_write_tx: Option<mpsc::UnboundedSender<FreshWriteEvent>>,
404    /// The node's P2P handle, attached post-construction via
405    /// `attach_p2p_node`. Drives the self-closeness gate on client PUTs;
406    /// `None` in unit tests that never attach a node.
407    p2p_node: RwLock<Option<Arc<P2PNode>>>,
408    /// Serves pointer requests, when the node has a pointer store.
409    ///
410    /// `None` on a node built without one, so a peer that sends a pointer
411    /// message to a node that does not keep pointers gets a clean refusal
412    /// rather than a silent drop.
413    pointers: Option<PointerService>,
414}
415
416impl AntProtocol {
417    /// Create a new ANT protocol handler.
418    ///
419    /// # Arguments
420    ///
421    /// * `storage` - the chunk store
422    /// * `payment_verifier` - Payment verifier for validating payments
423    /// * `quote_generator` - Quote generator for creating storage quotes
424    #[must_use]
425    pub fn new(
426        storage: Arc<ChunkStore>,
427        payment_verifier: Arc<PaymentVerifier>,
428        quote_generator: Arc<QuoteGenerator>,
429    ) -> Self {
430        // Wire the PaymentVerifier to the same authoritative store used by this
431        // protocol handler. Historically the verifier read `current_chunks()`
432        // for the paid-quote price floor; ADR-0004 retired that gate (price is
433        // bound to the live storage commitment, not the local record count), so
434        // the store is no longer consulted for pricing. The attachment is kept
435        // so any future store-backed verifier check reads the same record count
436        // this handler serves, for every AntProtocol construction path.
437        //
438        // ADR-0004: the QuoteGenerator no longer prices off `current_chunks()`
439        // — its price is bound to the live storage commitment (see
440        // `attach_commitment_source`, wired by the node once the replication
441        // engine exists), or baseline when none — so it is NOT attached to the
442        // store here.
443        payment_verifier.attach_storage(Arc::clone(&storage));
444
445        Self {
446            storage,
447            payment_verifier,
448            quote_generator,
449            fresh_write_tx: None,
450            p2p_node: RwLock::new(None),
451            pointers: None,
452        }
453    }
454
455    /// Serve pointer requests from `pointers`.
456    ///
457    /// Opt-in rather than built in: a node with no pointer store refuses
458    /// pointer messages cleanly instead of pretending to hold them.
459    #[must_use]
460    pub fn with_pointer_service(mut self, pointers: PointerService) -> Self {
461        self.pointers = Some(pointers);
462        self
463    }
464
465    /// The pointer service, if this node serves pointers.
466    #[must_use]
467    pub const fn pointer_service(&self) -> Option<&PointerService> {
468        self.pointers.as_ref()
469    }
470
471    /// Attach the node's P2P handle for payment live-DHT checks.
472    ///
473    /// Wires the handle into the payment verifier so payment-proof closeness
474    /// checks can use the live routing view. Idempotent: calling twice
475    /// replaces the verifier handle.
476    pub fn attach_p2p_node(&self, node: Arc<P2PNode>) {
477        *self.p2p_node.write() = Some(Arc::clone(&node));
478        if let Some(pointers) = &self.pointers {
479            // Pointers take the same self-closeness gate as chunks, judged at
480            // the pointer address because that is what the network routes on.
481            pointers.attach_p2p_node(Arc::clone(&node));
482        }
483        self.payment_verifier.attach_p2p_node(node);
484        debug!("AntProtocol: P2PNode attached for payment live-DHT checks and self-closeness gate");
485    }
486
487    /// Set the channel sender for fresh-write replication events.
488    ///
489    /// When set, successful chunk PUTs will notify the replication engine
490    /// so it can fan out fresh offers to the close group.
491    pub fn set_fresh_write_sender(&mut self, tx: mpsc::UnboundedSender<FreshWriteEvent>) {
492        self.fresh_write_tx = Some(tx);
493    }
494
495    /// The fresh-write sender, if one was set. Lets tests drive the
496    /// replication engine's fresh-write pipeline exactly as a PUT would.
497    #[cfg(any(test, feature = "test-utils"))]
498    pub fn fresh_write_sender(&self) -> Option<mpsc::UnboundedSender<FreshWriteEvent>> {
499        self.fresh_write_tx.clone()
500    }
501
502    /// Get the protocol identifier.
503    #[must_use]
504    pub fn protocol_id(&self) -> &'static str {
505        CHUNK_PROTOCOL_ID
506    }
507
508    /// Get a reference to the underlying chunk store.
509    #[must_use]
510    pub fn storage(&self) -> Arc<ChunkStore> {
511        Arc::clone(&self.storage)
512    }
513
514    /// Test-only: the record count the quote generator currently prices on.
515    /// Used to assert that quote-time resync tracks records actually held.
516    #[cfg(test)]
517    #[must_use]
518    pub(crate) fn priced_records_stored(&self) -> usize {
519        self.quote_generator.records_stored()
520    }
521
522    /// Get a shared reference to the payment verifier.
523    #[must_use]
524    pub fn payment_verifier_arc(&self) -> Arc<PaymentVerifier> {
525        Arc::clone(&self.payment_verifier)
526    }
527
528    /// ADR-0004: attach the replication engine's commitment state as the quote
529    /// generator's commitment source, so quotes force their price from the live
530    /// storage commitment and refresh its answerability on issuance.
531    ///
532    /// Called once, after both the protocol and the replication engine exist
533    /// (the engine owns the [`ResponderCommitmentState`](crate::replication::commitment_state::ResponderCommitmentState)).
534    /// Until this is wired, the quote generator has no commitment source and
535    /// falls back to baseline (no-pin) pricing.
536    ///
537    /// The same source is forwarded to the payment verifier's price-floor
538    /// policy (read-only snapshot), so this node's quotes and its floor are
539    /// priced from one commitment by construction.
540    pub fn attach_commitment_source(
541        &self,
542        source: Arc<dyn crate::payment::quote::CommitmentSource>,
543    ) {
544        self.quote_generator
545            .attach_commitment_source(Arc::clone(&source));
546        self.payment_verifier.attach_local_commitment_source(source);
547    }
548
549    /// ADR-0004: return the proof with any commitment sidecars stripped, so a
550    /// replicated/persisted receipt carries only the pin and count (stored
551    /// proofs do not grow). Handles BOTH proof types — single-node and
552    /// merkle-batch — since both now carry sidecars. An unknown-tagged or
553    /// unparseable proof is returned unchanged. Best-effort: any
554    /// deserialize/reserialize failure returns the original bytes rather than
555    /// corrupting the proof.
556    fn strip_commitment_sidecars(proof: Vec<u8>) -> Vec<u8> {
557        use crate::payment::proof::{
558            deserialize_merkle_proof, deserialize_single_node_proof, detect_proof_type,
559            serialize_merkle_proof, serialize_single_node_proof, ProofType,
560        };
561        match detect_proof_type(&proof) {
562            Some(ProofType::SingleNode) => match deserialize_single_node_proof(&proof) {
563                Ok(mut parsed) if !parsed.commitment_sidecars.is_empty() => {
564                    parsed.commitment_sidecars.clear();
565                    serialize_single_node_proof(&parsed).unwrap_or(proof)
566                }
567                _ => proof, // already sidecar-free, or unparseable: leave as-is
568            },
569            Some(ProofType::Merkle) => match deserialize_merkle_proof(&proof) {
570                Ok(mut parsed) if !parsed.commitment_sidecars.is_empty() => {
571                    parsed.commitment_sidecars.clear();
572                    serialize_merkle_proof(&parsed).unwrap_or(proof)
573                }
574                _ => proof,
575            },
576            _ => proof, // unknown tag: nothing to strip
577        }
578    }
579
580    /// Handle an incoming request and produce a response.
581    ///
582    /// Decodes the raw message, processes it if it is a request variant,
583    /// and returns the encoded response bytes.  Returns `Ok(None)` for
584    /// response messages (which are meant for client subscribers, not for
585    /// the protocol handler).
586    ///
587    /// # Errors
588    ///
589    /// Returns an error if message decoding, handling, or encoding fails.
590    pub async fn try_handle_request(&self, data: &[u8]) -> Result<Option<Bytes>> {
591        self.try_handle_request_with_context(data, None)
592            .await
593            .response
594    }
595
596    /// Handle a request while carrying authenticated receipt context through a
597    /// GET response hand-off. The context is local-only observability metadata.
598    pub(crate) async fn try_handle_request_with_context(
599        &self,
600        data: &[u8],
601        context: Option<ChunkRequestContext>,
602    ) -> HandledChunkRequest {
603        let message = match ChunkMessage::decode(data) {
604            Ok(message) => message,
605            Err(e) => {
606                traffic::record_rx(ChunkRequestKind::DecodeError, data.len());
607                return HandledChunkRequest {
608                    response: Err(Error::Protocol(format!("Failed to decode message: {e}"))),
609                    get_telemetry: None,
610                    traffic_key: None,
611                };
612            }
613        };
614
615        // V2-834: attribute inbound bytes by request kind at the decode
616        // choke point. Only this entry point has the wire length; the browser
617        // adapter below is handed an already-decoded message.
618        traffic::record_rx(ChunkRequestKind::of(&message.body), data.len());
619
620        let (response, mut get_telemetry, traffic_key) =
621            self.handle_message_with_context(message, context).await;
622        let encode_started = Instant::now();
623        let encoded = response
624            .map(|response| {
625                response
626                    .encode()
627                    .map(Bytes::from)
628                    .map_err(|e| Error::Protocol(format!("Failed to encode response: {e}")))
629            })
630            .transpose();
631        if let Some(telemetry) = &mut get_telemetry {
632            telemetry.set_response_encode_ms(encode_started.elapsed());
633        }
634
635        HandledChunkRequest {
636            response: encoded,
637            get_telemetry,
638            traffic_key,
639        }
640    }
641
642    /// Dispatch an already decoded request without copying its chunk buffer.
643    /// The wire adapter and browser adapter share all storage and payment checks.
644    #[cfg(any(feature = "webrtc-direct", test))]
645    pub(crate) async fn try_handle_message(&self, message: ChunkMessage) -> Option<ChunkMessage> {
646        self.handle_message_with_context(message, None).await.0
647    }
648
649    async fn handle_message_with_context(
650        &self,
651        message: ChunkMessage,
652        context: Option<ChunkRequestContext>,
653    ) -> (
654        Option<ChunkMessage>,
655        Option<GetRequestTelemetry>,
656        Option<ChunkResponseKey>,
657    ) {
658        let request_id = message.request_id;
659        let mut get_telemetry = None;
660
661        // Each arm yields the response body and its V2-834 traffic key.
662        let (response_body, traffic_key) = match message.body {
663            ChunkMessageBody::PutRequest(req) => {
664                let response = self.handle_put(req).await;
665                let key = ChunkResponseKey::of_put(&response);
666                (ChunkMessageBody::PutResponse(response), key)
667            }
668            ChunkMessageBody::GetRequest(req) => {
669                let chunk_address = hex::encode(req.address);
670                let storage_started = Instant::now();
671                let response = self.handle_get_inner(req).await;
672                let storage_read_ms = duration_ms(storage_started.elapsed());
673                let key = ChunkResponseKey::of_get(&response);
674                if let Some(context) = context {
675                    get_telemetry = Some(GetRequestTelemetry::from_response(
676                        context,
677                        request_id,
678                        chunk_address,
679                        storage_read_ms,
680                        &response,
681                    ));
682                }
683                (ChunkMessageBody::GetResponse(response), key)
684            }
685            ChunkMessageBody::QuoteRequest(ref req) => {
686                Self::note_unversioned_quote("single_node");
687                (
688                    ChunkMessageBody::QuoteResponse(self.handle_quote(req)),
689                    ChunkResponseKey::Quote,
690                )
691            }
692            ChunkMessageBody::MerkleCandidateQuoteRequest(ref req) => {
693                Self::note_unversioned_quote("merkle");
694                (
695                    ChunkMessageBody::MerkleCandidateQuoteResponse(
696                        self.handle_merkle_candidate_quote(req),
697                    ),
698                    ChunkResponseKey::MerkleQuote,
699                )
700            }
701            ChunkMessageBody::QuoteRequestV2(ref req) => (
702                ChunkMessageBody::QuoteResponse(self.handle_quote_v2(req)),
703                ChunkResponseKey::QuoteV2,
704            ),
705            ChunkMessageBody::MerkleCandidateQuoteRequestV2(ref req) => (
706                ChunkMessageBody::MerkleCandidateQuoteResponse(
707                    self.handle_merkle_candidate_quote_v2(req),
708                ),
709                ChunkResponseKey::MerkleQuoteV2,
710            ),
711            ChunkMessageBody::PointerPutRequest(req) => {
712                let started = Instant::now();
713                let record_size = req.record.len();
714                let response = match &self.pointers {
715                    Some(service) => service.handle_put(req).await,
716                    None => PointerPutResponse::Error(ProtocolError::StorageFailed(
717                        "this node does not store pointers".to_string(),
718                    )),
719                };
720                log_pointer_put_rpc(started.elapsed(), record_size, &response);
721                let key = ChunkResponseKey::of_pointer_put(&response);
722                (ChunkMessageBody::PointerPutResponse(response), key)
723            }
724            ChunkMessageBody::GetOrCloserRequest(req) => {
725                let (response, telemetry) =
726                    self.handle_get_or_closer(req, request_id, context).await;
727                get_telemetry = telemetry;
728                let key = ChunkResponseKey::of_get_or_closer(&response);
729                (ChunkMessageBody::GetOrCloserResponse(response), key)
730            }
731            ChunkMessageBody::PointerGetRequest(req) => {
732                let started = Instant::now();
733                let address = req.address;
734                let response = match &self.pointers {
735                    Some(service) => service.handle_get(req).await,
736                    None => PointerGetResponse::NotFound { address },
737                };
738                log_pointer_get_rpc(started.elapsed(), &address, &response);
739                let key = ChunkResponseKey::of_pointer_get(&response);
740                (ChunkMessageBody::PointerGetResponse(response), key)
741            }
742            // Anything else — response messages are handled by client
743            // subscribers (e.g. send_and_await_chunk_response), not by the
744            // protocol handler. Returning None prevents the caller from
745            // sending a reply, which would create an infinite ping-pong
746            // loop.
747            //
748            // `ChunkMessageBody` is `#[non_exhaustive]` in ant-protocol, so
749            // a future wire variant added on a protocol minor bump also
750            // lands here and is dropped. The CHUNK_PROTOCOL_ID multistream-
751            // select handshake version-gates peers, so this arm should
752            // only be reached by a misconfigured peer.
753            _ => {
754                return (None, None, None);
755            }
756        };
757
758        (
759            Some(ChunkMessage {
760                request_id,
761                body: response_body,
762            }),
763            get_telemetry,
764            Some(traffic_key),
765        )
766    }
767
768    /// Handle a PUT request.
769    ///
770    /// Wraps `handle_put_inner` to emit a single structured tracing event per
771    /// PUT RPC at every exit path, including early-return validation paths.
772    /// The event uses `target: "ant_node::storage::rpc_latency"` so that
773    /// Elasticsearch / Kibana can build p50/p95/p99 store-RPC latency
774    /// histograms from the existing telegraf log forwarding.
775    async fn handle_put(&self, request: ChunkPutRequest) -> ChunkPutResponse {
776        let start = std::time::Instant::now();
777        let addr_hex = hex::encode(request.address);
778        let chunk_size = request.content.len();
779        let response = self.handle_put_inner(request).await;
780        let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
781        let outcome: &'static str = match &response {
782            ChunkPutResponse::Success { .. } => "success",
783            ChunkPutResponse::AlreadyExists { .. } => "already_exists",
784            ChunkPutResponse::PaymentRequired { .. } => "payment_required",
785            ChunkPutResponse::Error(_) => "error",
786            _ => "unknown",
787        };
788        info!(
789            target: "ant_node::storage::rpc_latency",
790            duration_ms,
791            chunk_size,
792            outcome,
793            addr = %addr_hex,
794            "put_rpc"
795        );
796        response
797    }
798
799    /// Inner body of `handle_put` — see the wrapper for the per-RPC latency log.
800    async fn handle_put_inner(&self, request: ChunkPutRequest) -> ChunkPutResponse {
801        let address = request.address;
802        let addr_hex = hex::encode(address);
803        debug!("Handling PUT request for {addr_hex}");
804
805        // 1. Validate chunk size
806        if request.content.len() > MAX_CHUNK_SIZE {
807            return ChunkPutResponse::Error(ProtocolError::ChunkTooLarge {
808                size: request.content.len(),
809                max_size: MAX_CHUNK_SIZE,
810            });
811        }
812
813        // 2. Verify content address matches BLAKE3(content)
814        let computed = compute_address(&request.content);
815        if computed != address {
816            return ChunkPutResponse::Error(ProtocolError::AddressMismatch {
817                expected: address,
818                actual: computed,
819            });
820        }
821
822        // 2b. Refuse a chunk whose address a pointer already occupies.
823        //
824        // The mirror of the check the pointer path makes. Both kinds draw
825        // addresses from the same 32-byte range, and a collision — however
826        // infeasible — must not be resolved by whichever kind arrived second,
827        // because that silently destroys the other's data.
828        if let Some(pointers) = &self.pointers {
829            if pointers.store().contains(&address) {
830                warn!("Refusing chunk {addr_hex}: a pointer already occupies that address");
831                return ChunkPutResponse::Error(ProtocolError::StorageFailed(format!(
832                    "address {addr_hex} is already occupied by a pointer; refusing to \
833                     store a chunk over it"
834                )));
835            }
836        }
837
838        // 3. Check if already exists (idempotent success)
839        //
840        // Verified against the offered bytes, not answered from the name. A name can
841        // outlive the bytes under it, and acknowledging a good copy of a chunk this node
842        // holds only a damaged version of throws that copy away and does not get offered
843        // another. Reached only when this node already has the chunk, and the content
844        // address was checked in step 2, so a damaged copy is repaired from these bytes
845        // rather than the offer being refused.
846        if self
847            .storage
848            .holds_verified(&address, &request.content)
849            .await
850        {
851            debug!("Chunk {addr_hex} already exists");
852            return ChunkPutResponse::AlreadyExists { address };
853        }
854
855        // 4. Cheap disk-space pre-check — runs BEFORE the expensive payment
856        //    verification path (ML-DSA pool checks, a Kademlia closeness
857        //    lookup, and an on-chain Arbitrum RPC). A disk-full node can never
858        //    satisfy this PUT, so reject it here rather than burning that work
859        //    only to fail the reserve check inside `storage.put` (V2-411). The
860        //    check caches passing results, so it is free per-PUT on a healthy
861        //    node; a disk-full node re-runs a cheap `available_space` syscall
862        //    each PUT (still negligible next to the verification it avoids) and
863        //    so detects freed space promptly. The store path keeps its own
864        //    check as defence-in-depth.
865        if let Err(e) = self.storage.check_capacity() {
866            info!(
867                target: "ant_node::storage::disk_precheck",
868                addr = %addr_hex,
869                "Rejecting PUT before payment verification: {e}"
870            );
871            return ChunkPutResponse::Error(ProtocolError::StorageFailed(e.to_string()));
872        }
873
874        // Self-closeness gate (ADR-0003): accept a client PUT only when this
875        // node is within its own local closest view of the address, so the
876        // fresh replication it triggers is legitimate and cannot mis-penalise
877        // honest peers. The width is the client's PUT fallback ceiling
878        // (`SELF_CLOSENESS_GATE_WIDTH`), so a client routing past full
879        // close-group members onto further peers is still accepted here.
880        // Skipped when no P2P handle is attached (unit tests). Bind the handle
881        // out of the lock first so no guard is held across the `.await`.
882        let attached = self.p2p_node.read().as_ref().map(Arc::clone);
883        if let Some(p2p) = attached {
884            let self_id = *p2p.peer_id();
885            if !admission::is_responsible(&self_id, &address, &p2p, SELF_CLOSENESS_GATE_WIDTH).await
886            {
887                debug!("Rejecting PUT for {addr_hex}: not within local closest peers");
888                return ChunkPutResponse::Error(ProtocolError::StorageFailed(
889                    "node is not within its local closest peers for this address".to_string(),
890                ));
891            }
892        }
893
894        // 5. Verify payment. The ClientPut context applies the store-strength
895        //    payment cache and verifies live proofs.
896        let payment_result = self
897            .payment_verifier
898            .verify_payment(
899                &address,
900                request.payment_proof.as_deref(),
901                VerificationContext::ClientPut,
902            )
903            .await;
904
905        match payment_result {
906            Ok(status) if status.can_store() => {
907                // Payment verified or cached
908            }
909            Ok(_) => {
910                return ChunkPutResponse::PaymentRequired {
911                    message: "Payment required for new chunk".to_string(),
912                };
913            }
914            Err(e) => {
915                return ChunkPutResponse::Error(ProtocolError::PaymentFailed(e.to_string()));
916            }
917        }
918
919        // 6. Store chunk
920        match self.storage.put(&address, &request.content).await {
921            Ok(_) => {
922                let content_len = request.content.len();
923                info!("Stored chunk {addr_hex} ({content_len} bytes)");
924                // Bump the in-memory fallback record counter. Under ADR-0004
925                // neither pricing nor the receiver-side price floor reads this
926                // counter: both are bound to the live storage commitment
927                // (committed responsible key count), pricing via the quote
928                // generator's commitment source and the floor via the
929                // verifier's non-mutating snapshot of the same commitment. The
930                // counter only matters as a warm fallback surface when no
931                // commitment source is attached (unit tests / pre-replication
932                // startup).
933                self.quote_generator.record_store();
934
935                // 7. Notify replication engine for fresh fan-out.
936                //    Only emit when a real proof is present — cached-as-verified
937                //    PUTs have no proof to forward, and the chunk would have
938                //    already replicated on the original write that carried one.
939                if let (Some(ref tx), Some(proof)) = (&self.fresh_write_tx, request.payment_proof) {
940                    // ADR-0004: strip any commitment sidecars before forwarding
941                    // to replication — the ADR specifies persisted/replicated
942                    // receipts "keep only the pin and count, so stored proofs do
943                    // not grow." The sidecars were already consumed by this
944                    // node's client-put cross-check; replicas resolve pins via
945                    // gossip/fetch (their context is Replication, which skips the
946                    // cross-check anyway). Best-effort: if sanitisation fails,
947                    // fall back to the original proof rather than dropping the
948                    // replication entirely.
949                    let proof = Self::strip_commitment_sidecars(proof);
950                    // Storage has already accepted the chunk on this path, so
951                    // the event carries only the key; the offer dispatcher
952                    // reads the chunk back when it is ready to send it.
953                    let event = FreshWriteEvent {
954                        key: address,
955                        payment_proof: proof,
956                    };
957                    if tx.send(event).is_err() {
958                        debug!("Fresh-write channel closed, skipping replication for {addr_hex}");
959                    }
960                }
961
962                ChunkPutResponse::Success { address }
963            }
964            Err(e) => {
965                warn!("Failed to store chunk {addr_hex}: {e}");
966                ChunkPutResponse::Error(ProtocolError::StorageFailed(e.to_string()))
967            }
968        }
969    }
970
971    /// Read a chunk from local storage for a GET request.
972    async fn handle_get_inner(&self, request: ChunkGetRequest) -> ChunkGetResponse {
973        let address = request.address;
974        let addr_hex = hex::encode(address);
975        debug!("Handling GET request for {addr_hex}");
976
977        match self.storage.get(&address).await {
978            Ok(Some(content)) => {
979                let content_len = content.len();
980                debug!("Retrieved chunk {addr_hex} ({content_len} bytes)");
981                ChunkGetResponse::Success { address, content }
982            }
983            Ok(None) => {
984                debug!("Chunk {addr_hex} not found");
985                ChunkGetResponse::NotFound { address }
986            }
987            Err(e) => {
988                warn!("Failed to retrieve chunk {addr_hex}: {e}");
989                ChunkGetResponse::Error(ProtocolError::StorageFailed(e.to_string()))
990            }
991        }
992    }
993
994    /// Answer a get-or-closer request (ADR-0020): the chunk when this node
995    /// holds it, otherwise the `FIND_NODE` answer it would give the requester
996    /// for the address. With a request context, also returns the read's
997    /// telemetry, as a GET's.
998    async fn handle_get_or_closer(
999        &self,
1000        request: ChunkGetOrCloserRequest,
1001        request_id: u64,
1002        context: Option<ChunkRequestContext>,
1003    ) -> (ChunkGetOrCloserResponse, Option<GetRequestTelemetry>) {
1004        let address = request.address;
1005        let requester = context.as_ref().and_then(|context| context.requester);
1006        let storage_started = Instant::now();
1007        let stored = self.storage.get(&address).await;
1008        let storage_read_ms = duration_ms(storage_started.elapsed());
1009        let response = match stored {
1010            Ok(Some(chunk)) => ChunkGetOrCloserResponse::Found {
1011                address,
1012                content: Bytes::from(chunk),
1013            },
1014            Ok(None) => self.closer_peers(address, requester).await,
1015            Err(e) => {
1016                warn!(
1017                    "Failed to read chunk {} for get-or-closer: {e}",
1018                    hex::encode(address)
1019                );
1020                ChunkGetOrCloserResponse::Error(ProtocolError::StorageFailed(e.to_string()))
1021            }
1022        };
1023        let telemetry = context.map(|context| {
1024            GetRequestTelemetry::from_get_or_closer_response(
1025                context,
1026                request_id,
1027                hex::encode(address),
1028                storage_read_ms,
1029                &response,
1030            )
1031        });
1032        (response, telemetry)
1033    }
1034
1035    /// This node's closest known peers to `address`, encoded by saorsa-core
1036    /// exactly as its `FIND_NODE` answer to `requester` would hold them.
1037    async fn closer_peers(
1038        &self,
1039        address: XorName,
1040        requester: Option<PeerId>,
1041    ) -> ChunkGetOrCloserResponse {
1042        // Bind the handle out of the lock so no guard is held across `.await`.
1043        let attached = self.p2p_node.read().as_ref().map(Arc::clone);
1044        let Some(p2p) = attached else {
1045            return ChunkGetOrCloserResponse::Error(ProtocolError::Internal(
1046                "this node has no routing table to answer from".to_string(),
1047            ));
1048        };
1049        // Without a known requester there is no one to leave out; the local
1050        // node never appears in its own answer.
1051        let requester = requester.unwrap_or_else(|| *p2p.peer_id());
1052        match p2p
1053            .dht_manager()
1054            .encode_closer_peers(&address, &requester)
1055            .await
1056        {
1057            Ok(peers) => ChunkGetOrCloserResponse::Closer {
1058                address,
1059                peers: Bytes::from(peers),
1060            },
1061            Err(e) => {
1062                warn!(
1063                    "Failed to encode closer peers for {}: {e}",
1064                    hex::encode(address)
1065                );
1066                ChunkGetOrCloserResponse::Error(ProtocolError::Internal(e.to_string()))
1067            }
1068        }
1069    }
1070
1071    /// Resync the quoting metric to the authoritative count of records the node
1072    /// actually holds.
1073    ///
1074    /// The quote price is driven by `QuoteGenerator::records_stored()`. Reading
1075    /// the live chunk count right before
1076    /// pricing makes the metric deletion-aware: any chunk removed by
1077    /// [`ChunkStore::delete`] or by the replication prune pass is reflected
1078    /// immediately, with no risk of missing a delete path.
1079    ///
1080    /// On a storage read error — or a count that does not fit `usize` — the
1081    /// previous metric value is left untouched so a transient read error never
1082    /// disrupts quote generation.
1083    fn resync_quote_metric(&self) {
1084        match self.storage.current_chunks() {
1085            // Saturating an overflowing count to usize::MAX would jump the
1086            // metric to the maximum possible price driver; keep the previous
1087            // value instead, as for a read error.
1088            Ok(count) => usize::try_from(count).map_or_else(
1089                |_| {
1090                    warn!(
1091                        "current_chunks() count {count} overflows usize; keeping previous quote \
1092                         metric"
1093                    );
1094                },
1095                |records| self.quote_generator.resync_records(records),
1096            ),
1097            Err(e) => {
1098                warn!("Failed to read current_chunks() for quote metric resync: {e}");
1099            }
1100        }
1101    }
1102
1103    /// Handle a quote request.
1104    fn handle_quote(&self, request: &ChunkQuoteRequest) -> ChunkQuoteResponse {
1105        let addr_hex = hex::encode(request.address);
1106        let data_size = request.data_size;
1107        debug!("Handling quote request for {addr_hex} (size: {data_size})");
1108
1109        // Price on records ACTUALLY HELD, not a monotonic store counter.
1110        self.resync_quote_metric();
1111
1112        // Check if the chunk is already stored so we can tell the client
1113        // to skip payment (already_stored = true).
1114        //
1115        // Only chunks: this reads the chunk store, so asking it about any other
1116        // kind answers a question about the wrong address space. A pointer
1117        // quote names a state, not content, and every pointer state — creation
1118        // or update — is paid for, so it is never already stored.
1119        //
1120        // The match intentionally logs the error when the `logging` feature is
1121        // active. Clippy suggests `unwrap_or_default()` when logging is compiled
1122        // out, but keeping the explicit match preserves the diagnostic intent.
1123        #[allow(clippy::manual_unwrap_or_default)]
1124        let already_stored = request.data_type == DATA_TYPE_CHUNK
1125            && match self.storage.exists(&request.address) {
1126                Ok(exists) => exists,
1127                Err(e) => {
1128                    warn!("Storage check failed for {addr_hex}: {e}");
1129                    false // Assume not stored on error — generate a normal quote.
1130                }
1131            };
1132
1133        if already_stored {
1134            debug!("Chunk {addr_hex} already stored — returning quote with already_stored=true");
1135        }
1136
1137        // Validate data size - data_size is u64, cast carefully and reject overflow
1138        let Ok(data_size_usize) = usize::try_from(request.data_size) else {
1139            return ChunkQuoteResponse::Error(ProtocolError::ChunkTooLarge {
1140                size: MAX_CHUNK_SIZE + 1,
1141                max_size: MAX_CHUNK_SIZE,
1142            });
1143        };
1144        if data_size_usize > MAX_CHUNK_SIZE {
1145            return ChunkQuoteResponse::Error(ProtocolError::ChunkTooLarge {
1146                size: data_size_usize,
1147                max_size: MAX_CHUNK_SIZE,
1148            });
1149        }
1150
1151        match self
1152            .quote_generator
1153            .create_quote(request.address, data_size_usize, request.data_type)
1154        {
1155            Ok(quote) => {
1156                // ADR-0004: ship the signed commitment the price was bound to
1157                // alongside the quote ("the commitment arrived with the quote"),
1158                // so the client can verify the binding before paying and forward
1159                // it as a sidecar in the PUT bundle. Only a commitment-bound
1160                // quote pins anything; a baseline `(0, None)` quote carries no
1161                // commitment. A pin that has rotated out resolves to `None` and
1162                // the client falls back to gossip/fetch.
1163                let commitment = quote
1164                    .commitment_pin
1165                    .and_then(|pin| self.quote_generator.commitment_blob_for_pin(pin));
1166                // Serialize the quote
1167                match rmp_serde::to_vec(&quote) {
1168                    Ok(quote_bytes) => ChunkQuoteResponse::Success {
1169                        quote: quote_bytes,
1170                        already_stored,
1171                        commitment,
1172                    },
1173                    Err(e) => ChunkQuoteResponse::Error(ProtocolError::QuoteFailed(format!(
1174                        "Failed to serialize quote: {e}"
1175                    ))),
1176                }
1177            }
1178            Err(e) => ChunkQuoteResponse::Error(ProtocolError::QuoteFailed(e.to_string())),
1179        }
1180    }
1181
1182    /// Handle a version-declaring storage quote request.
1183    ///
1184    /// Refuse first, then fall through to the existing unversioned handler
1185    /// with the same request. The gate is the only difference between the two
1186    /// paths, so nothing else is duplicated and the two cannot drift.
1187    fn handle_quote_v2(&self, request: &ChunkQuoteRequestV2) -> ChunkQuoteResponse {
1188        if let Some(refusal) = settlement_gate(request.settlement_version, "single_node") {
1189            return ChunkQuoteResponse::Error(refusal);
1190        }
1191        self.handle_quote(&ChunkQuoteRequest {
1192            address: request.address,
1193            data_size: request.data_size,
1194            data_type: request.data_type,
1195        })
1196    }
1197
1198    /// Handle a version-declaring merkle candidate quote request.
1199    ///
1200    /// The gate matters most here: a merkle batch settles on-chain before any
1201    /// storer sees a PUT, so this is the last point at which refusing costs
1202    /// the client nothing.
1203    fn handle_merkle_candidate_quote_v2(
1204        &self,
1205        request: &MerkleCandidateQuoteRequestV2,
1206    ) -> MerkleCandidateQuoteResponse {
1207        if let Some(refusal) = settlement_gate(request.settlement_version, "merkle") {
1208            return MerkleCandidateQuoteResponse::Error(refusal);
1209        }
1210        self.handle_merkle_candidate_quote(&MerkleCandidateQuoteRequest {
1211            address: request.address,
1212            data_type: request.data_type,
1213            data_size: request.data_size,
1214            merkle_payment_timestamp: request.merkle_payment_timestamp,
1215        })
1216    }
1217
1218    /// Record that a client asked for a quote without declaring a settlement
1219    /// version, and periodically report the running count.
1220    ///
1221    /// Unversioned requests are still served. A node cannot tell a client that
1222    /// settles correctly but predates the version field from one that does
1223    /// not, and refusing both would break clients that are behaving. What the
1224    /// count buys is the evidence for flipping that policy later: once
1225    /// unversioned traffic has decayed, refusing it stops turning away only
1226    /// the clients that were already going to lose their money.
1227    fn note_unversioned_quote(path: &str) {
1228        let slot = usize::from(path == "merkle");
1229        let Some(counter) = UNVERSIONED_QUOTE_REQUESTS.get(slot) else {
1230            return;
1231        };
1232        let seen = counter.fetch_add(1, Ordering::Relaxed).saturating_add(1);
1233        if seen % UNVERSIONED_QUOTE_LOG_INTERVAL == 0 {
1234            info!(
1235                target: "ant_node::quote::settlement",
1236                "Received {seen} {path} quote requests from clients that declare no \
1237                 settlement version. These clients cannot be told to upgrade before \
1238                 they pay.",
1239            );
1240        }
1241    }
1242
1243    /// Handle a merkle candidate quote request.
1244    fn handle_merkle_candidate_quote(
1245        &self,
1246        request: &MerkleCandidateQuoteRequest,
1247    ) -> MerkleCandidateQuoteResponse {
1248        let addr_hex = hex::encode(request.address);
1249        let data_size = request.data_size;
1250        debug!(
1251            "Handling merkle candidate quote request for {addr_hex} (size: {data_size}, ts: {})",
1252            request.merkle_payment_timestamp
1253        );
1254
1255        // Price on records ACTUALLY HELD, not a monotonic store counter.
1256        self.resync_quote_metric();
1257
1258        let Ok(data_size_usize) = usize::try_from(request.data_size) else {
1259            return MerkleCandidateQuoteResponse::Error(ProtocolError::QuoteFailed(format!(
1260                "data_size {} overflows usize",
1261                request.data_size
1262            )));
1263        };
1264        if data_size_usize > MAX_CHUNK_SIZE {
1265            return MerkleCandidateQuoteResponse::Error(ProtocolError::ChunkTooLarge {
1266                size: data_size_usize,
1267                max_size: MAX_CHUNK_SIZE,
1268            });
1269        }
1270
1271        match self.quote_generator.create_merkle_candidate_quote(
1272            data_size_usize,
1273            request.data_type,
1274            request.merkle_payment_timestamp,
1275        ) {
1276            Ok(candidate_node) => {
1277                // ADR-0004: ship the signed commitment this candidate priced
1278                // against, so the client can verify the binding before paying
1279                // and forward it as a sidecar. Baseline candidates ship none.
1280                let commitment = candidate_node
1281                    .commitment_pin
1282                    .and_then(|pin| self.quote_generator.commitment_blob_for_pin(pin));
1283                match rmp_serde::to_vec(&candidate_node) {
1284                    Ok(bytes) => MerkleCandidateQuoteResponse::Success {
1285                        candidate_node: bytes,
1286                        commitment,
1287                    },
1288                    Err(e) => MerkleCandidateQuoteResponse::Error(ProtocolError::QuoteFailed(
1289                        format!("Failed to serialize merkle candidate node: {e}"),
1290                    )),
1291                }
1292            }
1293            Err(e) => {
1294                MerkleCandidateQuoteResponse::Error(ProtocolError::QuoteFailed(e.to_string()))
1295            }
1296        }
1297    }
1298
1299    /// Get storage statistics.
1300    #[must_use]
1301    pub fn storage_stats(&self) -> crate::storage::StorageStats {
1302        self.storage.stats()
1303    }
1304
1305    /// Get payment cache statistics.
1306    #[must_use]
1307    pub fn payment_cache_stats(&self) -> crate::payment::CacheStats {
1308        self.payment_verifier.cache_stats()
1309    }
1310
1311    /// Get a reference to the payment verifier.
1312    ///
1313    /// Exposed for **test harnesses only** — production code should not call
1314    /// this directly. Use `cache_insert()` on the returned verifier to
1315    /// pre-populate the payment cache in test setups.
1316    #[cfg(any(test, feature = "test-utils"))]
1317    #[must_use]
1318    pub fn payment_verifier(&self) -> &PaymentVerifier {
1319        &self.payment_verifier
1320    }
1321
1322    /// Check if a chunk exists locally.
1323    ///
1324    /// # Errors
1325    ///
1326    /// Returns an error if the storage read fails.
1327    pub fn exists(&self, address: &[u8; 32]) -> Result<bool> {
1328        self.storage.exists(address)
1329    }
1330
1331    /// Get a chunk directly from local storage.
1332    ///
1333    /// # Errors
1334    ///
1335    /// Returns an error if storage access fails.
1336    pub async fn get_local(&self, address: &[u8; 32]) -> Result<Option<Vec<u8>>> {
1337        self.storage.get(address).await
1338    }
1339
1340    /// Store a chunk directly to local storage (bypasses payment verification).
1341    ///
1342    /// TEST ONLY - This method bypasses payment verification and should only be used in tests.
1343    ///
1344    /// # Errors
1345    ///
1346    /// Returns an error if storage fails or content doesn't match address.
1347    #[cfg(test)]
1348    pub async fn put_local(&self, address: &[u8; 32], content: &[u8]) -> Result<bool> {
1349        self.storage.put(address, content).await
1350    }
1351}
1352
1353#[cfg(test)]
1354#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1355mod tests {
1356    use super::*;
1357    use crate::payment::metrics::QuotingMetricsTracker;
1358    use crate::payment::{EvmVerifierConfig, PaymentVerifierConfig};
1359    use crate::pointer::{DATA_TYPE_POINTER, POINTER_WIRE_LEN};
1360    use crate::storage::ChunkStoreConfig;
1361    use evmlib::RewardsAddress;
1362    use saorsa_core::identity::NodeIdentity;
1363    use saorsa_core::MlDsa65;
1364    use saorsa_pqc::pqc::types::MlDsaSecretKey;
1365    use tempfile::TempDir;
1366
1367    async fn create_test_protocol() -> (AntProtocol, TempDir) {
1368        // `test_default()` sets `disk_reserve: 0`, so the disk pre-check always
1369        // passes for the regular tests.
1370        create_test_protocol_with_reserve(0).await
1371    }
1372
1373    /// Build a test protocol whose storage enforces the given disk reserve.
1374    ///
1375    /// A very large reserve (e.g. `u64::MAX`) makes `available < reserve`
1376    /// always true, so the disk-space pre-check in `handle_put_inner` fails —
1377    /// used to exercise the V2-411 early-return path.
1378    async fn create_test_protocol_with_reserve(disk_reserve: u64) -> (AntProtocol, TempDir) {
1379        let temp_dir = TempDir::new().expect("create temp dir");
1380
1381        let storage_config = ChunkStoreConfig {
1382            root_dir: temp_dir.path().to_path_buf(),
1383            disk_reserve,
1384            ..ChunkStoreConfig::test_default()
1385        };
1386        let storage = Arc::new(
1387            ChunkStore::new(storage_config)
1388                .await
1389                .expect("create storage"),
1390        );
1391
1392        let rewards_address = RewardsAddress::new([1u8; 20]);
1393        let payment_config = PaymentVerifierConfig {
1394            evm: EvmVerifierConfig::default(),
1395            cache_capacity: 100_000,
1396            close_group_size: crate::ant_protocol::CLOSE_GROUP_SIZE,
1397            local_rewards_address: rewards_address,
1398            price_floor: crate::payment::PriceFloorConfig::default(),
1399        };
1400        let payment_verifier = Arc::new(PaymentVerifier::new(payment_config));
1401        let metrics_tracker = QuotingMetricsTracker::new(100);
1402        let mut quote_generator = QuoteGenerator::new(rewards_address, metrics_tracker);
1403
1404        // Wire ML-DSA-65 signing so quote requests succeed
1405        let identity = NodeIdentity::generate().expect("generate identity");
1406        let pub_key_bytes = identity.public_key().as_bytes().to_vec();
1407        let sk_bytes = identity.secret_key_bytes().to_vec();
1408        let sk = MlDsaSecretKey::from_bytes(&sk_bytes).expect("deserialize secret key");
1409        quote_generator.set_signer(pub_key_bytes, move |msg| {
1410            use saorsa_pqc::pqc::MlDsaOperations;
1411            let ml_dsa = MlDsa65::new();
1412            ml_dsa
1413                .sign(&sk, msg)
1414                .map_or_else(|_| vec![], |sig| sig.as_bytes().to_vec())
1415        });
1416
1417        let protocol = AntProtocol::new(storage, payment_verifier, Arc::new(quote_generator));
1418        (protocol, temp_dir)
1419    }
1420
1421    #[tokio::test]
1422    async fn test_put_and_get_chunk() {
1423        let (protocol, _temp) = create_test_protocol().await;
1424
1425        let content = b"hello world";
1426        let address = ChunkStore::compute_address(content);
1427
1428        // Pre-populate payment cache so EVM verification is bypassed
1429        protocol.payment_verifier().cache_insert(address);
1430
1431        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
1432        let put_msg = ChunkMessage {
1433            request_id: 1,
1434            body: ChunkMessageBody::PutRequest(put_request),
1435        };
1436        let put_bytes = put_msg.encode().expect("encode put");
1437
1438        // Handle PUT
1439        let response_bytes = protocol
1440            .try_handle_request(&put_bytes)
1441            .await
1442            .expect("handle put")
1443            .expect("expected response");
1444        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
1445
1446        assert_eq!(response.request_id, 1);
1447        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Success { address: addr }) =
1448            response.body
1449        {
1450            assert_eq!(addr, address);
1451        } else {
1452            panic!("expected PutResponse::Success, got: {response:?}");
1453        }
1454
1455        // Create GET request
1456        let get_request = ChunkGetRequest::new(address);
1457        let get_msg = ChunkMessage {
1458            request_id: 2,
1459            body: ChunkMessageBody::GetRequest(get_request),
1460        };
1461        let get_bytes = get_msg.encode().expect("encode get");
1462
1463        // Handle GET with the same local context the authenticated router adds.
1464        let handled = protocol
1465            .try_handle_request_with_context(
1466                &get_bytes,
1467                Some(ChunkRequestContext::new(
1468                    "peer-success".to_string(),
1469                    Instant::now(),
1470                    Duration::from_millis(4),
1471                )),
1472            )
1473            .await;
1474        let telemetry = handled.get_telemetry.expect("GET telemetry");
1475        assert_eq!(telemetry.source_peer, "peer-success");
1476        assert_eq!(telemetry.request_id, 2);
1477        assert_eq!(telemetry.chunk_address, hex::encode(address));
1478        assert_eq!(telemetry.queue_wait_ms, 4);
1479        assert_eq!(telemetry.storage_outcome, "success");
1480        assert_eq!(telemetry.storage_error_category, "none");
1481
1482        let response_bytes = handled
1483            .response
1484            .expect("handle get")
1485            .expect("expected response");
1486        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
1487
1488        assert_eq!(response.request_id, 2);
1489        if let ChunkMessageBody::GetResponse(ChunkGetResponse::Success {
1490            address: addr,
1491            content: data,
1492        }) = response.body
1493        {
1494            assert_eq!(addr, address);
1495            assert_eq!(data, content.to_vec());
1496        } else {
1497            panic!("expected GetResponse::Success");
1498        }
1499        telemetry.finish_send(Duration::from_millis(2), true);
1500    }
1501
1502    #[tokio::test]
1503    async fn typed_put_preserves_native_validation_and_storage() {
1504        let (protocol, _temp) = create_test_protocol().await;
1505        let content = Bytes::from(vec![0x5a; MAX_CHUNK_SIZE]);
1506        let address = ChunkStore::compute_address(&content);
1507
1508        // Typed callers still encounter content, size, and payment admission.
1509        for (request_id, request) in [
1510            (1, ChunkPutRequest::new([0; 32], content.clone())),
1511            (
1512                2,
1513                ChunkPutRequest::new(address, Bytes::from(vec![0; MAX_CHUNK_SIZE + 1])),
1514            ),
1515            (3, ChunkPutRequest::new(address, content.clone())),
1516        ] {
1517            let message = ChunkMessage {
1518                request_id,
1519                body: ChunkMessageBody::PutRequest(request),
1520            };
1521            let wire = message.encode().expect("encode request");
1522            let typed = protocol
1523                .try_handle_message(message)
1524                .await
1525                .expect("response");
1526            let native = protocol
1527                .try_handle_request(&wire)
1528                .await
1529                .expect("native request")
1530                .expect("native response");
1531            assert_eq!(typed.encode().expect("encode response"), native.as_ref());
1532            assert!(matches!(
1533                typed.body,
1534                ChunkMessageBody::PutResponse(
1535                    ChunkPutResponse::Error(_) | ChunkPutResponse::PaymentRequired { .. }
1536                )
1537            ));
1538        }
1539        assert!(protocol
1540            .storage()
1541            .get(&address)
1542            .await
1543            .expect("read")
1544            .is_none());
1545
1546        protocol.payment_verifier().cache_insert(address);
1547        let response = protocol
1548            .try_handle_message(ChunkMessage {
1549                request_id: 4,
1550                body: ChunkMessageBody::PutRequest(ChunkPutRequest::new(address, content.clone())),
1551            })
1552            .await
1553            .expect("paid response");
1554        assert_eq!(response.request_id, 4);
1555        assert!(matches!(
1556            response.body,
1557            ChunkMessageBody::PutResponse(ChunkPutResponse::Success { .. })
1558        ));
1559        assert_eq!(
1560            protocol
1561                .storage()
1562                .get(&address)
1563                .await
1564                .expect("read")
1565                .expect("stored"),
1566            content.as_ref()
1567        );
1568        assert!(protocol.try_handle_message(response).await.is_none());
1569    }
1570
1571    #[tokio::test]
1572    async fn test_get_not_found() {
1573        let (protocol, _temp) = create_test_protocol().await;
1574
1575        let address = [0xAB; 32];
1576        let get_request = ChunkGetRequest::new(address);
1577        let get_msg = ChunkMessage {
1578            request_id: 10,
1579            body: ChunkMessageBody::GetRequest(get_request),
1580        };
1581        let get_bytes = get_msg.encode().expect("encode get");
1582
1583        let response_bytes = protocol
1584            .try_handle_request(&get_bytes)
1585            .await
1586            .expect("handle get")
1587            .expect("expected response");
1588        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
1589
1590        assert_eq!(response.request_id, 10);
1591        if let ChunkMessageBody::GetResponse(ChunkGetResponse::NotFound { address: addr }) =
1592            response.body
1593        {
1594            assert_eq!(addr, address);
1595        } else {
1596            panic!("expected GetResponse::NotFound");
1597        }
1598    }
1599
1600    #[tokio::test]
1601    async fn test_get_or_closer_returns_a_held_chunk() {
1602        let (protocol, _temp) = create_test_protocol().await;
1603        let content = b"get-or-closer content";
1604        let address = compute_address(content);
1605        protocol
1606            .put_local(&address, content)
1607            .await
1608            .expect("store chunk");
1609        let request = ChunkMessage {
1610            request_id: 30,
1611            body: ChunkMessageBody::GetOrCloserRequest(ChunkGetOrCloserRequest::new(address)),
1612        };
1613
1614        let response_bytes = protocol
1615            .try_handle_request(&request.encode().expect("encode"))
1616            .await
1617            .expect("handle get-or-closer")
1618            .expect("expected response");
1619        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
1620
1621        assert_eq!(response.request_id, 30);
1622        let ChunkMessageBody::GetOrCloserResponse(ChunkGetOrCloserResponse::Found {
1623            address: found,
1624            content: found_content,
1625        }) = response.body
1626        else {
1627            panic!("expected GetOrCloserResponse::Found");
1628        };
1629        assert_eq!(found, address);
1630        assert_eq!(found_content.as_ref(), content);
1631    }
1632
1633    #[tokio::test]
1634    async fn test_get_or_closer_without_a_routing_table_is_an_error() {
1635        // A node always has a routing table; a protocol without an attached
1636        // P2P node must refuse rather than claim it knows no closer peers.
1637        let (protocol, _temp) = create_test_protocol().await;
1638        let request = ChunkMessage {
1639            request_id: 31,
1640            body: ChunkMessageBody::GetOrCloserRequest(ChunkGetOrCloserRequest::new([0xCD; 32])),
1641        };
1642
1643        let response_bytes = protocol
1644            .try_handle_request(&request.encode().expect("encode"))
1645            .await
1646            .expect("handle get-or-closer")
1647            .expect("expected response");
1648        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
1649
1650        assert!(matches!(
1651            response.body,
1652            ChunkMessageBody::GetOrCloserResponse(ChunkGetOrCloserResponse::Error(_))
1653        ));
1654    }
1655
1656    #[tokio::test]
1657    async fn test_get_telemetry_preserves_join_fields_and_response() {
1658        let (protocol, _temp) = create_test_protocol().await;
1659
1660        let address = [0xCD; 32];
1661        let request_id = 995;
1662        let get_msg = ChunkMessage {
1663            request_id,
1664            body: ChunkMessageBody::GetRequest(ChunkGetRequest::new(address)),
1665        };
1666        let get_bytes = get_msg.encode().expect("encode get");
1667        let received_at = Instant::now();
1668        let handled = protocol
1669            .try_handle_request_with_context(
1670                &get_bytes,
1671                Some(ChunkRequestContext::new(
1672                    "peer-v2-995".to_string(),
1673                    received_at,
1674                    Duration::from_millis(17),
1675                )),
1676            )
1677            .await;
1678
1679        let telemetry = handled.get_telemetry.expect("GET telemetry");
1680        assert_eq!(telemetry.request, "get");
1681        assert_eq!(telemetry.source_peer, "peer-v2-995");
1682        assert_eq!(telemetry.request_id, request_id);
1683        assert_eq!(telemetry.chunk_address, hex::encode(address));
1684        assert_eq!(telemetry.queue_wait_ms, 17);
1685        assert_eq!(telemetry.storage_outcome, "not_found");
1686        assert_eq!(telemetry.storage_error_category, "none");
1687
1688        let response_bytes = handled
1689            .response
1690            .expect("handle get")
1691            .expect("expected response");
1692        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
1693        assert_eq!(response.request_id, request_id);
1694        assert!(matches!(
1695            response.body,
1696            ChunkMessageBody::GetResponse(ChunkGetResponse::NotFound { address: found })
1697                if found == address
1698        ));
1699
1700        telemetry.finish_send(Duration::from_millis(3), true);
1701    }
1702
1703    /// A get-or-closer is a read, so it carries the same telemetry as a GET.
1704    #[tokio::test]
1705    async fn test_get_or_closer_found_carries_read_telemetry() {
1706        let (protocol, _temp) = create_test_protocol().await;
1707        let content = b"get-or-closer telemetry";
1708        let address = compute_address(content);
1709        protocol
1710            .put_local(&address, content)
1711            .await
1712            .expect("store chunk");
1713        let request_id = 996;
1714        let request = ChunkMessage {
1715            request_id,
1716            body: ChunkMessageBody::GetOrCloserRequest(ChunkGetOrCloserRequest::new(address)),
1717        };
1718
1719        let handled = protocol
1720            .try_handle_request_with_context(
1721                &request.encode().expect("encode get-or-closer"),
1722                Some(ChunkRequestContext::new(
1723                    "peer-v2-996".to_string(),
1724                    Instant::now(),
1725                    Duration::ZERO,
1726                )),
1727            )
1728            .await;
1729
1730        let telemetry = handled.get_telemetry.expect("get-or-closer telemetry");
1731        assert_eq!(telemetry.request, "get_or_closer");
1732        assert_eq!(telemetry.request_id, request_id);
1733        assert_eq!(telemetry.chunk_address, hex::encode(address));
1734        assert_eq!(telemetry.storage_outcome, "success");
1735        assert_eq!(
1736            handled.traffic_key,
1737            Some(ChunkResponseKey::GetOrCloserFound)
1738        );
1739        telemetry.finish_send(Duration::from_millis(3), true);
1740    }
1741
1742    #[tokio::test]
1743    async fn test_put_address_mismatch() {
1744        let (protocol, _temp) = create_test_protocol().await;
1745
1746        let content = b"test content";
1747        let wrong_address = [0xFF; 32]; // Wrong address
1748
1749        // Pre-populate cache for the wrong address so we test address mismatch, not payment
1750        protocol.payment_verifier().cache_insert(wrong_address);
1751
1752        let put_request = ChunkPutRequest::new(wrong_address, Bytes::copy_from_slice(content));
1753        let put_msg = ChunkMessage {
1754            request_id: 20,
1755            body: ChunkMessageBody::PutRequest(put_request),
1756        };
1757        let put_bytes = put_msg.encode().expect("encode put");
1758
1759        let response_bytes = protocol
1760            .try_handle_request(&put_bytes)
1761            .await
1762            .expect("handle put")
1763            .expect("expected response");
1764        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
1765
1766        assert_eq!(response.request_id, 20);
1767        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Error(
1768            ProtocolError::AddressMismatch { .. },
1769        )) = response.body
1770        {
1771            // Expected
1772        } else {
1773            panic!("expected AddressMismatch error, got: {response:?}");
1774        }
1775    }
1776
1777    #[tokio::test]
1778    async fn test_put_chunk_too_large() {
1779        let (protocol, _temp) = create_test_protocol().await;
1780
1781        // Create oversized content
1782        let content = vec![0u8; MAX_CHUNK_SIZE + 1];
1783        let address = ChunkStore::compute_address(&content);
1784
1785        let put_request = ChunkPutRequest::new(address, Bytes::from(content));
1786        let put_msg = ChunkMessage {
1787            request_id: 30,
1788            body: ChunkMessageBody::PutRequest(put_request),
1789        };
1790        let put_bytes = put_msg.encode().expect("encode put");
1791
1792        let response_bytes = protocol
1793            .try_handle_request(&put_bytes)
1794            .await
1795            .expect("handle put")
1796            .expect("expected response");
1797        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
1798
1799        assert_eq!(response.request_id, 30);
1800        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Error(
1801            ProtocolError::ChunkTooLarge { .. },
1802        )) = response.body
1803        {
1804            // Expected
1805        } else {
1806            panic!("expected ChunkTooLarge error");
1807        }
1808    }
1809
1810    /// A node that is genuinely full must reject a PUT with the disk-space
1811    /// error *before* running payment verification (`V2-411`).
1812    ///
1813    /// "Full" now means both halves of the predicate: the volume is below the
1814    /// reserve **and** the store has no reusable space. A freshly created store
1815    /// has no freed pages, so both hold and the pre-check short-circuits, as it
1816    /// always did. The companion cases in `storage::chunk_store::tests` cover the half
1817    /// that changed, where pruning has left reusable pages and the node must be
1818    /// admitted rather than refused on `statvfs` alone.
1819    ///
1820    /// The chunk is intentionally **not** cache-inserted, so if the handler
1821    /// reached `verify_payment` it would return `PaymentFailed` (an uncached
1822    /// chunk with no proof). Observing the `StorageFailed` disk error instead
1823    /// proves the pre-check short-circuited ahead of verification.
1824    #[tokio::test]
1825    async fn test_put_rejected_on_insufficient_capacity_before_verification() {
1826        // u64::MAX reserve guarantees `available < reserve`, and a fresh store
1827        // has no reusable pages, so the node is full on both halves.
1828        let (protocol, _temp) = create_test_protocol_with_reserve(u64::MAX).await;
1829
1830        let content = b"chunk for a disk-full node";
1831        let address = ChunkStore::compute_address(content);
1832
1833        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
1834        let put_msg = ChunkMessage {
1835            request_id: 41,
1836            body: ChunkMessageBody::PutRequest(put_request),
1837        };
1838        let put_bytes = put_msg.encode().expect("encode put");
1839
1840        let response_bytes = protocol
1841            .try_handle_request(&put_bytes)
1842            .await
1843            .expect("handle put")
1844            .expect("expected response");
1845        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
1846
1847        assert_eq!(response.request_id, 41);
1848        match response.body {
1849            ChunkMessageBody::PutResponse(ChunkPutResponse::Error(
1850                ProtocolError::StorageFailed(msg),
1851            )) => {
1852                assert!(
1853                    msg.contains("Insufficient disk space"),
1854                    "expected disk-space error, got: {msg}"
1855                );
1856            }
1857            other => {
1858                panic!("expected StorageFailed disk error before verification, got: {other:?}")
1859            }
1860        }
1861
1862        // And nothing was stored.
1863        assert!(!protocol.exists(&address).expect("exists check"));
1864    }
1865
1866    #[tokio::test]
1867    async fn test_put_already_exists() {
1868        let (protocol, _temp) = create_test_protocol().await;
1869
1870        let content = b"duplicate content";
1871        let address = ChunkStore::compute_address(content);
1872
1873        // Pre-populate cache so EVM verification is bypassed
1874        protocol.payment_verifier().cache_insert(address);
1875
1876        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
1877        let put_msg = ChunkMessage {
1878            request_id: 40,
1879            body: ChunkMessageBody::PutRequest(put_request),
1880        };
1881        let put_bytes = put_msg.encode().expect("encode put");
1882
1883        let _ = protocol
1884            .try_handle_request(&put_bytes)
1885            .await
1886            .expect("handle put");
1887
1888        // Store again - should return AlreadyExists
1889        let response_bytes = protocol
1890            .try_handle_request(&put_bytes)
1891            .await
1892            .expect("handle put 2")
1893            .expect("expected response");
1894        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
1895
1896        assert_eq!(response.request_id, 40);
1897        if let ChunkMessageBody::PutResponse(ChunkPutResponse::AlreadyExists { address: addr }) =
1898            response.body
1899        {
1900            assert_eq!(addr, address);
1901        } else {
1902            panic!("expected AlreadyExists");
1903        }
1904    }
1905
1906    #[tokio::test]
1907    async fn test_protocol_id() {
1908        let (protocol, _temp) = create_test_protocol().await;
1909        assert_eq!(protocol.protocol_id(), CHUNK_PROTOCOL_ID);
1910    }
1911
1912    #[tokio::test]
1913    async fn test_exists_and_local_access() {
1914        let (protocol, _temp) = create_test_protocol().await;
1915
1916        let content = b"local access test";
1917        let address = ChunkStore::compute_address(content);
1918
1919        assert!(!protocol.exists(&address).expect("exists check"));
1920
1921        protocol
1922            .put_local(&address, content)
1923            .await
1924            .expect("put local");
1925
1926        assert!(protocol.exists(&address).expect("exists check"));
1927
1928        let retrieved = protocol.get_local(&address).await.expect("get local");
1929        assert_eq!(retrieved, Some(content.to_vec()));
1930    }
1931
1932    #[tokio::test]
1933    async fn test_cache_insert_is_visible() {
1934        let (protocol, _temp) = create_test_protocol().await;
1935
1936        let content = b"cache test content";
1937        let address = ChunkStore::compute_address(content);
1938
1939        // Before insert: cache should be empty
1940        let stats_before = protocol.payment_cache_stats();
1941        assert_eq!(stats_before.additions, 0);
1942
1943        // Pre-populate cache
1944        protocol.payment_verifier().cache_insert(address);
1945
1946        // After insert: cache should have the xorname
1947        let stats_after = protocol.payment_cache_stats();
1948        assert_eq!(stats_after.additions, 1);
1949
1950        // PUT should succeed (cache hit)
1951        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
1952        let put_msg = ChunkMessage {
1953            request_id: 100,
1954            body: ChunkMessageBody::PutRequest(put_request),
1955        };
1956        let put_bytes = put_msg.encode().expect("encode put");
1957        let response_bytes = protocol
1958            .try_handle_request(&put_bytes)
1959            .await
1960            .expect("handle put")
1961            .expect("expected response");
1962        let response = ChunkMessage::decode(&response_bytes).expect("decode");
1963
1964        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Success { .. }) = response.body {
1965            // expected
1966        } else {
1967            panic!("expected success, got: {response:?}");
1968        }
1969    }
1970
1971    #[tokio::test]
1972    async fn test_put_same_chunk_twice_hits_cache() {
1973        let (protocol, _temp) = create_test_protocol().await;
1974
1975        let content = b"duplicate cache test";
1976        let address = ChunkStore::compute_address(content);
1977
1978        // Pre-populate cache for first PUT
1979        protocol.payment_verifier().cache_insert(address);
1980
1981        // First PUT
1982        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
1983        let put_msg = ChunkMessage {
1984            request_id: 110,
1985            body: ChunkMessageBody::PutRequest(put_request),
1986        };
1987        let put_bytes = put_msg.encode().expect("encode put");
1988        let _ = protocol
1989            .try_handle_request(&put_bytes)
1990            .await
1991            .expect("handle put 1");
1992
1993        // Second PUT should return AlreadyExists from the storage idempotency check.
1994        let response_bytes = protocol
1995            .try_handle_request(&put_bytes)
1996            .await
1997            .expect("handle put 2")
1998            .expect("expected response");
1999        let response = ChunkMessage::decode(&response_bytes).expect("decode");
2000
2001        if let ChunkMessageBody::PutResponse(ChunkPutResponse::AlreadyExists { .. }) = response.body
2002        {
2003            // expected
2004        } else {
2005            panic!("expected AlreadyExists, got: {response:?}");
2006        }
2007    }
2008
2009    #[tokio::test]
2010    async fn test_payment_cache_stats_returns_correct_values() {
2011        let (protocol, _temp) = create_test_protocol().await;
2012
2013        let stats = protocol.payment_cache_stats();
2014        assert_eq!(stats.hits, 0);
2015        assert_eq!(stats.misses, 0);
2016        assert_eq!(stats.additions, 0);
2017
2018        // Pre-populate cache, then store a chunk to test stats
2019        let content = b"stats test";
2020        let address = ChunkStore::compute_address(content);
2021        protocol.payment_verifier().cache_insert(address);
2022
2023        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
2024        let put_msg = ChunkMessage {
2025            request_id: 120,
2026            body: ChunkMessageBody::PutRequest(put_request),
2027        };
2028        let put_bytes = put_msg.encode().expect("encode put");
2029        let _ = protocol
2030            .try_handle_request(&put_bytes)
2031            .await
2032            .expect("handle put");
2033
2034        let stats = protocol.payment_cache_stats();
2035        // Should have 1 addition (from cache_insert) + 1 hit (payment verification found cache)
2036        assert_eq!(stats.additions, 1);
2037        assert_eq!(stats.hits, 1);
2038    }
2039
2040    #[tokio::test]
2041    async fn test_storage_stats() {
2042        let (protocol, _temp) = create_test_protocol().await;
2043        let stats = protocol.storage_stats();
2044        assert_eq!(stats.chunks_stored, 0);
2045    }
2046
2047    #[tokio::test]
2048    async fn test_merkle_candidate_quote_request() {
2049        use ant_protocol::payment::verify::verify_merkle_candidate_signature;
2050        use evmlib::merkle_payments::MerklePaymentCandidateNode;
2051
2052        // create_test_protocol already wires ML-DSA-65 signing
2053        let (protocol, _temp) = create_test_protocol().await;
2054
2055        let address = [0x77; 32];
2056        let timestamp = std::time::SystemTime::now()
2057            .duration_since(std::time::UNIX_EPOCH)
2058            .expect("system time")
2059            .as_secs();
2060
2061        let request = MerkleCandidateQuoteRequest {
2062            address,
2063            data_type: DATA_TYPE_CHUNK,
2064            data_size: 4096,
2065            merkle_payment_timestamp: timestamp,
2066        };
2067        let msg = ChunkMessage {
2068            request_id: 600,
2069            body: ChunkMessageBody::MerkleCandidateQuoteRequest(request),
2070        };
2071        let msg_bytes = msg.encode().expect("encode request");
2072
2073        let response_bytes = protocol
2074            .try_handle_request(&msg_bytes)
2075            .await
2076            .expect("handle merkle candidate quote")
2077            .expect("expected response");
2078        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
2079
2080        assert_eq!(response.request_id, 600);
2081        match response.body {
2082            ChunkMessageBody::MerkleCandidateQuoteResponse(
2083                MerkleCandidateQuoteResponse::Success { candidate_node, .. },
2084            ) => {
2085                let candidate: MerklePaymentCandidateNode =
2086                    rmp_serde::from_slice(&candidate_node).expect("deserialize candidate node");
2087
2088                // Verify ML-DSA-65 signature
2089                assert!(
2090                    verify_merkle_candidate_signature(&candidate),
2091                    "ML-DSA-65 candidate signature must be valid"
2092                );
2093
2094                assert_eq!(candidate.merkle_payment_timestamp, timestamp);
2095                // Node-calculated price based on records stored
2096                assert!(candidate.price >= evmlib::common::Amount::ZERO);
2097            }
2098            other => panic!("expected MerkleCandidateQuoteResponse::Success, got: {other:?}"),
2099        }
2100    }
2101
2102    /// A current client gets a quote through the versioned request, exactly as
2103    /// it would through the legacy one. The gate must be invisible to clients
2104    /// that can pay.
2105    #[tokio::test]
2106    async fn v2_merkle_quote_is_served_at_the_current_settlement_version() {
2107        let (protocol, _temp) = create_test_protocol().await;
2108        let timestamp = std::time::SystemTime::now()
2109            .duration_since(std::time::UNIX_EPOCH)
2110            .expect("system time")
2111            .as_secs();
2112
2113        let msg = ChunkMessage {
2114            request_id: 700,
2115            body: ChunkMessageBody::MerkleCandidateQuoteRequestV2(
2116                MerkleCandidateQuoteRequestV2::new([0x88; 32], 4096, timestamp),
2117            ),
2118        };
2119        let response_bytes = protocol
2120            .try_handle_request(&msg.encode().expect("encode request"))
2121            .await
2122            .expect("handle v2 merkle candidate quote")
2123            .expect("expected response");
2124        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
2125
2126        assert_eq!(response.request_id, 700);
2127        match response.body {
2128            ChunkMessageBody::MerkleCandidateQuoteResponse(
2129                MerkleCandidateQuoteResponse::Success { .. },
2130            ) => {}
2131            other => panic!("expected Success, got: {other:?}"),
2132        }
2133    }
2134
2135    /// The point of the whole change: a client that cannot settle correctly is
2136    /// turned away at quote time, so it never reaches the on-chain payment it
2137    /// would not be able to spend.
2138    #[tokio::test]
2139    async fn v2_merkle_quote_is_refused_below_the_minimum_settlement_version() {
2140        let (protocol, _temp) = create_test_protocol().await;
2141        let timestamp = std::time::SystemTime::now()
2142            .duration_since(std::time::UNIX_EPOCH)
2143            .expect("system time")
2144            .as_secs();
2145
2146        let stale = MIN_SUPPORTED_SETTLEMENT_VERSION.saturating_sub(1);
2147        let mut request = MerkleCandidateQuoteRequestV2::new([0x99; 32], 4096, timestamp);
2148        request.settlement_version = stale;
2149
2150        let msg = ChunkMessage {
2151            request_id: 701,
2152            body: ChunkMessageBody::MerkleCandidateQuoteRequestV2(request),
2153        };
2154        let response_bytes = protocol
2155            .try_handle_request(&msg.encode().expect("encode request"))
2156            .await
2157            .expect("handle v2 merkle candidate quote")
2158            .expect("expected response");
2159        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
2160
2161        match response.body {
2162            ChunkMessageBody::MerkleCandidateQuoteResponse(
2163                MerkleCandidateQuoteResponse::Error(ProtocolError::ClientUpdateRequired {
2164                    client_settlement_version,
2165                    min_settlement_version,
2166                }),
2167            ) => {
2168                assert_eq!(client_settlement_version, stale);
2169                assert_eq!(min_settlement_version, MIN_SUPPORTED_SETTLEMENT_VERSION);
2170                // The refusal has to be actionable, not just correct.
2171                let rendered = ProtocolError::ClientUpdateRequired {
2172                    client_settlement_version,
2173                    min_settlement_version,
2174                }
2175                .to_string();
2176                assert!(rendered.contains("ant update"), "{rendered}");
2177            }
2178            other => panic!("expected ClientUpdateRequired, got: {other:?}"),
2179        }
2180    }
2181
2182    /// Same gate on the single-node path, so a refused merkle client cannot
2183    /// simply fall back to per-chunk quotes and burn money that way instead.
2184    #[tokio::test]
2185    async fn v2_single_node_quote_is_refused_below_the_minimum_settlement_version() {
2186        let (protocol, _temp) = create_test_protocol().await;
2187
2188        let mut request = ChunkQuoteRequestV2::new([0xAA; 32], 4096);
2189        request.settlement_version = MIN_SUPPORTED_SETTLEMENT_VERSION.saturating_sub(1);
2190
2191        let msg = ChunkMessage {
2192            request_id: 702,
2193            body: ChunkMessageBody::QuoteRequestV2(request),
2194        };
2195        let response_bytes = protocol
2196            .try_handle_request(&msg.encode().expect("encode request"))
2197            .await
2198            .expect("handle v2 quote")
2199            .expect("expected response");
2200        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
2201
2202        match response.body {
2203            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Error(
2204                ProtocolError::ClientUpdateRequired { .. },
2205            )) => {}
2206            other => panic!("expected ClientUpdateRequired, got: {other:?}"),
2207        }
2208    }
2209
2210    /// A settlement version this node has never heard of is refused, because
2211    /// quoting it would promise to accept a payment whose rules the verifier
2212    /// does not know. That promise would be broken at PUT time, which is after
2213    /// the client has settled on-chain and can no longer be refunded.
2214    ///
2215    /// It must be refused as `StorerUpdateRequired`, not `ClientUpdateRequired`.
2216    /// The client is fine; this node is behind. Telling an up-to-date user to
2217    /// upgrade would be wrong, and during a client-first rollout it would be
2218    /// wrong for most of the fleet at once.
2219    #[tokio::test]
2220    async fn a_newer_settlement_version_is_refused_as_this_nodes_fault() {
2221        let (protocol, _temp) = create_test_protocol().await;
2222
2223        let mut request = ChunkQuoteRequestV2::new([0xBB; 32], 4096);
2224        request.settlement_version = CURRENT_SETTLEMENT_VERSION.saturating_add(1);
2225
2226        let msg = ChunkMessage {
2227            request_id: 703,
2228            body: ChunkMessageBody::QuoteRequestV2(request),
2229        };
2230        let response_bytes = protocol
2231            .try_handle_request(&msg.encode().expect("encode request"))
2232            .await
2233            .expect("handle v2 quote")
2234            .expect("expected response");
2235        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
2236
2237        match response.body {
2238            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Error(
2239                ProtocolError::StorerUpdateRequired {
2240                    client_settlement_version,
2241                    node_settlement_version,
2242                },
2243            )) => {
2244                assert_eq!(
2245                    client_settlement_version,
2246                    CURRENT_SETTLEMENT_VERSION.saturating_add(1)
2247                );
2248                assert_eq!(node_settlement_version, CURRENT_SETTLEMENT_VERSION);
2249            }
2250            other => panic!("expected StorerUpdateRequired, got: {other:?}"),
2251        }
2252    }
2253
2254    /// Legacy requests keep working. A node cannot tell a client that settles
2255    /// correctly but predates the version field from one that does not, so
2256    /// refusing both would break clients that are behaving.
2257    #[tokio::test]
2258    async fn unversioned_requests_are_still_served() {
2259        let (protocol, _temp) = create_test_protocol().await;
2260        let timestamp = std::time::SystemTime::now()
2261            .duration_since(std::time::UNIX_EPOCH)
2262            .expect("system time")
2263            .as_secs();
2264
2265        let msg = ChunkMessage {
2266            request_id: 704,
2267            body: ChunkMessageBody::MerkleCandidateQuoteRequest(MerkleCandidateQuoteRequest {
2268                address: [0xCC; 32],
2269                data_type: DATA_TYPE_CHUNK,
2270                data_size: 4096,
2271                merkle_payment_timestamp: timestamp,
2272            }),
2273        };
2274        let response_bytes = protocol
2275            .try_handle_request(&msg.encode().expect("encode request"))
2276            .await
2277            .expect("handle legacy merkle candidate quote")
2278            .expect("expected response");
2279        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
2280
2281        match response.body {
2282            ChunkMessageBody::MerkleCandidateQuoteResponse(
2283                MerkleCandidateQuoteResponse::Success { .. },
2284            ) => {}
2285            other => panic!("expected Success for a legacy request, got: {other:?}"),
2286        }
2287    }
2288
2289    #[tokio::test]
2290    async fn test_handle_unexpected_response_message() {
2291        let (protocol, _temp) = create_test_protocol().await;
2292
2293        // Send a PutResponse as if it were a request — should return None
2294        let msg = ChunkMessage {
2295            request_id: 200,
2296            body: ChunkMessageBody::PutResponse(ChunkPutResponse::Success { address: [0u8; 32] }),
2297        };
2298        let msg_bytes = msg.encode().expect("encode");
2299
2300        let result = protocol
2301            .try_handle_request(&msg_bytes)
2302            .await
2303            .expect("handle msg");
2304
2305        assert!(
2306            result.is_none(),
2307            "expected None for response message, got: {result:?}"
2308        );
2309    }
2310
2311    #[tokio::test]
2312    async fn a_stored_chunk_does_not_suppress_a_pointer_quote() {
2313        // A pointer quote names a state, not content. If a chunk sitting at
2314        // that address could set `already_stored`, a majority of nodes would
2315        // tell the client to skip payment and the write would then be refused
2316        // as unpaid. Only chunks may answer from the chunk store.
2317        let (protocol, _temp) = create_test_protocol().await;
2318
2319        let content = b"a chunk that shares a pointer state address";
2320        let address = ChunkStore::compute_address(content);
2321        protocol.payment_verifier().cache_insert(address);
2322        let put_msg = ChunkMessage {
2323            request_id: 320,
2324            body: ChunkMessageBody::PutRequest(ChunkPutRequest::new(
2325                address,
2326                Bytes::copy_from_slice(content),
2327            )),
2328        };
2329        let put_bytes = put_msg.encode().expect("encode put");
2330        let _ = protocol
2331            .try_handle_request(&put_bytes)
2332            .await
2333            .expect("handle put");
2334
2335        let quote_msg = ChunkMessage {
2336            request_id: 321,
2337            body: ChunkMessageBody::QuoteRequest(ChunkQuoteRequest {
2338                address,
2339                data_size: POINTER_WIRE_LEN as u64,
2340                data_type: DATA_TYPE_POINTER,
2341            }),
2342        };
2343        let quote_bytes = quote_msg.encode().expect("encode quote");
2344        let response_bytes = protocol
2345            .try_handle_request(&quote_bytes)
2346            .await
2347            .expect("handle quote")
2348            .expect("expected response");
2349
2350        match ChunkMessage::decode(&response_bytes).expect("decode").body {
2351            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Success {
2352                already_stored, ..
2353            }) => assert!(
2354                !already_stored,
2355                "a chunk must not answer for a pointer state"
2356            ),
2357            other => panic!("expected a quote, got: {other:?}"),
2358        }
2359    }
2360
2361    #[tokio::test]
2362    async fn test_quote_already_stored_flag() {
2363        let (protocol, _temp) = create_test_protocol().await;
2364
2365        let content = b"already stored quote test";
2366        let address = ChunkStore::compute_address(content);
2367
2368        // Store the chunk first
2369        protocol.payment_verifier().cache_insert(address);
2370        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
2371        let put_msg = ChunkMessage {
2372            request_id: 300,
2373            body: ChunkMessageBody::PutRequest(put_request),
2374        };
2375        let put_bytes = put_msg.encode().expect("encode put");
2376        let _ = protocol
2377            .try_handle_request(&put_bytes)
2378            .await
2379            .expect("handle put");
2380
2381        // Now request a quote for the same address — already_stored should be true
2382        let quote_request = ChunkQuoteRequest {
2383            address,
2384            data_size: content.len() as u64,
2385            data_type: DATA_TYPE_CHUNK,
2386        };
2387        let quote_msg = ChunkMessage {
2388            request_id: 301,
2389            body: ChunkMessageBody::QuoteRequest(quote_request),
2390        };
2391        let quote_bytes = quote_msg.encode().expect("encode quote");
2392        let response_bytes = protocol
2393            .try_handle_request(&quote_bytes)
2394            .await
2395            .expect("handle quote")
2396            .expect("expected response");
2397        let response = ChunkMessage::decode(&response_bytes).expect("decode");
2398
2399        match response.body {
2400            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Success {
2401                already_stored, ..
2402            }) => {
2403                assert!(
2404                    already_stored,
2405                    "already_stored should be true for existing chunk"
2406                );
2407            }
2408            other => panic!("expected Success with already_stored, got: {other:?}"),
2409        }
2410
2411        // Request a quote for a chunk that does NOT exist — already_stored should be false
2412        let new_address = [0xFFu8; 32];
2413        let quote_request2 = ChunkQuoteRequest {
2414            address: new_address,
2415            data_size: 100,
2416            data_type: DATA_TYPE_CHUNK,
2417        };
2418        let quote_msg2 = ChunkMessage {
2419            request_id: 302,
2420            body: ChunkMessageBody::QuoteRequest(quote_request2),
2421        };
2422        let quote_bytes2 = quote_msg2.encode().expect("encode quote2");
2423        let response_bytes2 = protocol
2424            .try_handle_request(&quote_bytes2)
2425            .await
2426            .expect("handle quote2")
2427            .expect("expected response");
2428        let response2 = ChunkMessage::decode(&response_bytes2).expect("decode2");
2429
2430        match response2.body {
2431            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Success {
2432                already_stored, ..
2433            }) => {
2434                assert!(
2435                    !already_stored,
2436                    "already_stored should be false for new chunk"
2437                );
2438            }
2439            other => panic!("expected Success with already_stored=false, got: {other:?}"),
2440        }
2441    }
2442
2443    /// Drive the real quote handler, then read the record count it priced on.
2444    /// The handler calls `resync_quote_metric` first, so this reflects records
2445    /// ACTUALLY HELD.
2446    fn priced_records_after_quote(protocol: &AntProtocol) -> usize {
2447        let quote_request = ChunkQuoteRequest {
2448            address: [0xAAu8; 32], // a quote-only probe, not one of the stored chunks
2449            data_size: 100,
2450            data_type: DATA_TYPE_CHUNK,
2451        };
2452        let _ = protocol.handle_quote(&quote_request);
2453        protocol.priced_records_stored()
2454    }
2455
2456    /// The quote price must track records ACTUALLY HELD: deleting stored chunks
2457    /// must lower the priced record count, not keep quoting as if the data were
2458    /// still held. Exercises the storage-driven resync in `resync_quote_metric`.
2459    #[tokio::test]
2460    async fn test_quote_metric_reflects_deletions() {
2461        let (protocol, _temp) = create_test_protocol().await;
2462
2463        // Distinct content -> distinct content-addressed keys.
2464        let contents: Vec<Vec<u8>> = (0u8..5).map(|i| vec![i; 64]).collect();
2465        let mut addresses = Vec::new();
2466        for content in &contents {
2467            let addr = ChunkStore::compute_address(content);
2468            protocol.put_local(&addr, content).await.expect("put_local");
2469            addresses.push(addr);
2470        }
2471
2472        // 5 records held -> priced count 5.
2473        assert_eq!(priced_records_after_quote(&protocol), 5);
2474
2475        // Delete 2 chunks the node was holding.
2476        for addr in addresses.iter().take(2) {
2477            assert!(protocol.storage().delete(addr).await.expect("delete"));
2478        }
2479        assert_eq!(priced_records_after_quote(&protocol), 3);
2480
2481        // Delete the rest; priced count floors at 0, never underflows.
2482        for addr in addresses.iter().skip(2) {
2483            assert!(protocol.storage().delete(addr).await.expect("delete"));
2484        }
2485        assert_eq!(priced_records_after_quote(&protocol), 0);
2486    }
2487
2488    /// Stronger, externally-observable proof: the actual quote PRICE returned
2489    /// to a client must drop after the node deletes data it held. A monotonic
2490    /// store counter would keep the price elevated; the resync ties price to
2491    /// records actually held.
2492    /// FLIPS IF: `resync_quote_metric` is removed — the price would stay at the
2493    /// 10-record level even after deletions (`record_store` only ever increments).
2494    #[tokio::test]
2495    async fn test_quote_price_drops_after_deletion() {
2496        use crate::payment::pricing::calculate_price;
2497
2498        let (protocol, _temp) = create_test_protocol().await;
2499        let contents: Vec<Vec<u8>> = (0u8..10).map(|i| vec![i; 64]).collect();
2500        let mut addresses = Vec::new();
2501        for content in &contents {
2502            let addr = ChunkStore::compute_address(content);
2503            protocol.put_local(&addr, content).await.expect("put_local");
2504            addresses.push(addr);
2505        }
2506
2507        // Drive a real quote; the priced count must equal records held (10),
2508        // and the price must equal calculate_price(10) — the externally
2509        // observable contract.
2510        assert_eq!(priced_records_after_quote(&protocol), 10);
2511        let price_full = calculate_price(10);
2512
2513        // Delete 8 of 10 held chunks.
2514        for addr in addresses.iter().take(8) {
2515            assert!(protocol.storage().delete(addr).await.expect("delete"));
2516        }
2517        // The next quote must price on 2 records, and the price must be the
2518        // calculate_price(2) value — strictly different from the 10-record
2519        // price (price is monotonic non-decreasing in records_stored).
2520        assert_eq!(priced_records_after_quote(&protocol), 2);
2521        let price_after = calculate_price(2);
2522        assert!(
2523            price_after < price_full,
2524            "deleting data must lower the observable quote price \
2525             (full={price_full:?}, after={price_after:?})"
2526        );
2527    }
2528
2529    /// ADR-0004: `strip_commitment_sidecars` removes sidecars from a single-node
2530    /// proof before replication/persistence (stored proofs do not grow), and is
2531    /// a no-op on a sidecar-free proof.
2532    #[test]
2533    fn strip_commitment_sidecars_clears_single_node_sidecars() {
2534        use crate::payment::proof::{
2535            deserialize_single_node_proof, serialize_single_node_proof, PaymentProof,
2536        };
2537        use evmlib::ProofOfPayment;
2538
2539        let with_sidecars = PaymentProof {
2540            proof_of_payment: ProofOfPayment {
2541                peer_quotes: vec![],
2542            },
2543            tx_hashes: vec![],
2544            commitment_sidecars: vec![vec![1u8; 16], vec![2u8; 16]],
2545        };
2546        let bytes = serialize_single_node_proof(&with_sidecars).expect("serialize");
2547        let stripped = AntProtocol::strip_commitment_sidecars(bytes);
2548        let parsed = deserialize_single_node_proof(&stripped).expect("deserialize stripped");
2549        assert!(
2550            parsed.commitment_sidecars.is_empty(),
2551            "sidecars must be stripped before replication"
2552        );
2553
2554        // Idempotent: stripping an already-sidecar-free proof returns it intact.
2555        let again = AntProtocol::strip_commitment_sidecars(stripped.clone());
2556        assert_eq!(again, stripped, "stripping a sidecar-free proof is a no-op");
2557    }
2558}