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