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