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    LmdbStorage│
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    ChunkGetRequest, ChunkGetResponse, ChunkMessage, ChunkMessageBody, ChunkPutRequest,
34    ChunkPutResponse, ChunkQuoteRequest, ChunkQuoteResponse, MerkleCandidateQuoteRequest,
35    MerkleCandidateQuoteResponse, ProtocolError, CHUNK_PROTOCOL_ID, MAX_CHUNK_SIZE,
36};
37use crate::client::compute_address;
38use crate::error::{Error, Result};
39use crate::logging::{debug, info, warn};
40use crate::payment::{PaymentVerifier, QuoteGenerator, VerificationContext};
41use crate::replication::admission;
42use crate::replication::config::K_BUCKET_SIZE;
43use crate::replication::fresh::FreshWriteEvent;
44use crate::storage::lmdb::LmdbStorage;
45use bytes::Bytes;
46use parking_lot::RwLock;
47use saorsa_core::P2PNode;
48use std::sync::Arc;
49use tokio::sync::mpsc;
50
51/// Width of the self-closeness gate on client PUTs (ADR-0003): a node accepts
52/// a PUT only when it is within its own local `SELF_CLOSENESS_GATE_WIDTH`
53/// closest peers to the address.
54///
55/// Set to the client's PUT fallback ceiling (`K_BUCKET_SIZE`), wider than the
56/// storage-admission width, so a client routing past full close-group members
57/// onto further peers (ADR-0002) is still accepted here, while a genuinely far
58/// node — which could only mis-attribute fresh-replication failures — is
59/// turned away.
60const SELF_CLOSENESS_GATE_WIDTH: usize = K_BUCKET_SIZE;
61
62/// ANT protocol handler.
63///
64/// Handles chunk PUT/GET/Quote requests using LMDB storage for persistence
65/// and optional payment verification.
66pub struct AntProtocol {
67    /// LMDB storage for chunk persistence.
68    storage: Arc<LmdbStorage>,
69    /// Payment verifier for checking payments.
70    payment_verifier: Arc<PaymentVerifier>,
71    /// Quote generator for creating storage quotes.
72    /// Also handles merkle candidate quote signing via ML-DSA-65.
73    quote_generator: Arc<QuoteGenerator>,
74    /// Channel for notifying the replication engine about newly-stored chunks.
75    fresh_write_tx: Option<mpsc::UnboundedSender<FreshWriteEvent>>,
76    /// The node's P2P handle, attached post-construction via
77    /// `attach_p2p_node`. Drives the self-closeness gate on client PUTs;
78    /// `None` in unit tests that never attach a node.
79    p2p_node: RwLock<Option<Arc<P2PNode>>>,
80}
81
82impl AntProtocol {
83    /// Create a new ANT protocol handler.
84    ///
85    /// # Arguments
86    ///
87    /// * `storage` - LMDB storage for chunk persistence
88    /// * `payment_verifier` - Payment verifier for validating payments
89    /// * `quote_generator` - Quote generator for creating storage quotes
90    #[must_use]
91    pub fn new(
92        storage: Arc<LmdbStorage>,
93        payment_verifier: Arc<PaymentVerifier>,
94        quote_generator: Arc<QuoteGenerator>,
95    ) -> Self {
96        // Wire the PaymentVerifier to the same authoritative store used by this
97        // protocol handler. Historically the verifier read `current_chunks()`
98        // for the paid-quote price floor; ADR-0004 retired that gate (price is
99        // bound to the live storage commitment, not the local record count), so
100        // the store is no longer consulted for pricing. The attachment is kept
101        // so any future store-backed verifier check reads the same record count
102        // this handler serves, for every AntProtocol construction path.
103        //
104        // ADR-0004: the QuoteGenerator no longer prices off `current_chunks()`
105        // — its price is bound to the live storage commitment (see
106        // `attach_commitment_source`, wired by the node once the replication
107        // engine exists), or baseline when none — so it is NOT attached to the
108        // store here.
109        payment_verifier.attach_storage(Arc::clone(&storage));
110
111        Self {
112            storage,
113            payment_verifier,
114            quote_generator,
115            fresh_write_tx: None,
116            p2p_node: RwLock::new(None),
117        }
118    }
119
120    /// Attach the node's P2P handle for payment live-DHT checks.
121    ///
122    /// Wires the handle into the payment verifier so payment-proof closeness
123    /// checks can use the live routing view. Idempotent: calling twice
124    /// replaces the verifier handle.
125    pub fn attach_p2p_node(&self, node: Arc<P2PNode>) {
126        *self.p2p_node.write() = Some(Arc::clone(&node));
127        self.payment_verifier.attach_p2p_node(node);
128        debug!("AntProtocol: P2PNode attached for payment live-DHT checks and self-closeness gate");
129    }
130
131    /// Set the channel sender for fresh-write replication events.
132    ///
133    /// When set, successful chunk PUTs will notify the replication engine
134    /// so it can fan out fresh offers to the close group.
135    pub fn set_fresh_write_sender(&mut self, tx: mpsc::UnboundedSender<FreshWriteEvent>) {
136        self.fresh_write_tx = Some(tx);
137    }
138
139    /// Get the protocol identifier.
140    #[must_use]
141    pub fn protocol_id(&self) -> &'static str {
142        CHUNK_PROTOCOL_ID
143    }
144
145    /// Get a reference to the underlying LMDB storage.
146    #[must_use]
147    pub fn storage(&self) -> Arc<LmdbStorage> {
148        Arc::clone(&self.storage)
149    }
150
151    /// Test-only: the record count the quote generator currently prices on.
152    /// Used to assert that quote-time resync tracks records actually held.
153    #[cfg(test)]
154    #[must_use]
155    pub(crate) fn priced_records_stored(&self) -> usize {
156        self.quote_generator.records_stored()
157    }
158
159    /// Get a shared reference to the payment verifier.
160    #[must_use]
161    pub fn payment_verifier_arc(&self) -> Arc<PaymentVerifier> {
162        Arc::clone(&self.payment_verifier)
163    }
164
165    /// ADR-0004: attach the replication engine's commitment state as the quote
166    /// generator's commitment source, so quotes force their price from the live
167    /// storage commitment and refresh its answerability on issuance.
168    ///
169    /// Called once, after both the protocol and the replication engine exist
170    /// (the engine owns the [`ResponderCommitmentState`](crate::replication::commitment_state::ResponderCommitmentState)).
171    /// Until this is wired, the quote generator has no commitment source and
172    /// falls back to baseline (no-pin) pricing.
173    ///
174    /// The same source is forwarded to the payment verifier's price-floor
175    /// policy (read-only snapshot), so this node's quotes and its floor are
176    /// priced from one commitment by construction.
177    pub fn attach_commitment_source(
178        &self,
179        source: Arc<dyn crate::payment::quote::CommitmentSource>,
180    ) {
181        self.quote_generator
182            .attach_commitment_source(Arc::clone(&source));
183        self.payment_verifier.attach_local_commitment_source(source);
184    }
185
186    /// ADR-0004: return the proof with any commitment sidecars stripped, so a
187    /// replicated/persisted receipt carries only the pin and count (stored
188    /// proofs do not grow). Handles BOTH proof types — single-node and
189    /// merkle-batch — since both now carry sidecars. An unknown-tagged or
190    /// unparseable proof is returned unchanged. Best-effort: any
191    /// deserialize/reserialize failure returns the original bytes rather than
192    /// corrupting the proof.
193    fn strip_commitment_sidecars(proof: Vec<u8>) -> Vec<u8> {
194        use crate::payment::proof::{
195            deserialize_merkle_proof, deserialize_single_node_proof, detect_proof_type,
196            serialize_merkle_proof, serialize_single_node_proof, ProofType,
197        };
198        match detect_proof_type(&proof) {
199            Some(ProofType::SingleNode) => match deserialize_single_node_proof(&proof) {
200                Ok(mut parsed) if !parsed.commitment_sidecars.is_empty() => {
201                    parsed.commitment_sidecars.clear();
202                    serialize_single_node_proof(&parsed).unwrap_or(proof)
203                }
204                _ => proof, // already sidecar-free, or unparseable: leave as-is
205            },
206            Some(ProofType::Merkle) => match deserialize_merkle_proof(&proof) {
207                Ok(mut parsed) if !parsed.commitment_sidecars.is_empty() => {
208                    parsed.commitment_sidecars.clear();
209                    serialize_merkle_proof(&parsed).unwrap_or(proof)
210                }
211                _ => proof,
212            },
213            _ => proof, // unknown tag: nothing to strip
214        }
215    }
216
217    /// Handle an incoming request and produce a response.
218    ///
219    /// Decodes the raw message, processes it if it is a request variant,
220    /// and returns the encoded response bytes.  Returns `Ok(None)` for
221    /// response messages (which are meant for client subscribers, not for
222    /// the protocol handler).
223    ///
224    /// # Errors
225    ///
226    /// Returns an error if message decoding, handling, or encoding fails.
227    pub async fn try_handle_request(&self, data: &[u8]) -> Result<Option<Bytes>> {
228        let message = ChunkMessage::decode(data)
229            .map_err(|e| Error::Protocol(format!("Failed to decode message: {e}")))?;
230
231        let request_id = message.request_id;
232
233        let response_body = match message.body {
234            ChunkMessageBody::PutRequest(req) => {
235                ChunkMessageBody::PutResponse(self.handle_put(req).await)
236            }
237            ChunkMessageBody::GetRequest(req) => {
238                ChunkMessageBody::GetResponse(self.handle_get(req).await)
239            }
240            ChunkMessageBody::QuoteRequest(ref req) => {
241                ChunkMessageBody::QuoteResponse(self.handle_quote(req))
242            }
243            ChunkMessageBody::MerkleCandidateQuoteRequest(ref req) => {
244                ChunkMessageBody::MerkleCandidateQuoteResponse(
245                    self.handle_merkle_candidate_quote(req),
246                )
247            }
248            // Anything else — response messages are handled by client
249            // subscribers (e.g. send_and_await_chunk_response), not by the
250            // protocol handler. Returning None prevents the caller from
251            // sending a reply, which would create an infinite ping-pong
252            // loop.
253            //
254            // `ChunkMessageBody` is `#[non_exhaustive]` in ant-protocol, so
255            // a future wire variant added on a protocol minor bump also
256            // lands here and is dropped. The CHUNK_PROTOCOL_ID multistream-
257            // select handshake version-gates peers, so this arm should
258            // only be reached by a misconfigured peer.
259            _ => return Ok(None),
260        };
261
262        let response = ChunkMessage {
263            request_id,
264            body: response_body,
265        };
266
267        response
268            .encode()
269            .map(|b| Some(Bytes::from(b)))
270            .map_err(|e| Error::Protocol(format!("Failed to encode response: {e}")))
271    }
272
273    /// Handle a PUT request.
274    ///
275    /// Wraps `handle_put_inner` to emit a single structured tracing event per
276    /// PUT RPC at every exit path, including early-return validation paths.
277    /// The event uses `target: "ant_node::storage::rpc_latency"` so that
278    /// Elasticsearch / Kibana can build p50/p95/p99 store-RPC latency
279    /// histograms from the existing telegraf log forwarding.
280    async fn handle_put(&self, request: ChunkPutRequest) -> ChunkPutResponse {
281        let start = std::time::Instant::now();
282        let addr_hex = hex::encode(request.address);
283        let chunk_size = request.content.len();
284        let response = self.handle_put_inner(request).await;
285        let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
286        let outcome: &'static str = match &response {
287            ChunkPutResponse::Success { .. } => "success",
288            ChunkPutResponse::AlreadyExists { .. } => "already_exists",
289            ChunkPutResponse::PaymentRequired { .. } => "payment_required",
290            ChunkPutResponse::Error(_) => "error",
291            _ => "unknown",
292        };
293        info!(
294            target: "ant_node::storage::rpc_latency",
295            duration_ms,
296            chunk_size,
297            outcome,
298            addr = %addr_hex,
299            "put_rpc"
300        );
301        response
302    }
303
304    /// Inner body of `handle_put` — see the wrapper for the per-RPC latency log.
305    async fn handle_put_inner(&self, request: ChunkPutRequest) -> ChunkPutResponse {
306        let address = request.address;
307        let addr_hex = hex::encode(address);
308        debug!("Handling PUT request for {addr_hex}");
309
310        // 1. Validate chunk size
311        if request.content.len() > MAX_CHUNK_SIZE {
312            return ChunkPutResponse::Error(ProtocolError::ChunkTooLarge {
313                size: request.content.len(),
314                max_size: MAX_CHUNK_SIZE,
315            });
316        }
317
318        // 2. Verify content address matches BLAKE3(content)
319        let computed = compute_address(&request.content);
320        if computed != address {
321            return ChunkPutResponse::Error(ProtocolError::AddressMismatch {
322                expected: address,
323                actual: computed,
324            });
325        }
326
327        // 3. Check if already exists (idempotent success)
328        match self.storage.exists(&address) {
329            Ok(true) => {
330                debug!("Chunk {addr_hex} already exists");
331                return ChunkPutResponse::AlreadyExists { address };
332            }
333            Err(e) => {
334                return ChunkPutResponse::Error(ProtocolError::Internal(format!(
335                    "Storage read failed: {e}"
336                )));
337            }
338            Ok(false) => {}
339        }
340
341        // 4. Cheap disk-space pre-check — runs BEFORE the expensive payment
342        //    verification path (ML-DSA pool checks, a Kademlia closeness
343        //    lookup, and an on-chain Arbitrum RPC). A disk-full node can never
344        //    satisfy this PUT, so reject it here rather than burning that work
345        //    only to fail the reserve check inside `storage.put` (V2-411). The
346        //    check caches passing results, so it is free per-PUT on a healthy
347        //    node; a disk-full node re-runs a cheap `available_space` syscall
348        //    each PUT (still negligible next to the verification it avoids) and
349        //    so detects freed space promptly. The store path keeps its own
350        //    check as defence-in-depth.
351        if let Err(e) = self.storage.check_capacity() {
352            info!(
353                target: "ant_node::storage::disk_precheck",
354                addr = %addr_hex,
355                "Rejecting PUT before payment verification: {e}"
356            );
357            return ChunkPutResponse::Error(ProtocolError::StorageFailed(e.to_string()));
358        }
359
360        // Self-closeness gate (ADR-0003): accept a client PUT only when this
361        // node is within its own local closest view of the address, so the
362        // fresh replication it triggers is legitimate and cannot mis-penalise
363        // honest peers. The width is the client's PUT fallback ceiling
364        // (`SELF_CLOSENESS_GATE_WIDTH`), so a client routing past full
365        // close-group members onto further peers is still accepted here.
366        // Skipped when no P2P handle is attached (unit tests). Bind the handle
367        // out of the lock first so no guard is held across the `.await`.
368        let attached = self.p2p_node.read().as_ref().map(Arc::clone);
369        if let Some(p2p) = attached {
370            let self_id = *p2p.peer_id();
371            if !admission::is_responsible(&self_id, &address, &p2p, SELF_CLOSENESS_GATE_WIDTH).await
372            {
373                debug!("Rejecting PUT for {addr_hex}: not within local closest peers");
374                return ChunkPutResponse::Error(ProtocolError::StorageFailed(
375                    "node is not within its local closest peers for this address".to_string(),
376                ));
377            }
378        }
379
380        // 5. Verify payment. The ClientPut context applies the store-strength
381        //    payment cache and verifies live proofs.
382        let payment_result = self
383            .payment_verifier
384            .verify_payment(
385                &address,
386                request.payment_proof.as_deref(),
387                VerificationContext::ClientPut,
388            )
389            .await;
390
391        match payment_result {
392            Ok(status) if status.can_store() => {
393                // Payment verified or cached
394            }
395            Ok(_) => {
396                return ChunkPutResponse::PaymentRequired {
397                    message: "Payment required for new chunk".to_string(),
398                };
399            }
400            Err(e) => {
401                return ChunkPutResponse::Error(ProtocolError::PaymentFailed(e.to_string()));
402            }
403        }
404
405        // 6. Store chunk
406        match self.storage.put(&address, &request.content).await {
407            Ok(_) => {
408                let content_len = request.content.len();
409                info!("Stored chunk {addr_hex} ({content_len} bytes)");
410                // Bump the in-memory fallback record counter. Under ADR-0004
411                // neither pricing nor the receiver-side price floor reads this
412                // counter: both are bound to the live storage commitment
413                // (committed responsible key count), pricing via the quote
414                // generator's commitment source and the floor via the
415                // verifier's non-mutating snapshot of the same commitment. The
416                // counter only matters as a warm fallback surface when no
417                // commitment source is attached (unit tests / pre-replication
418                // startup).
419                self.quote_generator.record_store();
420
421                // 7. Notify replication engine for fresh fan-out.
422                //    Only emit when a real proof is present — cached-as-verified
423                //    PUTs have no proof to forward, and the chunk would have
424                //    already replicated on the original write that carried one.
425                if let (Some(ref tx), Some(proof)) = (&self.fresh_write_tx, request.payment_proof) {
426                    // ADR-0004: strip any commitment sidecars before forwarding
427                    // to replication — the ADR specifies persisted/replicated
428                    // receipts "keep only the pin and count, so stored proofs do
429                    // not grow." The sidecars were already consumed by this
430                    // node's client-put cross-check; replicas resolve pins via
431                    // gossip/fetch (their context is Replication, which skips the
432                    // cross-check anyway). Best-effort: if sanitisation fails,
433                    // fall back to the original proof rather than dropping the
434                    // replication entirely.
435                    let proof = Self::strip_commitment_sidecars(proof);
436                    // `request.content` is now `bytes::Bytes`; FreshWriteEvent
437                    // still carries the chunk as `Vec<u8>` for compatibility
438                    // with the replication wire format, so materialise once
439                    // here. Done only on the success path, where storage has
440                    // already accepted the chunk.
441                    let event = FreshWriteEvent {
442                        key: address,
443                        data: request.content.to_vec(),
444                        payment_proof: proof,
445                    };
446                    if tx.send(event).is_err() {
447                        debug!("Fresh-write channel closed, skipping replication for {addr_hex}");
448                    }
449                }
450
451                ChunkPutResponse::Success { address }
452            }
453            Err(e) => {
454                warn!("Failed to store chunk {addr_hex}: {e}");
455                ChunkPutResponse::Error(ProtocolError::StorageFailed(e.to_string()))
456            }
457        }
458    }
459
460    /// Handle a GET request.
461    ///
462    /// Wraps `handle_get_inner` to emit a single structured tracing event per
463    /// GET RPC at every exit path. See `handle_put` for the rationale.
464    async fn handle_get(&self, request: ChunkGetRequest) -> ChunkGetResponse {
465        let start = std::time::Instant::now();
466        let addr_hex = hex::encode(request.address);
467        let response = self.handle_get_inner(request).await;
468        let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
469        let outcome: &'static str = match &response {
470            ChunkGetResponse::Success { .. } => "success",
471            ChunkGetResponse::NotFound { .. } => "not_found",
472            ChunkGetResponse::Error(_) => "error",
473            _ => "unknown",
474        };
475        info!(
476            target: "ant_node::storage::rpc_latency",
477            duration_ms,
478            outcome,
479            addr = %addr_hex,
480            "get_rpc"
481        );
482        response
483    }
484
485    /// Inner body of `handle_get` — see the wrapper for the per-RPC latency log.
486    async fn handle_get_inner(&self, request: ChunkGetRequest) -> ChunkGetResponse {
487        let address = request.address;
488        let addr_hex = hex::encode(address);
489        debug!("Handling GET request for {addr_hex}");
490
491        match self.storage.get(&address).await {
492            Ok(Some(content)) => {
493                let content_len = content.len();
494                debug!("Retrieved chunk {addr_hex} ({content_len} bytes)");
495                ChunkGetResponse::Success { address, content }
496            }
497            Ok(None) => {
498                debug!("Chunk {addr_hex} not found");
499                ChunkGetResponse::NotFound { address }
500            }
501            Err(e) => {
502                warn!("Failed to retrieve chunk {addr_hex}: {e}");
503                ChunkGetResponse::Error(ProtocolError::StorageFailed(e.to_string()))
504            }
505        }
506    }
507
508    /// Resync the quoting metric to the authoritative count of records the node
509    /// actually holds.
510    ///
511    /// The quote price is driven by `QuoteGenerator::records_stored()`. Reading
512    /// the live LMDB entry count (an O(1) B-tree page-header read) right before
513    /// pricing makes the metric deletion-aware: any chunk removed by
514    /// [`LmdbStorage::delete`] or by the replication prune pass is reflected
515    /// immediately, with no risk of missing a delete path.
516    ///
517    /// On a storage read error — or a count that does not fit `usize` — the
518    /// previous metric value is left untouched so a transient LMDB error never
519    /// disrupts quote generation.
520    fn resync_quote_metric(&self) {
521        match self.storage.current_chunks() {
522            // Saturating an overflowing count to usize::MAX would jump the
523            // metric to the maximum possible price driver; keep the previous
524            // value instead, as for a read error.
525            Ok(count) => usize::try_from(count).map_or_else(
526                |_| {
527                    warn!(
528                        "current_chunks() count {count} overflows usize; keeping previous quote \
529                         metric"
530                    );
531                },
532                |records| self.quote_generator.resync_records(records),
533            ),
534            Err(e) => {
535                warn!("Failed to read current_chunks() for quote metric resync: {e}");
536            }
537        }
538    }
539
540    /// Handle a quote request.
541    fn handle_quote(&self, request: &ChunkQuoteRequest) -> ChunkQuoteResponse {
542        let addr_hex = hex::encode(request.address);
543        let data_size = request.data_size;
544        debug!("Handling quote request for {addr_hex} (size: {data_size})");
545
546        // Price on records ACTUALLY HELD, not a monotonic store counter.
547        self.resync_quote_metric();
548
549        // Check if the chunk is already stored so we can tell the client
550        // to skip payment (already_stored = true).
551        // The match intentionally logs the error when the `logging` feature is
552        // active. Clippy suggests `unwrap_or_default()` when logging is compiled
553        // out, but keeping the explicit match preserves the diagnostic intent.
554        #[allow(clippy::manual_unwrap_or_default)]
555        let already_stored = match self.storage.exists(&request.address) {
556            Ok(exists) => exists,
557            Err(e) => {
558                warn!("Storage check failed for {addr_hex}: {e}");
559                false // Assume not stored on error — generate a normal quote.
560            }
561        };
562
563        if already_stored {
564            debug!("Chunk {addr_hex} already stored — returning quote with already_stored=true");
565        }
566
567        // Validate data size - data_size is u64, cast carefully and reject overflow
568        let Ok(data_size_usize) = usize::try_from(request.data_size) else {
569            return ChunkQuoteResponse::Error(ProtocolError::ChunkTooLarge {
570                size: MAX_CHUNK_SIZE + 1,
571                max_size: MAX_CHUNK_SIZE,
572            });
573        };
574        if data_size_usize > MAX_CHUNK_SIZE {
575            return ChunkQuoteResponse::Error(ProtocolError::ChunkTooLarge {
576                size: data_size_usize,
577                max_size: MAX_CHUNK_SIZE,
578            });
579        }
580
581        match self
582            .quote_generator
583            .create_quote(request.address, data_size_usize, request.data_type)
584        {
585            Ok(quote) => {
586                // ADR-0004: ship the signed commitment the price was bound to
587                // alongside the quote ("the commitment arrived with the quote"),
588                // so the client can verify the binding before paying and forward
589                // it as a sidecar in the PUT bundle. Only a commitment-bound
590                // quote pins anything; a baseline `(0, None)` quote carries no
591                // commitment. A pin that has rotated out resolves to `None` and
592                // the client falls back to gossip/fetch.
593                let commitment = quote
594                    .commitment_pin
595                    .and_then(|pin| self.quote_generator.commitment_blob_for_pin(pin));
596                // Serialize the quote
597                match rmp_serde::to_vec(&quote) {
598                    Ok(quote_bytes) => ChunkQuoteResponse::Success {
599                        quote: quote_bytes,
600                        already_stored,
601                        commitment,
602                    },
603                    Err(e) => ChunkQuoteResponse::Error(ProtocolError::QuoteFailed(format!(
604                        "Failed to serialize quote: {e}"
605                    ))),
606                }
607            }
608            Err(e) => ChunkQuoteResponse::Error(ProtocolError::QuoteFailed(e.to_string())),
609        }
610    }
611
612    /// Handle a merkle candidate quote request.
613    fn handle_merkle_candidate_quote(
614        &self,
615        request: &MerkleCandidateQuoteRequest,
616    ) -> MerkleCandidateQuoteResponse {
617        let addr_hex = hex::encode(request.address);
618        let data_size = request.data_size;
619        debug!(
620            "Handling merkle candidate quote request for {addr_hex} (size: {data_size}, ts: {})",
621            request.merkle_payment_timestamp
622        );
623
624        // Price on records ACTUALLY HELD, not a monotonic store counter.
625        self.resync_quote_metric();
626
627        let Ok(data_size_usize) = usize::try_from(request.data_size) else {
628            return MerkleCandidateQuoteResponse::Error(ProtocolError::QuoteFailed(format!(
629                "data_size {} overflows usize",
630                request.data_size
631            )));
632        };
633        if data_size_usize > MAX_CHUNK_SIZE {
634            return MerkleCandidateQuoteResponse::Error(ProtocolError::ChunkTooLarge {
635                size: data_size_usize,
636                max_size: MAX_CHUNK_SIZE,
637            });
638        }
639
640        match self.quote_generator.create_merkle_candidate_quote(
641            data_size_usize,
642            request.data_type,
643            request.merkle_payment_timestamp,
644        ) {
645            Ok(candidate_node) => {
646                // ADR-0004: ship the signed commitment this candidate priced
647                // against, so the client can verify the binding before paying
648                // and forward it as a sidecar. Baseline candidates ship none.
649                let commitment = candidate_node
650                    .commitment_pin
651                    .and_then(|pin| self.quote_generator.commitment_blob_for_pin(pin));
652                match rmp_serde::to_vec(&candidate_node) {
653                    Ok(bytes) => MerkleCandidateQuoteResponse::Success {
654                        candidate_node: bytes,
655                        commitment,
656                    },
657                    Err(e) => MerkleCandidateQuoteResponse::Error(ProtocolError::QuoteFailed(
658                        format!("Failed to serialize merkle candidate node: {e}"),
659                    )),
660                }
661            }
662            Err(e) => {
663                MerkleCandidateQuoteResponse::Error(ProtocolError::QuoteFailed(e.to_string()))
664            }
665        }
666    }
667
668    /// Get storage statistics.
669    #[must_use]
670    pub fn storage_stats(&self) -> crate::storage::StorageStats {
671        self.storage.stats()
672    }
673
674    /// Get payment cache statistics.
675    #[must_use]
676    pub fn payment_cache_stats(&self) -> crate::payment::CacheStats {
677        self.payment_verifier.cache_stats()
678    }
679
680    /// Get a reference to the payment verifier.
681    ///
682    /// Exposed for **test harnesses only** — production code should not call
683    /// this directly. Use `cache_insert()` on the returned verifier to
684    /// pre-populate the payment cache in test setups.
685    #[cfg(any(test, feature = "test-utils"))]
686    #[must_use]
687    pub fn payment_verifier(&self) -> &PaymentVerifier {
688        &self.payment_verifier
689    }
690
691    /// Check if a chunk exists locally.
692    ///
693    /// # Errors
694    ///
695    /// Returns an error if the storage read fails.
696    pub fn exists(&self, address: &[u8; 32]) -> Result<bool> {
697        self.storage.exists(address)
698    }
699
700    /// Get a chunk directly from local storage.
701    ///
702    /// # Errors
703    ///
704    /// Returns an error if storage access fails.
705    pub async fn get_local(&self, address: &[u8; 32]) -> Result<Option<Vec<u8>>> {
706        self.storage.get(address).await
707    }
708
709    /// Store a chunk directly to local storage (bypasses payment verification).
710    ///
711    /// TEST ONLY - This method bypasses payment verification and should only be used in tests.
712    ///
713    /// # Errors
714    ///
715    /// Returns an error if storage fails or content doesn't match address.
716    #[cfg(test)]
717    pub async fn put_local(&self, address: &[u8; 32], content: &[u8]) -> Result<bool> {
718        self.storage.put(address, content).await
719    }
720}
721
722#[cfg(test)]
723#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
724mod tests {
725    use super::*;
726    use crate::payment::metrics::QuotingMetricsTracker;
727    use crate::payment::{EvmVerifierConfig, PaymentVerifierConfig};
728    use crate::storage::LmdbStorageConfig;
729    use evmlib::RewardsAddress;
730    use saorsa_core::identity::NodeIdentity;
731    use saorsa_core::MlDsa65;
732    use saorsa_pqc::pqc::types::MlDsaSecretKey;
733    use tempfile::TempDir;
734
735    async fn create_test_protocol() -> (AntProtocol, TempDir) {
736        // `test_default()` sets `disk_reserve: 0`, so the disk pre-check always
737        // passes for the regular tests.
738        create_test_protocol_with_reserve(0).await
739    }
740
741    /// Build a test protocol whose storage enforces the given disk reserve.
742    ///
743    /// A very large reserve (e.g. `u64::MAX`) makes `available < reserve`
744    /// always true, so the disk-space pre-check in `handle_put_inner` fails —
745    /// used to exercise the V2-411 early-return path.
746    async fn create_test_protocol_with_reserve(disk_reserve: u64) -> (AntProtocol, TempDir) {
747        let temp_dir = TempDir::new().expect("create temp dir");
748
749        let storage_config = LmdbStorageConfig {
750            root_dir: temp_dir.path().to_path_buf(),
751            disk_reserve,
752            ..LmdbStorageConfig::test_default()
753        };
754        let storage = Arc::new(
755            LmdbStorage::new(storage_config)
756                .await
757                .expect("create storage"),
758        );
759
760        let rewards_address = RewardsAddress::new([1u8; 20]);
761        let payment_config = PaymentVerifierConfig {
762            evm: EvmVerifierConfig::default(),
763            cache_capacity: 100_000,
764            close_group_size: crate::ant_protocol::CLOSE_GROUP_SIZE,
765            local_rewards_address: rewards_address,
766            price_floor: crate::payment::PriceFloorConfig::default(),
767        };
768        let payment_verifier = Arc::new(PaymentVerifier::new(payment_config));
769        let metrics_tracker = QuotingMetricsTracker::new(100);
770        let mut quote_generator = QuoteGenerator::new(rewards_address, metrics_tracker);
771
772        // Wire ML-DSA-65 signing so quote requests succeed
773        let identity = NodeIdentity::generate().expect("generate identity");
774        let pub_key_bytes = identity.public_key().as_bytes().to_vec();
775        let sk_bytes = identity.secret_key_bytes().to_vec();
776        let sk = MlDsaSecretKey::from_bytes(&sk_bytes).expect("deserialize secret key");
777        quote_generator.set_signer(pub_key_bytes, move |msg| {
778            use saorsa_pqc::pqc::MlDsaOperations;
779            let ml_dsa = MlDsa65::new();
780            ml_dsa
781                .sign(&sk, msg)
782                .map_or_else(|_| vec![], |sig| sig.as_bytes().to_vec())
783        });
784
785        let protocol = AntProtocol::new(storage, payment_verifier, Arc::new(quote_generator));
786        (protocol, temp_dir)
787    }
788
789    #[tokio::test]
790    async fn test_put_and_get_chunk() {
791        let (protocol, _temp) = create_test_protocol().await;
792
793        let content = b"hello world";
794        let address = LmdbStorage::compute_address(content);
795
796        // Pre-populate payment cache so EVM verification is bypassed
797        protocol.payment_verifier().cache_insert(address);
798
799        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
800        let put_msg = ChunkMessage {
801            request_id: 1,
802            body: ChunkMessageBody::PutRequest(put_request),
803        };
804        let put_bytes = put_msg.encode().expect("encode put");
805
806        // Handle PUT
807        let response_bytes = protocol
808            .try_handle_request(&put_bytes)
809            .await
810            .expect("handle put")
811            .expect("expected response");
812        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
813
814        assert_eq!(response.request_id, 1);
815        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Success { address: addr }) =
816            response.body
817        {
818            assert_eq!(addr, address);
819        } else {
820            panic!("expected PutResponse::Success, got: {response:?}");
821        }
822
823        // Create GET request
824        let get_request = ChunkGetRequest::new(address);
825        let get_msg = ChunkMessage {
826            request_id: 2,
827            body: ChunkMessageBody::GetRequest(get_request),
828        };
829        let get_bytes = get_msg.encode().expect("encode get");
830
831        // Handle GET
832        let response_bytes = protocol
833            .try_handle_request(&get_bytes)
834            .await
835            .expect("handle get")
836            .expect("expected response");
837        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
838
839        assert_eq!(response.request_id, 2);
840        if let ChunkMessageBody::GetResponse(ChunkGetResponse::Success {
841            address: addr,
842            content: data,
843        }) = response.body
844        {
845            assert_eq!(addr, address);
846            assert_eq!(data, content.to_vec());
847        } else {
848            panic!("expected GetResponse::Success");
849        }
850    }
851
852    #[tokio::test]
853    async fn test_get_not_found() {
854        let (protocol, _temp) = create_test_protocol().await;
855
856        let address = [0xAB; 32];
857        let get_request = ChunkGetRequest::new(address);
858        let get_msg = ChunkMessage {
859            request_id: 10,
860            body: ChunkMessageBody::GetRequest(get_request),
861        };
862        let get_bytes = get_msg.encode().expect("encode get");
863
864        let response_bytes = protocol
865            .try_handle_request(&get_bytes)
866            .await
867            .expect("handle get")
868            .expect("expected response");
869        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
870
871        assert_eq!(response.request_id, 10);
872        if let ChunkMessageBody::GetResponse(ChunkGetResponse::NotFound { address: addr }) =
873            response.body
874        {
875            assert_eq!(addr, address);
876        } else {
877            panic!("expected GetResponse::NotFound");
878        }
879    }
880
881    #[tokio::test]
882    async fn test_put_address_mismatch() {
883        let (protocol, _temp) = create_test_protocol().await;
884
885        let content = b"test content";
886        let wrong_address = [0xFF; 32]; // Wrong address
887
888        // Pre-populate cache for the wrong address so we test address mismatch, not payment
889        protocol.payment_verifier().cache_insert(wrong_address);
890
891        let put_request = ChunkPutRequest::new(wrong_address, Bytes::copy_from_slice(content));
892        let put_msg = ChunkMessage {
893            request_id: 20,
894            body: ChunkMessageBody::PutRequest(put_request),
895        };
896        let put_bytes = put_msg.encode().expect("encode put");
897
898        let response_bytes = protocol
899            .try_handle_request(&put_bytes)
900            .await
901            .expect("handle put")
902            .expect("expected response");
903        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
904
905        assert_eq!(response.request_id, 20);
906        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Error(
907            ProtocolError::AddressMismatch { .. },
908        )) = response.body
909        {
910            // Expected
911        } else {
912            panic!("expected AddressMismatch error, got: {response:?}");
913        }
914    }
915
916    #[tokio::test]
917    async fn test_put_chunk_too_large() {
918        let (protocol, _temp) = create_test_protocol().await;
919
920        // Create oversized content
921        let content = vec![0u8; MAX_CHUNK_SIZE + 1];
922        let address = LmdbStorage::compute_address(&content);
923
924        let put_request = ChunkPutRequest::new(address, Bytes::from(content));
925        let put_msg = ChunkMessage {
926            request_id: 30,
927            body: ChunkMessageBody::PutRequest(put_request),
928        };
929        let put_bytes = put_msg.encode().expect("encode put");
930
931        let response_bytes = protocol
932            .try_handle_request(&put_bytes)
933            .await
934            .expect("handle put")
935            .expect("expected response");
936        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
937
938        assert_eq!(response.request_id, 30);
939        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Error(
940            ProtocolError::ChunkTooLarge { .. },
941        )) = response.body
942        {
943            // Expected
944        } else {
945            panic!("expected ChunkTooLarge error");
946        }
947    }
948
949    /// V2-411: a disk-full node must reject a PUT with the disk-space error
950    /// *before* running payment verification.
951    ///
952    /// The chunk is intentionally **not** cache-inserted, so if the handler
953    /// reached `verify_payment` it would return `PaymentRequired`/`PaymentFailed`
954    /// (an uncached chunk with no proof). Observing the `StorageFailed` disk
955    /// error instead proves the disk pre-check short-circuited ahead of
956    /// verification — there is no on-chain path to reach.
957    #[tokio::test]
958    async fn test_put_rejected_on_insufficient_disk_before_verification() {
959        // u64::MAX reserve guarantees `available < reserve`, so the cached
960        // disk-space check always fails.
961        let (protocol, _temp) = create_test_protocol_with_reserve(u64::MAX).await;
962
963        let content = b"chunk for a disk-full node";
964        let address = LmdbStorage::compute_address(content);
965
966        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
967        let put_msg = ChunkMessage {
968            request_id: 41,
969            body: ChunkMessageBody::PutRequest(put_request),
970        };
971        let put_bytes = put_msg.encode().expect("encode put");
972
973        let response_bytes = protocol
974            .try_handle_request(&put_bytes)
975            .await
976            .expect("handle put")
977            .expect("expected response");
978        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
979
980        assert_eq!(response.request_id, 41);
981        match response.body {
982            ChunkMessageBody::PutResponse(ChunkPutResponse::Error(
983                ProtocolError::StorageFailed(msg),
984            )) => {
985                assert!(
986                    msg.contains("Insufficient disk space"),
987                    "expected disk-space error, got: {msg}"
988                );
989            }
990            other => {
991                panic!("expected StorageFailed disk error before verification, got: {other:?}")
992            }
993        }
994
995        // And nothing was stored.
996        assert!(!protocol.exists(&address).expect("exists check"));
997    }
998
999    #[tokio::test]
1000    async fn test_put_already_exists() {
1001        let (protocol, _temp) = create_test_protocol().await;
1002
1003        let content = b"duplicate content";
1004        let address = LmdbStorage::compute_address(content);
1005
1006        // Pre-populate cache so EVM verification is bypassed
1007        protocol.payment_verifier().cache_insert(address);
1008
1009        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
1010        let put_msg = ChunkMessage {
1011            request_id: 40,
1012            body: ChunkMessageBody::PutRequest(put_request),
1013        };
1014        let put_bytes = put_msg.encode().expect("encode put");
1015
1016        let _ = protocol
1017            .try_handle_request(&put_bytes)
1018            .await
1019            .expect("handle put");
1020
1021        // Store again - should return AlreadyExists
1022        let response_bytes = protocol
1023            .try_handle_request(&put_bytes)
1024            .await
1025            .expect("handle put 2")
1026            .expect("expected response");
1027        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
1028
1029        assert_eq!(response.request_id, 40);
1030        if let ChunkMessageBody::PutResponse(ChunkPutResponse::AlreadyExists { address: addr }) =
1031            response.body
1032        {
1033            assert_eq!(addr, address);
1034        } else {
1035            panic!("expected AlreadyExists");
1036        }
1037    }
1038
1039    #[tokio::test]
1040    async fn test_protocol_id() {
1041        let (protocol, _temp) = create_test_protocol().await;
1042        assert_eq!(protocol.protocol_id(), CHUNK_PROTOCOL_ID);
1043    }
1044
1045    #[tokio::test]
1046    async fn test_exists_and_local_access() {
1047        let (protocol, _temp) = create_test_protocol().await;
1048
1049        let content = b"local access test";
1050        let address = LmdbStorage::compute_address(content);
1051
1052        assert!(!protocol.exists(&address).expect("exists check"));
1053
1054        protocol
1055            .put_local(&address, content)
1056            .await
1057            .expect("put local");
1058
1059        assert!(protocol.exists(&address).expect("exists check"));
1060
1061        let retrieved = protocol.get_local(&address).await.expect("get local");
1062        assert_eq!(retrieved, Some(content.to_vec()));
1063    }
1064
1065    #[tokio::test]
1066    async fn test_cache_insert_is_visible() {
1067        let (protocol, _temp) = create_test_protocol().await;
1068
1069        let content = b"cache test content";
1070        let address = LmdbStorage::compute_address(content);
1071
1072        // Before insert: cache should be empty
1073        let stats_before = protocol.payment_cache_stats();
1074        assert_eq!(stats_before.additions, 0);
1075
1076        // Pre-populate cache
1077        protocol.payment_verifier().cache_insert(address);
1078
1079        // After insert: cache should have the xorname
1080        let stats_after = protocol.payment_cache_stats();
1081        assert_eq!(stats_after.additions, 1);
1082
1083        // PUT should succeed (cache hit)
1084        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
1085        let put_msg = ChunkMessage {
1086            request_id: 100,
1087            body: ChunkMessageBody::PutRequest(put_request),
1088        };
1089        let put_bytes = put_msg.encode().expect("encode put");
1090        let response_bytes = protocol
1091            .try_handle_request(&put_bytes)
1092            .await
1093            .expect("handle put")
1094            .expect("expected response");
1095        let response = ChunkMessage::decode(&response_bytes).expect("decode");
1096
1097        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Success { .. }) = response.body {
1098            // expected
1099        } else {
1100            panic!("expected success, got: {response:?}");
1101        }
1102    }
1103
1104    #[tokio::test]
1105    async fn test_put_same_chunk_twice_hits_cache() {
1106        let (protocol, _temp) = create_test_protocol().await;
1107
1108        let content = b"duplicate cache test";
1109        let address = LmdbStorage::compute_address(content);
1110
1111        // Pre-populate cache for first PUT
1112        protocol.payment_verifier().cache_insert(address);
1113
1114        // First PUT
1115        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
1116        let put_msg = ChunkMessage {
1117            request_id: 110,
1118            body: ChunkMessageBody::PutRequest(put_request),
1119        };
1120        let put_bytes = put_msg.encode().expect("encode put");
1121        let _ = protocol
1122            .try_handle_request(&put_bytes)
1123            .await
1124            .expect("handle put 1");
1125
1126        // Second PUT should return AlreadyExists from the storage idempotency check.
1127        let response_bytes = protocol
1128            .try_handle_request(&put_bytes)
1129            .await
1130            .expect("handle put 2")
1131            .expect("expected response");
1132        let response = ChunkMessage::decode(&response_bytes).expect("decode");
1133
1134        if let ChunkMessageBody::PutResponse(ChunkPutResponse::AlreadyExists { .. }) = response.body
1135        {
1136            // expected
1137        } else {
1138            panic!("expected AlreadyExists, got: {response:?}");
1139        }
1140    }
1141
1142    #[tokio::test]
1143    async fn test_payment_cache_stats_returns_correct_values() {
1144        let (protocol, _temp) = create_test_protocol().await;
1145
1146        let stats = protocol.payment_cache_stats();
1147        assert_eq!(stats.hits, 0);
1148        assert_eq!(stats.misses, 0);
1149        assert_eq!(stats.additions, 0);
1150
1151        // Pre-populate cache, then store a chunk to test stats
1152        let content = b"stats test";
1153        let address = LmdbStorage::compute_address(content);
1154        protocol.payment_verifier().cache_insert(address);
1155
1156        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
1157        let put_msg = ChunkMessage {
1158            request_id: 120,
1159            body: ChunkMessageBody::PutRequest(put_request),
1160        };
1161        let put_bytes = put_msg.encode().expect("encode put");
1162        let _ = protocol
1163            .try_handle_request(&put_bytes)
1164            .await
1165            .expect("handle put");
1166
1167        let stats = protocol.payment_cache_stats();
1168        // Should have 1 addition (from cache_insert) + 1 hit (payment verification found cache)
1169        assert_eq!(stats.additions, 1);
1170        assert_eq!(stats.hits, 1);
1171    }
1172
1173    #[tokio::test]
1174    async fn test_storage_stats() {
1175        let (protocol, _temp) = create_test_protocol().await;
1176        let stats = protocol.storage_stats();
1177        assert_eq!(stats.chunks_stored, 0);
1178    }
1179
1180    #[tokio::test]
1181    async fn test_merkle_candidate_quote_request() {
1182        use ant_protocol::payment::verify::verify_merkle_candidate_signature;
1183        use evmlib::merkle_payments::MerklePaymentCandidateNode;
1184
1185        // create_test_protocol already wires ML-DSA-65 signing
1186        let (protocol, _temp) = create_test_protocol().await;
1187
1188        let address = [0x77; 32];
1189        let timestamp = std::time::SystemTime::now()
1190            .duration_since(std::time::UNIX_EPOCH)
1191            .expect("system time")
1192            .as_secs();
1193
1194        let request = MerkleCandidateQuoteRequest {
1195            address,
1196            data_type: DATA_TYPE_CHUNK,
1197            data_size: 4096,
1198            merkle_payment_timestamp: timestamp,
1199        };
1200        let msg = ChunkMessage {
1201            request_id: 600,
1202            body: ChunkMessageBody::MerkleCandidateQuoteRequest(request),
1203        };
1204        let msg_bytes = msg.encode().expect("encode request");
1205
1206        let response_bytes = protocol
1207            .try_handle_request(&msg_bytes)
1208            .await
1209            .expect("handle merkle candidate quote")
1210            .expect("expected response");
1211        let response = ChunkMessage::decode(&response_bytes).expect("decode response");
1212
1213        assert_eq!(response.request_id, 600);
1214        match response.body {
1215            ChunkMessageBody::MerkleCandidateQuoteResponse(
1216                MerkleCandidateQuoteResponse::Success { candidate_node, .. },
1217            ) => {
1218                let candidate: MerklePaymentCandidateNode =
1219                    rmp_serde::from_slice(&candidate_node).expect("deserialize candidate node");
1220
1221                // Verify ML-DSA-65 signature
1222                assert!(
1223                    verify_merkle_candidate_signature(&candidate),
1224                    "ML-DSA-65 candidate signature must be valid"
1225                );
1226
1227                assert_eq!(candidate.merkle_payment_timestamp, timestamp);
1228                // Node-calculated price based on records stored
1229                assert!(candidate.price >= evmlib::common::Amount::ZERO);
1230            }
1231            other => panic!("expected MerkleCandidateQuoteResponse::Success, got: {other:?}"),
1232        }
1233    }
1234
1235    #[tokio::test]
1236    async fn test_handle_unexpected_response_message() {
1237        let (protocol, _temp) = create_test_protocol().await;
1238
1239        // Send a PutResponse as if it were a request — should return None
1240        let msg = ChunkMessage {
1241            request_id: 200,
1242            body: ChunkMessageBody::PutResponse(ChunkPutResponse::Success { address: [0u8; 32] }),
1243        };
1244        let msg_bytes = msg.encode().expect("encode");
1245
1246        let result = protocol
1247            .try_handle_request(&msg_bytes)
1248            .await
1249            .expect("handle msg");
1250
1251        assert!(
1252            result.is_none(),
1253            "expected None for response message, got: {result:?}"
1254        );
1255    }
1256
1257    #[tokio::test]
1258    async fn test_quote_already_stored_flag() {
1259        let (protocol, _temp) = create_test_protocol().await;
1260
1261        let content = b"already stored quote test";
1262        let address = LmdbStorage::compute_address(content);
1263
1264        // Store the chunk first
1265        protocol.payment_verifier().cache_insert(address);
1266        let put_request = ChunkPutRequest::new(address, Bytes::copy_from_slice(content));
1267        let put_msg = ChunkMessage {
1268            request_id: 300,
1269            body: ChunkMessageBody::PutRequest(put_request),
1270        };
1271        let put_bytes = put_msg.encode().expect("encode put");
1272        let _ = protocol
1273            .try_handle_request(&put_bytes)
1274            .await
1275            .expect("handle put");
1276
1277        // Now request a quote for the same address — already_stored should be true
1278        let quote_request = ChunkQuoteRequest {
1279            address,
1280            data_size: content.len() as u64,
1281            data_type: DATA_TYPE_CHUNK,
1282        };
1283        let quote_msg = ChunkMessage {
1284            request_id: 301,
1285            body: ChunkMessageBody::QuoteRequest(quote_request),
1286        };
1287        let quote_bytes = quote_msg.encode().expect("encode quote");
1288        let response_bytes = protocol
1289            .try_handle_request(&quote_bytes)
1290            .await
1291            .expect("handle quote")
1292            .expect("expected response");
1293        let response = ChunkMessage::decode(&response_bytes).expect("decode");
1294
1295        match response.body {
1296            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Success {
1297                already_stored, ..
1298            }) => {
1299                assert!(
1300                    already_stored,
1301                    "already_stored should be true for existing chunk"
1302                );
1303            }
1304            other => panic!("expected Success with already_stored, got: {other:?}"),
1305        }
1306
1307        // Request a quote for a chunk that does NOT exist — already_stored should be false
1308        let new_address = [0xFFu8; 32];
1309        let quote_request2 = ChunkQuoteRequest {
1310            address: new_address,
1311            data_size: 100,
1312            data_type: DATA_TYPE_CHUNK,
1313        };
1314        let quote_msg2 = ChunkMessage {
1315            request_id: 302,
1316            body: ChunkMessageBody::QuoteRequest(quote_request2),
1317        };
1318        let quote_bytes2 = quote_msg2.encode().expect("encode quote2");
1319        let response_bytes2 = protocol
1320            .try_handle_request(&quote_bytes2)
1321            .await
1322            .expect("handle quote2")
1323            .expect("expected response");
1324        let response2 = ChunkMessage::decode(&response_bytes2).expect("decode2");
1325
1326        match response2.body {
1327            ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Success {
1328                already_stored, ..
1329            }) => {
1330                assert!(
1331                    !already_stored,
1332                    "already_stored should be false for new chunk"
1333                );
1334            }
1335            other => panic!("expected Success with already_stored=false, got: {other:?}"),
1336        }
1337    }
1338
1339    /// Drive the real quote handler, then read the record count it priced on.
1340    /// The handler calls `resync_quote_metric` first, so this reflects records
1341    /// ACTUALLY HELD.
1342    fn priced_records_after_quote(protocol: &AntProtocol) -> usize {
1343        let quote_request = ChunkQuoteRequest {
1344            address: [0xAAu8; 32], // a quote-only probe, not one of the stored chunks
1345            data_size: 100,
1346            data_type: DATA_TYPE_CHUNK,
1347        };
1348        let _ = protocol.handle_quote(&quote_request);
1349        protocol.priced_records_stored()
1350    }
1351
1352    /// The quote price must track records ACTUALLY HELD: deleting stored chunks
1353    /// must lower the priced record count, not keep quoting as if the data were
1354    /// still held. Exercises the storage-driven resync in `resync_quote_metric`.
1355    #[tokio::test]
1356    async fn test_quote_metric_reflects_deletions() {
1357        let (protocol, _temp) = create_test_protocol().await;
1358
1359        // Distinct content -> distinct content-addressed keys.
1360        let contents: Vec<Vec<u8>> = (0u8..5).map(|i| vec![i; 64]).collect();
1361        let mut addresses = Vec::new();
1362        for content in &contents {
1363            let addr = LmdbStorage::compute_address(content);
1364            protocol.put_local(&addr, content).await.expect("put_local");
1365            addresses.push(addr);
1366        }
1367
1368        // 5 records held -> priced count 5.
1369        assert_eq!(priced_records_after_quote(&protocol), 5);
1370
1371        // Delete 2 chunks the node was holding.
1372        for addr in addresses.iter().take(2) {
1373            assert!(protocol.storage().delete(addr).await.expect("delete"));
1374        }
1375        assert_eq!(priced_records_after_quote(&protocol), 3);
1376
1377        // Delete the rest; priced count floors at 0, never underflows.
1378        for addr in addresses.iter().skip(2) {
1379            assert!(protocol.storage().delete(addr).await.expect("delete"));
1380        }
1381        assert_eq!(priced_records_after_quote(&protocol), 0);
1382    }
1383
1384    /// Stronger, externally-observable proof: the actual quote PRICE returned
1385    /// to a client must drop after the node deletes data it held. A monotonic
1386    /// store counter would keep the price elevated; the resync ties price to
1387    /// records actually held.
1388    /// FLIPS IF: `resync_quote_metric` is removed — the price would stay at the
1389    /// 10-record level even after deletions (`record_store` only ever increments).
1390    #[tokio::test]
1391    async fn test_quote_price_drops_after_deletion() {
1392        use crate::payment::pricing::calculate_price;
1393
1394        let (protocol, _temp) = create_test_protocol().await;
1395        let contents: Vec<Vec<u8>> = (0u8..10).map(|i| vec![i; 64]).collect();
1396        let mut addresses = Vec::new();
1397        for content in &contents {
1398            let addr = LmdbStorage::compute_address(content);
1399            protocol.put_local(&addr, content).await.expect("put_local");
1400            addresses.push(addr);
1401        }
1402
1403        // Drive a real quote; the priced count must equal records held (10),
1404        // and the price must equal calculate_price(10) — the externally
1405        // observable contract.
1406        assert_eq!(priced_records_after_quote(&protocol), 10);
1407        let price_full = calculate_price(10);
1408
1409        // Delete 8 of 10 held chunks.
1410        for addr in addresses.iter().take(8) {
1411            assert!(protocol.storage().delete(addr).await.expect("delete"));
1412        }
1413        // The next quote must price on 2 records, and the price must be the
1414        // calculate_price(2) value — strictly different from the 10-record
1415        // price (price is monotonic non-decreasing in records_stored).
1416        assert_eq!(priced_records_after_quote(&protocol), 2);
1417        let price_after = calculate_price(2);
1418        assert!(
1419            price_after < price_full,
1420            "deleting data must lower the observable quote price \
1421             (full={price_full:?}, after={price_after:?})"
1422        );
1423    }
1424
1425    /// ADR-0004: `strip_commitment_sidecars` removes sidecars from a single-node
1426    /// proof before replication/persistence (stored proofs do not grow), and is
1427    /// a no-op on a sidecar-free proof.
1428    #[test]
1429    fn strip_commitment_sidecars_clears_single_node_sidecars() {
1430        use crate::payment::proof::{
1431            deserialize_single_node_proof, serialize_single_node_proof, PaymentProof,
1432        };
1433        use evmlib::ProofOfPayment;
1434
1435        let with_sidecars = PaymentProof {
1436            proof_of_payment: ProofOfPayment {
1437                peer_quotes: vec![],
1438            },
1439            tx_hashes: vec![],
1440            commitment_sidecars: vec![vec![1u8; 16], vec![2u8; 16]],
1441        };
1442        let bytes = serialize_single_node_proof(&with_sidecars).expect("serialize");
1443        let stripped = AntProtocol::strip_commitment_sidecars(bytes);
1444        let parsed = deserialize_single_node_proof(&stripped).expect("deserialize stripped");
1445        assert!(
1446            parsed.commitment_sidecars.is_empty(),
1447            "sidecars must be stripped before replication"
1448        );
1449
1450        // Idempotent: stripping an already-sidecar-free proof returns it intact.
1451        let again = AntProtocol::strip_commitment_sidecars(stripped.clone());
1452        assert_eq!(again, stripped, "stripping a sidecar-free proof is a no-op");
1453    }
1454}