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