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