Skip to main content

ant_node/storage/
handler.rs

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