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