Skip to main content

ant_node/payment/
verifier.rs

1//! Payment verifier with LRU cache and EVM verification.
2//!
3//! This is the core payment verification logic for ant-node.
4//! All new data requires EVM payment on Arbitrum (no free tier).
5
6use crate::ant_protocol::CLOSE_GROUP_SIZE;
7use crate::error::{Error, Result};
8use crate::logging::{debug, info, warn};
9use crate::payment::cache::{CacheStats, VerifiedCache, XorName};
10use crate::payment::pricing::{calculate_price, derive_records_stored_from_price};
11use crate::payment::proof::{
12    deserialize_merkle_proof, deserialize_single_node_proof, detect_proof_type, ProofType,
13};
14use crate::replication::config::K_BUCKET_SIZE;
15use crate::storage::lmdb::LmdbStorage;
16use ant_protocol::payment::verify::{verify_quote_content, verify_quote_signature};
17use evmlib::common::{Amount, QuoteHash};
18use evmlib::contract::payment_vault;
19use evmlib::merkle_batch_payment::{OnChainPaymentInfo, PoolHash};
20use evmlib::Network as EvmNetwork;
21use evmlib::PaymentQuote;
22use evmlib::ProofOfPayment;
23use evmlib::RewardsAddress;
24use lru::LruCache;
25use parking_lot::{Mutex, RwLock};
26use saorsa_core::identity::node_identity::peer_id_from_public_key_bytes;
27use saorsa_core::identity::PeerId;
28use saorsa_core::P2PNode;
29use std::collections::HashMap;
30use std::num::NonZeroUsize;
31use std::sync::Arc;
32use std::time::Instant;
33
34/// Minimum allowed size for a payment proof in bytes.
35///
36/// This minimum ensures the proof contains at least a basic cryptographic hash or identifier.
37/// Proofs smaller than this are rejected as they cannot contain sufficient payment information.
38pub const MIN_PAYMENT_PROOF_SIZE_BYTES: usize = 32;
39
40/// Maximum allowed size for a payment proof in bytes (512 KB).
41///
42/// Single-node proofs with 7 ML-DSA-65 quotes reach ~40 KB; with ADR-0004
43/// commitment sidecars (one ~5.3 KB commitment per bound quote, ~13 KB each
44/// after rmp encoding) they reach ~150 KB.
45/// Merkle proofs include 16 candidate nodes (each with ~1,952-byte ML-DSA pub
46/// key and ~3,309-byte signature) plus merkle branch hashes, totaling ~130 KB.
47/// A merkle proof that ALSO ships all 16 commitment sidecars (clients built
48/// before the sidecars were dropped from the per-chunk bundle) reaches
49/// ~342 KB — the previous 256 KB cap rejected every such PUT the moment nodes
50/// carried live commitments, which is exactly how it was discovered.
51/// 512 KB accepts every shape above with headroom while still capping memory
52/// during verification.
53pub const MAX_PAYMENT_PROOF_SIZE_BYTES: usize = 524_288;
54
55const PAID_QUOTE_PAYMENT_MULTIPLIER: u64 = 3;
56const PAYMENT_VERIFY_SLOW_LOG_MS: u128 = 500;
57
58/// Number of nearest DHT peers accepted for paid-quote issuer locality.
59///
60/// This is the Kademlia K width, intentionally wider than `CLOSE_GROUP_SIZE`.
61const PAID_QUOTE_ISSUER_CLOSENESS_WIDTH: usize = K_BUCKET_SIZE;
62
63#[derive(Clone, Copy)]
64struct LegacyMedianCandidate<'a> {
65    encoded_peer_id: &'a evmlib::EncodedPeerId,
66    quote: &'a PaymentQuote,
67    expected_amount: Amount,
68}
69
70fn median_quote_index(quote_count: usize) -> usize {
71    quote_count / 2
72}
73
74fn payment_proof_type_label(payment_proof: Option<&[u8]>) -> &'static str {
75    match payment_proof.and_then(detect_proof_type) {
76        Some(ProofType::Merkle) => "merkle",
77        Some(ProofType::SingleNode) => "single_node",
78        Some(_) => "unsupported",
79        None if payment_proof.is_some() => "unknown",
80        None => "none",
81    }
82}
83
84/// Configuration for EVM payment verification.
85///
86/// EVM verification is always on. All new data requires on-chain
87/// payment verification. The network field selects which EVM chain to use.
88#[derive(Debug, Clone)]
89pub struct EvmVerifierConfig {
90    /// EVM network to use (Arbitrum One, Arbitrum Sepolia, etc.)
91    pub network: EvmNetwork,
92}
93
94impl Default for EvmVerifierConfig {
95    fn default() -> Self {
96        Self {
97            network: EvmNetwork::ArbitrumOne,
98        }
99    }
100}
101
102/// Configuration for the payment verifier.
103///
104/// All new data requires EVM payment on Arbitrum. The cache stores
105/// previously verified payments to avoid redundant on-chain lookups.
106#[derive(Debug, Clone)]
107pub struct PaymentVerifierConfig {
108    /// EVM verifier configuration.
109    pub evm: EvmVerifierConfig,
110    /// Cache capacity (number of `XorName` values to cache).
111    pub cache_capacity: usize,
112    /// Close-group width exposed to storage and replication admission callers.
113    pub close_group_size: usize,
114    /// Local node's rewards address.
115    ///
116    /// Kept in the verifier config for payment policies that bind receipts to
117    /// this node's payout address.
118    pub local_rewards_address: RewardsAddress,
119}
120
121/// The fresh admission path a payment proof is being verified for.
122///
123/// - **`ClientPut`** — the node is admitting a chunk store. The verifier
124///   applies store-strength cache semantics and live payment checks.
125/// - **`PaidListAdmission`** — the node is admitting fresh paid-list metadata.
126///   It runs the same live payment checks as `ClientPut`, but writes a weaker
127///   cache entry that does not authorize future chunk stores.
128///
129/// The caller must check local receiver/admission membership before invoking
130/// the verifier for replication admission: fresh chunk replication requires
131/// local close-group responsibility, and fresh paid-list replication requires
132/// local paid-list close-group membership. Direct client PUT deliberately does
133/// not perform a receiver-responsibility gate. The verifier itself only checks
134/// payment proof validity and that the paid quote's issuer is in the K closest
135/// peers for the quoted chunk address.
136///
137/// Immediate fresh chunk replication is different: the receiver is about to
138/// store the newly written chunk as if the client PUT it there directly, so
139/// that call site deliberately uses `ClientPut`.
140///
141/// Later neighbour-sync repair does not include proof-of-payment bytes and
142/// does not call this verifier. It authorizes repair from network evidence:
143/// majority storage among the configured close group, or majority paid-list
144/// membership among the closest K.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub enum VerificationContext {
147    /// The node is admitting a chunk store with store-strength cache semantics.
148    ClientPut,
149    /// The node is admitting fresh paid-list metadata with paid-list-strength
150    /// cache semantics.
151    PaidListAdmission,
152}
153
154/// Status returned by payment verification.
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub enum PaymentStatus {
157    /// Data was found in local cache - previously paid.
158    CachedAsVerified,
159    /// New data - payment required.
160    PaymentRequired,
161    /// Payment was provided and verified.
162    PaymentVerified,
163}
164
165/// Outcome of the ADR-0004 quote-vs-commitment cross-check (see
166/// [`PaymentVerifier::cross_check_binding`]).
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168pub enum CrossCheck {
169    /// Pin resolves to the commitment and the counts agree: nothing to report.
170    Match,
171    /// Pin resolves to the commitment but the claimed and committed counts
172    /// disagree: deterministic, first-occurrence contradiction (evidence).
173    Mismatch {
174        /// The key count the quote claimed.
175        quoted_key_count: u32,
176        /// The key count the pinned commitment actually attests.
177        committed_key_count: u32,
178    },
179    /// The supplied commitment does not hash to the quote's pin: the pin is
180    /// unresolved (treat as fetch/skip), never evidence.
181    PinDoesNotResolve,
182}
183
184impl PaymentStatus {
185    /// Returns true if the data can be stored (cached or payment verified).
186    #[must_use]
187    pub fn can_store(&self) -> bool {
188        matches!(self, Self::CachedAsVerified | Self::PaymentVerified)
189    }
190
191    /// Returns true if this status indicates the data was already paid for.
192    #[must_use]
193    pub fn is_cached(&self) -> bool {
194        matches!(self, Self::CachedAsVerified)
195    }
196}
197
198/// Default capacity for the merkle pool cache (number of pool hashes to cache).
199const DEFAULT_POOL_CACHE_CAPACITY: usize = 1_000;
200
201/// ADR-0004: max commitment sidecars processed per bundle. A legitimate bundle
202/// carries at most one commitment per quote/candidate — `CANDIDATES_PER_POOL`
203/// (16) is the larger of the single-node (`CLOSE_GROUP_SIZE` = 7) and merkle
204/// cases, so it covers both. Excess sidecars from a malicious client are
205/// ignored before any deserialize/verify work (bounds the hot-path cost).
206const MAX_SIDECARS_PER_BUNDLE: usize = evmlib::merkle_batch_payment::CANDIDATES_PER_POOL;
207
208/// Shared handle to the replication engine's gossip commitment cache
209/// (`last_commitment_by_peer`), used by the ADR-0004 cross-check to resolve a
210/// quote's pin against a neighbour's recently gossiped commitment. A `tokio`
211/// `RwLock` to match the engine's; read with `.await` on the async path.
212type CommitmentCache = Arc<
213    tokio::sync::RwLock<
214        HashMap<PeerId, crate::replication::commitment_state::PeerCommitmentRecord>,
215    >,
216>;
217
218/// Per-`(peer, pin)` negative cache for unresolved ADR-0004 pin fetches: a pin a
219/// peer answered `NotRetained` (or that timed out) is remembered so repeated
220/// bundles don't re-fetch it. Behind an `Arc` so the detached fetch task owns a
221/// handle without borrowing the verifier.
222type PinFetchNegativeCache = Arc<Mutex<LruCache<(PeerId, [u8; 32]), ()>>>;
223
224/// Main payment verifier for ant-node.
225///
226/// Uses:
227/// 1. LRU cache for fast lookups of previously verified `XorName` values
228/// 2. EVM payment verification for new data (always required)
229/// 3. Pool-level cache for merkle batch payments (avoids repeated on-chain queries)
230pub struct PaymentVerifier {
231    /// LRU cache of verified `XorName` values.
232    cache: VerifiedCache,
233    /// LRU cache of verified merkle pool hashes → on-chain payment info.
234    pool_cache: Mutex<LruCache<PoolHash, OnChainPaymentInfo>>,
235    /// LRU cache of pool hashes whose candidate closeness has already been
236    /// verified by this node. Collapses the per-chunk Kademlia lookup cost
237    /// within a batch (256 chunks × 1 pool = 1 lookup instead of 256).
238    closeness_pass_cache: Mutex<LruCache<PoolHash, ()>>,
239    /// In-flight closeness lookups, keyed by pool hash. Lets concurrent PUTs
240    /// for the same pool coalesce onto a single Kademlia lookup AND share
241    /// its result — on both success and failure — which bounds `DoS`
242    /// amplification to one lookup per unique `pool_hash` regardless of
243    /// concurrency.
244    inflight_closeness: Mutex<LruCache<PoolHash, Arc<ClosenessSlot>>>,
245    /// P2P node handle, attached post-construction so paid-quote verification
246    /// can check paid-quote issuer K-closeness, and merkle verification can
247    /// check that candidate `pub_keys` map to peers actually close to the pool
248    /// midpoint in the live DHT. `None` in unit tests that don't exercise
249    /// live-DHT checks; production startup MUST call [`attach_p2p_node`].
250    p2p_node: RwLock<Option<Arc<P2PNode>>>,
251    /// LMDB storage handle, attached post-construction so the paid-quote
252    /// price-floor check can read the authoritative on-disk record count without
253    /// depending on a side counter that may drift from replication/repair/prune
254    /// paths. `None` in unit tests that pre-set [`Self::test_records_override`];
255    /// production startup MUST call [`attach_storage`].
256    storage: RwLock<Option<Arc<LmdbStorage>>>,
257    /// Test-only override for the paid-quote issuer K-closest check.
258    ///
259    /// Production code derives closest peers from the attached [`P2PNode`].
260    #[cfg(any(test, feature = "test-utils"))]
261    test_paid_quote_k_closest_override: RwLock<Option<Vec<[u8; 32]>>>,
262    /// Test-only override for `completedPayments(quote_hash)`.
263    ///
264    /// Production always queries the payment vault; unit tests use this to
265    /// exercise the full verifier path without starting an EVM chain.
266    #[cfg(any(test, feature = "test-utils"))]
267    test_completed_payments_override: RwLock<HashMap<QuoteHash, Amount>>,
268    // NOTE: the test-only own-peer-id override was removed with the ADR-retired
269    // quote-freshness/staleness gate (ADR-0004 binds price to the committed
270    // count instead), so it no longer has any reader.
271    /// ADR-0004 gossip commitment cache, shared with the replication engine
272    /// (`last_commitment_by_peer`). The cross-check resolves a quote's
273    /// `commitment_pin` against the neighbour's most recently gossiped
274    /// commitment held here, *only if seen within the answerability TTL*;
275    /// otherwise the pin is treated as unknown (fetch/skip), never a penalty.
276    /// A `tokio` `RwLock` to match the engine's; read with `.await` on the
277    /// async verification path. `None` until [`Self::attach_commitment_cache`]
278    /// (unit tests, or pre-replication startup).
279    commitment_cache: RwLock<Option<CommitmentCache>>,
280    /// ADR-0004 negative cache for unresolved pin fetches: a `(peer, pin)` that
281    /// resolved to `NotRetained` or timed out is remembered here so repeated
282    /// bundles citing the same unknown pin don't re-fetch (bounding the
283    /// amplification an attacker can drive). Keyed by `(PeerId, pin)`. Behind an
284    /// `Arc` so the detached background fetch task (which runs off the payment
285    /// hot path) can read and update it without borrowing the verifier.
286    pin_fetch_negative_cache: PinFetchNegativeCache,
287    /// ADR-0004: sender to surface monetized pins (commitments that backed a
288    /// payment) to the replication engine's deterministic first-audit drainer.
289    /// `None` until [`Self::attach_monetized_pin_sender`] (unit tests, or
290    /// pre-replication startup), in which case no first audit is scheduled.
291    monetized_pin_tx:
292        RwLock<Option<tokio::sync::mpsc::UnboundedSender<crate::replication::MonetizedPinEvent>>>,
293    /// Configuration.
294    config: PaymentVerifierConfig,
295}
296
297/// Shared state for an inflight closeness verification. The leader publishes
298/// its result via the `OnceLock`; waiters read that result directly instead
299/// of racing on a cache re-check. Wrapped in an `Arc` and held both by the
300/// leader's drop guard and by each waiting task.
301struct ClosenessSlot {
302    notify: Arc<tokio::sync::Notify>,
303    /// `Some(Ok(()))` on success, `Some(Err(msg))` on failure, `None` if the
304    /// leader disappeared without publishing (panic, cancellation).
305    result: std::sync::OnceLock<std::result::Result<(), String>>,
306}
307
308impl ClosenessSlot {
309    fn new() -> Self {
310        Self {
311            notify: Arc::new(tokio::sync::Notify::new()),
312            result: std::sync::OnceLock::new(),
313        }
314    }
315
316    /// Build an owned `Notified` future that snapshots the `notify_waiters`
317    /// counter at call time. Awaiting this future after dropping external
318    /// locks is race-free: if `notify_waiters` fires between construction
319    /// and the first poll, the snapshot mismatch resolves the future
320    /// immediately.
321    fn notified_owned(&self) -> tokio::sync::futures::OwnedNotified {
322        Arc::clone(&self.notify).notified_owned()
323    }
324}
325
326/// Drop guard that publishes the leader's result, clears the inflight slot,
327/// and wakes all waiters. Fires on every exit path: success, failure, panic,
328/// future-cancellation.
329///
330/// The guard owns its own `Arc<ClosenessSlot>` so `notify_waiters` still
331/// fires even if LRU pressure evicted the slot before the leader finished.
332/// Waiters see the published result via `result.get()`; the `Notify` is only
333/// the wake-up signal.
334struct InflightGuard<'a> {
335    slot_cache: &'a Mutex<LruCache<PoolHash, Arc<ClosenessSlot>>>,
336    pool_hash: PoolHash,
337    slot: Arc<ClosenessSlot>,
338}
339
340impl InflightGuard<'_> {
341    /// Publish the leader's result. Called exactly once by the leader on
342    /// every successful or explicit-error exit. If dropped without calling
343    /// (panic, cancellation) the guard still wakes waiters but leaves
344    /// `result` empty, which waiters treat as a transient failure and retry.
345    fn publish(&self, result: &Result<()>) {
346        let stored: std::result::Result<(), String> = match result {
347            Ok(()) => Ok(()),
348            Err(e) => Err(e.to_string()),
349        };
350        let _ = self.slot.result.set(stored);
351    }
352}
353
354impl Drop for InflightGuard<'_> {
355    fn drop(&mut self) {
356        // Remove the slot entry if it's still ours. A separate leader may
357        // have inserted a new slot for the same pool_hash after LRU
358        // eviction — don't pop someone else's entry.
359        {
360            let mut cache = self.slot_cache.lock();
361            if let Some(existing) = cache.peek(&self.pool_hash) {
362                if Arc::ptr_eq(existing, &self.slot) {
363                    cache.pop(&self.pool_hash);
364                }
365            }
366        }
367        // Wake every waiter registered against OUR slot, regardless of
368        // whether the cache entry is still ours.
369        self.slot.notify.notify_waiters();
370    }
371}
372
373impl PaymentVerifier {
374    /// Create a new payment verifier.
375    #[must_use]
376    pub fn new(config: PaymentVerifierConfig) -> Self {
377        const _: () = assert!(
378            DEFAULT_POOL_CACHE_CAPACITY > 0,
379            "pool cache capacity must be > 0"
380        );
381        let cache = VerifiedCache::with_capacity(config.cache_capacity);
382        let pool_cache_size =
383            NonZeroUsize::new(DEFAULT_POOL_CACHE_CAPACITY).unwrap_or(NonZeroUsize::MIN);
384        let pool_cache = Mutex::new(LruCache::new(pool_cache_size));
385        let closeness_pass_cache = Mutex::new(LruCache::new(pool_cache_size));
386        let inflight_closeness = Mutex::new(LruCache::new(pool_cache_size));
387
388        let cache_capacity = config.cache_capacity;
389        info!("Payment verifier initialized (cache_capacity={cache_capacity}, evm=always-on, pool_cache={DEFAULT_POOL_CACHE_CAPACITY})");
390
391        // Loud warning if a production binary was accidentally built with
392        // `test-utils`: that feature flips the live-DHT payment-check
393        // fail-open switches when P2PNode isn't attached. Safe in tests, never
394        // intended for prod.
395        #[cfg(feature = "test-utils")]
396        crate::logging::error!(
397            "PaymentVerifier: built with `test-utils` feature — payment live-DHT \
398             checks fall back to fail-open when no P2PNode is attached. This \
399             feature is for test binaries only; production nodes must be built \
400             without it."
401        );
402
403        Self {
404            cache,
405            pool_cache,
406            closeness_pass_cache,
407            inflight_closeness,
408            p2p_node: RwLock::new(None),
409            storage: RwLock::new(None),
410            #[cfg(any(test, feature = "test-utils"))]
411            test_paid_quote_k_closest_override: RwLock::new(None),
412            #[cfg(any(test, feature = "test-utils"))]
413            test_completed_payments_override: RwLock::new(HashMap::new()),
414            commitment_cache: RwLock::new(None),
415            pin_fetch_negative_cache: Arc::new(Mutex::new(LruCache::new(
416                NonZeroUsize::new(crate::replication::config::PIN_FETCH_NEGATIVE_CACHE_CAPACITY)
417                    .unwrap_or(NonZeroUsize::MIN),
418            ))),
419            monetized_pin_tx: RwLock::new(None),
420            config,
421        }
422    }
423
424    /// Attach the ADR-0004 monetized-pin sender (the replication engine's
425    /// first-audit drainer channel) so the cross-check can route commitments
426    /// that backed a payment into a deterministic first audit. Idempotent;
427    /// absent (unit tests / pre-replication) no first audit is scheduled.
428    pub fn attach_monetized_pin_sender(
429        &self,
430        tx: tokio::sync::mpsc::UnboundedSender<crate::replication::MonetizedPinEvent>,
431    ) {
432        *self.monetized_pin_tx.write() = Some(tx);
433        debug!("PaymentVerifier: ADR-0004 monetized-pin sender attached");
434    }
435
436    /// Attach the ADR-0004 gossip commitment cache (the replication engine's
437    /// `last_commitment_by_peer`) so the cross-check can resolve a quote's
438    /// `commitment_pin` against the neighbour's recently gossiped commitment.
439    ///
440    /// Wired by the node once the replication engine exists, alongside the
441    /// quote generator's commitment source. Idempotent. Absent (unit tests,
442    /// pre-replication startup), the cross-check resolves no pins from gossip
443    /// and falls back to fetch/skip — never a penalty.
444    pub fn attach_commitment_cache(&self, cache: CommitmentCache) {
445        *self.commitment_cache.write() = Some(cache);
446        debug!("PaymentVerifier: ADR-0004 commitment cache attached");
447    }
448
449    /// Attach the node's [`P2PNode`] handle so paid-quote verification can
450    /// check issuer closeness, and merkle-payment verification can check
451    /// candidate `pub_keys` against the DHT's actual closest peers to the pool
452    /// midpoint.
453    ///
454    /// Production startup MUST call this once the `P2PNode` exists. Without
455    /// it, live-DHT payment checks fail CLOSED in release builds with a visible
456    /// error and fail open in test builds. Idempotent: calling twice replaces
457    /// the handle.
458    pub fn attach_p2p_node(&self, node: Arc<P2PNode>) {
459        *self.p2p_node.write() = Some(node);
460        debug!("PaymentVerifier: P2PNode attached for payment live-DHT checks");
461    }
462
463    /// Configured close-group width used by storage admission callers.
464    #[must_use]
465    pub fn close_group_size(&self) -> usize {
466        self.config.close_group_size
467    }
468
469    /// Attach the node's [`LmdbStorage`] handle so paid-quote price-floor
470    /// checks can query the authoritative on-disk record count.
471    ///
472    /// Production startup MUST call this once the storage exists; otherwise
473    /// client PUTs using paid-quote verification are rejected because
474    /// the local economic floor cannot be checked. Idempotent: calling twice
475    /// replaces the handle.
476    pub fn attach_storage(&self, storage: Arc<LmdbStorage>) {
477        *self.storage.write() = Some(storage);
478        debug!("PaymentVerifier: LmdbStorage attached for paid-quote price-floor checks");
479    }
480
481    /// Test-only setter for local closest peers used by the paid-quote
482    /// issuer K-closest check.
483    #[cfg(any(test, feature = "test-utils"))]
484    pub fn set_paid_quote_k_closest_for_tests(&self, peer_ids: Vec<[u8; 32]>) {
485        *self.test_paid_quote_k_closest_override.write() = Some(peer_ids);
486    }
487
488    /// Compatibility alias for older tests that called this the close group.
489    /// The check now accepts the K closest peers for the quoted chunk address.
490    #[cfg(any(test, feature = "test-utils"))]
491    pub fn set_paid_quote_close_group_for_tests(&self, peer_ids: Vec<[u8; 32]>) {
492        self.set_paid_quote_k_closest_for_tests(peer_ids);
493    }
494
495    /// Compatibility alias for older tests that called this the known-peer
496    /// set. The check now accepts the K closest peers for the quoted chunk
497    /// address.
498    #[cfg(any(test, feature = "test-utils"))]
499    pub fn set_paid_quote_known_peers_for_tests(&self, peer_ids: Vec<[u8; 32]>) {
500        self.set_paid_quote_k_closest_for_tests(peer_ids);
501    }
502
503    /// Test-only setter for an on-chain completed payment amount.
504    #[cfg(any(test, feature = "test-utils"))]
505    pub fn set_completed_payment_for_tests(&self, quote_hash: QuoteHash, amount: Amount) {
506        self.test_completed_payments_override
507            .write()
508            .insert(quote_hash, amount);
509    }
510
511    /// Check if payment is required for the given `XorName`.
512    ///
513    /// This is the main entry point for payment verification:
514    /// 1. Check LRU cache (fast path)
515    /// 2. If not cached, payment is required
516    ///
517    /// The fast path is context-aware. A `ClientPut` lookup is satisfied only
518    /// by a close-group store verification. A `PaidListAdmission` lookup is
519    /// satisfied by either a paid-list or client-PUT verification.
520    ///
521    /// # Arguments
522    ///
523    /// * `xorname` - The content-addressed name of the data
524    /// * `context` - The verification context of the caller
525    ///
526    /// # Returns
527    ///
528    /// * `PaymentStatus::CachedAsVerified` - Found in local cache (previously paid)
529    /// * `PaymentStatus::PaymentRequired` - Not cached (payment required)
530    pub fn check_payment_required(
531        &self,
532        xorname: &XorName,
533        context: VerificationContext,
534    ) -> PaymentStatus {
535        // Check LRU cache (fast path)
536        let cached = match context {
537            VerificationContext::ClientPut => self.cache.contains_client_put_verified(xorname),
538            VerificationContext::PaidListAdmission => {
539                self.cache.contains_paid_list_verified(xorname)
540            }
541        };
542        if cached {
543            if crate::logging::enabled!(crate::logging::Level::DEBUG) {
544                debug!("Data {} found in verified cache", hex::encode(xorname));
545            }
546            return PaymentStatus::CachedAsVerified;
547        }
548
549        // Not in cache - payment required
550        if crate::logging::enabled!(crate::logging::Level::DEBUG) {
551            debug!(
552                "Data {} not in cache - payment required",
553                hex::encode(xorname)
554            );
555        }
556        PaymentStatus::PaymentRequired
557    }
558
559    /// Verify that a PUT request has valid payment.
560    ///
561    /// This is the complete payment verification flow:
562    /// 1. Check if data is in cache (previously paid)
563    /// 2. If not, verify the provided payment proof
564    ///
565    /// # Arguments
566    ///
567    /// * `xorname` - The content-addressed name of the data
568    /// * `payment_proof` - Optional payment proof (required if not in cache)
569    /// * `context` - Which fresh admission path is verifying the proof — see
570    ///   [`VerificationContext`] for cache-strength semantics
571    ///
572    /// # Returns
573    ///
574    /// * `Ok(PaymentStatus)` - Verification succeeded
575    /// * `Err(Error::Payment)` - No payment and not cached, or payment invalid
576    ///
577    /// # Errors
578    ///
579    /// Returns an error if payment is required but not provided, or if payment is invalid.
580    pub async fn verify_payment(
581        &self,
582        xorname: &XorName,
583        payment_proof: Option<&[u8]>,
584        context: VerificationContext,
585    ) -> Result<PaymentStatus> {
586        let started = Instant::now();
587        let proof_type = payment_proof_type_label(payment_proof);
588        let proof_bytes = payment_proof.map_or(0, <[u8]>::len);
589        let result = self
590            .verify_payment_inner(xorname, payment_proof, context)
591            .await;
592        let elapsed_ms = started.elapsed().as_millis();
593
594        match &result {
595            Ok(status) if elapsed_ms >= PAYMENT_VERIFY_SLOW_LOG_MS => {
596                info!(
597                    target: "ant_node::payment::verify",
598                    "Slow payment verification: context={context:?}, proof_type={proof_type}, proof_bytes={proof_bytes}, status={status:?}, elapsed_ms={elapsed_ms}",
599                );
600            }
601            Ok(status) => {
602                debug!(
603                    target: "ant_node::payment::verify",
604                    "Payment verification: context={context:?}, proof_type={proof_type}, proof_bytes={proof_bytes}, status={status:?}, elapsed_ms={elapsed_ms}",
605                );
606            }
607            Err(e) if elapsed_ms >= PAYMENT_VERIFY_SLOW_LOG_MS => {
608                warn!(
609                    target: "ant_node::payment::verify",
610                    "Slow payment verification failed: context={context:?}, proof_type={proof_type}, proof_bytes={proof_bytes}, elapsed_ms={elapsed_ms}: {e}",
611                );
612            }
613            Err(e) => {
614                debug!(
615                    target: "ant_node::payment::verify",
616                    "Payment verification failed: context={context:?}, proof_type={proof_type}, proof_bytes={proof_bytes}, elapsed_ms={elapsed_ms}: {e}",
617                );
618            }
619        }
620
621        result
622    }
623
624    async fn verify_payment_inner(
625        &self,
626        xorname: &XorName,
627        payment_proof: Option<&[u8]>,
628        context: VerificationContext,
629    ) -> Result<PaymentStatus> {
630        // First check if payment is required
631        let status = self.check_payment_required(xorname, context);
632
633        match status {
634            PaymentStatus::CachedAsVerified => {
635                // No payment needed - already in cache
636                Ok(status)
637            }
638            PaymentStatus::PaymentRequired => {
639                // EVM verification is always on — verify the proof
640                if let Some(proof) = payment_proof {
641                    let proof_len = proof.len();
642                    if proof_len < MIN_PAYMENT_PROOF_SIZE_BYTES {
643                        return Err(Error::Payment(format!(
644                            "Payment proof too small: {proof_len} bytes (min {MIN_PAYMENT_PROOF_SIZE_BYTES})"
645                        )));
646                    }
647                    if proof_len > MAX_PAYMENT_PROOF_SIZE_BYTES {
648                        return Err(Error::Payment(format!(
649                            "Payment proof too large: {proof_len} bytes (max {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes)"
650                        )));
651                    }
652
653                    // Detect proof type from version tag byte
654                    match detect_proof_type(proof) {
655                        Some(ProofType::Merkle) => {
656                            self.verify_merkle_payment(xorname, proof, context).await?;
657                        }
658                        Some(ProofType::SingleNode) => {
659                            let parsed = deserialize_single_node_proof(proof).map_err(|e| {
660                                Error::Payment(format!("Failed to deserialize payment proof: {e}"))
661                            })?;
662
663                            if !parsed.tx_hashes.is_empty() {
664                                debug!(
665                                    "Proof includes {} transaction hash(es)",
666                                    parsed.tx_hashes.len()
667                                );
668                            }
669
670                            self.verify_evm_payment(
671                                xorname,
672                                &parsed.proof_of_payment,
673                                &parsed.commitment_sidecars,
674                                context,
675                            )
676                            .await?;
677                        }
678                        None => {
679                            let tag = proof.first().copied().unwrap_or(0);
680                            return Err(Error::Payment(format!(
681                                "Unknown payment proof type tag: 0x{tag:02x}"
682                            )));
683                        }
684                        // ant-protocol marks `ProofType` as `#[non_exhaustive]`.
685                        // A future proof variant that this node does not yet
686                        // understand must be rejected, not silently accepted.
687                        Some(_) => {
688                            let tag = proof.first().copied().unwrap_or(0);
689                            return Err(Error::Payment(format!(
690                                "Unsupported payment proof type tag: 0x{tag:02x} (this node's protocol version does not handle it — upgrade ant-node)"
691                            )));
692                        }
693                    }
694
695                    // Cache the verified xorname at the context's verification
696                    // strength. Stronger entries satisfy weaker future lookups,
697                    // but not the reverse.
698                    match context {
699                        VerificationContext::ClientPut => self.cache.insert(*xorname),
700                        VerificationContext::PaidListAdmission => {
701                            self.cache.insert_paid_list_verified(*xorname);
702                        }
703                    }
704
705                    Ok(PaymentStatus::PaymentVerified)
706                } else {
707                    // No payment provided in production mode
708                    let xorname_hex = hex::encode(xorname);
709                    Err(Error::Payment(format!(
710                        "Payment required for new data {xorname_hex}"
711                    )))
712                }
713            }
714            PaymentStatus::PaymentVerified => Err(Error::Payment(
715                "Unexpected PaymentVerified status from check_payment_required".to_string(),
716            )),
717        }
718    }
719
720    /// Get cache statistics.
721    #[must_use]
722    pub fn cache_stats(&self) -> CacheStats {
723        self.cache.stats()
724    }
725
726    /// Get the number of cached entries.
727    #[must_use]
728    pub fn cache_len(&self) -> usize {
729        self.cache.len()
730    }
731
732    /// Pre-populate the payment cache for a given address.
733    ///
734    /// This marks the address as already paid, so subsequent `verify_payment`
735    /// calls will return `CachedAsVerified` without on-chain verification.
736    /// Useful for test setups where real EVM payment is not needed.
737    #[cfg(any(test, feature = "test-utils"))]
738    pub fn cache_insert(&self, xorname: XorName) {
739        self.cache.insert(xorname);
740    }
741
742    /// Pre-populate the merkle pool cache. Testing helper that lets e2e tests
743    /// bypass the on-chain `completedMerklePayments` lookup when the point of
744    /// the test is to exercise merkle-verification logic BEFORE the on-chain
745    /// call (e.g. the pay-yourself closeness check).
746    #[cfg(any(test, feature = "test-utils"))]
747    pub fn pool_cache_insert(&self, pool_hash: PoolHash, info: OnChainPaymentInfo) {
748        let mut cache = self.pool_cache.lock();
749        cache.put(pool_hash, info);
750    }
751
752    /// Verify a single-node EVM payment proof.
753    ///
754    /// Verification steps:
755    /// 1. Between 1 and `CLOSE_GROUP_SIZE` quotes are present
756    /// 2. Median-priced candidate quotes are derived from the supplied bundle
757    /// 3. Each candidate is checked for content binding, peer binding, and a
758    ///    valid ML-DSA-65 signature
759    /// 4. Each candidate must also come from a local K-close peer
760    /// 5. A candidate is accepted only if `completedPayments(quoteHash)` is at
761    ///    least 3x the median price
762    ///
763    /// Non-median quotes are parsed only to locate the median. Their content,
764    /// peer bindings, and signatures are deliberately ignored: the paid
765    /// quote's content hash, quote hash, signature, issuer
766    /// K-closeness check, and on-chain settlement are the authority. A
767    /// one-quote proof is valid when that single quote passes these checks and
768    /// was paid 3x.
769    async fn verify_evm_payment(
770        &self,
771        xorname: &XorName,
772        payment: &ProofOfPayment,
773        commitment_sidecars: &[Vec<u8>],
774        context: VerificationContext,
775    ) -> Result<()> {
776        if crate::logging::enabled!(crate::logging::Level::DEBUG) {
777            let xorname_hex = hex::encode(xorname);
778            let quote_count = payment.peer_quotes.len();
779            debug!(
780                "Verifying EVM payment for {xorname_hex} with {quote_count} quotes ({context:?})"
781            );
782        }
783
784        Self::validate_quote_structure(payment)?;
785        // ADR-0004: re-run the `price == calculate_price(committed_key_count)`
786        // arithmetic/binding check on EVERY quote in the bundle (all single-node
787        // quotes), per the ADR's "every storer re-runs the
788        // price-equals-formula-of-count check on every quote in the bundle"
789        // rule — bundle-level, before median selection (the candidate loop below
790        // only sees median-priced quotes). This hard cutover also RETIRES the
791        // percentage-based own-quote price-staleness gate: a quote's price is
792        // now exactly bound to its committed count here (both the `(n>0, Some)`
793        // and baseline `(0, None)` shapes), and the committed responsible count
794        // legitimately differs from the on-disk count, so the old gate would
795        // FALSE-REJECT healthy ADR quotes. The binding gate supersedes it.
796        Self::validate_quote_arithmetic(payment)?;
797        let candidates = Self::legacy_median_candidates(payment)?;
798        let mut failures = Vec::with_capacity(candidates.len());
799        let mut verified_paid_quote = false;
800
801        for candidate in candidates {
802            match self
803                .verify_legacy_median_candidate(xorname, candidate)
804                .await
805            {
806                Ok(()) => {
807                    verified_paid_quote = true;
808                    break;
809                }
810                Err(err) => failures.push(err.to_string()),
811            }
812        }
813
814        if !verified_paid_quote {
815            let xorname_hex = hex::encode(xorname);
816            let details = if failures.is_empty() {
817                "no median-priced candidates were available".to_string()
818            } else {
819                failures.join("; ")
820            };
821            return Err(Error::Payment(format!(
822                "Median quote payment verification failed for {xorname_hex}: {details}"
823            )));
824        }
825
826        // ADR-0004 observe-only telemetry: log off-curve quotes only AFTER the
827        // paid (median) quote's ML-DSA-65 signature has verified above, so
828        // unauthenticated senders cannot poison rollout logs. In enforce mode
829        // `validate_quote_arithmetic` already rejected; this is a no-op there.
830        Self::log_off_curve_single_node(payment);
831
832        // ADR-0004 cross-check + first-audit enqueue (ClientPut only) runs ONLY
833        // after on-chain payment verification has SUCCEEDED above, so an unpaid
834        // (but signed) bundle can never enqueue audits or drive pin fetches —
835        // closing the free-amplification path. Fresh client-put bundles only.
836        if context == VerificationContext::ClientPut {
837            self.cross_check_quotes(payment, commitment_sidecars).await;
838        }
839
840        if crate::logging::enabled!(crate::logging::Level::INFO) {
841            let xorname_hex = hex::encode(xorname);
842            info!("EVM payment verified for {xorname_hex}");
843        }
844        Ok(())
845    }
846
847    fn legacy_median_candidates(
848        payment: &ProofOfPayment,
849    ) -> Result<Vec<LegacyMedianCandidate<'_>>> {
850        let mut sorted_quotes: Vec<(&evmlib::EncodedPeerId, &PaymentQuote)> = payment
851            .peer_quotes
852            .iter()
853            .map(|(encoded_peer_id, quote)| (encoded_peer_id, quote))
854            .collect();
855        sorted_quotes.sort_by_key(|(_, quote)| quote.price);
856        let quote_count = sorted_quotes.len();
857        let median_index = median_quote_index(quote_count);
858        let median_price = sorted_quotes
859            .get(median_index)
860            .ok_or_else(|| {
861                Error::Payment(format!("Missing paid quote at median index {median_index}"))
862            })?
863            .1
864            .price;
865        let expected_amount = median_price
866            .checked_mul(Amount::from(PAID_QUOTE_PAYMENT_MULTIPLIER))
867            .ok_or_else(|| {
868                Error::Payment(format!(
869                    "Median quote payment amount overflow for price {median_price}"
870                ))
871            })?;
872
873        if expected_amount == Amount::ZERO || median_price == Amount::ZERO {
874            return Err(Error::Payment(format!(
875                "Median quote has zero price/amount (price={median_price}, amount={expected_amount}); refusing to verify as paid"
876            )));
877        }
878
879        Ok(sorted_quotes
880            .into_iter()
881            .filter(|(_, quote)| quote.price == median_price)
882            .map(|(encoded_peer_id, quote)| LegacyMedianCandidate {
883                encoded_peer_id,
884                quote,
885                expected_amount,
886            })
887            .collect())
888    }
889
890    async fn verify_legacy_median_candidate(
891        &self,
892        xorname: &XorName,
893        candidate: LegacyMedianCandidate<'_>,
894    ) -> Result<()> {
895        Self::validate_paid_quote_content(xorname, candidate)?;
896        let issuer_peer_id =
897            Self::validate_paid_quote_peer_binding(candidate.encoded_peer_id, candidate.quote)?;
898
899        self.validate_paid_quote_issuer_k_closest(xorname, &issuer_peer_id)
900            .await?;
901
902        Self::validate_paid_quote_signature(candidate).await?;
903
904        let on_chain_amount = self
905            .completed_payment_amount(candidate.quote.hash())
906            .await?;
907        if on_chain_amount >= candidate.expected_amount {
908            return Ok(());
909        }
910
911        Err(Error::Payment(format!(
912            "Median-priced quote for peer {:?} was not paid enough: expected at least {}, got {on_chain_amount}",
913            candidate.encoded_peer_id, candidate.expected_amount
914        )))
915    }
916
917    fn validate_paid_quote_content(
918        xorname: &XorName,
919        candidate: LegacyMedianCandidate<'_>,
920    ) -> Result<()> {
921        if verify_quote_content(candidate.quote, xorname) {
922            return Ok(());
923        }
924
925        let expected_hex = hex::encode(xorname);
926        let actual_hex = hex::encode(candidate.quote.content.0);
927        Err(Error::Payment(format!(
928            "Paid quote content address mismatch for peer {:?}: expected {expected_hex}, got {actual_hex}",
929            candidate.encoded_peer_id
930        )))
931    }
932
933    async fn validate_paid_quote_signature(candidate: LegacyMedianCandidate<'_>) -> Result<()> {
934        let quote_for_signature = candidate.quote.clone();
935        let peer_id_for_error = candidate.encoded_peer_id.clone();
936        tokio::task::spawn_blocking(move || {
937            if !verify_quote_signature(&quote_for_signature) {
938                return Err(Error::Payment(format!(
939                    "Paid quote ML-DSA-65 signature verification failed for peer {peer_id_for_error:?}"
940                )));
941            }
942            Ok(())
943        })
944        .await
945        .map_err(|e| Error::Payment(format!("Signature verification task failed: {e}")))?
946    }
947
948    async fn completed_payment_amount(&self, quote_hash: QuoteHash) -> Result<Amount> {
949        #[cfg(any(test, feature = "test-utils"))]
950        {
951            let completed_payment_override = {
952                self.test_completed_payments_override
953                    .read()
954                    .get(&quote_hash)
955                    .copied()
956            };
957            if let Some(amount) = completed_payment_override {
958                return Ok(amount);
959            }
960        }
961
962        let provider = evmlib::utils::http_provider(self.config.evm.network.rpc_url().clone());
963        let vault_address = *self.config.evm.network.payment_vault_address();
964        let contract = payment_vault::interface::IPaymentVault::new(vault_address, provider);
965
966        let result = contract
967            .completedPayments(quote_hash)
968            .call()
969            .await
970            .map_err(|e| Error::Payment(format!("completedPayments lookup failed: {e}")))?;
971
972        Ok(Amount::from(result.amount))
973    }
974
975    fn validate_paid_quote_peer_binding(
976        encoded_peer_id: &evmlib::EncodedPeerId,
977        quote: &PaymentQuote,
978    ) -> Result<PeerId> {
979        let expected_peer_id = peer_id_from_public_key_bytes(&quote.pub_key)
980            .map_err(|e| Error::Payment(format!("Invalid ML-DSA public key in quote: {e}")))?;
981
982        if expected_peer_id.as_bytes() != encoded_peer_id.as_bytes() {
983            let expected_hex = expected_peer_id.to_hex();
984            let actual_hex = hex::encode(encoded_peer_id.as_bytes());
985            return Err(Error::Payment(format!(
986                "Paid quote pub_key does not belong to claimed peer {encoded_peer_id:?}: \
987                 BLAKE3(pub_key) = {expected_hex}, peer_id = {actual_hex}"
988            )));
989        }
990
991        Ok(expected_peer_id)
992    }
993
994    async fn validate_paid_quote_issuer_k_closest(
995        &self,
996        xorname: &XorName,
997        issuer_peer_id: &PeerId,
998    ) -> Result<()> {
999        #[cfg(any(test, feature = "test-utils"))]
1000        if let Some(k_closest_peer_ids) = self.test_paid_quote_k_closest_override.read().as_ref() {
1001            if k_closest_peer_ids
1002                .iter()
1003                .any(|peer_id| peer_id == issuer_peer_id.as_bytes())
1004            {
1005                return Ok(());
1006            }
1007            let issuer_closeness_width = PAID_QUOTE_ISSUER_CLOSENESS_WIDTH;
1008            return Err(Error::Payment(format!(
1009                "Paid quote issuer {} is not among this node's local K={issuer_closeness_width} closest peers for {}",
1010                issuer_peer_id.to_hex(),
1011                hex::encode(xorname)
1012            )));
1013        }
1014
1015        let attached = self.p2p_node.read().as_ref().map(Arc::clone);
1016        let Some(p2p_node) = attached else {
1017            #[cfg(any(test, feature = "test-utils"))]
1018            {
1019                crate::logging::warn!(
1020                    "PaymentVerifier: no P2PNode attached; paid-quote issuer \
1021                     K-closest check SKIPPED (test build). Production startup MUST call \
1022                     PaymentVerifier::attach_p2p_node."
1023                );
1024                return Ok(());
1025            }
1026            #[cfg(not(any(test, feature = "test-utils")))]
1027            {
1028                crate::logging::error!(
1029                    "PaymentVerifier: no P2PNode attached; rejecting paid-quote \
1030                     payment. This is a node-startup bug — \
1031                     PaymentVerifier::attach_p2p_node must be called before \
1032                     any PUT handler runs."
1033                );
1034                return Err(Error::Payment(
1035                    "Paid quote rejected: verifier is not wired to the P2P \
1036                     layer; cannot verify issuer closeness."
1037                        .into(),
1038                ));
1039            }
1040        };
1041
1042        // Closeness *verification* must mirror the uploader's pure XOR-distance
1043        // peer selection. `find_closest_nodes_local_with_self` reranks the local
1044        // routing table by reachability (preferring directly-reachable peers,
1045        // XOR only as a tiebreaker), which demotes an XOR-close relay-only /
1046        // NAT'd peer out of the compared window and falsely rejects an honest
1047        // payment that legitimately quoted that peer. Use the XOR-only sibling
1048        // so this check matches how the client chose the quoted K-closest set.
1049        let issuer_closeness_width = PAID_QUOTE_ISSUER_CLOSENESS_WIDTH;
1050        let closest = p2p_node
1051            .dht_manager()
1052            .find_closest_nodes_local_by_distance_with_self(xorname, issuer_closeness_width)
1053            .await;
1054        if closest.iter().any(|node| node.peer_id == *issuer_peer_id) {
1055            return Ok(());
1056        }
1057
1058        Err(Error::Payment(format!(
1059            "Paid quote issuer {} is not among this node's local K={issuer_closeness_width} closest peers for {}",
1060            issuer_peer_id.to_hex(),
1061            hex::encode(xorname)
1062        )))
1063    }
1064
1065    /// Validate quote count, uniqueness, and basic structure.
1066    fn validate_quote_structure(payment: &ProofOfPayment) -> Result<()> {
1067        if payment.peer_quotes.is_empty() {
1068            return Err(Error::Payment("Payment has no quotes".to_string()));
1069        }
1070
1071        let quote_count = payment.peer_quotes.len();
1072        if quote_count > CLOSE_GROUP_SIZE {
1073            return Err(Error::Payment(format!(
1074                "Payment must have at most {CLOSE_GROUP_SIZE} quotes, got {quote_count}"
1075            )));
1076        }
1077
1078        let mut seen: Vec<&evmlib::EncodedPeerId> = Vec::with_capacity(quote_count);
1079        for (encoded_peer_id, _) in &payment.peer_quotes {
1080            if seen.contains(&encoded_peer_id) {
1081                return Err(Error::Payment(format!(
1082                    "Duplicate peer ID in payment quotes: {encoded_peer_id:?}"
1083                )));
1084            }
1085            seen.push(encoded_peer_id);
1086        }
1087
1088        Ok(())
1089    }
1090
1091    /// ADR-0004: enforce that every quoted price lies exactly on the public
1092    /// pricing curve.
1093    ///
1094    /// **Scope** (this slice): canonicality only. The gate proves the price is
1095    /// some `calculate_price(n)` for a non-negative integer `n`; it does NOT
1096    /// yet prove `n` matches a signed commitment, because `PaymentQuote` lives
1097    /// in evmlib (crates.io) and has no `claimed_key_count` / `commitment_pin`
1098    /// fields yet. A future slice will bind `n` to a signed commitment once
1099    /// the evmlib quote payload is extended. Until then, an attacker can still
1100    /// quote `calculate_price(fake_n)` for any fake count and pass this gate;
1101    /// what dies here is the strictly weaker attack of picking a price *off*
1102    /// the curve altogether.
1103    ///
1104    /// **Check**: exact recomputation, never price-inversion. We derive the
1105    /// candidate `n` for which `quote.price` would be the curve value (using
1106    /// the existing inverse `derive_records_stored_from_price`, which floors),
1107    /// then recompute `calculate_price(n)` and require strict equality.
1108    /// On-curve prices round-trip exactly; off-curve prices floor to a smaller
1109    /// `n` whose recomputed value is strictly less than `quote.price` and so
1110    /// are rejected. Floor-then-equality is the canonicality test the ADR
1111    /// specifies; price inversion alone would silently accept any value
1112    /// between two curve points.
1113    ///
1114    /// **Where it runs**: in every [`VerificationContext`] over **every**
1115    /// quote in **both** quote types — all 7 single-node quotes
1116    /// ([`Self::validate_quote_arithmetic`]) and all 16 merkle candidates
1117    /// ([`Self::validate_merkle_candidate_arithmetic`]) — because the rule
1118    /// "every storer re-runs the price-equals-formula-of-count check on every
1119    /// quote in the bundle" (ADR-0004) needs no peer-specific state and depends
1120    /// only on the bundle itself, so every honest storer reaches the same
1121    /// verdict with no split-brain risk.
1122    ///
1123    /// **Reject-only**, per ADR-0004: no trust evidence is emitted, no audit
1124    /// is scheduled. The rejection is the consequence. The gate is
1125    /// rollout-gated by
1126    /// [`crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED`]; when
1127    /// `false`, off-curve quotes are accepted and only telemetered
1128    /// ([`Self::log_off_curve_single_node`] /
1129    /// [`Self::log_off_curve_merkle`]), matching ADR-0004's observe-only
1130    /// rollout. Telemetry is invoked **after** ML-DSA-65 signature
1131    /// verification so unauthenticated senders cannot poison the rollout
1132    /// logs.
1133    fn validate_quote_arithmetic(payment: &ProofOfPayment) -> Result<()> {
1134        if !crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED {
1135            return Ok(());
1136        }
1137        for (encoded_peer_id, quote) in &payment.peer_quotes {
1138            if let Some(detail) = Self::quote_arithmetic_violation(quote) {
1139                return Err(Error::Payment(format!(
1140                    "ADR-0004 off-curve quote rejected for peer {encoded_peer_id:?}: {detail}"
1141                )));
1142            }
1143        }
1144        Ok(())
1145    }
1146
1147    /// The ADR-0004 forced-price rule for a single quote, returning a human
1148    /// diagnostic iff the quote violates it. Shared by single-node quotes and
1149    /// merkle candidates via [`Self::binding_violation`].
1150    ///
1151    /// The rule is the ADR's exact one — `price == calculate_price(
1152    /// committed_key_count)`, recomputed, never inverted from the price (which
1153    /// rounds) — PLUS a binding-shape check. There is no "legacy degradation"
1154    /// that infers an old quote from its field values: a `(0, None)` quote is
1155    /// rejected unless its price is exactly `calculate_price(0)`, closing the
1156    /// bypass where a modified node strips the pin yet prices above baseline.
1157    /// Old-format quotes (which never carried these fields) are tolerated only
1158    /// at the *wire-decode* layer, where they decode as `(0, None)` and are then
1159    /// held to the same baseline rule; an explicit version negotiation, not
1160    /// field inference, is the sanctioned path if non-baseline legacy quotes
1161    /// must ever be accepted.
1162    fn quote_arithmetic_violation(quote: &evmlib::PaymentQuote) -> Option<String> {
1163        Self::binding_violation(
1164            quote.committed_key_count,
1165            quote.commitment_pin,
1166            &quote.price,
1167        )
1168    }
1169
1170    /// The shared ADR-0004 binding rule over a `(committed_key_count,
1171    /// commitment_pin, price)` triple, used for both quote types.
1172    ///
1173    /// Enforces, in order:
1174    /// 1. **Shape.** `(0, None)` baseline or `(n>0, Some(pin))` bound; the mixed
1175    ///    shapes `(n>0, None)` and `(0, Some(_))` are always rejected — a count
1176    ///    without a pin is unauditable, and a pin without a count is incoherent.
1177    /// 2. **Cap.** `committed_key_count <= MAX_COMMITMENT_KEY_COUNT`; a count a
1178    ///    commitment could never legitimately attest is rejected before pricing.
1179    /// 3. **Forced price.** `price == calculate_price(committed_key_count)`, by
1180    ///    exact recomputation.
1181    fn binding_violation(
1182        committed_key_count: u32,
1183        commitment_pin: Option<[u8; 32]>,
1184        price: &Amount,
1185    ) -> Option<String> {
1186        match (committed_key_count, commitment_pin.is_some()) {
1187            (0, false) | (1.., true) => {}
1188            (1.., false) => {
1189                return Some(format!(
1190                    "binding shape invalid: committed_key_count={committed_key_count} > 0 \
1191                     but commitment_pin is None (unauditable count)"
1192                ));
1193            }
1194            (0, true) => {
1195                return Some(
1196                    "binding shape invalid: committed_key_count=0 with a commitment_pin \
1197                     (incoherent baseline)"
1198                        .to_string(),
1199                );
1200            }
1201        }
1202        if committed_key_count > crate::replication::commitment::MAX_COMMITMENT_KEY_COUNT {
1203            return Some(format!(
1204                "committed_key_count={committed_key_count} exceeds MAX_COMMITMENT_KEY_COUNT={}",
1205                crate::replication::commitment::MAX_COMMITMENT_KEY_COUNT
1206            ));
1207        }
1208        let expected = calculate_price(Self::candidate_count_to_usize(u64::from(
1209            committed_key_count,
1210        )));
1211        if &expected == price {
1212            None
1213        } else {
1214            Some(format!(
1215                "price {price} does not equal calculate_price(committed_key_count={committed_key_count}) = {expected}"
1216            ))
1217        }
1218    }
1219
1220    /// Pure ADR-0004 cross-check: compare a quote's claimed `(key_count, pin)`
1221    /// against a resolved signed commitment.
1222    ///
1223    /// This is the decision core of "peers cross-check the original": given a
1224    /// quote's binding and the actual `StorageCommitment` the pin was resolved
1225    /// to (from the sidecar, the gossip cache, or a fetch), decide whether the
1226    /// quote contradicts the commitment. It is deliberately a pure function over
1227    /// the two artifacts so it is exhaustively unit-testable without any cache,
1228    /// network, or trust wiring; the caller owns resolution and emission.
1229    ///
1230    /// Outcomes:
1231    /// - [`CrossCheck::Match`] — the pin matches the commitment's hash and the
1232    ///   counts agree: nothing to report.
1233    /// - [`CrossCheck::Mismatch`] — the pin matches the commitment's hash but
1234    ///   the quote's `committed_key_count` differs from the commitment's
1235    ///   `key_count`. Two artifacts signed by the same key contradict each
1236    ///   other: this is the deterministic, first-occurrence evidence.
1237    /// - [`CrossCheck::PinDoesNotResolve`] — the supplied commitment's hash does
1238    ///   not equal the quote's pin (wrong/garbled resolution). NOT evidence: the
1239    ///   caller must treat it as an unresolved pin (fetch/skip), never a
1240    ///   penalty, exactly like an unanswerable pin.
1241    ///
1242    /// A baseline quote `(0, None)` is never cross-checked (it pins nothing);
1243    /// callers skip it before reaching here.
1244    fn cross_check_binding(
1245        quoted_key_count: u32,
1246        quoted_pin: [u8; 32],
1247        commitment: &crate::replication::commitment::StorageCommitment,
1248    ) -> CrossCheck {
1249        // The pin IS the commitment hash; if the resolved commitment hashes to
1250        // something else, this is not the artifact the quote pinned.
1251        match crate::replication::commitment::commitment_hash(commitment) {
1252            Some(h) if h == quoted_pin => {
1253                if commitment.key_count == quoted_key_count {
1254                    CrossCheck::Match
1255                } else {
1256                    CrossCheck::Mismatch {
1257                        quoted_key_count,
1258                        committed_key_count: commitment.key_count,
1259                    }
1260                }
1261            }
1262            _ => CrossCheck::PinDoesNotResolve,
1263        }
1264    }
1265
1266    /// Resolve a cached peer commitment record to its commitment *only if* it
1267    /// was seen within the answerability TTL; a staler entry is treated as
1268    /// unknown (ADR-0004: "a cached commitment older than the answerability TTL
1269    /// is treated as unknown"). Pure over `(record, now, ttl)` so the TTL
1270    /// boundary is unit-testable without the async cache/network path.
1271    fn fresh_cached_commitment(
1272        rec: &crate::replication::commitment_state::PeerCommitmentRecord,
1273        pin: [u8; 32],
1274        now: std::time::Instant,
1275        ttl: std::time::Duration,
1276    ) -> Option<crate::replication::commitment::StorageCommitment> {
1277        if now.saturating_duration_since(rec.received_at) >= ttl {
1278            return None; // stale cache entry -> treat as unknown
1279        }
1280        // Only resolve when the cached commitment is actually the one the quote
1281        // pinned. The auditor cache holds a peer's LATEST gossiped commitment,
1282        // which may be a DIFFERENT pin than this quote's; returning it would make
1283        // `cross_check_binding` yield `PinDoesNotResolve` and wrongly suppress
1284        // the fetch fallback for the quoted pin. A pin mismatch here means "not
1285        // cached" -> fall through to fetch.
1286        if rec.commitment_hash() != Some(pin) {
1287            return None;
1288        }
1289        rec.last_commitment().cloned()
1290    }
1291
1292    /// Resolve a `(peer, pin)` from the gossip commitment cache, if the cache is
1293    /// wired and holds a fresh entry whose hash matches the pin. Shared by the
1294    /// single-node and merkle cross-check paths.
1295    async fn cache_resolve(
1296        cache: Option<&CommitmentCache>,
1297        peer_id: PeerId,
1298        pin: [u8; 32],
1299        now: std::time::Instant,
1300        ttl: std::time::Duration,
1301    ) -> Option<crate::replication::commitment::StorageCommitment> {
1302        let cache = cache?;
1303        let guard = cache.read().await;
1304        guard
1305            .get(&peer_id)
1306            .and_then(|rec| Self::fresh_cached_commitment(rec, pin, now, ttl))
1307    }
1308
1309    /// Parse and validate ADR-0004 commitment sidecars into a `(peer, pin) ->
1310    /// commitment` map. Each blob is deserialized and held to the SAME gates as
1311    /// a gossip-ingested or fetched commitment (peer id derived from its own
1312    /// `sender_peer_id`, `BLAKE3(pubkey) == sender_peer_id`, valid signature),
1313    /// keyed by `(its own peer, its own hash)`. Resolution then matches a quote
1314    /// only when both the quote's peer AND pin equal the sidecar's, so a sidecar
1315    /// can never satisfy a different peer's or a different pin's quote. An
1316    /// unparseable or invalid sidecar is silently skipped (resolution falls back
1317    /// to gossip/fetch), never a hard error on the payment path.
1318    fn index_valid_sidecars(
1319        sidecars: &[Vec<u8>],
1320    ) -> HashMap<(PeerId, [u8; 32]), crate::replication::commitment::StorageCommitment> {
1321        use crate::replication::commitment::MAX_COMMITMENT_SIDECAR_BYTES;
1322        let mut map = HashMap::new();
1323        // Bound the number of sidecars we even look at: a legitimate bundle has
1324        // at most one commitment per quote/candidate. `MAX_SIDECARS_PER_BUNDLE`
1325        // (= CANDIDATES_PER_POOL, the larger of the two) caps the deserialize/
1326        // verify work a malicious client can force on the hot path.
1327        for blob in sidecars.iter().take(MAX_SIDECARS_PER_BUNDLE) {
1328            // Cap blob size before parsing: never attempt to deserialize an
1329            // oversized commitment.
1330            if blob.len() > MAX_COMMITMENT_SIDECAR_BYTES {
1331                continue;
1332            }
1333            let Ok(commitment) =
1334                rmp_serde::from_slice::<crate::replication::commitment::StorageCommitment>(blob)
1335            else {
1336                continue; // unparseable -> skip
1337            };
1338            let peer_id = PeerId::from_bytes(commitment.sender_peer_id);
1339            let Some(pin) = crate::replication::commitment::commitment_hash(&commitment) else {
1340                continue;
1341            };
1342            // Validate against its own (peer, pin): peer binding + pubkey
1343            // derivation + signature + hash==pin.
1344            if Self::fetched_commitment_is_valid(&commitment, &peer_id, pin) {
1345                map.insert((peer_id, pin), commitment);
1346            }
1347        }
1348        map
1349    }
1350
1351    /// ADR-0004 "peers cross-check the original": for each non-baseline quote in
1352    /// a client-put bundle, resolve its `commitment_pin` and report a count/pin
1353    /// contradiction.
1354    ///
1355    /// Resolution order: the sidecar first (the commitment arrived with the
1356    /// quote, validated synchronously — no state, no network), then the gossip
1357    /// cache (only if the neighbour's commitment was seen within
1358    /// `GOSSIP_ANSWERABILITY_TTL`; a staler entry is treated as unknown, per the
1359    /// ADR's "cached commitment older than the answerability TTL is treated as
1360    /// unknown"), then an off-hot-path `GetCommitmentByPin` fetch for pins still
1361    /// unresolved. A pin that resolves nowhere is simply skipped — an unresolved
1362    /// pin is never a penalty.
1363    ///
1364    /// A genuine [`CrossCheck::Mismatch`] is a deterministic, first-occurrence
1365    /// contradiction between two same-key-signed artifacts: when enforcing, it
1366    /// emits [`FailureEvidence::QuoteCommitmentMismatch`] to the trust engine
1367    /// (same lane as a confirmed deterministic audit failure — NOT the timeout
1368    /// silence lane); when observe-only, it only logs. Always best-effort: a
1369    /// missing cache or absent `P2PNode` degrades to "resolve nothing", never an
1370    /// error on the payment path — the synchronous arithmetic gate and the
1371    /// later audit remain the load-bearing checks.
1372    async fn cross_check_quotes(&self, payment: &ProofOfPayment, commitment_sidecars: &[Vec<u8>]) {
1373        let now = std::time::Instant::now();
1374        let ttl = crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
1375        let p2p = self.p2p_node.read().as_ref().map(Arc::clone);
1376        let monetized_pin_tx = self.monetized_pin_tx.read().as_ref().cloned();
1377        let cache = self.commitment_cache.read().as_ref().map(Arc::clone);
1378
1379        // ADR-0004 "the commitment arrived with the quote": parse and FULLY
1380        // validate the sidecars (peer/pubkey/signature/hash gates, keyed by
1381        // `(peer, pin)`), so the cross-check resolves synchronously without a
1382        // gossip-cache hit or a post-payment fetch. An invalid sidecar is simply
1383        // dropped (resolution falls back to gossip/fetch), never a hard error.
1384        let sidecar_map = Self::index_valid_sidecars(commitment_sidecars);
1385
1386        // Inline pass: resolve from the sidecar first, then the gossip cache
1387        // (cheap, no network). Pins that don't resolve here are collected for
1388        // the off-hot-path fetch.
1389        let mut unresolved: Vec<(PeerId, [u8; 32], u32, Vec<u8>)> = Vec::new();
1390        for (encoded_peer_id, quote) in &payment.peer_quotes {
1391            let Some(pin) = quote.commitment_pin else {
1392                continue; // baseline quote pins nothing
1393            };
1394            let peer_id = PeerId::from_bytes(*encoded_peer_id.as_bytes());
1395
1396            // ADR-0004: this commitment backed a payment — route it for a
1397            // deterministic first audit (the drainer dedups by pin and respects
1398            // the cooldown). Best-effort: a closed channel just means no first
1399            // audit is scheduled, never an error on the payment path.
1400            if let Some(ref tx) = monetized_pin_tx {
1401                let _ = tx.send(crate::replication::MonetizedPinEvent {
1402                    peer: peer_id,
1403                    pin,
1404                    key_count: quote.committed_key_count,
1405                    quote_ts: quote.timestamp,
1406                });
1407            }
1408            // Resolution order: sidecar (synchronous, no state) -> gossip cache
1409            // (fresh within TTL) -> fetch fallback (collected as unresolved).
1410            let resolved = match sidecar_map.get(&(peer_id, pin)) {
1411                Some(c) => Some(c.clone()),
1412                None => Self::cache_resolve(cache.as_ref(), peer_id, pin, now, ttl).await,
1413            };
1414            match resolved {
1415                Some(commitment) => {
1416                    let artifact = rmp_serde::to_vec(quote).unwrap_or_default();
1417                    Self::handle_cross_check(
1418                        &peer_id,
1419                        pin,
1420                        quote.committed_key_count,
1421                        artifact,
1422                        &commitment,
1423                        p2p.as_ref(),
1424                    )
1425                    .await;
1426                }
1427                None => unresolved.push((
1428                    peer_id,
1429                    pin,
1430                    quote.committed_key_count,
1431                    rmp_serde::to_vec(quote).unwrap_or_default(),
1432                )),
1433            }
1434        }
1435
1436        // Off-hot-path fallback: fetch the unresolved pins via
1437        // `GetCommitmentByPin` and cross-check the results in a detached task,
1438        // so `verify_payment` does not block on the network.
1439        if unresolved.is_empty() {
1440            return;
1441        }
1442        let Some(p2p) = p2p else {
1443            return; // no P2P handle: cannot fetch, leave graced
1444        };
1445        let neg_cache = Arc::clone(&self.pin_fetch_negative_cache);
1446        tokio::spawn(async move {
1447            Self::drain_unresolved_pin_fetches(&p2p, &neg_cache, unresolved).await;
1448        });
1449    }
1450
1451    /// Fetch each unresolved pin via `GetCommitmentByPin` and cross-check the
1452    /// result. Bounded at [`MAX_PIN_FETCHES_PER_BUNDLE`] per call, negatively
1453    /// cached per `(peer, pin)`, and graced on any miss/timeout. Shared by the
1454    /// single-node and merkle cross-check paths; meant to run in a detached task
1455    /// off the payment hot path.
1456    async fn drain_unresolved_pin_fetches(
1457        p2p: &Arc<P2PNode>,
1458        neg_cache: &PinFetchNegativeCache,
1459        unresolved: Vec<(PeerId, [u8; 32], u32, Vec<u8>)>,
1460    ) {
1461        let mut fetched = 0usize;
1462        for (peer_id, pin, quoted_key_count, artifact) in unresolved {
1463            if fetched >= crate::replication::config::MAX_PIN_FETCHES_PER_BUNDLE {
1464                debug!("ADR-0004 pin-fetch cap reached for this bundle; leaving rest graced");
1465                break;
1466            }
1467            // Skip pins already known-unresolvable for this peer.
1468            if neg_cache.lock().get(&(peer_id, pin)).is_some() {
1469                continue;
1470            }
1471            fetched += 1;
1472            match Self::fetch_commitment_by_pin(p2p, &peer_id, pin).await {
1473                Some(commitment) => {
1474                    Self::handle_cross_check(
1475                        &peer_id,
1476                        pin,
1477                        quoted_key_count,
1478                        artifact,
1479                        &commitment,
1480                        Some(p2p),
1481                    )
1482                    .await;
1483                }
1484                None => {
1485                    // NotRetained / timeout / malformed: graced (never a
1486                    // penalty), but remembered so we don't re-fetch.
1487                    neg_cache.lock().put((peer_id, pin), ());
1488                }
1489            }
1490        }
1491    }
1492
1493    /// Apply the ADR-0004 cross-check verdict for one resolved `(peer, pin,
1494    /// quoted_count)` against `commitment`, emitting a trust failure on a
1495    /// genuine mismatch (when enforcing) or logging it (observe-only). Shared by
1496    /// the inline cache pass and the background fetch path so both reach the
1497    /// same verdict and emission.
1498    async fn handle_cross_check(
1499        peer_id: &PeerId,
1500        pin: [u8; 32],
1501        quoted_key_count: u32,
1502        quote_artifact: Vec<u8>,
1503        commitment: &crate::replication::commitment::StorageCommitment,
1504        p2p: Option<&Arc<P2PNode>>,
1505    ) {
1506        let CrossCheck::Mismatch {
1507            quoted_key_count,
1508            committed_key_count,
1509        } = Self::cross_check_binding(quoted_key_count, pin, commitment)
1510        else {
1511            return; // Match or PinDoesNotResolve: nothing to report
1512        };
1513        // The evidence is only meaningful if it carries the signed quote
1514        // artifact (one of the two contradicting same-key signatures). An empty
1515        // artifact — a re-serialization failure upstream — would produce
1516        // non-portable, unverifiable evidence, so grace it (log) instead of
1517        // emitting it: the deterministic first audit still convicts a genuine
1518        // inflater on the disk bytes.
1519        if quote_artifact.is_empty() {
1520            warn!(
1521                "ADR-0004 quote/commitment mismatch for {peer_id}: dropping evidence, \
1522                 quote artifact failed to serialize (graced; the audit still runs)"
1523            );
1524            return;
1525        }
1526        // Build the portable evidence variant — the two same-key-signed
1527        // artifacts that contradict each other, carried in full so any third
1528        // party can re-verify both signatures and recompute the contradiction.
1529        // This value IS the record; `emit_mismatch_evidence` turns it into the
1530        // trust action (or an observe-only log).
1531        let evidence = crate::replication::types::FailureEvidence::QuoteCommitmentMismatch {
1532            peer: *peer_id,
1533            pinned_commitment: pin,
1534            quoted_key_count,
1535            committed_key_count,
1536            quote_artifact,
1537            commitment: Box::new(commitment.clone()),
1538        };
1539        Self::emit_mismatch_evidence(&evidence, p2p).await;
1540    }
1541
1542    /// Route a `QuoteCommitmentMismatch` evidence record: when enforcing, report
1543    /// it to the trust engine as a confirmed deterministic failure (an
1544    /// `ApplicationFailure` — same lane as a confirmed audit failure, NOT the
1545    /// timeout silence lane); when observe-only, only log it. Separated so the
1546    /// evidence→action mapping is unit-testable independent of resolution.
1547    async fn emit_mismatch_evidence(
1548        evidence: &crate::replication::types::FailureEvidence,
1549        p2p: Option<&Arc<P2PNode>>,
1550    ) {
1551        let crate::replication::types::FailureEvidence::QuoteCommitmentMismatch {
1552            peer,
1553            quoted_key_count,
1554            committed_key_count,
1555            ..
1556        } = evidence
1557        else {
1558            return; // only this variant is handled here
1559        };
1560        let enforce = crate::replication::config::QUOTE_COMMITMENT_MISMATCH_TRUST_ENABLED;
1561        if enforce {
1562            warn!(
1563                "ADR-0004 quote/commitment mismatch (enforcing) for {peer}: quote claims \
1564                 {quoted_key_count} keys but pinned commitment attests {committed_key_count}"
1565            );
1566            if let Some(p2p) = p2p {
1567                p2p.report_trust_event(
1568                    peer,
1569                    saorsa_core::TrustEvent::ApplicationFailure(
1570                        crate::replication::config::AUDIT_FAILURE_TRUST_WEIGHT,
1571                    ),
1572                )
1573                .await;
1574            }
1575        } else {
1576            warn!(
1577                "ADR-0004 quote/commitment mismatch observed (not enforcing) for {peer}: quote \
1578                 claims {quoted_key_count} keys but pinned commitment attests {committed_key_count}"
1579            );
1580        }
1581    }
1582
1583    /// Fetch a peer's commitment by pin via `GetCommitmentByPin`, returning it
1584    /// only if the peer answered `Found` with a commitment that (a) is validly
1585    /// signed and peer-bound and (b) actually hashes to the requested pin.
1586    /// `None` on `NotRetained`, timeout, malformed, or any verification failure
1587    /// — all graced (the caller never penalises an unresolved pin).
1588    async fn fetch_commitment_by_pin(
1589        p2p: &Arc<P2PNode>,
1590        peer_id: &PeerId,
1591        pin: [u8; 32],
1592    ) -> Option<crate::replication::commitment::StorageCommitment> {
1593        use crate::replication::config::{PIN_FETCH_TIMEOUT, REPLICATION_PROTOCOL_ID};
1594        use crate::replication::protocol::{
1595            GetCommitmentByPin, GetCommitmentByPinResponse, ReplicationMessage,
1596            ReplicationMessageBody,
1597        };
1598        let msg = ReplicationMessage {
1599            request_id: 0,
1600            body: ReplicationMessageBody::GetCommitmentByPin(GetCommitmentByPin { pin }),
1601        };
1602        let encoded = msg.encode().ok()?;
1603        let resp = p2p
1604            .send_request(peer_id, REPLICATION_PROTOCOL_ID, encoded, PIN_FETCH_TIMEOUT)
1605            .await
1606            .ok()?;
1607        let decoded = ReplicationMessage::decode(&resp.data).ok()?;
1608        let ReplicationMessageBody::GetCommitmentByPinResponse(GetCommitmentByPinResponse::Found {
1609            commitment,
1610        }) = decoded.body
1611        else {
1612            return None; // NotRetained / unexpected -> graced
1613        };
1614        Self::fetched_commitment_is_valid(&commitment, peer_id, pin).then_some(commitment)
1615    }
1616
1617    /// The untrusted-fetched-commitment validation gates, pure over
1618    /// `(commitment, peer_id, pin)` so they are unit-testable. A fetched
1619    /// commitment is accepted only if it passes the SAME gates as a gossip
1620    /// ingest, so a peer cannot answer with another peer's (validly signed)
1621    /// commitment and have it pass as its own:
1622    ///   (a) it is bound to THIS peer (`sender_peer_id == peer_id`),
1623    ///   (b) the embedded pubkey derives that peer id (`BLAKE3(pk) == id`),
1624    ///   (c) its signature is valid (binds the pubkey),
1625    ///   (d) it actually hashes to the pin we asked for.
1626    fn fetched_commitment_is_valid(
1627        commitment: &crate::replication::commitment::StorageCommitment,
1628        peer_id: &PeerId,
1629        pin: [u8; 32],
1630    ) -> bool {
1631        commitment.sender_peer_id == *peer_id.as_bytes()
1632            && *blake3::hash(&commitment.sender_public_key).as_bytes() == commitment.sender_peer_id
1633            && crate::replication::commitment::verify_commitment_signature(commitment)
1634            && crate::replication::commitment::commitment_hash(commitment) == Some(pin)
1635    }
1636
1637    /// Single-node telemetry for off-curve quotes. Always returns; never
1638    /// errors. MUST be called only after ML-DSA-65 signature verification has
1639    /// passed, so unauthenticated peers cannot drive log volume.
1640    fn log_off_curve_single_node(payment: &ProofOfPayment) {
1641        if crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED {
1642            return; // enforce mode already rejected; no separate telemetry.
1643        }
1644        for (encoded_peer_id, quote) in &payment.peer_quotes {
1645            if let Some(detail) = Self::quote_arithmetic_violation(quote) {
1646                warn!(
1647                    "ADR-0004 off-curve single-node quote observed (not enforcing): \
1648                     peer {encoded_peer_id:?} {detail}"
1649                );
1650            }
1651        }
1652    }
1653
1654    /// ADR-0004 sister gate for the merkle batch path: every candidate's
1655    /// `price` field must lie on the pricing curve, by exact recomputation.
1656    /// See [`Self::validate_quote_arithmetic`] for the rationale; semantics
1657    /// (reject-only, rollout-gated, no trust evidence) are identical.
1658    fn validate_merkle_candidate_arithmetic(
1659        pool: &evmlib::merkle_payments::MerklePaymentCandidatePool,
1660    ) -> Result<()> {
1661        if !crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED {
1662            return Ok(());
1663        }
1664        for candidate in &pool.candidate_nodes {
1665            if let Some(detail) = Self::binding_violation(
1666                candidate.committed_key_count,
1667                candidate.commitment_pin,
1668                &candidate.price,
1669            ) {
1670                return Err(Error::Payment(format!(
1671                    "ADR-0004 merkle candidate rejected (reward {}): {detail}",
1672                    candidate.reward_address
1673                )));
1674            }
1675        }
1676        Ok(())
1677    }
1678
1679    /// Merkle batch telemetry for off-curve candidates. Always returns; never
1680    /// errors. MUST be called only after ML-DSA-65 signature verification has
1681    /// passed.
1682    fn log_off_curve_merkle(pool: &evmlib::merkle_payments::MerklePaymentCandidatePool) {
1683        if crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED {
1684            return; // enforce mode already rejected; no separate telemetry.
1685        }
1686        for candidate in &pool.candidate_nodes {
1687            if let Some(detail) = Self::binding_violation(
1688                candidate.committed_key_count,
1689                candidate.commitment_pin,
1690                &candidate.price,
1691            ) {
1692                warn!(
1693                    "ADR-0004 merkle candidate violation observed (not enforcing): \
1694                     reward {} {detail}",
1695                    candidate.reward_address
1696                );
1697            }
1698        }
1699    }
1700
1701    /// Pure curve-canonicality predicate: does `price` lie exactly on the
1702    /// pricing curve? Equivalent to "there exists some non-negative integer
1703    /// `n` such that `calculate_price(n) == price`".
1704    ///
1705    /// Separated from the rollout-gated outer gates so the canonicality rule
1706    /// itself is unit-testable independent of the gate. Callers MUST use this
1707    /// and not `derive_records_stored_from_price` directly: the latter floors
1708    /// and is not a canonicality test.
1709    ///
1710    /// Saturation: `derive_records_stored_from_price` saturates to `u64::MAX`
1711    /// for prices beyond `calculate_price(u64::MAX)`, and
1712    /// [`Self::candidate_count_to_usize`] saturates to `usize::MAX` on 32-bit
1713    /// targets. Both saturation regimes converge on `calculate_price`'s own
1714    /// saturation ceiling; an honest in-range price (which can never approach
1715    /// these regions — `MAX_COMMITMENT_KEY_COUNT` is `1_000_000`) round-trips
1716    /// exactly.
1717    #[allow(dead_code)] // boolean convenience for tests + follow-up slices
1718    fn quote_price_is_on_curve(price: &Amount) -> bool {
1719        Self::price_off_curve_diagnostics(price).is_none()
1720    }
1721
1722    /// Returns `Some((candidate_count, recomputed))` iff `price` is off-curve;
1723    /// `None` iff `price` is on-curve. The tuple is the diagnostic detail used
1724    /// by both the rejection error message and the telemetry warning.
1725    fn price_off_curve_diagnostics(price: &Amount) -> Option<(u64, Amount)> {
1726        let candidate_count = derive_records_stored_from_price(*price);
1727        let recomputed = calculate_price(Self::candidate_count_to_usize(candidate_count));
1728        if recomputed == *price {
1729            None
1730        } else {
1731            Some((candidate_count, recomputed))
1732        }
1733    }
1734
1735    /// Narrow the canonicality predicate's `u64` candidate into `usize` for
1736    /// [`calculate_price`]. On every 64-bit target (the only supported
1737    /// production target) this is the identity; on 32-bit targets we saturate
1738    /// to `usize::MAX`, which matches `calculate_price`'s own
1739    /// `Amount::saturating_mul` behaviour so the round-trip still terminates
1740    /// in the same saturation regime rather than panicking.
1741    fn candidate_count_to_usize(candidate_count: u64) -> usize {
1742        usize::try_from(candidate_count).unwrap_or(usize::MAX)
1743    }
1744
1745    /// Minimum number of candidate `pub_keys` (out of 16) whose derived
1746    /// `PeerId` must be among the DHT's actual closest peers to the pool
1747    /// midpoint address for the pool to be accepted.
1748    ///
1749    /// Set to a simple majority (9/16). Two nodes' views of the closest set
1750    /// to a midpoint diverge on a young, high-churn, NAT-heavy network — by
1751    /// more than a near-unanimous threshold tolerates — so a stricter bar
1752    /// rejected honest pools whose candidates are genuinely drawn from the
1753    /// midpoint's close group but don't all reappear in this storer's own
1754    /// lookup. A majority absorbs that divergence while still requiring most
1755    /// candidates to be real peers the live DHT lists as closest.
1756    ///
1757    /// Security cost: a lower threshold widens the room for the "pay-yourself"
1758    /// attack — an attacker running real neighbourhood peers needs fewer of
1759    /// them to clear a majority than to clear a near-unanimous bar. No theft
1760    /// of funds is possible regardless (payment binds on-chain to the rewards
1761    /// address); the cost is that grinding storage payments back to your own
1762    /// nodes gets cheaper. Each counted candidate must still be a peer the
1763    /// live DHT actually returns as closest — a fabricated off-network key
1764    /// cannot satisfy this — so the floor is "run N real top-K Sybil nodes
1765    /// AND grind the midpoint", just with a smaller N. Pairs with the planned
1766    /// pool-midpoint consensus-anchor work, which removes the midpoint
1767    /// grinding freedom that makes a low threshold dangerous.
1768    const CANDIDATE_CLOSENESS_REQUIRED: usize = 9;
1769
1770    /// Timeout for the authoritative network lookup used by the closeness
1771    /// check.
1772    ///
1773    /// Iterative Kademlia lookups can cascade through `MAX_ITERATIONS = 20`
1774    /// rounds in saorsa-core's `find_closest_nodes_network`, and a single
1775    /// unresponsive peer's dial can take 20–30s before timing out. On a
1776    /// young network (e.g. fresh testnet, NAT-simulated peers in 30% of
1777    /// the swarm) iterations average ~10s each — captured trace from
1778    /// STG-01 EWR-3 ant-node-1 just before a pre-fix timeout:
1779    ///
1780    /// ```text
1781    /// Iter 0: +0.0s | Iter 1: +0.2s | Iter 2: +6.6s | Iter 3: +13.1s
1782    /// Iter 4: +20.9s | Iter 5: +39.8s | Iter 6: +50.8s | [60s wall]
1783    /// ```
1784    ///
1785    /// 60s caps the lookup at ~7 iterations and rejects honest pools whose
1786    /// candidates only emerge after iteration 7. 240s gives ~1.2× headroom
1787    /// over the ~200s natural worst-case runtime on a 1k-node testnet.
1788    ///
1789    /// `DoS` amplification stays bounded at roughly one in-flight lookup
1790    /// per unique `pool_hash` under typical load, via
1791    /// [`closeness_pass_cache`] + [`inflight_closeness`]. The bound is
1792    /// "typical" because `inflight_closeness` is an LRU and a sustained
1793    /// flood of unique `pool_hash` entries can evict an in-flight slot,
1794    /// at which point a second leader can race for the same pool (see
1795    /// [`InflightGuard::drop`]). At steady state the pool cache and pool
1796    /// signature verification gate keep this rare in practice.
1797    const CLOSENESS_LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(240);
1798
1799    /// Width of the storer's authoritative network lookup, in peers.
1800    ///
1801    /// The client over-queries `2 * CANDIDATES_PER_POOL = 32` peers via
1802    /// `find_closest_peers(addr, 32)` (see
1803    /// `ant-client/ant-core/src/data/client/merkle.rs::get_merkle_candidate_pool`)
1804    /// and selects 16 valid responders by XOR distance — so truly-close
1805    /// peers that are slow, NAT'd, or briefly unreachable get filtered
1806    /// out and replaced by peers from positions 17–32 of the network's
1807    /// actual ranking. The storer must therefore verify against the same
1808    /// wider window: a pool containing peers from positions 17–32 is
1809    /// honest (those peers really exist in the network's closest-32 set),
1810    /// it's just that the client's quote-collection step couldn't reach
1811    /// the peers at positions <17 in time.
1812    ///
1813    /// Empirical effect on STG-01 (1k-node testnet, 30% NAT-simulated):
1814    /// widening from K=16 to K=32 dropped client-side closeness
1815    /// mismatches from ~115 to ~31 per 5 min, a 73% reduction.
1816    ///
1817    /// Performance note: `count` does not just truncate the lookup —
1818    /// `find_closest_nodes_network` keeps iterating until either
1819    /// `MAX_ITERATIONS` is reached or `best_nodes.len() >= count`. K=32
1820    /// can therefore extend lookups by a few iterations on sparse
1821    /// networks vs K=16, which reinforces (rather than undermines) the
1822    /// timeout bump above.
1823    ///
1824    /// Security: the pay-yourself attack still requires the attacker's
1825    /// fabricated `PeerId`s to land in the storer's authoritative top-K, so
1826    /// the dominant cost is Sybil-grinding midpoint addresses or running real
1827    /// nodes near the target. The leniency for honest divergence comes from
1828    /// the `CANDIDATE_CLOSENESS_REQUIRED` majority threshold, not from this
1829    /// window; widening the window further was measured as too heavy on the
1830    /// lookup path.
1831    const CLOSENESS_LOOKUP_WIDTH: usize = 2 * evmlib::merkle_payments::CANDIDATES_PER_POOL;
1832
1833    /// Maximum waiter → leader retries when the leader's future was cancelled
1834    /// or panicked before publishing a result. Beyond this the waiter returns
1835    /// a visible error rather than spinning indefinitely through a
1836    /// cancellation cascade.
1837    ///
1838    /// Worst-case waiter wall-clock is `(MAX_LEADER_RETRIES + 1) *
1839    /// CLOSENESS_LOOKUP_TIMEOUT` (one wait per attempt). Kept low (1)
1840    /// because the only realistic trigger is leader future-cancellation,
1841    /// which should be extraordinarily rare; under sustained adversarial
1842    /// cancellation a higher cap doesn't add resilience, it just hides
1843    /// the symptom. With `CLOSENESS_LOOKUP_TIMEOUT = 240s` this caps a
1844    /// single user-visible verification at ~8 min worst case (vs ~20 min
1845    /// at the previous value of 4).
1846    const MAX_LEADER_RETRIES: usize = 1;
1847
1848    /// Compute the storer's authoritative-lookup width for a candidate pool.
1849    ///
1850    /// Returns `max(CLOSENESS_LOOKUP_WIDTH, pool_len)`: matches the client's
1851    /// over-query width today, and scales with the pool if a future protocol
1852    /// bump grows pool size beyond `CLOSENESS_LOOKUP_WIDTH`. Truncating to
1853    /// `CLOSENESS_LOOKUP_WIDTH` in that future case would re-open the
1854    /// K-too-small failure mode (the storer would reject honest pools whose
1855    /// candidates legitimately span a wider XOR range than the storer
1856    /// fetched). Pinned by `closeness_lookup_count_uses_max_of_width_and_pool_len`.
1857    const fn closeness_lookup_count(pool_len: usize) -> usize {
1858        if Self::CLOSENESS_LOOKUP_WIDTH > pool_len {
1859            Self::CLOSENESS_LOOKUP_WIDTH
1860        } else {
1861            pool_len
1862        }
1863    }
1864
1865    /// Verify that the candidate pool's `pub_keys` correspond to peers that
1866    /// are actually XOR-closest to the pool midpoint address, by querying
1867    /// the DHT for its closest peers to that address and requiring that a
1868    /// majority of the candidates match.
1869    ///
1870    /// **What this blocks**: the "pay yourself" attack. Candidate signatures
1871    /// only cover `(price, reward_address, timestamp)` and the `pub_key` bytes —
1872    /// nothing ties a candidate to a network-registered identity or to the
1873    /// pool neighbourhood. Without this check an attacker can generate 16
1874    /// ML-DSA keypairs locally, point all 16 `reward_address` fields at a
1875    /// single attacker-controlled wallet, submit the merkle payment, and drain
1876    /// their own payment back out.
1877    ///
1878    /// **How it blocks**: each candidate's `PeerId = BLAKE3(pub_key)`; the DHT
1879    /// is the authoritative source of "which peers exist at this XOR
1880    /// coordinate". If the attacker's 16 fabricated `PeerId`s are not among
1881    /// the peers the network actually lists as closest to the pool address,
1882    /// the pool is forged.
1883    ///
1884    /// **Scope**: a `MerklePaymentProof` carries exactly one `winner_pool`
1885    /// (the pool the smart contract selected for the batch). Every storing
1886    /// node that receives the proof independently re-runs this check against
1887    /// that same pool, so a forged pool is rejected at every node it
1888    /// reaches.
1889    ///
1890    /// **Known limitation — Sybil-grinding**: `midpoint_proof.address()` is a
1891    /// BLAKE3 hash of attacker-controllable inputs (leaf bytes, tree root,
1892    /// timestamp). A determined attacker who *also* runs Sybil DHT nodes can
1893    /// grind the midpoint until it lands in a region where a majority of
1894    /// their Sybil keys are the true network-closest — at which point this check
1895    /// passes for the attacker. Closing that gap requires binding the
1896    /// midpoint to an attacker-uncontrolled value (e.g. a block hash at
1897    /// payment time or an on-chain VRF) or a Sybil-resistant identity
1898    /// layer. This defence raises the attack cost from "free" to "run N
1899    /// Sybil nodes AND grind", which is a meaningful but not complete
1900    /// improvement.
1901    async fn verify_merkle_candidate_closeness(
1902        &self,
1903        pool: &evmlib::merkle_payments::MerklePaymentCandidatePool,
1904        pool_hash: PoolHash,
1905    ) -> Result<()> {
1906        // Fast path: this node already verified this pool successfully.
1907        // A batch of 256 chunks shares one winner_pool, so without this cache
1908        // we'd pay a Kademlia lookup per chunk.
1909        if self.closeness_pass_cache.lock().get(&pool_hash).is_some() {
1910            return Ok(());
1911        }
1912
1913        // Single-flight: on each attempt, either claim leadership by
1914        // inserting a fresh `ClosenessSlot`, or wait on an existing leader
1915        // and read its published result. The leader holds an `Arc` to the
1916        // slot independent of the LruCache so waiters are still woken if
1917        // eviction pressure kicked the cache entry.
1918        //
1919        // The `notified_owned()` future snapshots the `notify_waiters`
1920        // counter at the moment of construction (while we hold the lock),
1921        // which makes the subsequent `.await` race-free: if the leader
1922        // calls `notify_waiters` between our construction and our poll, the
1923        // counter has advanced and the future resolves immediately on first
1924        // poll.
1925        //
1926        // Bounded retry: if we're a waiter and the leader gets cancelled or
1927        // panics (slot.result.get() == None after wake-up), we loop back to
1928        // claim leadership. `MAX_LEADER_RETRIES` bounds the attempts so
1929        // adversarial cancellation cascades cannot spin this indefinitely.
1930        for attempt in 0..=Self::MAX_LEADER_RETRIES {
1931            // Release the mutex guard explicitly before any await below.
1932            // Clippy wants `if let ... else` written as `map_or_else`, but
1933            // any such rewrite re-borrows the locked `inflight` inside the
1934            // closure and fails the borrow checker — so the lint is
1935            // silenced here.
1936            #[allow(clippy::option_if_let_else)]
1937            let (waiter_slot, leader_slot) = {
1938                let mut inflight = self.inflight_closeness.lock();
1939                let chosen = if let Some(existing) = inflight.get(&pool_hash) {
1940                    (Some(Arc::clone(existing)), None)
1941                } else {
1942                    let slot = Arc::new(ClosenessSlot::new());
1943                    inflight.put(pool_hash, Arc::clone(&slot));
1944                    (None, Some(slot))
1945                };
1946                drop(inflight);
1947                chosen
1948            };
1949
1950            if let Some(slot) = waiter_slot {
1951                // Build the owned-notified future BEFORE awaiting, so it
1952                // snapshots the `notify_waiters` counter now. The slot
1953                // already existed when we locked, so the leader is either
1954                // running or finished; in both cases the snapshot + counter
1955                // check ensures we wake up correctly.
1956                let notified = slot.notified_owned();
1957                notified.await;
1958
1959                // Leader published a result — use it directly.
1960                if let Some(result) = slot.result.get() {
1961                    return result.clone().map_err(Error::Payment);
1962                }
1963                // Leader disappeared without publishing (panic or
1964                // cancellation). Slot was cleared by the leader's drop
1965                // guard; loop to become the new leader — unless we've
1966                // hit the retry bound (see MAX_LEADER_RETRIES).
1967                if attempt == Self::MAX_LEADER_RETRIES {
1968                    return Err(Error::Payment(
1969                        "Merkle candidate pool rejected: closeness leader \
1970                         repeatedly failed to publish a result (likely \
1971                         repeated cancellation or panic)."
1972                            .into(),
1973                    ));
1974                }
1975                continue;
1976            }
1977
1978            // Leader path. Drop guard clears the slot and wakes waiters on
1979            // every exit (success, failure, panic, cancellation).
1980            let Some(slot) = leader_slot else {
1981                // Unreachable by construction.
1982                return Err(Error::Payment(
1983                    "internal error: neither leader nor waiter in closeness check".into(),
1984                ));
1985            };
1986            let guard = InflightGuard {
1987                slot_cache: &self.inflight_closeness,
1988                pool_hash,
1989                slot,
1990            };
1991
1992            let result = self.verify_merkle_candidate_closeness_inner(pool).await;
1993            guard.publish(&result);
1994            if result.is_ok() {
1995                self.closeness_pass_cache.lock().put(pool_hash, ());
1996            }
1997            return result;
1998        }
1999        // Unreachable: the for-loop body always either `return`s or `continue`s,
2000        // and the waiter branch's `continue` only runs when `attempt <
2001        // Self::MAX_LEADER_RETRIES`. The last iteration's waiter branch returns
2002        // via the retry-bound check; the leader branch always returns.
2003        Err(Error::Payment(
2004            "internal error: closeness retry loop exited without returning".into(),
2005        ))
2006    }
2007
2008    /// Inner closeness check: the actual DHT lookup + set-membership test.
2009    /// Wrapped by [`verify_merkle_candidate_closeness`] with a pass-cache and
2010    /// single-flight guard so a batch of chunks and a storm of forged PUTs
2011    /// don't multiply the lookup cost.
2012    /// Derive each candidate's `PeerId` from its `pub_key` and reject the
2013    /// pool if any `PeerId` appears more than once.
2014    ///
2015    /// This is a pure-validation pre-check, runnable without a `P2PNode`:
2016    /// catches the case where one real peer's `pub_key` is repeated to
2017    /// inflate the closeness match count, without paying for a Kademlia
2018    /// lookup. An honest pool has [`evmlib::merkle_payments::CANDIDATES_PER_POOL`]
2019    /// distinct candidate `pub_keys` by construction.
2020    fn derive_distinct_candidate_peer_ids(
2021        pool: &evmlib::merkle_payments::MerklePaymentCandidatePool,
2022    ) -> Result<Vec<PeerId>> {
2023        let mut candidate_peer_ids = Vec::with_capacity(pool.candidate_nodes.len());
2024        let mut seen = std::collections::HashSet::with_capacity(pool.candidate_nodes.len());
2025        for candidate in &pool.candidate_nodes {
2026            let pid = peer_id_from_public_key_bytes(&candidate.pub_key).map_err(|e| {
2027                Error::Payment(format!(
2028                    "Invalid ML-DSA public key in merkle candidate: {e}"
2029                ))
2030            })?;
2031            if !seen.insert(pid) {
2032                return Err(Error::Payment(
2033                    "Merkle candidate pool rejected: duplicate candidate PeerId. An \
2034                     honest pool has 16 distinct candidate pub_keys; duplicates would \
2035                     let a single real peer satisfy the closeness threshold by being \
2036                     counted multiple times."
2037                        .into(),
2038                ));
2039            }
2040            candidate_peer_ids.push(pid);
2041        }
2042        Ok(candidate_peer_ids)
2043    }
2044
2045    /// Pure-logic closeness check: given the pool's candidate peer IDs and
2046    /// the storer's authoritative network view (closest peers to the pool
2047    /// midpoint), decide whether the pool passes the
2048    /// `CANDIDATE_CLOSENESS_REQUIRED`-of-N threshold.
2049    ///
2050    /// A candidate counts only if its `PeerId` is one of the peers the
2051    /// storer's own network lookup returned (exact set membership). This is
2052    /// the property that makes the gate meaningful: a passing candidate must
2053    /// be a real, reachable peer the live DHT actually routes to and lists
2054    /// among the closest — it cannot be a key fabricated off-network. The
2055    /// leniency in this check is purely the lowered threshold (a majority
2056    /// rather than near-unanimity), which tolerates the closest-set
2057    /// divergence between two nodes' views without admitting fabricated keys.
2058    ///
2059    /// Extracted from `verify_merkle_candidate_closeness_inner` so tests
2060    /// can exercise the matching logic without standing up a real DHT.
2061    /// Mirrors the runtime path exactly: same sparse-network short-circuit,
2062    /// same set-membership check, same error strings.
2063    fn check_closeness_match(
2064        candidate_peer_ids: &[PeerId],
2065        network_peer_ids: &[PeerId],
2066        pool_address: &[u8; 32],
2067    ) -> Result<()> {
2068        // Sparse-network short-circuit: if the DHT itself returned fewer
2069        // peers than the closeness threshold, the proof can never pass —
2070        // not because the candidates are forged, but because we don't
2071        // have an authoritative view to compare against. Surface this
2072        // distinct cause so operators can tell "retry once the network
2073        // settles" apart from "this peer sent a forged pool".
2074        if network_peer_ids.len() < Self::CANDIDATE_CLOSENESS_REQUIRED {
2075            debug!(
2076                "Merkle closeness deferred: network lookup returned {} peers \
2077                 for pool midpoint {} (need at least {} to verify)",
2078                network_peer_ids.len(),
2079                hex::encode(pool_address),
2080                Self::CANDIDATE_CLOSENESS_REQUIRED,
2081            );
2082            return Err(Error::Payment(format!(
2083                "Merkle candidate pool rejected: authoritative DHT lookup returned \
2084                 only {} peers, less than the {} required to verify candidate \
2085                 closeness. Retry once the routing table populates further.",
2086                network_peer_ids.len(),
2087                Self::CANDIDATE_CLOSENESS_REQUIRED,
2088            )));
2089        }
2090
2091        // Exact-match membership against the returned closest peers.
2092        // Candidate `PeerId`s are deduplicated upstream, so each match
2093        // corresponds to a distinct peer.
2094        let network_set: std::collections::HashSet<PeerId> =
2095            network_peer_ids.iter().copied().collect();
2096        let matched = candidate_peer_ids
2097            .iter()
2098            .filter(|pid| network_set.contains(pid))
2099            .count();
2100
2101        if matched < Self::CANDIDATE_CLOSENESS_REQUIRED {
2102            debug!(
2103                "Merkle closeness rejected: {matched}/{} candidates match the DHT's closest peers \
2104                 for pool midpoint {} (required: {}, network returned {} peers)",
2105                candidate_peer_ids.len(),
2106                hex::encode(pool_address),
2107                Self::CANDIDATE_CLOSENESS_REQUIRED,
2108                network_peer_ids.len(),
2109            );
2110            return Err(Error::Payment(
2111                "Merkle candidate pool rejected: candidate pub_keys do not match the \
2112                 network's closest peers to the pool midpoint address. Pools must be \
2113                 collected from the pool-address close group, not fabricated off-network."
2114                    .into(),
2115            ));
2116        }
2117
2118        debug!(
2119            "Merkle closeness passed: {matched}/{} candidates matched the DHT's closest peers \
2120             for pool midpoint {}",
2121            candidate_peer_ids.len(),
2122            hex::encode(pool_address),
2123        );
2124        Ok(())
2125    }
2126
2127    #[allow(clippy::too_many_lines)]
2128    async fn verify_merkle_candidate_closeness_inner(
2129        &self,
2130        pool: &evmlib::merkle_payments::MerklePaymentCandidatePool,
2131    ) -> Result<()> {
2132        // Pre-check: catch malformed/hostile pools (duplicate candidate
2133        // PeerIds) before paying for the Kademlia lookup. Runs in unit
2134        // tests without a P2PNode too.
2135        let candidate_peer_ids = Self::derive_distinct_candidate_peer_ids(pool)?;
2136
2137        // Release the RwLock guard before any await to avoid holding it
2138        // across an iterative Kademlia lookup.
2139        let attached = self.p2p_node.read().as_ref().map(Arc::clone);
2140        let Some(p2p_node) = attached else {
2141            // Production must call attach_p2p_node at startup. Fail CLOSED
2142            // to avoid silently disabling the defence if a startup path
2143            // regresses and loses the attach call. Unit-test builds that
2144            // construct a PaymentVerifier directly without exercising merkle
2145            // verification are opted-in via `test-utils` to fall back to
2146            // fail-open.
2147            #[cfg(any(test, feature = "test-utils"))]
2148            {
2149                crate::logging::warn!(
2150                    "PaymentVerifier: no P2PNode attached; merkle pay-yourself \
2151                     defence SKIPPED (test build). Production startup MUST call \
2152                     PaymentVerifier::attach_p2p_node."
2153                );
2154                return Ok(());
2155            }
2156            #[cfg(not(any(test, feature = "test-utils")))]
2157            {
2158                crate::logging::error!(
2159                    "PaymentVerifier: no P2PNode attached; rejecting merkle \
2160                     payment. This is a node-startup bug — \
2161                     PaymentVerifier::attach_p2p_node must be called before \
2162                     any PUT handler runs."
2163                );
2164                return Err(Error::Payment(
2165                    "Merkle candidate pool rejected: verifier is not wired to \
2166                     the P2P layer; cannot verify candidate closeness."
2167                        .into(),
2168                ));
2169            }
2170        };
2171
2172        let pool_address = pool.midpoint_proof.address();
2173        // Match the client's over-query width. The client's
2174        // `get_merkle_candidate_pool` queries 2 × `CANDIDATES_PER_POOL` peers
2175        // and picks the 16 closest *valid responders* — so legitimate pools
2176        // routinely include peers from positions 17–32 of the network's true
2177        // ranking when the closer peers are slow or NAT-stuck. The storer
2178        // must look at the same window or it will reject honest pools with
2179        // no security benefit.
2180        //
2181        // `pool.candidate_nodes` is currently a fixed-size array of length
2182        // `CANDIDATES_PER_POOL` (= 16), so `.max(...)` always evaluates to
2183        // `CLOSENESS_LOOKUP_WIDTH` today. The compile-time
2184        // `const _: () = assert!(WIDTH >= CANDIDATES_PER_POOL)` in the test
2185        // module pins that invariant. The `.max(...)` form is belt-and-braces
2186        // for a hypothetical future protocol that grows pool size to a
2187        // `Vec`-typed candidate set: the storer would scale its lookup with
2188        // the pool rather than truncating, which would otherwise re-open the
2189        // K-too-small failure mode.
2190        let lookup_count = Self::closeness_lookup_count(pool.candidate_nodes.len());
2191        let network_lookup = p2p_node
2192            .dht_manager()
2193            .find_closest_nodes_network(&pool_address.0, lookup_count);
2194        let network_peers =
2195            match tokio::time::timeout(Self::CLOSENESS_LOOKUP_TIMEOUT, network_lookup).await {
2196                Ok(Ok(peers)) => peers,
2197                Ok(Err(e)) => {
2198                    debug!(
2199                        "Merkle closeness network-lookup failed for pool midpoint {}: {e}",
2200                        hex::encode(pool_address.0),
2201                    );
2202                    return Err(Error::Payment(
2203                        "Merkle candidate pool rejected: could not verify candidate \
2204                     closeness against the authoritative network view."
2205                            .into(),
2206                    ));
2207                }
2208                Err(_) => {
2209                    debug!(
2210                        "Merkle closeness network-lookup timeout ({:?}) for pool midpoint {}",
2211                        Self::CLOSENESS_LOOKUP_TIMEOUT,
2212                        hex::encode(pool_address.0),
2213                    );
2214                    return Err(Error::Payment(
2215                        "Merkle candidate pool rejected: authoritative network lookup \
2216                     timed out. Retry once the network lookup completes."
2217                            .into(),
2218                    ));
2219                }
2220            };
2221
2222        let network_peer_ids: Vec<PeerId> = network_peers.iter().map(|n| n.peer_id).collect();
2223        Self::check_closeness_match(&candidate_peer_ids, &network_peer_ids, &pool_address.0)
2224    }
2225
2226    /// Verify a merkle batch payment proof.
2227    ///
2228    /// This verification flow:
2229    /// 1. Deserialize the `MerklePaymentProof`
2230    /// 2. Check pool cache for previously verified pool hash
2231    /// 3. If not cached, query on-chain for payment info
2232    /// 4. Validate the proof against on-chain data
2233    /// 5. Cache the pool hash for subsequent chunk verifications in the same batch
2234    #[allow(clippy::too_many_lines)]
2235    async fn verify_merkle_payment(
2236        &self,
2237        xorname: &XorName,
2238        proof_bytes: &[u8],
2239        context: VerificationContext,
2240    ) -> Result<()> {
2241        if crate::logging::enabled!(crate::logging::Level::DEBUG) {
2242            debug!(
2243                "Verifying merkle payment for {} ({context:?})",
2244                hex::encode(xorname)
2245            );
2246        }
2247
2248        // Deserialize the merkle proof
2249        let merkle_proof = deserialize_merkle_proof(proof_bytes)
2250            .map_err(|e| Error::Payment(format!("Failed to deserialize merkle proof: {e}")))?;
2251
2252        // Verify the address in the proof matches the xorname being stored
2253        if merkle_proof.address.0 != *xorname {
2254            let proof_hex = hex::encode(merkle_proof.address.0);
2255            let store_hex = hex::encode(xorname);
2256            return Err(Error::Payment(format!(
2257                "Merkle proof address mismatch: proof is for {proof_hex}, but storing {store_hex}"
2258            )));
2259        }
2260
2261        let pool_hash = merkle_proof.winner_pool_hash();
2262
2263        // Run cheap local checks BEFORE expensive on-chain queries.
2264        // This prevents DoS via garbage proofs that trigger RPC lookups.
2265        for candidate in &merkle_proof.winner_pool.candidate_nodes {
2266            if !crate::payment::verify_merkle_candidate_signature(candidate) {
2267                return Err(Error::Payment(format!(
2268                    "Invalid ML-DSA-65 signature on merkle candidate node (reward: {})",
2269                    candidate.reward_address
2270                )));
2271            }
2272        }
2273
2274        // ADR-0004: every storer re-runs the price-equals-formula-of-count
2275        // check on every merkle candidate, in every context, before median
2276        // reconstruction. Runs AFTER signature verification so observe-only
2277        // telemetry cannot be spoofed by unauthenticated senders. Reject-only
2278        // when enforcement is enabled; no trust evidence emitted in either
2279        // mode.
2280        Self::validate_merkle_candidate_arithmetic(&merkle_proof.winner_pool)?;
2281        Self::log_off_curve_merkle(&merkle_proof.winner_pool);
2282
2283        // Pay-yourself defence: the candidate pub_keys must map to peers the
2284        // live DHT actually considers closest to the pool midpoint. Without
2285        // this, an attacker can point all 16 reward_address fields at a
2286        // self-owned wallet and drain their own payment. Every storing node
2287        // runs this check against the single `winner_pool` in the proof, so a
2288        // forged pool is rejected everywhere it lands. The pass cache and
2289        // single-flight keyed on pool_hash collapse the Kademlia lookup cost
2290        // within a batch and across concurrent PUTs for the same pool.
2291        //
2292        self.verify_merkle_candidate_closeness(&merkle_proof.winner_pool, pool_hash)
2293            .await?;
2294
2295        // Check pool cache first
2296        let cached_info = {
2297            let mut pool_cache = self.pool_cache.lock();
2298            pool_cache.get(&pool_hash).cloned()
2299        };
2300
2301        let payment_info = if let Some(info) = cached_info {
2302            debug!("Pool cache hit for hash {}", hex::encode(pool_hash));
2303            info
2304        } else {
2305            // Query on-chain for completed merkle payment
2306            let info =
2307                payment_vault::get_completed_merkle_payment(&self.config.evm.network, pool_hash)
2308                    .await
2309                    .map_err(|e| {
2310                        let pool_hex = hex::encode(pool_hash);
2311                        Error::Payment(format!(
2312                            "Failed to query merkle payment info for pool {pool_hex}: {e}"
2313                        ))
2314                    })?;
2315
2316            let paid_node_addresses: Vec<_> = info
2317                .paidNodeAddresses
2318                .iter()
2319                .map(|pna| (pna.rewardsAddress, usize::from(pna.poolIndex), pna.amount))
2320                .collect();
2321
2322            let on_chain_info = OnChainPaymentInfo {
2323                depth: info.depth,
2324                merkle_payment_timestamp: info.merklePaymentTimestamp,
2325                paid_node_addresses,
2326            };
2327
2328            // Cache the pool info for subsequent chunks in the same batch
2329            {
2330                let mut pool_cache = self.pool_cache.lock();
2331                pool_cache.put(pool_hash, on_chain_info.clone());
2332            }
2333
2334            debug!(
2335                "Queried on-chain merkle payment info for pool {}: depth={}, timestamp={}, paid_nodes={}",
2336                hex::encode(pool_hash),
2337                on_chain_info.depth,
2338                on_chain_info.merkle_payment_timestamp,
2339                on_chain_info.paid_node_addresses.len()
2340            );
2341
2342            on_chain_info
2343        };
2344
2345        // Verify timestamp consistency (signatures already checked above before RPC).
2346        for candidate in &merkle_proof.winner_pool.candidate_nodes {
2347            if candidate.merkle_payment_timestamp != payment_info.merkle_payment_timestamp {
2348                return Err(Error::Payment(format!(
2349                    "Candidate timestamp mismatch: expected {}, got {} (reward: {})",
2350                    payment_info.merkle_payment_timestamp,
2351                    candidate.merkle_payment_timestamp,
2352                    candidate.reward_address
2353                )));
2354            }
2355        }
2356
2357        // Get the root from the winner pool's midpoint proof
2358        let smart_contract_root = merkle_proof.winner_pool.midpoint_proof.root();
2359
2360        // Verify the cryptographic merkle proofs (address belongs to tree,
2361        // midpoint belongs to tree, roots match, timestamps valid).
2362        evmlib::merkle_payments::verify_merkle_proof(
2363            &merkle_proof.address,
2364            &merkle_proof.data_proof,
2365            &merkle_proof.winner_pool.midpoint_proof,
2366            payment_info.depth,
2367            smart_contract_root,
2368            payment_info.merkle_payment_timestamp,
2369        )
2370        .map_err(|e| {
2371            let xorname_hex = hex::encode(xorname);
2372            Error::Payment(format!(
2373                "Merkle proof verification failed for {xorname_hex}: {e}"
2374            ))
2375        })?;
2376
2377        // Verify paid node count matches depth
2378        let expected_depth = payment_info.depth as usize;
2379        let actual_paid = payment_info.paid_node_addresses.len();
2380        if actual_paid != expected_depth {
2381            return Err(Error::Payment(format!(
2382                "Wrong number of paid nodes: expected {expected_depth}, got {actual_paid}"
2383            )));
2384        }
2385
2386        // Compute expected per-node payment using the contract formula:
2387        // totalAmount = median16(candidate_prices) * (1 << depth)
2388        // amountPerNode = totalAmount / depth
2389        let expected_per_node = if payment_info.depth > 0 {
2390            let mut candidate_prices: Vec<Amount> = merkle_proof
2391                .winner_pool
2392                .candidate_nodes
2393                .iter()
2394                .map(|c| c.price)
2395                .collect();
2396            candidate_prices.sort_unstable(); // ascending
2397                                              // Upper median (index 8 of 16) — matches Solidity's median16 (k = 8)
2398            let median_price = *candidate_prices
2399                .get(candidate_prices.len() / 2)
2400                .ok_or_else(|| Error::Payment("empty candidate pool in merkle proof".into()))?;
2401            let shift = u32::from(payment_info.depth);
2402            let multiplier = 1u64
2403                .checked_shl(shift)
2404                .ok_or_else(|| Error::Payment("merkle proof depth too large".into()))?;
2405            let total_amount = median_price * Amount::from(multiplier);
2406            total_amount / Amount::from(u64::from(payment_info.depth))
2407        } else {
2408            Amount::ZERO
2409        };
2410
2411        // Verify paid node indices, addresses, and amounts against the candidate pool.
2412        //
2413        // Each paid node must:
2414        // 1. Have a valid index within the candidate pool
2415        // 2. Match the expected reward address at that index
2416        // 3. Have been paid at least the expected per-node amount from the
2417        //    contract formula: median16(prices) * 2^depth / depth
2418        //
2419        // Note: unlike single-node payments, merkle proofs are NOT bound to a
2420        // specific storing node. The contract pays `depth` random nodes from the
2421        // winner pool; the storing node is whichever close-group peer the client
2422        // routes the chunk to. There is no local-recipient check here because
2423        // any node that can verify the merkle proof is allowed to store the chunk.
2424        // Replay protection comes from the per-address proof binding (each proof
2425        // is for a specific XorName in the paid tree).
2426        for (addr, idx, paid_amount) in &payment_info.paid_node_addresses {
2427            let node = merkle_proof
2428                .winner_pool
2429                .candidate_nodes
2430                .get(*idx)
2431                .ok_or_else(|| {
2432                    Error::Payment(format!(
2433                        "Paid node index {idx} out of bounds for pool size {}",
2434                        merkle_proof.winner_pool.candidate_nodes.len()
2435                    ))
2436                })?;
2437            if node.reward_address != *addr {
2438                return Err(Error::Payment(format!(
2439                    "Paid node address mismatch at index {idx}: expected {addr}, got {}",
2440                    node.reward_address
2441                )));
2442            }
2443            if *paid_amount < expected_per_node {
2444                return Err(Error::Payment(format!(
2445                    "Underpayment for node at index {idx}: paid {paid_amount}, \
2446                     expected at least {expected_per_node} \
2447                     (median16 formula, depth={})",
2448                    payment_info.depth
2449                )));
2450            }
2451        }
2452
2453        if crate::logging::enabled!(crate::logging::Level::INFO) {
2454            info!(
2455                "Merkle payment verified for {} (pool: {})",
2456                hex::encode(xorname),
2457                hex::encode(pool_hash)
2458            );
2459        }
2460
2461        // ADR-0004: route the merkle-batch candidates through the SAME
2462        // cross-check + first-audit funnel as single-node quotes, AFTER on-chain
2463        // verification has succeeded (so an unpaid pool cannot drive audits or
2464        // fetches). ClientPut only — a replication receipt's pins have aged out.
2465        if context == VerificationContext::ClientPut {
2466            self.cross_check_merkle_candidates(
2467                &merkle_proof.winner_pool,
2468                &merkle_proof.commitment_sidecars,
2469            )
2470            .await;
2471        }
2472
2473        Ok(())
2474    }
2475
2476    /// ADR-0004 cross-check for the merkle-batch path: every candidate carries
2477    /// the same signed `(committed_key_count, commitment_pin)` binding as a
2478    /// single-node quote, so each non-baseline candidate is resolved against the
2479    /// gossip cache (or fetched) and routed into the deterministic first audit,
2480    /// exactly like [`Self::cross_check_quotes`]. The candidate's peer id is
2481    /// derived from its `pub_key` (`PeerId = BLAKE3(pub_key)`), matching how the
2482    /// network binds identities.
2483    async fn cross_check_merkle_candidates(
2484        &self,
2485        pool: &evmlib::merkle_payments::MerklePaymentCandidatePool,
2486        commitment_sidecars: &[Vec<u8>],
2487    ) {
2488        let now = std::time::Instant::now();
2489        let ttl = crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
2490        let p2p = self.p2p_node.read().as_ref().map(Arc::clone);
2491        let monetized_pin_tx = self.monetized_pin_tx.read().as_ref().cloned();
2492        let cache = self.commitment_cache.read().as_ref().map(Arc::clone);
2493        // ADR-0004 "the commitment arrived with the quote" for the merkle path:
2494        // validate sidecars exactly as the single-node path does.
2495        let sidecar_map = Self::index_valid_sidecars(commitment_sidecars);
2496
2497        let mut unresolved: Vec<(PeerId, [u8; 32], u32, Vec<u8>)> = Vec::new();
2498        for candidate in &pool.candidate_nodes {
2499            let Some(pin) = candidate.commitment_pin else {
2500                continue; // baseline candidate pins nothing
2501            };
2502            let peer_id = PeerId::from_bytes(*blake3::hash(&candidate.pub_key).as_bytes());
2503
2504            if let Some(ref tx) = monetized_pin_tx {
2505                let _ = tx.send(crate::replication::MonetizedPinEvent {
2506                    peer: peer_id,
2507                    pin,
2508                    key_count: candidate.committed_key_count,
2509                    quote_ts: std::time::UNIX_EPOCH
2510                        .checked_add(std::time::Duration::from_secs(
2511                            candidate.merkle_payment_timestamp,
2512                        ))
2513                        .unwrap_or(std::time::UNIX_EPOCH),
2514                });
2515            }
2516
2517            let resolved = match sidecar_map.get(&(peer_id, pin)) {
2518                Some(c) => Some(c.clone()),
2519                None => Self::cache_resolve(cache.as_ref(), peer_id, pin, now, ttl).await,
2520            };
2521            match resolved {
2522                Some(commitment) => {
2523                    let artifact = rmp_serde::to_vec(candidate).unwrap_or_default();
2524                    Self::handle_cross_check(
2525                        &peer_id,
2526                        pin,
2527                        candidate.committed_key_count,
2528                        artifact,
2529                        &commitment,
2530                        p2p.as_ref(),
2531                    )
2532                    .await;
2533                }
2534                None => unresolved.push((
2535                    peer_id,
2536                    pin,
2537                    candidate.committed_key_count,
2538                    rmp_serde::to_vec(candidate).unwrap_or_default(),
2539                )),
2540            }
2541        }
2542
2543        if unresolved.is_empty() {
2544            return;
2545        }
2546        let Some(p2p) = p2p else {
2547            return;
2548        };
2549        let neg_cache = Arc::clone(&self.pin_fetch_negative_cache);
2550        tokio::spawn(async move {
2551            Self::drain_unresolved_pin_fetches(&p2p, &neg_cache, unresolved).await;
2552        });
2553    }
2554}
2555
2556#[cfg(test)]
2557#[allow(clippy::expect_used, clippy::panic)]
2558mod tests {
2559    use super::*;
2560    use evmlib::merkle_payments::MerklePaymentCandidatePool;
2561    use evmlib::PaymentQuote;
2562    use saorsa_core::MlDsa65;
2563    use saorsa_pqc::pqc::types::MlDsaSecretKey;
2564    use saorsa_pqc::pqc::MlDsaOperations;
2565    use std::time::SystemTime;
2566
2567    /// Create a verifier for unit tests. EVM is always on, but tests can
2568    /// pre-populate the cache to bypass on-chain verification.
2569    fn create_test_verifier() -> PaymentVerifier {
2570        let config = PaymentVerifierConfig {
2571            evm: EvmVerifierConfig::default(),
2572            cache_capacity: 100,
2573            close_group_size: CLOSE_GROUP_SIZE,
2574            local_rewards_address: RewardsAddress::new([1u8; 20]),
2575        };
2576        PaymentVerifier::new(config)
2577    }
2578
2579    #[test]
2580    fn paid_quote_issuer_closeness_width_uses_k() {
2581        let issuer_closeness_width = PAID_QUOTE_ISSUER_CLOSENESS_WIDTH;
2582        let k_bucket_size = K_BUCKET_SIZE;
2583        let close_group_size = CLOSE_GROUP_SIZE;
2584
2585        assert_eq!(issuer_closeness_width, k_bucket_size);
2586        assert!(issuer_closeness_width > close_group_size);
2587    }
2588
2589    fn make_signed_quote(
2590        xorname: XorName,
2591        price: Amount,
2592        rewards_seed: u8,
2593    ) -> (evmlib::EncodedPeerId, PaymentQuote) {
2594        let ml_dsa = MlDsa65::new();
2595        let (public_key, secret_key) = ml_dsa.generate_keypair().expect("keygen");
2596        let pub_key_bytes = public_key.as_bytes().to_vec();
2597        let peer_id = encoded_peer_id_for_pub_key(&pub_key_bytes);
2598        let mut quote = PaymentQuote {
2599            content: xor_name::XorName(xorname),
2600            timestamp: SystemTime::now(),
2601            price,
2602            rewards_address: RewardsAddress::new([rewards_seed; 20]),
2603            committed_key_count: 0,
2604            commitment_pin: None,
2605            pub_key: pub_key_bytes,
2606            signature: Vec::new(),
2607        };
2608        let secret_key = MlDsaSecretKey::from_bytes(secret_key.as_bytes()).expect("secret key");
2609        quote.signature = ml_dsa
2610            .sign(&secret_key, &quote.bytes_for_sig())
2611            .expect("sign quote")
2612            .as_bytes()
2613            .to_vec();
2614        (peer_id, quote)
2615    }
2616
2617    fn make_signed_legacy_bundle(
2618        xorname: XorName,
2619        prices: [Amount; CLOSE_GROUP_SIZE],
2620    ) -> Vec<(evmlib::EncodedPeerId, PaymentQuote)> {
2621        prices
2622            .into_iter()
2623            .enumerate()
2624            .map(|(index, price)| {
2625                let rewards_seed = u8::try_from(index + 1).expect("small test index");
2626                make_signed_quote(xorname, price, rewards_seed)
2627            })
2628            .collect()
2629    }
2630
2631    fn price_at_records(records: usize) -> Amount {
2632        crate::payment::pricing::calculate_price(records)
2633    }
2634
2635    fn unique_test_prices() -> [Amount; CLOSE_GROUP_SIZE] {
2636        [
2637            price_at_records(0),
2638            price_at_records(1),
2639            price_at_records(2),
2640            price_at_records(3),
2641            price_at_records(4),
2642            price_at_records(5),
2643            price_at_records(6),
2644        ]
2645    }
2646
2647    fn tied_median_test_prices() -> [Amount; CLOSE_GROUP_SIZE] {
2648        [
2649            price_at_records(0),
2650            price_at_records(1),
2651            price_at_records(2),
2652            price_at_records(3),
2653            price_at_records(3),
2654            price_at_records(4),
2655            price_at_records(5),
2656        ]
2657    }
2658
2659    fn median_test_candidates(
2660        peer_quotes: &[(evmlib::EncodedPeerId, PaymentQuote)],
2661    ) -> Vec<(evmlib::EncodedPeerId, PaymentQuote)> {
2662        let mut sorted_quotes: Vec<_> = peer_quotes.iter().collect();
2663        sorted_quotes.sort_by_key(|(_, quote)| quote.price);
2664        let median_index = median_quote_index(sorted_quotes.len());
2665        let median_price = sorted_quotes
2666            .get(median_index)
2667            .expect("median quote")
2668            .1
2669            .price;
2670
2671        sorted_quotes
2672            .into_iter()
2673            .filter(|(_, quote)| quote.price == median_price)
2674            .map(|(peer_id, quote)| (peer_id.clone(), quote.clone()))
2675            .collect()
2676    }
2677
2678    fn expected_median_payment(peer_quotes: &[(evmlib::EncodedPeerId, PaymentQuote)]) -> Amount {
2679        let median_price = median_test_candidates(peer_quotes)
2680            .first()
2681            .expect("median candidate")
2682            .1
2683            .price;
2684        median_price * Amount::from(PAID_QUOTE_PAYMENT_MULTIPLIER)
2685    }
2686
2687    fn mark_k_closest_paid_candidates(
2688        verifier: &PaymentVerifier,
2689        peer_quotes: &[(evmlib::EncodedPeerId, PaymentQuote)],
2690    ) {
2691        let k_closest_peers = median_test_candidates(peer_quotes)
2692            .iter()
2693            .map(|(peer_id, _)| *peer_id.as_bytes())
2694            .collect();
2695        verifier.set_paid_quote_k_closest_for_tests(k_closest_peers);
2696    }
2697
2698    fn mark_candidate_paid(verifier: &PaymentVerifier, quote: &PaymentQuote, amount: Amount) {
2699        verifier.set_completed_payment_for_tests(quote.hash(), amount);
2700    }
2701
2702    fn mark_all_median_candidates_unpaid(
2703        verifier: &PaymentVerifier,
2704        peer_quotes: &[(evmlib::EncodedPeerId, PaymentQuote)],
2705    ) {
2706        for (_, quote) in median_test_candidates(peer_quotes) {
2707            mark_candidate_paid(verifier, &quote, Amount::ZERO);
2708        }
2709    }
2710
2711    #[test]
2712    fn test_payment_required_for_new_data() {
2713        let verifier = create_test_verifier();
2714        let xorname = [1u8; 32];
2715
2716        // All uncached data requires payment
2717        let status = verifier.check_payment_required(&xorname, VerificationContext::ClientPut);
2718        assert_eq!(status, PaymentStatus::PaymentRequired);
2719    }
2720
2721    #[test]
2722    fn test_cache_hit() {
2723        let verifier = create_test_verifier();
2724        let xorname = [1u8; 32];
2725
2726        // Manually add to cache
2727        verifier.cache.insert(xorname);
2728
2729        // Should return CachedAsVerified
2730        let status = verifier.check_payment_required(&xorname, VerificationContext::ClientPut);
2731        assert_eq!(status, PaymentStatus::CachedAsVerified);
2732    }
2733
2734    #[tokio::test]
2735    async fn test_verify_payment_without_proof_rejected() {
2736        let verifier = create_test_verifier();
2737        let xorname = [1u8; 32];
2738
2739        // No proof provided => should return an error (EVM is always on)
2740        let result = verifier
2741            .verify_payment(&xorname, None, VerificationContext::ClientPut)
2742            .await;
2743        assert!(
2744            result.is_err(),
2745            "Expected Err without proof, got: {result:?}"
2746        );
2747    }
2748
2749    #[tokio::test]
2750    async fn test_verify_payment_cached() {
2751        let verifier = create_test_verifier();
2752        let xorname = [1u8; 32];
2753
2754        // Add to cache — simulates previously-paid data
2755        verifier.cache.insert(xorname);
2756
2757        // Should succeed without payment (cached)
2758        let result = verifier
2759            .verify_payment(&xorname, None, VerificationContext::ClientPut)
2760            .await;
2761        assert!(result.is_ok());
2762        assert_eq!(result.expect("cached"), PaymentStatus::CachedAsVerified);
2763    }
2764
2765    #[tokio::test]
2766    async fn test_paid_list_cache_entry_does_not_satisfy_client_put() {
2767        let verifier = create_test_verifier();
2768        let xorname = [0xB8u8; 32];
2769        verifier.cache.insert_paid_list_verified(xorname);
2770
2771        assert_eq!(
2772            verifier.check_payment_required(&xorname, VerificationContext::PaidListAdmission),
2773            PaymentStatus::CachedAsVerified,
2774            "paid-list lookups must hit a paid-list-verified entry"
2775        );
2776        assert_eq!(
2777            verifier.check_payment_required(&xorname, VerificationContext::ClientPut),
2778            PaymentStatus::PaymentRequired,
2779            "client PUT must not fast-path on a paid-list-verified entry"
2780        );
2781
2782        let err = verifier
2783            .verify_payment(&xorname, None, VerificationContext::ClientPut)
2784            .await
2785            .expect_err("proof-less client PUT must not ride the paid-list entry");
2786        assert!(
2787            format!("{err}").contains("Payment required"),
2788            "client PUT must still demand payment: {err}"
2789        );
2790    }
2791
2792    #[test]
2793    fn test_payment_status_can_store() {
2794        assert!(PaymentStatus::CachedAsVerified.can_store());
2795        assert!(PaymentStatus::PaymentVerified.can_store());
2796        assert!(!PaymentStatus::PaymentRequired.can_store());
2797    }
2798
2799    #[test]
2800    fn test_payment_status_is_cached() {
2801        assert!(PaymentStatus::CachedAsVerified.is_cached());
2802        assert!(!PaymentStatus::PaymentVerified.is_cached());
2803        assert!(!PaymentStatus::PaymentRequired.is_cached());
2804    }
2805
2806    #[tokio::test]
2807    async fn test_cache_preload_bypasses_evm() {
2808        let verifier = create_test_verifier();
2809        let xorname = [42u8; 32];
2810
2811        // Not yet cached — should require payment
2812        assert_eq!(
2813            verifier.check_payment_required(&xorname, VerificationContext::ClientPut),
2814            PaymentStatus::PaymentRequired
2815        );
2816
2817        // Pre-populate cache (simulates a previous successful payment)
2818        verifier.cache.insert(xorname);
2819
2820        // Now the xorname should be cached
2821        assert_eq!(
2822            verifier.check_payment_required(&xorname, VerificationContext::ClientPut),
2823            PaymentStatus::CachedAsVerified
2824        );
2825    }
2826
2827    #[tokio::test]
2828    async fn test_proof_too_small() {
2829        let verifier = create_test_verifier();
2830        let xorname = [1u8; 32];
2831
2832        // Proof smaller than MIN_PAYMENT_PROOF_SIZE_BYTES
2833        let small_proof = vec![0u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
2834        let result = verifier
2835            .verify_payment(&xorname, Some(&small_proof), VerificationContext::ClientPut)
2836            .await;
2837        assert!(result.is_err());
2838        let err_msg = format!("{}", result.expect_err("should fail"));
2839        assert!(
2840            err_msg.contains("too small"),
2841            "Error should mention 'too small': {err_msg}"
2842        );
2843    }
2844
2845    #[tokio::test]
2846    async fn test_proof_too_large() {
2847        let verifier = create_test_verifier();
2848        let xorname = [2u8; 32];
2849
2850        // Proof larger than MAX_PAYMENT_PROOF_SIZE_BYTES
2851        let large_proof = vec![0u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
2852        let result = verifier
2853            .verify_payment(&xorname, Some(&large_proof), VerificationContext::ClientPut)
2854            .await;
2855        assert!(result.is_err());
2856        let err_msg = format!("{}", result.expect_err("should fail"));
2857        assert!(
2858            err_msg.contains("too large"),
2859            "Error should mention 'too large': {err_msg}"
2860        );
2861    }
2862
2863    #[tokio::test]
2864    async fn test_proof_at_min_boundary_unknown_tag() {
2865        let verifier = create_test_verifier();
2866        let xorname = [3u8; 32];
2867
2868        // Exactly MIN_PAYMENT_PROOF_SIZE_BYTES with unknown tag — rejected
2869        let boundary_proof = vec![0xFFu8; MIN_PAYMENT_PROOF_SIZE_BYTES];
2870        let result = verifier
2871            .verify_payment(
2872                &xorname,
2873                Some(&boundary_proof),
2874                VerificationContext::ClientPut,
2875            )
2876            .await;
2877        assert!(result.is_err());
2878        let err_msg = format!("{}", result.expect_err("should fail"));
2879        assert!(
2880            err_msg.contains("Unknown payment proof type tag"),
2881            "Error should mention unknown tag: {err_msg}"
2882        );
2883    }
2884
2885    #[tokio::test]
2886    async fn test_proof_at_max_boundary_unknown_tag() {
2887        let verifier = create_test_verifier();
2888        let xorname = [4u8; 32];
2889
2890        // Exactly MAX_PAYMENT_PROOF_SIZE_BYTES with unknown tag — rejected
2891        let boundary_proof = vec![0xFFu8; MAX_PAYMENT_PROOF_SIZE_BYTES];
2892        let result = verifier
2893            .verify_payment(
2894                &xorname,
2895                Some(&boundary_proof),
2896                VerificationContext::ClientPut,
2897            )
2898            .await;
2899        assert!(result.is_err());
2900        let err_msg = format!("{}", result.expect_err("should fail"));
2901        assert!(
2902            err_msg.contains("Unknown payment proof type tag"),
2903            "Error should mention unknown tag: {err_msg}"
2904        );
2905    }
2906
2907    /// Regression pin for the DEV-01 (2026-07-06) outage: a merkle proof that
2908    /// ships all 16 ADR-0004 commitment sidecars serializes to ~342 KB, and the
2909    /// old 256 KB cap size-rejected every merkle PUT as soon as nodes carried
2910    /// live commitments. The cap must keep accepting that legacy client shape;
2911    /// a proof of that size must fail on content, never on size.
2912    #[tokio::test]
2913    async fn test_sidecar_bearing_merkle_proof_size_is_accepted() {
2914        const LEGACY_SIDECAR_PROOF_BYTES: usize = 342_171;
2915
2916        let verifier = create_test_verifier();
2917        let xorname = [6u8; 32];
2918
2919        let legacy_sized_proof = vec![0xFFu8; LEGACY_SIDECAR_PROOF_BYTES];
2920        let result = verifier
2921            .verify_payment(
2922                &xorname,
2923                Some(&legacy_sized_proof),
2924                VerificationContext::ClientPut,
2925            )
2926            .await;
2927        assert!(result.is_err());
2928        let err_msg = format!("{}", result.expect_err("should fail"));
2929        assert!(
2930            !err_msg.contains("too large"),
2931            "A {LEGACY_SIDECAR_PROOF_BYTES}-byte proof must not be size-rejected \
2932             (sidecar-bearing merkle proofs from pre-fix clients): {err_msg}"
2933        );
2934    }
2935
2936    #[tokio::test]
2937    async fn test_malformed_single_node_proof() {
2938        let verifier = create_test_verifier();
2939        let xorname = [5u8; 32];
2940
2941        // Valid tag (0x01) but garbage payload — should fail deserialization
2942        let mut garbage = vec![crate::ant_protocol::PROOF_TAG_SINGLE_NODE];
2943        garbage.extend_from_slice(&[0xAB; 63]);
2944        let result = verifier
2945            .verify_payment(&xorname, Some(&garbage), VerificationContext::ClientPut)
2946            .await;
2947        assert!(result.is_err());
2948        let err_msg = format!("{}", result.expect_err("should fail"));
2949        assert!(
2950            err_msg.contains("deserialize") || err_msg.contains("Failed"),
2951            "Error should mention deserialization failure: {err_msg}"
2952        );
2953    }
2954
2955    #[tokio::test]
2956    async fn test_legacy_paid_median_full_path_accepted() {
2957        let verifier = create_test_verifier();
2958        let xorname = [0xA1u8; 32];
2959        let peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
2960        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
2961        let expected_amount = expected_median_payment(&peer_quotes);
2962        let paid_quote = median_test_candidates(&peer_quotes)
2963            .first()
2964            .expect("median candidate")
2965            .1
2966            .clone();
2967        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
2968
2969        let proof_bytes = serialize_proof(peer_quotes);
2970        let result = verifier
2971            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
2972            .await;
2973
2974        assert_eq!(
2975            result.expect("paid median should verify"),
2976            PaymentStatus::PaymentVerified
2977        );
2978    }
2979
2980    #[tokio::test]
2981    async fn test_legacy_single_quote_proof_accepted() {
2982        let verifier = create_test_verifier();
2983        let xorname = [0xB1u8; 32];
2984        let (peer_id, quote) = make_signed_quote(xorname, price_at_records(0), 1);
2985        let peer_quotes = vec![(peer_id, quote.clone())];
2986        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
2987        mark_candidate_paid(&verifier, &quote, expected_median_payment(&peer_quotes));
2988
2989        let proof_bytes = serialize_proof(peer_quotes);
2990        let result = verifier
2991            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
2992            .await;
2993
2994        assert_eq!(
2995            result.expect("single paid quote should verify"),
2996            PaymentStatus::PaymentVerified
2997        );
2998    }
2999
3000    #[tokio::test]
3001    async fn test_legacy_single_quote_proof_requires_three_x_payment() {
3002        let verifier = create_test_verifier();
3003        let xorname = [0xB2u8; 32];
3004        let (peer_id, quote) = make_signed_quote(xorname, price_at_records(0), 1);
3005        let peer_quotes = vec![(peer_id, quote.clone())];
3006        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
3007        mark_candidate_paid(&verifier, &quote, quote.price);
3008
3009        let proof_bytes = serialize_proof(peer_quotes);
3010        let err = verifier
3011            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3012            .await
3013            .expect_err("single quote paid less than 3x should be rejected");
3014
3015        assert!(
3016            format!("{err}").contains("not paid enough"),
3017            "Error should mention underpayment: {err}"
3018        );
3019    }
3020
3021    #[tokio::test]
3022    async fn test_legacy_too_many_quotes_rejected() {
3023        let verifier = create_test_verifier();
3024        let xorname = [0xB3u8; 32];
3025        let mut peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
3026        peer_quotes.push(make_signed_quote(xorname, price_at_records(7), 8));
3027
3028        let proof_bytes = serialize_proof(peer_quotes);
3029        let err = verifier
3030            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3031            .await
3032            .expect_err("proof with more than close-group quotes should be rejected");
3033
3034        assert!(
3035            format!("{err}").contains("at most"),
3036            "Error should mention max quote count: {err}"
3037        );
3038    }
3039
3040    #[tokio::test]
3041    async fn test_legacy_structural_majority_price_at_median_accepted() {
3042        let verifier = create_test_verifier();
3043        let xorname = [0xA2u8; 32];
3044        let peer_quotes = make_signed_legacy_bundle(
3045            xorname,
3046            [
3047                crate::payment::pricing::calculate_price(0),
3048                crate::payment::pricing::calculate_price(100),
3049                crate::payment::pricing::calculate_price(500),
3050                crate::payment::pricing::calculate_price(1000),
3051                crate::payment::pricing::calculate_price(2000),
3052                crate::payment::pricing::calculate_price(4000),
3053                crate::payment::pricing::calculate_price(6000),
3054            ],
3055        );
3056        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
3057        let expected_amount = expected_median_payment(&peer_quotes);
3058        let paid_quote = median_test_candidates(&peer_quotes)
3059            .first()
3060            .expect("median candidate")
3061            .1
3062            .clone();
3063        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
3064
3065        let proof_bytes = serialize_proof(peer_quotes);
3066        let result = verifier
3067            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3068            .await;
3069
3070        assert_eq!(
3071            result.expect("median-priced verifier should accept"),
3072            PaymentStatus::PaymentVerified
3073        );
3074    }
3075
3076    #[tokio::test]
3077    async fn test_legacy_paid_median_issuer_k_closest_rejection() {
3078        let verifier = create_test_verifier();
3079        verifier.set_paid_quote_k_closest_for_tests(vec![rand::random()]);
3080        let xorname = [0xA4u8; 32];
3081        let peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
3082        let expected_amount = expected_median_payment(&peer_quotes);
3083        let paid_quote = median_test_candidates(&peer_quotes)
3084            .first()
3085            .expect("median candidate")
3086            .1
3087            .clone();
3088        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
3089
3090        let proof_bytes = serialize_proof(peer_quotes);
3091        let err = verifier
3092            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3093            .await
3094            .expect_err("out-of-K paid issuer should be rejected");
3095
3096        assert!(
3097            format!("{err}").contains("not among this node's local"),
3098            "Error should mention local K-closest peers: {err}"
3099        );
3100    }
3101
3102    #[tokio::test]
3103    async fn test_legacy_zero_price_median_rejected() {
3104        let verifier = create_test_verifier();
3105        let xorname = [0xA6u8; 32];
3106        let peer_quotes = make_signed_legacy_bundle(
3107            xorname,
3108            [
3109                Amount::ZERO,
3110                Amount::ZERO,
3111                Amount::ZERO,
3112                Amount::ZERO,
3113                Amount::from(1u64),
3114                Amount::from(2u64),
3115                Amount::from(3u64),
3116            ],
3117        );
3118
3119        let proof_bytes = serialize_proof(peer_quotes);
3120        let err = verifier
3121            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3122            .await
3123            .expect_err("zero median must be rejected");
3124
3125        assert!(
3126            format!("{err}").contains("zero price"),
3127            "Error should mention zero price: {err}"
3128        );
3129    }
3130
3131    #[tokio::test]
3132    async fn test_legacy_paid_quote_content_mismatch_rejected() {
3133        let verifier = create_test_verifier();
3134        let xorname = [0xA7u8; 32];
3135        let mut peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
3136        let median_index = median_quote_index(peer_quotes.len());
3137        peer_quotes[median_index].1.content = xor_name::XorName([0xE7u8; 32]);
3138        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
3139
3140        let proof_bytes = serialize_proof(peer_quotes);
3141        let err = verifier
3142            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3143            .await
3144            .expect_err("paid quote content mismatch should be rejected");
3145
3146        assert!(
3147            format!("{err}").contains("content address mismatch"),
3148            "Error should mention content mismatch: {err}"
3149        );
3150    }
3151
3152    #[tokio::test]
3153    async fn test_legacy_unpaid_quote_content_mismatch_accepted() {
3154        let verifier = create_test_verifier();
3155        let xorname = [0xA8u8; 32];
3156        let mut peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
3157        peer_quotes[0].1.content = xor_name::XorName([0xE8u8; 32]);
3158        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
3159        let expected_amount = expected_median_payment(&peer_quotes);
3160        let paid_quote = median_test_candidates(&peer_quotes)
3161            .first()
3162            .expect("median candidate")
3163            .1
3164            .clone();
3165        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
3166
3167        let proof_bytes = serialize_proof(peer_quotes);
3168        let result = verifier
3169            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3170            .await;
3171
3172        assert_eq!(
3173            result.expect("unpaid content mismatch should be ignored"),
3174            PaymentStatus::PaymentVerified
3175        );
3176    }
3177
3178    #[tokio::test]
3179    async fn test_legacy_paid_quote_bad_signature_rejected() {
3180        let verifier = create_test_verifier();
3181        let xorname = [0xA9u8; 32];
3182        let mut peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
3183        let median_index = median_quote_index(peer_quotes.len());
3184        peer_quotes[median_index].1.signature.push(0xFF);
3185        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
3186        let expected_amount = expected_median_payment(&peer_quotes);
3187        let paid_quote = median_test_candidates(&peer_quotes)
3188            .first()
3189            .expect("median candidate")
3190            .1
3191            .clone();
3192        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
3193
3194        let proof_bytes = serialize_proof(peer_quotes);
3195        let err = verifier
3196            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3197            .await
3198            .expect_err("paid bad signature should be rejected");
3199
3200        assert!(
3201            format!("{err}").contains("signature verification failed"),
3202            "Error should mention signature failure: {err}"
3203        );
3204    }
3205
3206    #[tokio::test]
3207    async fn test_legacy_unpaid_quote_bad_signature_accepted() {
3208        let verifier = create_test_verifier();
3209        let xorname = [0xAAu8; 32];
3210        let mut peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
3211        peer_quotes[0].1.signature.push(0xFF);
3212        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
3213        let expected_amount = expected_median_payment(&peer_quotes);
3214        let paid_quote = median_test_candidates(&peer_quotes)
3215            .first()
3216            .expect("median candidate")
3217            .1
3218            .clone();
3219        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
3220
3221        let proof_bytes = serialize_proof(peer_quotes);
3222        let result = verifier
3223            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3224            .await;
3225
3226        assert_eq!(
3227            result.expect("unpaid bad signature should be ignored"),
3228            PaymentStatus::PaymentVerified
3229        );
3230    }
3231
3232    #[tokio::test]
3233    async fn test_legacy_unpaid_peer_binding_mismatch_accepted() {
3234        let verifier = create_test_verifier();
3235        let xorname = [0xABu8; 32];
3236        let mut peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
3237        peer_quotes[0].0 = evmlib::EncodedPeerId::new(rand::random());
3238        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
3239        let expected_amount = expected_median_payment(&peer_quotes);
3240        let paid_quote = median_test_candidates(&peer_quotes)
3241            .first()
3242            .expect("median candidate")
3243            .1
3244            .clone();
3245        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
3246
3247        let proof_bytes = serialize_proof(peer_quotes);
3248        let result = verifier
3249            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3250            .await;
3251
3252        assert_eq!(
3253            result.expect("unpaid peer binding mismatch should be ignored"),
3254            PaymentStatus::PaymentVerified
3255        );
3256    }
3257
3258    #[tokio::test]
3259    async fn test_legacy_median_tie_accepts_paid_candidate() {
3260        let verifier = create_test_verifier();
3261        let xorname = [0xACu8; 32];
3262        let peer_quotes = make_signed_legacy_bundle(xorname, tied_median_test_prices());
3263        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
3264        mark_all_median_candidates_unpaid(&verifier, &peer_quotes);
3265        let expected_amount = expected_median_payment(&peer_quotes);
3266        let paid_quote = median_test_candidates(&peer_quotes)
3267            .get(1)
3268            .expect("second tied median candidate")
3269            .1
3270            .clone();
3271        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
3272
3273        let proof_bytes = serialize_proof(peer_quotes);
3274        let result = verifier
3275            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3276            .await;
3277
3278        assert_eq!(
3279            result.expect("one paid tied median candidate should verify"),
3280            PaymentStatus::PaymentVerified
3281        );
3282    }
3283
3284    #[tokio::test]
3285    async fn test_legacy_paid_list_admission_enforces_issuer_k_closest() {
3286        let verifier = create_test_verifier();
3287        verifier.set_paid_quote_k_closest_for_tests(Vec::new());
3288        let xorname = [0xB5u8; 32];
3289        let peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
3290        let expected_amount = expected_median_payment(&peer_quotes);
3291        let paid_quote = median_test_candidates(&peer_quotes)
3292            .first()
3293            .expect("median candidate")
3294            .1
3295            .clone();
3296        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
3297
3298        let proof_bytes = serialize_proof(peer_quotes);
3299        let err = verifier
3300            .verify_payment(
3301                &xorname,
3302                Some(&proof_bytes),
3303                VerificationContext::PaidListAdmission,
3304            )
3305            .await
3306            .expect_err("paid-list admission must enforce the paid issuer K-closest check");
3307
3308        assert!(
3309            format!("{err}").contains("not among this node's local"),
3310            "Error should mention local K-closest peers: {err}"
3311        );
3312    }
3313
3314    #[test]
3315    fn test_cache_len_getter() {
3316        let verifier = create_test_verifier();
3317        assert_eq!(verifier.cache_len(), 0);
3318
3319        verifier.cache.insert([10u8; 32]);
3320        assert_eq!(verifier.cache_len(), 1);
3321
3322        verifier.cache.insert([20u8; 32]);
3323        assert_eq!(verifier.cache_len(), 2);
3324    }
3325
3326    #[test]
3327    fn test_cache_stats_after_operations() {
3328        let verifier = create_test_verifier();
3329        let xorname = [7u8; 32];
3330
3331        // Miss
3332        verifier.check_payment_required(&xorname, VerificationContext::ClientPut);
3333        let stats = verifier.cache_stats();
3334        assert_eq!(stats.misses, 1);
3335        assert_eq!(stats.hits, 0);
3336
3337        // Insert and hit
3338        verifier.cache.insert(xorname);
3339        verifier.check_payment_required(&xorname, VerificationContext::ClientPut);
3340        let stats = verifier.cache_stats();
3341        assert_eq!(stats.hits, 1);
3342        assert_eq!(stats.misses, 1);
3343        assert_eq!(stats.additions, 1);
3344    }
3345
3346    #[tokio::test]
3347    async fn test_concurrent_cache_lookups() {
3348        let verifier = std::sync::Arc::new(create_test_verifier());
3349
3350        // Pre-populate cache for all 10 xornames
3351        for i in 0..10u8 {
3352            verifier.cache.insert([i; 32]);
3353        }
3354
3355        let mut handles = Vec::new();
3356        for i in 0..10u8 {
3357            let v = verifier.clone();
3358            handles.push(tokio::spawn(async move {
3359                let xorname = [i; 32];
3360                v.verify_payment(&xorname, None, VerificationContext::ClientPut)
3361                    .await
3362            }));
3363        }
3364
3365        for handle in handles {
3366            let result = handle.await.expect("task panicked");
3367            assert!(result.is_ok());
3368            assert_eq!(result.expect("cached"), PaymentStatus::CachedAsVerified);
3369        }
3370
3371        assert_eq!(verifier.cache_len(), 10);
3372    }
3373
3374    #[test]
3375    fn test_default_evm_config() {
3376        let _config = EvmVerifierConfig::default();
3377        // EVM is always on — default network is ArbitrumOne
3378    }
3379
3380    #[test]
3381    fn test_real_ml_dsa_proof_size_within_limits() {
3382        use crate::payment::metrics::QuotingMetricsTracker;
3383        use crate::payment::proof::PaymentProof;
3384        use crate::payment::quote::{QuoteGenerator, XorName};
3385        use alloy::primitives::FixedBytes;
3386        use evmlib::{EncodedPeerId, RewardsAddress};
3387        use saorsa_core::MlDsa65;
3388        use saorsa_pqc::pqc::types::MlDsaSecretKey;
3389        use saorsa_pqc::pqc::MlDsaOperations;
3390
3391        let ml_dsa = MlDsa65::new();
3392        let mut peer_quotes = Vec::new();
3393
3394        for i in 0..5u8 {
3395            let (public_key, secret_key) = ml_dsa.generate_keypair().expect("keygen");
3396
3397            let rewards_address = RewardsAddress::new([i; 20]);
3398            let metrics_tracker = QuotingMetricsTracker::new(0);
3399            let mut generator = QuoteGenerator::new(rewards_address, metrics_tracker);
3400
3401            let pub_key_bytes = public_key.as_bytes().to_vec();
3402            let sk_bytes = secret_key.as_bytes().to_vec();
3403            generator.set_signer(pub_key_bytes, move |msg| {
3404                let sk = MlDsaSecretKey::from_bytes(&sk_bytes).expect("sk parse");
3405                let ml_dsa = MlDsa65::new();
3406                ml_dsa.sign(&sk, msg).expect("sign").as_bytes().to_vec()
3407            });
3408
3409            let content: XorName = [i; 32];
3410            let quote = generator.create_quote(content, 4096, 0).expect("quote");
3411
3412            peer_quotes.push((EncodedPeerId::new(rand::random()), quote));
3413        }
3414
3415        let proof = PaymentProof {
3416            proof_of_payment: ProofOfPayment { peer_quotes },
3417            tx_hashes: vec![FixedBytes::from([0xABu8; 32])],
3418            commitment_sidecars: vec![],
3419        };
3420
3421        let proof_bytes =
3422            crate::payment::proof::serialize_single_node_proof(&proof).expect("serialize");
3423
3424        // 7 ML-DSA-65 quotes with ~1952-byte pub keys and ~3309-byte signatures
3425        // should produce a proof in the 30-80 KB range
3426        assert!(
3427            proof_bytes.len() > 20_000,
3428            "Real 7-quote ML-DSA proof should be > 20 KB, got {} bytes",
3429            proof_bytes.len()
3430        );
3431        assert!(
3432            proof_bytes.len() < MAX_PAYMENT_PROOF_SIZE_BYTES,
3433            "Real 7-quote ML-DSA proof ({} bytes) should fit within {} byte limit",
3434            proof_bytes.len(),
3435            MAX_PAYMENT_PROOF_SIZE_BYTES
3436        );
3437    }
3438
3439    #[tokio::test]
3440    async fn test_content_address_mismatch_rejected() {
3441        use crate::payment::proof::{serialize_single_node_proof, PaymentProof};
3442        use evmlib::{EncodedPeerId, PaymentQuote, RewardsAddress};
3443        use std::time::SystemTime;
3444
3445        let verifier = create_test_verifier();
3446
3447        // The xorname we're trying to store
3448        let target_xorname = [0xAAu8; 32];
3449
3450        // Create a quote for a DIFFERENT xorname
3451        let wrong_xorname = [0xBBu8; 32];
3452        let quote = PaymentQuote {
3453            content: xor_name::XorName(wrong_xorname),
3454            timestamp: SystemTime::now(),
3455            price: Amount::from(1u64),
3456            rewards_address: RewardsAddress::new([1u8; 20]),
3457            committed_key_count: 0,
3458            commitment_pin: None,
3459            pub_key: vec![0u8; 64],
3460            signature: vec![0u8; 64],
3461        };
3462
3463        // Build CLOSE_GROUP_SIZE quotes with distinct peer IDs
3464        let mut peer_quotes = Vec::new();
3465        for _ in 0..CLOSE_GROUP_SIZE {
3466            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
3467        }
3468
3469        let proof = PaymentProof {
3470            proof_of_payment: ProofOfPayment { peer_quotes },
3471            tx_hashes: vec![],
3472            commitment_sidecars: vec![],
3473        };
3474
3475        let proof_bytes = serialize_single_node_proof(&proof).expect("serialize proof");
3476
3477        let result = verifier
3478            .verify_payment(
3479                &target_xorname,
3480                Some(&proof_bytes),
3481                VerificationContext::ClientPut,
3482            )
3483            .await;
3484
3485        assert!(result.is_err(), "Should reject mismatched content address");
3486        let err_msg = format!("{}", result.expect_err("should be error"));
3487        assert!(
3488            err_msg.contains("content address mismatch"),
3489            "Error should mention 'content address mismatch': {err_msg}"
3490        );
3491    }
3492
3493    /// Helper: create a fake quote with the given xorname and timestamp.
3494    fn make_fake_quote(
3495        xorname: [u8; 32],
3496        timestamp: SystemTime,
3497        rewards_address: RewardsAddress,
3498    ) -> evmlib::PaymentQuote {
3499        use evmlib::PaymentQuote;
3500
3501        PaymentQuote {
3502            content: xor_name::XorName(xorname),
3503            timestamp,
3504            price: Amount::from(1u64),
3505            rewards_address,
3506            committed_key_count: 0,
3507            commitment_pin: None,
3508            pub_key: vec![0u8; 64],
3509            signature: vec![0u8; 64],
3510        }
3511    }
3512
3513    /// Helper: create a fake quote priced on-curve at `records` stored records
3514    /// (price = `calculate_price(records)`), reusing [`make_fake_quote`] for the
3515    /// remaining fields. Used by the ADR-0004 arithmetic-gate tests.
3516    fn make_fake_quote_at_records(
3517        xorname: [u8; 32],
3518        timestamp: SystemTime,
3519        rewards_address: RewardsAddress,
3520        records: usize,
3521    ) -> evmlib::PaymentQuote {
3522        let mut quote = make_fake_quote(xorname, timestamp, rewards_address);
3523        quote.price = crate::payment::pricing::calculate_price(records);
3524        quote
3525    }
3526
3527    /// Helper: wrap quotes into a tagged serialized `PaymentProof`.
3528    fn serialize_proof(peer_quotes: Vec<(evmlib::EncodedPeerId, evmlib::PaymentQuote)>) -> Vec<u8> {
3529        use crate::payment::proof::{serialize_single_node_proof, PaymentProof};
3530
3531        let proof = PaymentProof {
3532            proof_of_payment: ProofOfPayment { peer_quotes },
3533            tx_hashes: vec![],
3534            commitment_sidecars: vec![],
3535        };
3536        serialize_single_node_proof(&proof).expect("serialize proof")
3537    }
3538
3539    #[tokio::test]
3540    async fn test_old_quote_uses_storage_delta_not_timestamp() {
3541        use evmlib::{EncodedPeerId, RewardsAddress};
3542        use std::time::Duration;
3543
3544        let verifier = create_test_verifier();
3545        let xorname = [0xCCu8; 32];
3546        let rewards_addr = RewardsAddress::new([1u8; 20]);
3547
3548        // Create a quote that's 25 hours old (exceeds 24-hour max)
3549        let old_timestamp = SystemTime::now() - Duration::from_secs(25 * 3600);
3550        let quote = make_fake_quote(xorname, old_timestamp, rewards_addr);
3551
3552        let mut peer_quotes = Vec::new();
3553        for _ in 0..CLOSE_GROUP_SIZE {
3554            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
3555        }
3556
3557        let proof_bytes = serialize_proof(peer_quotes);
3558        let result = verifier
3559            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3560            .await;
3561
3562        let err_msg = format!("{}", result.expect_err("should fail at later check"));
3563        assert!(
3564            !err_msg.contains("expired"),
3565            "Should not reject by timestamp age: {err_msg}"
3566        );
3567    }
3568
3569    #[tokio::test]
3570    async fn test_future_quote_uses_storage_delta_not_timestamp() {
3571        use evmlib::{EncodedPeerId, RewardsAddress};
3572        use std::time::Duration;
3573
3574        let verifier = create_test_verifier();
3575        let xorname = [0xDDu8; 32];
3576        let rewards_addr = RewardsAddress::new([1u8; 20]);
3577
3578        // Create a quote with a timestamp 1 hour in the future
3579        let future_timestamp = SystemTime::now() + Duration::from_secs(3600);
3580        let quote = make_fake_quote(xorname, future_timestamp, rewards_addr);
3581
3582        let mut peer_quotes = Vec::new();
3583        for _ in 0..CLOSE_GROUP_SIZE {
3584            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
3585        }
3586
3587        let proof_bytes = serialize_proof(peer_quotes);
3588        let result = verifier
3589            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3590            .await;
3591
3592        let err_msg = format!("{}", result.expect_err("should fail at later check"));
3593        assert!(
3594            !err_msg.contains("future"),
3595            "Should not reject by future timestamp: {err_msg}"
3596        );
3597    }
3598
3599    #[tokio::test]
3600    async fn test_quote_within_clock_skew_tolerance_accepted() {
3601        use evmlib::{EncodedPeerId, RewardsAddress};
3602        use std::time::Duration;
3603
3604        let verifier = create_test_verifier();
3605        let xorname = [0xD1u8; 32];
3606        let rewards_addr = RewardsAddress::new([1u8; 20]);
3607
3608        // Quote 30 seconds in the future — well within 300s tolerance
3609        let future_timestamp = SystemTime::now() + Duration::from_secs(30);
3610        let quote = make_fake_quote(xorname, future_timestamp, rewards_addr);
3611
3612        let mut peer_quotes = Vec::new();
3613        for _ in 0..CLOSE_GROUP_SIZE {
3614            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
3615        }
3616
3617        let proof_bytes = serialize_proof(peer_quotes);
3618        let result = verifier
3619            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3620            .await;
3621
3622        // Should NOT fail at timestamp check (will fail later at pub_key binding)
3623        let err_msg = format!("{}", result.expect_err("should fail at later check"));
3624        assert!(
3625            !err_msg.contains("future"),
3626            "Should pass timestamp check (within tolerance), but got: {err_msg}"
3627        );
3628    }
3629
3630    #[tokio::test]
3631    async fn test_quote_beyond_clock_skew_still_uses_storage_delta() {
3632        use evmlib::{EncodedPeerId, RewardsAddress};
3633        use std::time::Duration;
3634
3635        let verifier = create_test_verifier();
3636        let xorname = [0xD2u8; 32];
3637        let rewards_addr = RewardsAddress::new([1u8; 20]);
3638
3639        // Quote 360 seconds in the future — exceeds 300s tolerance
3640        let future_timestamp = SystemTime::now() + Duration::from_secs(360);
3641        let quote = make_fake_quote(xorname, future_timestamp, rewards_addr);
3642
3643        let mut peer_quotes = Vec::new();
3644        for _ in 0..CLOSE_GROUP_SIZE {
3645            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
3646        }
3647
3648        let proof_bytes = serialize_proof(peer_quotes);
3649        let result = verifier
3650            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3651            .await;
3652
3653        let err_msg = format!("{}", result.expect_err("should fail at later check"));
3654        assert!(
3655            !err_msg.contains("future"),
3656            "Should not reject by future timestamp: {err_msg}"
3657        );
3658    }
3659
3660    #[tokio::test]
3661    async fn test_quote_23h_old_still_accepted() {
3662        use evmlib::{EncodedPeerId, RewardsAddress};
3663        use std::time::Duration;
3664
3665        let verifier = create_test_verifier();
3666        let xorname = [0xD3u8; 32];
3667        let rewards_addr = RewardsAddress::new([1u8; 20]);
3668
3669        // Quote 23 hours old — within 24h max age
3670        let old_timestamp = SystemTime::now() - Duration::from_secs(23 * 3600);
3671        let quote = make_fake_quote(xorname, old_timestamp, rewards_addr);
3672
3673        let mut peer_quotes = Vec::new();
3674        for _ in 0..CLOSE_GROUP_SIZE {
3675            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
3676        }
3677
3678        let proof_bytes = serialize_proof(peer_quotes);
3679        let result = verifier
3680            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3681            .await;
3682
3683        // Should NOT fail at timestamp check (will fail later at pub_key binding)
3684        let err_msg = format!("{}", result.expect_err("should fail at later check"));
3685        assert!(
3686            !err_msg.contains("expired"),
3687            "Should pass expiry check (23h < 24h), but got: {err_msg}"
3688        );
3689    }
3690
3691    /// Helper: build an `EncodedPeerId` that matches the BLAKE3 hash of an ML-DSA public key.
3692    fn encoded_peer_id_for_pub_key(pub_key: &[u8]) -> evmlib::EncodedPeerId {
3693        let ant_peer_id = peer_id_from_public_key_bytes(pub_key).expect("valid ML-DSA pub key");
3694        evmlib::EncodedPeerId::new(*ant_peer_id.as_bytes())
3695    }
3696
3697    #[tokio::test]
3698    async fn test_wrong_peer_binding_rejected() {
3699        use evmlib::{EncodedPeerId, RewardsAddress};
3700        use saorsa_core::MlDsa65;
3701        use saorsa_pqc::pqc::MlDsaOperations;
3702
3703        let verifier = create_test_verifier();
3704        let xorname = [0xFFu8; 32];
3705        let rewards_addr = RewardsAddress::new([1u8; 20]);
3706
3707        // Generate a real ML-DSA keypair so pub_key is valid
3708        let ml_dsa = MlDsa65::new();
3709        let (public_key, _secret_key) = ml_dsa.generate_keypair().expect("keygen");
3710        let pub_key_bytes = public_key.as_bytes().to_vec();
3711
3712        // Create a quote with a real pub_key but attach it to a random peer ID
3713        // whose identity multihash does NOT match BLAKE3(pub_key)
3714        let mut quote = make_fake_quote(xorname, SystemTime::now(), rewards_addr);
3715        quote.pub_key = pub_key_bytes;
3716
3717        // Use random ed25519 peer IDs — they won't match BLAKE3(pub_key)
3718        let mut peer_quotes = Vec::new();
3719        for _ in 0..CLOSE_GROUP_SIZE {
3720            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
3721        }
3722
3723        let proof_bytes = serialize_proof(peer_quotes);
3724        let result = verifier
3725            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
3726            .await;
3727
3728        assert!(result.is_err(), "Should reject wrong peer binding");
3729        let err_msg = format!("{}", result.expect_err("should fail"));
3730        assert!(
3731            err_msg.contains("pub_key does not belong to claimed peer"),
3732            "Error should mention binding mismatch: {err_msg}"
3733        );
3734    }
3735
3736    // =========================================================================
3737    // VerificationContext tests — both contexts verify fresh proof admissions.
3738    // Later neighbour-sync repair has no proof-of-payment and is authorized by
3739    // closest-7 storage quorum or closest-K paid-list quorum instead.
3740    // =========================================================================
3741
3742    /// Content binding is required for every fresh proof context. A receipt for
3743    /// chunk A cannot admit chunk B as either a direct/fresh store or a fresh
3744    /// paid-list update.
3745    #[tokio::test]
3746    async fn test_fresh_contexts_reject_content_mismatch() {
3747        let verifier = create_test_verifier();
3748        let stored_xorname = [0xD2u8; 32];
3749        let quoted_xorname = [0xD3u8; 32];
3750        let rewards = RewardsAddress::new([1u8; 20]);
3751
3752        let mut peer_quotes = Vec::new();
3753        for _ in 0..CLOSE_GROUP_SIZE {
3754            let quote = make_fake_quote(quoted_xorname, SystemTime::now(), rewards);
3755            peer_quotes.push((evmlib::EncodedPeerId::new(rand::random()), quote));
3756        }
3757        let proof_bytes = serialize_proof(peer_quotes);
3758
3759        for context in [
3760            VerificationContext::ClientPut,
3761            VerificationContext::PaidListAdmission,
3762        ] {
3763            let err = verifier
3764                .verify_payment(&stored_xorname, Some(&proof_bytes), context)
3765                .await
3766                .expect_err("content binding must hold in every context");
3767            assert!(
3768                format!("{err}").contains("content address mismatch"),
3769                "{context:?} must reject a receipt for a different address: {err}"
3770            );
3771        }
3772    }
3773
3774    /// The merkle pay-yourself closeness defence (including its duplicate-
3775    /// candidate pre-check, which runs without a `P2PNode`) applies to every
3776    /// proof verification context because every context is a fresh admission.
3777    #[tokio::test]
3778    async fn test_fresh_contexts_enforce_merkle_closeness() {
3779        let verifier = create_test_verifier();
3780
3781        let (mut merkle_proof, _pool_hash, xorname, _timestamp) = make_valid_merkle_proof();
3782
3783        // 16 copies of one real candidate: every self-signature is valid, but
3784        // the candidate PeerIds are duplicates — the closeness pre-check
3785        // rejects this pool on a client PUT.
3786        let shared = merkle_proof
3787            .winner_pool
3788            .candidate_nodes
3789            .first()
3790            .expect("candidates")
3791            .clone();
3792        for c in &mut merkle_proof.winner_pool.candidate_nodes {
3793            *c = shared.clone();
3794        }
3795        let tagged =
3796            crate::payment::proof::serialize_merkle_proof(&merkle_proof).expect("serialize");
3797
3798        for context in [
3799            VerificationContext::ClientPut,
3800            VerificationContext::PaidListAdmission,
3801        ] {
3802            let err = verifier
3803                .verify_payment(&xorname, Some(&tagged), context)
3804                .await
3805                .expect_err("duplicate candidate PeerIds must fail fresh admission closeness");
3806            assert!(
3807                format!("{err}").contains("duplicate candidate PeerId"),
3808                "{context:?} must fail at the closeness pre-check: {err}"
3809            );
3810        }
3811    }
3812
3813    // =========================================================================
3814    // Merkle-tagged proof tests
3815    // =========================================================================
3816
3817    #[tokio::test]
3818    async fn test_merkle_tagged_proof_invalid_data_rejected() {
3819        use crate::ant_protocol::PROOF_TAG_MERKLE;
3820
3821        let verifier = create_test_verifier();
3822        let xorname = [0xA1u8; 32];
3823
3824        // Build a merkle-tagged proof with garbage body.
3825        // The tag byte is correct but the body is not valid msgpack.
3826        let mut merkle_garbage = Vec::with_capacity(64);
3827        merkle_garbage.push(PROOF_TAG_MERKLE);
3828        merkle_garbage.extend_from_slice(&[0xAB; 63]);
3829
3830        let result = verifier
3831            .verify_payment(
3832                &xorname,
3833                Some(&merkle_garbage),
3834                VerificationContext::ClientPut,
3835            )
3836            .await;
3837
3838        assert!(
3839            result.is_err(),
3840            "Should reject merkle proof with invalid body"
3841        );
3842        let err_msg = format!("{}", result.expect_err("should fail"));
3843        assert!(
3844            err_msg.contains("deserialize") || err_msg.contains("merkle proof"),
3845            "Error should mention deserialization failure: {err_msg}"
3846        );
3847    }
3848
3849    #[tokio::test]
3850    async fn test_single_node_tagged_proof_deserialization() {
3851        use crate::payment::proof::serialize_single_node_proof;
3852        use evmlib::{EncodedPeerId, RewardsAddress};
3853
3854        let verifier = create_test_verifier();
3855        let xorname = [0xA2u8; 32];
3856        let rewards_addr = RewardsAddress::new([1u8; 20]);
3857
3858        // Build a valid tagged single-node proof
3859        let quote = make_fake_quote(xorname, SystemTime::now(), rewards_addr);
3860        let mut peer_quotes = Vec::new();
3861        for _ in 0..CLOSE_GROUP_SIZE {
3862            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
3863        }
3864
3865        let proof = crate::payment::proof::PaymentProof {
3866            proof_of_payment: ProofOfPayment {
3867                peer_quotes: peer_quotes.clone(),
3868            },
3869            tx_hashes: vec![],
3870            commitment_sidecars: vec![],
3871        };
3872
3873        let tagged_bytes = serialize_single_node_proof(&proof).expect("serialize tagged proof");
3874
3875        // detect_proof_type should identify it as SingleNode
3876        assert_eq!(
3877            crate::payment::proof::detect_proof_type(&tagged_bytes),
3878            Some(crate::payment::proof::ProofType::SingleNode)
3879        );
3880
3881        // verify_payment should process it through the single-node path.
3882        // It will fail at quote validation (fake pub_key), but we verify
3883        // it passes the deserialization stage by checking the error type.
3884        let result = verifier
3885            .verify_payment(
3886                &xorname,
3887                Some(&tagged_bytes),
3888                VerificationContext::ClientPut,
3889            )
3890            .await;
3891
3892        assert!(result.is_err(), "Should fail at quote validation stage");
3893        let err_msg = format!("{}", result.expect_err("should fail"));
3894        // It should NOT be a deserialization error — it should get further
3895        assert!(
3896            !err_msg.contains("deserialize"),
3897            "Should pass deserialization but fail later: {err_msg}"
3898        );
3899    }
3900
3901    #[test]
3902    fn test_pool_cache_insert_and_lookup() {
3903        use evmlib::merkle_batch_payment::PoolHash;
3904
3905        // Verify the pool_cache field exists and works correctly.
3906        // Insert a pool hash, then verify it's present on lookup.
3907        let verifier = create_test_verifier();
3908
3909        let pool_hash: PoolHash = [0xBBu8; 32];
3910        let payment_info = evmlib::merkle_payments::OnChainPaymentInfo {
3911            depth: 4,
3912            merkle_payment_timestamp: 1_700_000_000,
3913            paid_node_addresses: vec![],
3914        };
3915
3916        // Insert into pool cache
3917        {
3918            let mut cache = verifier.pool_cache.lock();
3919            cache.put(pool_hash, payment_info);
3920        }
3921
3922        // First lookup — should find it
3923        {
3924            let found = verifier.pool_cache.lock().get(&pool_hash).cloned();
3925            assert!(found.is_some(), "Pool hash should be in cache after insert");
3926            let info = found.expect("cached info");
3927            assert_eq!(info.depth, 4);
3928            assert_eq!(info.merkle_payment_timestamp, 1_700_000_000);
3929        }
3930
3931        // Second lookup — same result (no double-query needed)
3932        {
3933            let found = verifier.pool_cache.lock().get(&pool_hash).cloned();
3934            assert!(
3935                found.is_some(),
3936                "Pool hash should still be in cache on second lookup"
3937            );
3938        }
3939
3940        // Different pool hash — should NOT be found
3941        let other_hash: PoolHash = [0xCCu8; 32];
3942        {
3943            let found = verifier.pool_cache.lock().get(&other_hash).cloned();
3944            assert!(found.is_none(), "Unknown pool hash should not be in cache");
3945        }
3946    }
3947
3948    #[tokio::test]
3949    async fn closeness_pass_cache_short_circuits_second_call() {
3950        // When a pool_hash is in the closeness_pass_cache, the outer
3951        // verify_merkle_candidate_closeness must return Ok(()) without
3952        // running the inner lookup — even if no P2PNode is attached.
3953        // That second half (no-p2p → would normally fail-closed in release)
3954        // is the proof the cache short-circuit ran first.
3955        let verifier = create_test_verifier();
3956        let pool_hash = [0xAAu8; 32];
3957        verifier.closeness_pass_cache.lock().put(pool_hash, ());
3958
3959        // Construct a dummy pool — contents don't matter because the cache
3960        // hit means we never look at them.
3961        let pool = MerklePaymentCandidatePool {
3962            midpoint_proof: fake_midpoint_proof(),
3963            candidate_nodes: make_candidate_nodes(1_700_000_000),
3964        };
3965
3966        let result = verifier
3967            .verify_merkle_candidate_closeness(&pool, pool_hash)
3968            .await;
3969        assert!(
3970            result.is_ok(),
3971            "cached pool hash must bypass the inner check and return Ok(()), got: {result:?}"
3972        );
3973    }
3974
3975    #[tokio::test]
3976    async fn closeness_single_flight_concurrent_readers_share_one_verification() {
3977        // Two concurrent callers for the same pool_hash should produce the
3978        // same outcome, and the cache should end up populated exactly once.
3979        // We use the test-utils fail-open path to short-circuit the inner
3980        // DHT lookup; the purpose of this test is the single-flight
3981        // plumbing, not the lookup itself.
3982        let verifier = Arc::new(create_test_verifier());
3983        let pool_hash = [0x77u8; 32];
3984        let pool = MerklePaymentCandidatePool {
3985            midpoint_proof: fake_midpoint_proof(),
3986            candidate_nodes: make_candidate_nodes(1_700_000_000),
3987        };
3988
3989        let v1 = Arc::clone(&verifier);
3990        let p1 = pool.clone();
3991        let v2 = Arc::clone(&verifier);
3992        let p2 = pool.clone();
3993
3994        let (r1, r2) = tokio::join!(
3995            async move { v1.verify_merkle_candidate_closeness(&p1, pool_hash).await },
3996            async move { v2.verify_merkle_candidate_closeness(&p2, pool_hash).await },
3997        );
3998
3999        assert_eq!(r1.is_ok(), r2.is_ok(), "concurrent callers must agree");
4000        assert!(
4001            r1.is_ok(),
4002            "both callers must succeed on the test-utils path"
4003        );
4004        assert!(
4005            verifier
4006                .closeness_pass_cache
4007                .lock()
4008                .get(&pool_hash)
4009                .is_some(),
4010            "success path must populate the pass cache"
4011        );
4012        assert!(
4013            verifier.inflight_closeness.lock().get(&pool_hash).is_none(),
4014            "inflight slot must be cleared after the leader finishes"
4015        );
4016    }
4017
4018    #[tokio::test]
4019    async fn closeness_waiter_reads_leaders_published_failure() {
4020        // Prove the waiter path actually surfaces a failure published by a
4021        // concurrent leader, without running its own inner check. Insert a
4022        // slot, spawn a waiter (which will park on notified_owned), then
4023        // publish failure + notify from the outside — simulating what the
4024        // leader's `publish` + drop-guard pair does.
4025        let verifier = Arc::new(create_test_verifier());
4026        let pool_hash = [0x55u8; 32];
4027        let slot = Arc::new(ClosenessSlot::new());
4028        verifier
4029            .inflight_closeness
4030            .lock()
4031            .put(pool_hash, Arc::clone(&slot));
4032
4033        let pool = MerklePaymentCandidatePool {
4034            midpoint_proof: fake_midpoint_proof(),
4035            candidate_nodes: make_candidate_nodes(1_700_000_000),
4036        };
4037
4038        let verifier_c = Arc::clone(&verifier);
4039        let pool_c = pool.clone();
4040        let waiter = tokio::spawn(async move {
4041            verifier_c
4042                .verify_merkle_candidate_closeness(&pool_c, pool_hash)
4043                .await
4044        });
4045
4046        // Yield so the waiter can run up to its `notified_owned().await`.
4047        // A few yields cover both single-threaded and multi-threaded tokio
4048        // runtimes regardless of scheduling.
4049        for _ in 0..5 {
4050            tokio::task::yield_now().await;
4051        }
4052
4053        // Simulate the leader's `publish` + drop-guard: publish the result,
4054        // clear the slot, wake waiters.
4055        slot.result
4056            .set(Err("forged pool: not close enough".to_string()))
4057            .expect("set once");
4058        verifier.inflight_closeness.lock().pop(&pool_hash);
4059        slot.notify.notify_waiters();
4060
4061        let result = waiter.await.expect("task panicked");
4062        let err = result.expect_err("waiter must return the leader's published failure");
4063        assert!(
4064            err.to_string().contains("forged pool"),
4065            "waiter must surface the leader's error message, got: {err}"
4066        );
4067    }
4068
4069    #[tokio::test]
4070    async fn closeness_rejects_pool_with_duplicate_candidate_pub_keys() {
4071        // An attacker who submits 16 copies of the same real peer's pub_key
4072        // would otherwise satisfy the closeness threshold trivially:
4073        // that one peer's membership in the DHT-returned set would count
4074        // 16 times. The dedupe check in verify_merkle_candidate_closeness_inner
4075        // must reject the pool BEFORE the network lookup runs (so this test
4076        // works even with no P2PNode attached).
4077        let verifier = create_test_verifier();
4078        let pool_hash = [0xDDu8; 32];
4079
4080        // Build a normal pool, then overwrite every candidate's pub_key
4081        // with a single shared key so all 16 derive to the same PeerId.
4082        let mut candidates = make_candidate_nodes(1_700_000_000);
4083        let shared_pub_key = candidates
4084            .first()
4085            .expect("make_candidate_nodes returns CANDIDATES_PER_POOL entries")
4086            .pub_key
4087            .clone();
4088        for c in &mut candidates {
4089            c.pub_key = shared_pub_key.clone();
4090        }
4091        let pool = MerklePaymentCandidatePool {
4092            midpoint_proof: fake_midpoint_proof(),
4093            candidate_nodes: candidates,
4094        };
4095
4096        let result = verifier
4097            .verify_merkle_candidate_closeness(&pool, pool_hash)
4098            .await;
4099        let err = result.expect_err("duplicate candidate PeerIds must be rejected");
4100        let msg = err.to_string();
4101        assert!(
4102            msg.contains("duplicate candidate PeerId"),
4103            "rejection must be the duplicate-PeerId branch, got: {msg}"
4104        );
4105    }
4106
4107    /// Build a deterministic but otherwise-unused `MidpointProof` so unit
4108    /// tests can construct a `MerklePaymentCandidatePool` without spinning
4109    /// up a real merkle tree. The closeness path only calls `.address()`
4110    /// on it, which is a pure BLAKE3 of the branch's leaf/root/timestamp —
4111    /// the values don't need to be tree-valid for these tests.
4112    fn fake_midpoint_proof() -> evmlib::merkle_payments::MidpointProof {
4113        // Build a minimal tree of two leaves so we get a real branch.
4114        let leaves = vec![xor_name::XorName([1u8; 32]), xor_name::XorName([2u8; 32])];
4115        let tree = evmlib::merkle_payments::MerkleTree::from_xornames(leaves).expect("tree");
4116        let candidates = tree.reward_candidates(1_700_000_000).expect("candidates");
4117        candidates.first().expect("at least one").clone()
4118    }
4119
4120    // =========================================================================
4121    // Merkle verification unit tests
4122    // =========================================================================
4123
4124    /// Helper: build 16 validly-signed ML-DSA-65 candidate nodes.
4125    fn make_candidate_nodes(
4126        timestamp: u64,
4127    ) -> [evmlib::merkle_payments::MerklePaymentCandidateNode;
4128           evmlib::merkle_payments::CANDIDATES_PER_POOL] {
4129        use evmlib::merkle_payments::{MerklePaymentCandidateNode, CANDIDATES_PER_POOL};
4130        use saorsa_core::MlDsa65;
4131        use saorsa_pqc::pqc::types::MlDsaSecretKey;
4132        use saorsa_pqc::pqc::MlDsaOperations;
4133
4134        std::array::from_fn::<_, CANDIDATES_PER_POOL, _>(|i| {
4135            let ml_dsa = MlDsa65::new();
4136            let (pub_key, secret_key) = ml_dsa.generate_keypair().expect("keygen");
4137            let price = evmlib::common::Amount::from(1024u64);
4138            #[allow(clippy::cast_possible_truncation)]
4139            let reward_address = RewardsAddress::new([i as u8; 20]);
4140            let msg = MerklePaymentCandidateNode::bytes_to_sign(
4141                &price,
4142                &reward_address,
4143                timestamp,
4144                0,
4145                &None,
4146            );
4147            let sk = MlDsaSecretKey::from_bytes(secret_key.as_bytes()).expect("sk");
4148            let signature = ml_dsa.sign(&sk, &msg).expect("sign").as_bytes().to_vec();
4149
4150            MerklePaymentCandidateNode {
4151                pub_key: pub_key.as_bytes().to_vec(),
4152                price,
4153                reward_address,
4154                merkle_payment_timestamp: timestamp,
4155                committed_key_count: 0,
4156                commitment_pin: None,
4157                signature,
4158            }
4159        })
4160    }
4161
4162    /// Helper: build a valid `MerklePaymentProof` with real ML-DSA-65
4163    /// signatures. Returns the raw proof, pool hash, xorname, and timestamp.
4164    fn make_valid_merkle_proof() -> (
4165        evmlib::merkle_payments::MerklePaymentProof,
4166        evmlib::merkle_batch_payment::PoolHash,
4167        [u8; 32],
4168        u64,
4169    ) {
4170        use evmlib::merkle_payments::{MerklePaymentCandidatePool, MerklePaymentProof, MerkleTree};
4171
4172        let timestamp = std::time::SystemTime::now()
4173            .duration_since(std::time::UNIX_EPOCH)
4174            .expect("system time")
4175            .as_secs();
4176
4177        let addresses: Vec<xor_name::XorName> = (0..4u8)
4178            .map(|i| xor_name::XorName::from_content(&[i]))
4179            .collect();
4180        let tree = MerkleTree::from_xornames(addresses.clone()).expect("tree");
4181
4182        let candidate_nodes = make_candidate_nodes(timestamp);
4183
4184        let reward_candidates = tree
4185            .reward_candidates(timestamp)
4186            .expect("reward candidates");
4187        let midpoint_proof = reward_candidates
4188            .first()
4189            .expect("at least one candidate")
4190            .clone();
4191
4192        let pool = MerklePaymentCandidatePool {
4193            midpoint_proof,
4194            candidate_nodes,
4195        };
4196
4197        let first_address = *addresses.first().expect("first address");
4198        let address_proof = tree
4199            .generate_address_proof(0, first_address)
4200            .expect("proof");
4201
4202        let merkle_proof = MerklePaymentProof::new(first_address, address_proof, pool);
4203        let pool_hash = merkle_proof.winner_pool_hash();
4204        let xorname = first_address.0;
4205
4206        (merkle_proof, pool_hash, xorname, timestamp)
4207    }
4208
4209    /// Helper: build a minimal valid `MerklePaymentProof` with real ML-DSA-65
4210    /// signatures. Returns `(xorname, serialized_tagged_proof, pool_hash, timestamp)`.
4211    fn make_valid_merkle_proof_bytes() -> (
4212        [u8; 32],
4213        Vec<u8>,
4214        evmlib::merkle_batch_payment::PoolHash,
4215        u64,
4216    ) {
4217        let (merkle_proof, pool_hash, xorname, timestamp) = make_valid_merkle_proof();
4218        let tagged = crate::payment::proof::serialize_merkle_proof(&merkle_proof)
4219            .expect("serialize merkle proof");
4220        (xorname, tagged, pool_hash, timestamp)
4221    }
4222
4223    #[tokio::test]
4224    async fn test_merkle_address_mismatch_rejected() {
4225        let verifier = create_test_verifier();
4226        let (_correct_xorname, tagged_proof, _pool_hash, _ts) = make_valid_merkle_proof_bytes();
4227
4228        // Use a DIFFERENT xorname than what the proof was built for
4229        let wrong_xorname = [0xFFu8; 32];
4230
4231        let result = verifier
4232            .verify_payment(
4233                &wrong_xorname,
4234                Some(&tagged_proof),
4235                VerificationContext::ClientPut,
4236            )
4237            .await;
4238
4239        assert!(
4240            result.is_err(),
4241            "Should reject merkle proof address mismatch"
4242        );
4243        let err_msg = format!("{}", result.expect_err("should fail"));
4244        assert!(
4245            err_msg.contains("address mismatch") || err_msg.contains("Merkle proof address"),
4246            "Error should mention address mismatch: {err_msg}"
4247        );
4248    }
4249
4250    #[tokio::test]
4251    async fn test_merkle_malformed_body_rejected() {
4252        let verifier = create_test_verifier();
4253        let xorname = [0xA3u8; 32];
4254
4255        // Valid merkle tag but truncated/corrupted msgpack body
4256        let mut bad_proof = vec![crate::ant_protocol::PROOF_TAG_MERKLE];
4257        bad_proof.extend_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF]);
4258        bad_proof.extend_from_slice(&[0x00; 10]);
4259        // pad to minimum size
4260        while bad_proof.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
4261            bad_proof.push(0x00);
4262        }
4263
4264        let result = verifier
4265            .verify_payment(&xorname, Some(&bad_proof), VerificationContext::ClientPut)
4266            .await;
4267
4268        assert!(result.is_err(), "Should reject malformed merkle body");
4269        let err_msg = format!("{}", result.expect_err("should fail"));
4270        assert!(
4271            err_msg.contains("deserialize") || err_msg.contains("Failed"),
4272            "Error should mention deserialization: {err_msg}"
4273        );
4274    }
4275
4276    #[test]
4277    fn test_merkle_proof_serialized_size_within_limits() {
4278        let (_xorname, tagged_proof, _pool_hash, _ts) = make_valid_merkle_proof_bytes();
4279
4280        // 16 ML-DSA-65 candidates (~1952 pub key + ~3309 sig each) ≈ 84 KB + tree data
4281        assert!(
4282            tagged_proof.len() >= MIN_PAYMENT_PROOF_SIZE_BYTES,
4283            "Merkle proof ({} bytes) should be >= min {} bytes",
4284            tagged_proof.len(),
4285            MIN_PAYMENT_PROOF_SIZE_BYTES
4286        );
4287        assert!(
4288            tagged_proof.len() <= MAX_PAYMENT_PROOF_SIZE_BYTES,
4289            "Merkle proof ({} bytes) should be <= max {} bytes",
4290            tagged_proof.len(),
4291            MAX_PAYMENT_PROOF_SIZE_BYTES
4292        );
4293    }
4294
4295    #[test]
4296    fn test_merkle_proof_tag_is_correct() {
4297        let (_xorname, tagged_proof, _pool_hash, _ts) = make_valid_merkle_proof_bytes();
4298
4299        assert_eq!(
4300            tagged_proof.first().copied(),
4301            Some(crate::ant_protocol::PROOF_TAG_MERKLE),
4302            "First byte must be the merkle tag"
4303        );
4304        assert_eq!(
4305            crate::payment::proof::detect_proof_type(&tagged_proof),
4306            Some(crate::payment::proof::ProofType::Merkle)
4307        );
4308    }
4309
4310    #[test]
4311    fn test_pool_cache_eviction() {
4312        use evmlib::merkle_batch_payment::PoolHash;
4313
4314        let config = PaymentVerifierConfig {
4315            evm: EvmVerifierConfig::default(),
4316            cache_capacity: 100,
4317            close_group_size: CLOSE_GROUP_SIZE,
4318            local_rewards_address: RewardsAddress::new([1u8; 20]),
4319        };
4320        let verifier = PaymentVerifier::new(config);
4321
4322        // Fill the pool cache to capacity (DEFAULT_POOL_CACHE_CAPACITY = 1000)
4323        for i in 0..DEFAULT_POOL_CACHE_CAPACITY {
4324            let mut hash: PoolHash = [0u8; 32];
4325            // Write index bytes into the hash
4326            let idx_bytes = i.to_le_bytes();
4327            for (j, b) in idx_bytes.iter().enumerate() {
4328                if j < 32 {
4329                    hash[j] = *b;
4330                }
4331            }
4332            let info = evmlib::merkle_payments::OnChainPaymentInfo {
4333                depth: 4,
4334                merkle_payment_timestamp: 1_700_000_000,
4335                paid_node_addresses: vec![],
4336            };
4337            verifier.pool_cache.lock().put(hash, info);
4338        }
4339
4340        assert_eq!(
4341            verifier.pool_cache.lock().len(),
4342            DEFAULT_POOL_CACHE_CAPACITY
4343        );
4344
4345        // Insert one more — should evict the oldest
4346        let overflow_hash: PoolHash = [0xFFu8; 32];
4347        let info = evmlib::merkle_payments::OnChainPaymentInfo {
4348            depth: 8,
4349            merkle_payment_timestamp: 1_800_000_000,
4350            paid_node_addresses: vec![],
4351        };
4352        verifier.pool_cache.lock().put(overflow_hash, info);
4353
4354        // Size should still be at capacity (not capacity + 1)
4355        assert_eq!(
4356            verifier.pool_cache.lock().len(),
4357            DEFAULT_POOL_CACHE_CAPACITY
4358        );
4359
4360        // The new entry should be present
4361        let found = verifier.pool_cache.lock().get(&overflow_hash).cloned();
4362        assert!(
4363            found.is_some(),
4364            "Newly inserted pool hash should be present"
4365        );
4366        assert_eq!(found.expect("info").depth, 8);
4367    }
4368
4369    #[test]
4370    fn test_pool_cache_concurrent_access() {
4371        use evmlib::merkle_batch_payment::PoolHash;
4372        use std::sync::Arc;
4373
4374        let verifier = Arc::new(create_test_verifier());
4375
4376        let mut handles = Vec::new();
4377        for i in 0..20u8 {
4378            let v = verifier.clone();
4379            handles.push(std::thread::spawn(move || {
4380                let hash: PoolHash = [i; 32];
4381                let info = evmlib::merkle_payments::OnChainPaymentInfo {
4382                    depth: i,
4383                    merkle_payment_timestamp: u64::from(i) * 1000,
4384                    paid_node_addresses: vec![],
4385                };
4386                v.pool_cache.lock().put(hash, info);
4387
4388                // Read back
4389                let found = v.pool_cache.lock().get(&hash).cloned();
4390                assert!(found.is_some(), "Entry {i} should be readable after insert");
4391            }));
4392        }
4393
4394        for handle in handles {
4395            handle.join().expect("thread panicked");
4396        }
4397
4398        // All 20 entries should be present (well under 1000 capacity)
4399        assert_eq!(verifier.pool_cache.lock().len(), 20);
4400    }
4401
4402    #[tokio::test]
4403    async fn test_merkle_tampered_candidate_signature_rejected() {
4404        let verifier = create_test_verifier();
4405
4406        let (mut merkle_proof, _pool_hash, xorname, timestamp) = make_valid_merkle_proof();
4407
4408        // Tamper the first candidate's signature
4409        if let Some(byte) = merkle_proof
4410            .winner_pool
4411            .candidate_nodes
4412            .first_mut()
4413            .and_then(|c| c.signature.first_mut())
4414        {
4415            *byte ^= 0xFF;
4416        }
4417
4418        // Recompute pool hash after tampering (signature change alters the hash)
4419        let tampered_pool_hash = merkle_proof.winner_pool_hash();
4420
4421        // Pre-populate pool cache so we skip the on-chain query
4422        {
4423            let info = evmlib::merkle_payments::OnChainPaymentInfo {
4424                depth: 4,
4425                merkle_payment_timestamp: timestamp,
4426                paid_node_addresses: vec![],
4427            };
4428            verifier.pool_cache.lock().put(tampered_pool_hash, info);
4429        }
4430
4431        let tagged =
4432            crate::payment::proof::serialize_merkle_proof(&merkle_proof).expect("serialize");
4433
4434        let result = verifier
4435            .verify_payment(&xorname, Some(&tagged), VerificationContext::ClientPut)
4436            .await;
4437
4438        assert!(
4439            result.is_err(),
4440            "Should reject merkle proof with tampered candidate signature"
4441        );
4442        let err_msg = format!("{}", result.expect_err("should fail"));
4443        assert!(
4444            err_msg.contains("Invalid ML-DSA-65 signature"),
4445            "Error should mention invalid signature: {err_msg}"
4446        );
4447    }
4448
4449    #[tokio::test]
4450    async fn test_merkle_timestamp_mismatch_rejected() {
4451        let verifier = create_test_verifier();
4452
4453        let (xorname, tagged, pool_hash, timestamp) = make_valid_merkle_proof_bytes();
4454
4455        // Pre-populate pool cache with a DIFFERENT timestamp than the candidates
4456        {
4457            let mismatched_ts = timestamp + 9999;
4458            let info = evmlib::merkle_payments::OnChainPaymentInfo {
4459                depth: 4,
4460                merkle_payment_timestamp: mismatched_ts,
4461                paid_node_addresses: vec![],
4462            };
4463            verifier.pool_cache.lock().put(pool_hash, info);
4464        }
4465
4466        let result = verifier
4467            .verify_payment(&xorname, Some(&tagged), VerificationContext::ClientPut)
4468            .await;
4469
4470        assert!(
4471            result.is_err(),
4472            "Should reject merkle proof with timestamp mismatch"
4473        );
4474        let err_msg = format!("{}", result.expect_err("should fail"));
4475        assert!(
4476            err_msg.contains("timestamp mismatch"),
4477            "Error should mention timestamp mismatch: {err_msg}"
4478        );
4479    }
4480
4481    #[tokio::test]
4482    async fn test_merkle_paid_node_index_out_of_bounds_rejected() {
4483        let verifier = create_test_verifier();
4484        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
4485
4486        // The test tree has 4 addresses → depth 2. We must match the tree depth
4487        // so verify_merkle_proof passes the depth check, then the paid node
4488        // index out-of-bounds check fires.
4489        {
4490            let info = evmlib::merkle_payments::OnChainPaymentInfo {
4491                depth: 2,
4492                merkle_payment_timestamp: ts,
4493                paid_node_addresses: vec![
4494                    // First paid node: valid (matches candidate 0, amount matches formula)
4495                    // Expected per-node: median(1024) * 2^2 / 2 = 2048
4496                    (RewardsAddress::new([0u8; 20]), 0, Amount::from(2048u64)),
4497                    // Second paid node: index 999 is way beyond CANDIDATES_PER_POOL (16)
4498                    (RewardsAddress::new([1u8; 20]), 999, Amount::from(2048u64)),
4499                ],
4500            };
4501            verifier.pool_cache.lock().put(pool_hash, info);
4502        }
4503
4504        let result = verifier
4505            .verify_payment(
4506                &xorname,
4507                Some(&tagged_proof),
4508                VerificationContext::ClientPut,
4509            )
4510            .await;
4511
4512        assert!(
4513            result.is_err(),
4514            "Should reject paid node index out of bounds"
4515        );
4516        let err_msg = format!("{}", result.expect_err("should fail"));
4517        assert!(
4518            err_msg.contains("out of bounds"),
4519            "Error should mention out of bounds: {err_msg}"
4520        );
4521    }
4522
4523    #[tokio::test]
4524    async fn test_merkle_paid_node_address_mismatch_rejected() {
4525        let verifier = create_test_verifier();
4526        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
4527
4528        // Tree has depth 2, so provide 2 paid node entries.
4529        // Both use valid indices but the second has a wrong reward address.
4530        {
4531            let info = evmlib::merkle_payments::OnChainPaymentInfo {
4532                depth: 2,
4533                merkle_payment_timestamp: ts,
4534                paid_node_addresses: vec![
4535                    // Index 0 with matching address [0x00; 20]
4536                    // Expected per-node: median(1024) * 2^2 / 2 = 2048
4537                    (RewardsAddress::new([0u8; 20]), 0, Amount::from(2048u64)),
4538                    // Index 1 with WRONG address — candidate 1's address is [0x01; 20]
4539                    (RewardsAddress::new([0xFF; 20]), 1, Amount::from(2048u64)),
4540                ],
4541            };
4542            verifier.pool_cache.lock().put(pool_hash, info);
4543        }
4544
4545        let result = verifier
4546            .verify_payment(
4547                &xorname,
4548                Some(&tagged_proof),
4549                VerificationContext::ClientPut,
4550            )
4551            .await;
4552
4553        assert!(result.is_err(), "Should reject paid node address mismatch");
4554        let err_msg = format!("{}", result.expect_err("should fail"));
4555        assert!(
4556            err_msg.contains("address mismatch"),
4557            "Error should mention address mismatch: {err_msg}"
4558        );
4559    }
4560
4561    #[tokio::test]
4562    async fn test_merkle_wrong_depth_rejected() {
4563        let verifier = create_test_verifier();
4564        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
4565
4566        // Pre-populate pool cache with depth=3 but only 1 paid node address
4567        // (depth must equal paid_node_addresses.len())
4568        {
4569            let info = evmlib::merkle_payments::OnChainPaymentInfo {
4570                depth: 3,
4571                merkle_payment_timestamp: ts,
4572                paid_node_addresses: vec![(
4573                    RewardsAddress::new([0u8; 20]),
4574                    0,
4575                    Amount::from(1024u64),
4576                )],
4577            };
4578            verifier.pool_cache.lock().put(pool_hash, info);
4579        }
4580
4581        let result = verifier
4582            .verify_payment(
4583                &xorname,
4584                Some(&tagged_proof),
4585                VerificationContext::ClientPut,
4586            )
4587            .await;
4588
4589        assert!(
4590            result.is_err(),
4591            "Should reject mismatched depth vs paid node count"
4592        );
4593        let err_msg = format!("{}", result.expect_err("should fail"));
4594        assert!(
4595            err_msg.contains("Wrong number of paid nodes")
4596                || err_msg.contains("verification failed"),
4597            "Error should mention depth/count mismatch: {err_msg}"
4598        );
4599    }
4600
4601    #[tokio::test]
4602    async fn test_merkle_underpayment_rejected() {
4603        let verifier = create_test_verifier();
4604        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
4605
4606        // Tree depth=2, so 2 paid nodes required. Candidates all quote price=1024.
4607        // Expected per-node: median(1024) * 2^2 / 2 = 2048.
4608        // Pay only 1 wei per node — far below the expected amount.
4609        {
4610            let info = evmlib::merkle_payments::OnChainPaymentInfo {
4611                depth: 2,
4612                merkle_payment_timestamp: ts,
4613                paid_node_addresses: vec![
4614                    (RewardsAddress::new([0u8; 20]), 0, Amount::from(1u64)),
4615                    (RewardsAddress::new([1u8; 20]), 1, Amount::from(1u64)),
4616                ],
4617            };
4618            verifier.pool_cache.lock().put(pool_hash, info);
4619        }
4620
4621        let result = verifier
4622            .verify_payment(
4623                &xorname,
4624                Some(&tagged_proof),
4625                VerificationContext::ClientPut,
4626            )
4627            .await;
4628
4629        assert!(
4630            result.is_err(),
4631            "Should reject merkle payment where paid amount < expected per-node amount"
4632        );
4633        let err_msg = format!("{}", result.expect_err("should fail"));
4634        assert!(
4635            err_msg.contains("Underpayment"),
4636            "Error should mention underpayment: {err_msg}"
4637        );
4638    }
4639
4640    // =========================================================================
4641    // Closeness-window constants regression tests
4642    //
4643    // These constants are load-bearing for both correctness (the storer
4644    // must look at the same window the client picks from, otherwise honest
4645    // pools are rejected) and DoS resistance (the timeout caps lookup
4646    // amplification per forged pool_hash). Pinning them with tests gives
4647    // future patches a one-line failure if either is silently changed
4648    // without updating the security argument in the doc comments.
4649    //
4650    // Empirical justification, captured during STG-01 investigation on
4651    // 2026-05-01:
4652    //
4653    //   - 60s timeout cut iterative lookups off after ~7 of 20 iterations
4654    //     (trace from EWR-3 ant-node-1 in CLOSENESS_LOOKUP_TIMEOUT doc).
4655    //   - K=16 storer window vs K=32 client over-query produced 73%
4656    //     false-positive mismatch rejections under realistic load
4657    //     (115 → 31 client mismatches per 5min after K=32 deploy).
4658    // =========================================================================
4659
4660    #[test]
4661    fn closeness_lookup_timeout_is_240s() {
4662        // Pin the timeout. If a future change drops it back to 60s the
4663        // failure mode from the trace in the doc comment will return.
4664        assert_eq!(
4665            PaymentVerifier::CLOSENESS_LOOKUP_TIMEOUT,
4666            std::time::Duration::from_secs(240),
4667            "CLOSENESS_LOOKUP_TIMEOUT must be 240s; if changing this, update \
4668             the iteration trace in the doc comment and re-validate on a \
4669             fresh testnet"
4670        );
4671    }
4672
4673    #[test]
4674    fn closeness_lookup_width_is_32() {
4675        // Pin the storer's lookup width. Must equal the client's
4676        // over-query factor (CANDIDATES_PER_POOL * 2 = 32) so the storer
4677        // sees the same peers the client legitimately picks from.
4678        assert_eq!(
4679            PaymentVerifier::CLOSENESS_LOOKUP_WIDTH,
4680            2 * evmlib::merkle_payments::CANDIDATES_PER_POOL,
4681            "CLOSENESS_LOOKUP_WIDTH must equal 2 * CANDIDATES_PER_POOL to \
4682             match the client's over-query in get_merkle_candidate_pool"
4683        );
4684    }
4685
4686    #[test]
4687    fn closeness_required_threshold_is_majority() {
4688        // Pin the threshold so a future change can't silently move it. This
4689        // is the security knob: a 9/16 majority tolerates closest-set
4690        // divergence between two nodes' views while still requiring most
4691        // candidates to be real peers the live DHT lists as closest.
4692        assert_eq!(
4693            PaymentVerifier::CANDIDATE_CLOSENESS_REQUIRED,
4694            9,
4695            "closeness threshold is a 9/16 majority"
4696        );
4697    }
4698
4699    #[test]
4700    fn closeness_lookup_count_uses_max_of_width_and_pool_len() {
4701        // The honest case: a 16-candidate pool must trigger a 32-peer
4702        // network lookup. This is the K=16-rejects-honest-pool fix from
4703        // the STG-01 investigation — without it, the storer never
4704        // observes the peers at network-true positions 17–32 that the
4705        // client legitimately picks from.
4706        let standard =
4707            PaymentVerifier::closeness_lookup_count(evmlib::merkle_payments::CANDIDATES_PER_POOL);
4708        assert_eq!(
4709            standard, 32,
4710            "honest 16-candidate pool must trigger a 32-peer DHT lookup"
4711        );
4712
4713        // Future-proof: if a protocol bump ever produces a pool larger
4714        // than CLOSENESS_LOOKUP_WIDTH, lookup_count must scale with the
4715        // pool — not truncate to WIDTH. Truncating would let an attacker
4716        // hide candidates by padding the pool past the storer's window.
4717        assert_eq!(
4718            PaymentVerifier::closeness_lookup_count(64),
4719            64,
4720            "lookup_count must scale up if pool exceeds CLOSENESS_LOOKUP_WIDTH"
4721        );
4722
4723        // Lower bound (also covered by the const-assert below; pin the
4724        // runtime path too in case the const-assert is ever removed).
4725        assert_eq!(
4726            PaymentVerifier::closeness_lookup_count(1),
4727            PaymentVerifier::CLOSENESS_LOOKUP_WIDTH,
4728            "lookup_count must never drop below CLOSENESS_LOOKUP_WIDTH"
4729        );
4730    }
4731
4732    // Compile-time invariant: the `closeness_lookup_count` formula relies
4733    // on WIDTH being ≥ CANDIDATES_PER_POOL so we never request fewer peers
4734    // than the pool itself contains.
4735    const _: () = assert!(
4736        PaymentVerifier::CLOSENESS_LOOKUP_WIDTH >= evmlib::merkle_payments::CANDIDATES_PER_POOL,
4737        "CLOSENESS_LOOKUP_WIDTH must be ≥ CANDIDATES_PER_POOL",
4738    );
4739
4740    // =========================================================================
4741    // Closeness-match logic tests
4742    //
4743    // These tests use the extracted `check_closeness_match` helper to
4744    // exercise the matching logic directly with synthetic peer-ID sets,
4745    // without standing up a real DHT. They cover:
4746    //
4747    //   - the 9/16 majority threshold (accept at exactly 9, reject below);
4748    //   - that a candidate counts only via exact membership in the storer's
4749    //     returned closest peers, so off-network fabrications are rejected;
4750    //   - the sparse-network short-circuit.
4751    //
4752    // Synthetic PeerIds put the tag in `bytes[0]`, so a candidate is in or
4753    // out of the network's returned set purely by tag value.
4754    // =========================================================================
4755
4756    /// Build a deterministic `PeerId` from a single byte tag.
4757    fn synthetic_peer_id(tag: u8) -> PeerId {
4758        let mut bytes = [0u8; 32];
4759        bytes[0] = tag;
4760        PeerId::from_bytes(bytes)
4761    }
4762
4763    /// Build a vector of synthetic `PeerId`s tagged with bytes 1..=n.
4764    fn synthetic_peer_ids(n: u8) -> Vec<PeerId> {
4765        (1..=n).map(synthetic_peer_id).collect()
4766    }
4767
4768    #[test]
4769    fn closeness_match_passes_when_all_16_candidates_in_top_16() {
4770        // Trivial case: every candidate is in the network's top-16.
4771        // Asserts the happy path still works after the refactor.
4772        let candidates = synthetic_peer_ids(16);
4773        let network = synthetic_peer_ids(16);
4774        let pool_address = [0u8; 32];
4775        let result = PaymentVerifier::check_closeness_match(&candidates, &network, &pool_address);
4776        assert!(result.is_ok(), "all-in-top-16 pool must pass: {result:?}");
4777    }
4778
4779    #[test]
4780    fn closeness_match_passes_when_candidates_span_positions_1_to_15_and_17() {
4781        // The client's pool contains 16 candidates, 15 at network-true
4782        // positions 1..=15 plus one at position 17 (the position-16 peer was
4783        // unresponsive when the client over-queried). Under K=32 all 16 are
4784        // exact matches, comfortably ≥ the 9/16 majority.
4785        let candidates = synthetic_peer_ids(15)
4786            .into_iter()
4787            .chain(std::iter::once(synthetic_peer_id(17)))
4788            .collect::<Vec<_>>();
4789        // Lookup window = 32, includes position 17.
4790        let network: Vec<PeerId> = (1..=32).map(synthetic_peer_id).collect();
4791        let pool_address = [0u8; 32];
4792        let result = PaymentVerifier::check_closeness_match(&candidates, &network, &pool_address);
4793        assert!(
4794            result.is_ok(),
4795            "pool with one candidate at position 17 must pass: {result:?}"
4796        );
4797    }
4798
4799    #[test]
4800    fn closeness_match_accepts_honest_skew_via_exact_matches() {
4801        // Honest skew: the client's 16 candidates span network-true positions
4802        // {1..=12, 17, 19, 21, 23}. The lookup window of 32 covers all of
4803        // them, so all 16 are exact matches — trivially ≥ the 9/16 majority.
4804        let candidates: Vec<PeerId> = (1..=12u8)
4805            .chain([17u8, 19, 21, 23])
4806            .map(synthetic_peer_id)
4807            .collect();
4808        let pool_address = [0u8; 32];
4809        let network: Vec<PeerId> = (1..=32).map(synthetic_peer_id).collect();
4810
4811        let result = PaymentVerifier::check_closeness_match(&candidates, &network, &pool_address);
4812        assert!(
4813            result.is_ok(),
4814            "honest pool fully inside the lookup window must pass: {result:?}"
4815        );
4816    }
4817
4818    #[test]
4819    fn closeness_match_rejects_forged_pool() {
4820        // Security floor: a fully-forged pool whose candidate PeerIds are
4821        // disjoint from the network's returned closest peers must be
4822        // rejected. The lowered majority threshold must NOT let off-network
4823        // fabrications pass — every counted candidate has to be a peer the
4824        // live DHT actually returned.
4825        let forged_candidates: Vec<PeerId> = (100..=115).map(synthetic_peer_id).collect();
4826        let network: Vec<PeerId> = (1..=32).map(synthetic_peer_id).collect();
4827        let pool_address = [0u8; 32];
4828
4829        let result =
4830            PaymentVerifier::check_closeness_match(&forged_candidates, &network, &pool_address);
4831        match result {
4832            Err(Error::Payment(msg)) => {
4833                assert!(
4834                    msg.contains("candidate pub_keys do not match"),
4835                    "expected forged-pool rejection message, got: {msg}"
4836                );
4837            }
4838            other => {
4839                panic!("forged pool disjoint from the network set must be rejected: {other:?}")
4840            }
4841        }
4842    }
4843
4844    #[test]
4845    fn closeness_match_rejects_pool_below_majority() {
4846        // Threshold sanity: 8 candidates are exact matches (tags 1..=8) and
4847        // the other 8 are off-network fabrications (tags 100..=107). 8 < 9
4848        // → reject.
4849        let mut candidates = synthetic_peer_ids(8);
4850        candidates.extend((100..=107).map(synthetic_peer_id)); // 8 fabrications
4851        let network: Vec<PeerId> = (1..=32).map(synthetic_peer_id).collect();
4852        let pool_address = [0u8; 32];
4853
4854        let result = PaymentVerifier::check_closeness_match(&candidates, &network, &pool_address);
4855        assert!(
4856            result.is_err(),
4857            "8 matches < majority of 9/16 must reject: {result:?}"
4858        );
4859    }
4860
4861    #[test]
4862    fn closeness_match_accepts_at_exactly_majority() {
4863        // Threshold sanity: exactly 9 candidates are exact matches (tags
4864        // 1..=9), the other 7 are off-network fabrications (tags 100..=106).
4865        // 9 ≥ 9 → accept.
4866        let mut candidates = synthetic_peer_ids(9);
4867        candidates.extend((100..=106).map(synthetic_peer_id)); // 7 fabrications
4868        let network: Vec<PeerId> = (1..=32).map(synthetic_peer_id).collect();
4869        let pool_address = [0u8; 32];
4870
4871        let result = PaymentVerifier::check_closeness_match(&candidates, &network, &pool_address);
4872        assert!(
4873            result.is_ok(),
4874            "9/16 ≥ majority threshold must accept: {result:?}"
4875        );
4876    }
4877
4878    #[test]
4879    fn closeness_match_returns_sparse_dht_error_when_lookup_too_small() {
4880        // The sparse-DHT short-circuit fires when the lookup returned
4881        // fewer peers than the threshold itself — even an all-matching
4882        // candidate set can't pass because the storer doesn't have an
4883        // authoritative view to compare against.
4884        let candidates = synthetic_peer_ids(16);
4885        let network = synthetic_peer_ids(8); // < CANDIDATE_CLOSENESS_REQUIRED (9)
4886        let pool_address = [0u8; 32];
4887
4888        let result = PaymentVerifier::check_closeness_match(&candidates, &network, &pool_address);
4889        match result {
4890            Err(Error::Payment(msg)) => {
4891                assert!(
4892                    msg.contains("authoritative DHT lookup returned only 8"),
4893                    "expected sparse-DHT error message, got: {msg}"
4894                );
4895            }
4896            other => panic!("expected sparse-DHT rejection, got: {other:?}"),
4897        }
4898    }
4899
4900    // ---------- ADR-0004: quote arithmetic re-check ----------
4901
4902    /// Curve canonicality: any price produced by `calculate_price(n)` is
4903    /// on-curve by construction. We exercise a spread of `n` covering the
4904    /// baseline floor (n=0), small counts, the pricing-curve knee
4905    /// (`n=PRICING_DIVISOR=6000`), and a saturating-arithmetic regime.
4906    #[test]
4907    fn adr0004_on_curve_prices_round_trip() {
4908        for &n in &[0usize, 1, 2, 100, 5999, 6000, 6001, 50_000, 1_000_000] {
4909            let price = crate::payment::pricing::calculate_price(n);
4910            assert!(
4911                PaymentVerifier::quote_price_is_on_curve(&price),
4912                "calculate_price({n}) = {price} must be on-curve"
4913            );
4914        }
4915    }
4916
4917    /// Off-curve canonicality: a price one wei above or below an on-curve
4918    /// point is between two adjacent curve values and must fail the
4919    /// canonicality predicate. The check IS exact equality, not a tolerance.
4920    #[test]
4921    fn adr0004_off_curve_prices_rejected_by_predicate() {
4922        // n=100 is well above baseline so price ± 1 is non-saturating.
4923        let on = crate::payment::pricing::calculate_price(100);
4924        let just_above = on + Amount::from(1u64);
4925        let just_below = on - Amount::from(1u64);
4926        assert!(
4927            !PaymentVerifier::quote_price_is_on_curve(&just_above),
4928            "price one wei above an on-curve point must be off-curve"
4929        );
4930        assert!(
4931            !PaymentVerifier::quote_price_is_on_curve(&just_below),
4932            "price one wei below an on-curve point must be off-curve"
4933        );
4934    }
4935
4936    /// A price strictly below the baseline floor is off-curve: the formula's
4937    /// minimum value is `calculate_price(0) = BASELINE`, so any smaller value
4938    /// has no corresponding `n`.
4939    #[test]
4940    fn adr0004_sub_baseline_price_is_off_curve() {
4941        let baseline = crate::payment::pricing::calculate_price(0);
4942        let sub_baseline = baseline - Amount::from(1u64);
4943        assert!(
4944            !PaymentVerifier::quote_price_is_on_curve(&sub_baseline),
4945            "price strictly below baseline must be off-curve"
4946        );
4947    }
4948
4949    /// ADR-0004 storer-side gate: a bundle in which every quote is on-curve
4950    /// passes the gate **and** the per-quote canonicality predicate. Runs in
4951    /// every context (no `ClientPut` split): the rule depends only on the
4952    /// bundle, not on per-peer state. The outer `validate_quote_arithmetic`
4953    /// short-circuits to `Ok` under the observe-only rollout const, so the
4954    /// per-quote diagnostics assertion is what proves the bundle is genuinely
4955    /// on-curve regardless of how the const ships.
4956    #[test]
4957    fn adr0004_validate_quote_arithmetic_passes_for_honest_bundle() {
4958        use evmlib::{EncodedPeerId, RewardsAddress};
4959
4960        let payment = ProofOfPayment {
4961            peer_quotes: (0..crate::ant_protocol::CLOSE_GROUP_SIZE)
4962                .map(|i| {
4963                    let id: [u8; 32] = rand::random();
4964                    let byte = u8::try_from(i & 0xFF).unwrap_or(0);
4965                    let quote = make_fake_quote_at_records(
4966                        [0xC0u8; 32],
4967                        SystemTime::now(),
4968                        RewardsAddress::new([byte; 20]),
4969                        100 * (i + 1),
4970                    );
4971                    (EncodedPeerId::new(id), quote)
4972                })
4973                .collect(),
4974        };
4975        PaymentVerifier::validate_quote_arithmetic(&payment)
4976            .expect("honest on-curve bundle must pass the gate (any const value)");
4977        for (_, quote) in &payment.peer_quotes {
4978            assert!(
4979                PaymentVerifier::price_off_curve_diagnostics(&quote.price).is_none(),
4980                "every quote in honest bundle must be canonically on-curve"
4981            );
4982        }
4983    }
4984
4985    /// Off-curve quote behaviour follows the rollout gate
4986    /// [`QUOTE_ARITHMETIC_RECHECK_ENABLED`]. We assert the gate's current
4987    /// observe-only stance: an off-curve quote is accepted with no error.
4988    /// The enforcement-branch behaviour is exercised separately by
4989    /// `adr0004_off_curve_diagnostics_yields_reject_payload` so both branches
4990    /// of the const-gated split are covered in CI.
4991    #[test]
4992    fn adr0004_observe_only_does_not_reject_off_curve_quote() {
4993        use evmlib::{EncodedPeerId, RewardsAddress};
4994
4995        let mut quote = make_fake_quote_at_records(
4996            [0xC1u8; 32],
4997            SystemTime::now(),
4998            RewardsAddress::new([1u8; 20]),
4999            100,
5000        );
5001        // Bump one wei off the curve.
5002        quote.price += Amount::from(1u64);
5003
5004        let id: [u8; 32] = rand::random();
5005        let payment = ProofOfPayment {
5006            peer_quotes: vec![(EncodedPeerId::new(id), quote)],
5007        };
5008
5009        // This test is only meaningful in the observe-only configuration
5010        // (which is the default at slice ship). If a future change flips the
5011        // const, the assertion documents the regression instead of silently
5012        // changing semantics.
5013        if !crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED {
5014            assert!(
5015                PaymentVerifier::validate_quote_arithmetic(&payment).is_ok(),
5016                "observe-only rollout must not reject off-curve quotes"
5017            );
5018        }
5019    }
5020
5021    /// Enforcement-branch coverage: the rejection payload (peer id, candidate
5022    /// `n`, recomputed price) is produced for off-curve prices independently
5023    /// of the rollout const, so CI exercises the rejection code path even
5024    /// while [`QUOTE_ARITHMETIC_RECHECK_ENABLED`] ships as `false`. Flipping
5025    /// the const to `true` then merely wires this diagnostic into the outer
5026    /// `Err` return, which is what `validate_quote_arithmetic` does.
5027    #[test]
5028    fn adr0004_off_curve_diagnostics_yields_reject_payload() {
5029        let on = crate::payment::pricing::calculate_price(100);
5030        let off = on + Amount::from(1u64);
5031
5032        let diag = PaymentVerifier::price_off_curve_diagnostics(&off)
5033            .expect("off-curve price must produce diagnostics");
5034        let (candidate_count, recomputed) = diag;
5035        assert_eq!(candidate_count, 100, "floor candidate must be n=100");
5036        assert_eq!(
5037            recomputed, on,
5038            "recomputed price must equal the floor curve point"
5039        );
5040        assert!(
5041            recomputed < off,
5042            "off-curve diagnostics' recomputed price must be strictly below the off-curve input"
5043        );
5044
5045        // And an on-curve price must produce no diagnostics.
5046        assert!(
5047            PaymentVerifier::price_off_curve_diagnostics(&on).is_none(),
5048            "on-curve price must yield no off-curve diagnostics"
5049        );
5050    }
5051
5052    /// Saturation regime: a price strictly above
5053    /// `calculate_price(u64::MAX-equivalent saturating ceiling)` is rejected.
5054    /// We do not have direct access to that ceiling, but `Amount::MAX` is
5055    /// guaranteed above it (since `calculate_price(usize::MAX)` saturates to
5056    /// some value strictly less than `Amount::MAX` due to the additive
5057    /// baseline). The gate must reject it.
5058    #[test]
5059    fn adr0004_amount_max_price_is_off_curve() {
5060        let price = Amount::MAX;
5061        assert!(
5062            !PaymentVerifier::quote_price_is_on_curve(&price),
5063            "Amount::MAX must not be a valid on-curve price"
5064        );
5065    }
5066
5067    /// Merkle gate, predicate-level: the same canonicality rule applies to
5068    /// `MerklePaymentCandidateNode.price`. We don't construct a full merkle
5069    /// proof here (the test fixtures for that live elsewhere); we prove the
5070    /// underlying decision matches the single-node side, so the Merkle gate
5071    /// inherits the same correctness as `validate_quote_arithmetic`.
5072    #[test]
5073    fn adr0004_merkle_candidate_canonicality_matches_single_node() {
5074        // Every on-curve `n` produces a price the predicate accepts; one wei
5075        // off produces a price the predicate rejects. This is the entire
5076        // contract; the Merkle gate's outer wrapper enforces the same const
5077        // as the single-node gate, so the wrappers are mechanically
5078        // equivalent.
5079        for &n in &[0usize, 1, 100, 6000, 1_000_000] {
5080            let on = crate::payment::pricing::calculate_price(n);
5081            assert!(
5082                PaymentVerifier::quote_price_is_on_curve(&on),
5083                "merkle candidate price for n={n} must be on-curve"
5084            );
5085            if n > 0 {
5086                let off = on + Amount::from(1u64);
5087                assert!(
5088                    !PaymentVerifier::quote_price_is_on_curve(&off),
5089                    "merkle candidate price one wei above n={n} must be off-curve"
5090                );
5091            }
5092        }
5093    }
5094
5095    /// Merkle gate, pool-level: build a real signed candidate pool, set every
5096    /// candidate's price to the same on-curve value, and assert the gate
5097    /// passes. Then bump one candidate's price one wei off-curve and assert
5098    /// the per-candidate diagnostics correctly identify it. We use the
5099    /// diagnostics predicate rather than the outer `validate_merkle_candidate_arithmetic`
5100    /// because the outer wrapper short-circuits to `Ok` under the observe-only
5101    /// rollout const; the diagnostics path is what carries the rejection
5102    /// information when enforcement flips on.
5103    #[test]
5104    fn adr0004_merkle_pool_off_curve_candidate_caught_by_diagnostics() {
5105        use evmlib::merkle_payments::MerklePaymentCandidatePool;
5106
5107        let timestamp = 1_700_000_000u64;
5108        let mut candidates = make_candidate_nodes(timestamp);
5109
5110        // Set every candidate price to calculate_price(500) so the pool is
5111        // honestly on-curve to start.
5112        let on_curve = crate::payment::pricing::calculate_price(500);
5113        for c in &mut candidates {
5114            c.price = on_curve;
5115        }
5116        let pool = MerklePaymentCandidatePool {
5117            midpoint_proof: fake_midpoint_proof(),
5118            candidate_nodes: candidates,
5119        };
5120        // The outer wrapper is rollout-gated, but a fully on-curve pool must
5121        // pass it under any const value because the loop finds no off-curve
5122        // candidate to reject.
5123        PaymentVerifier::validate_merkle_candidate_arithmetic(&pool)
5124            .expect("honest on-curve pool must pass merkle gate (any const value)");
5125        for c in &pool.candidate_nodes {
5126            assert!(
5127                PaymentVerifier::price_off_curve_diagnostics(&c.price).is_none(),
5128                "every honest candidate must be canonically on-curve"
5129            );
5130        }
5131
5132        // Now bump exactly one candidate off-curve and check that the
5133        // diagnostics path catches it. (The outer wrapper still short-circuits
5134        // under observe-only; this proves the underlying detection works
5135        // independently of the rollout const, exercising the rejection-payload
5136        // path in CI.)
5137        let mut tampered = pool;
5138        tampered.candidate_nodes[3].price += Amount::from(1u64);
5139        let mut off_curve_seen = 0;
5140        for c in &tampered.candidate_nodes {
5141            if PaymentVerifier::price_off_curve_diagnostics(&c.price).is_some() {
5142                off_curve_seen += 1;
5143            }
5144        }
5145        assert_eq!(
5146            off_curve_seen, 1,
5147            "exactly one tampered candidate must register as off-curve"
5148        );
5149    }
5150
5151    // === ADR-0004 binding-shape + cross-check unit tests ===
5152
5153    use crate::payment::pricing::calculate_price as cp;
5154
5155    /// Build a real signed commitment over `n` synthetic keys for tests.
5156    fn test_built_commitment(n: u32) -> crate::replication::commitment_state::BuiltCommitment {
5157        use saorsa_pqc::api::sig::ml_dsa_65;
5158        let (pk, sk) = ml_dsa_65().generate_keypair().expect("keypair");
5159        let pk_bytes = pk.to_bytes();
5160        let peer_id = blake3::hash(&pk_bytes);
5161        let entries: Vec<([u8; 32], [u8; 32])> = (0..n)
5162            .map(|i| {
5163                let mut k = [0u8; 32];
5164                k[..4].copy_from_slice(&i.to_le_bytes());
5165                let mut b = [1u8; 32];
5166                b[..4].copy_from_slice(&i.to_le_bytes());
5167                (k, b)
5168            })
5169            .collect();
5170        crate::replication::commitment_state::BuiltCommitment::build(
5171            entries,
5172            peer_id.as_bytes(),
5173            &sk,
5174            &pk_bytes,
5175        )
5176        .expect("build commitment")
5177    }
5178
5179    #[test]
5180    fn binding_baseline_ok_only_at_baseline_price() {
5181        // (0, None) with calculate_price(0) is the valid baseline.
5182        assert!(PaymentVerifier::binding_violation(0, None, &cp(0)).is_none());
5183        // (0, None) with a non-baseline price is REJECTED — this is the BLOCKER
5184        // bypass the round-1 review found (unpinned quote priced above baseline).
5185        assert!(PaymentVerifier::binding_violation(0, None, &cp(500)).is_some());
5186    }
5187
5188    #[test]
5189    fn binding_bound_ok_only_with_pin_and_exact_price() {
5190        let pin = [9u8; 32];
5191        // (n>0, Some(pin)) priced exactly is valid.
5192        assert!(PaymentVerifier::binding_violation(500, Some(pin), &cp(500)).is_none());
5193        // (n>0, Some(pin)) priced for a DIFFERENT count is rejected (on-curve
5194        // but wrong count — stronger than canonicality).
5195        assert!(PaymentVerifier::binding_violation(500, Some(pin), &cp(499)).is_some());
5196    }
5197
5198    #[test]
5199    fn binding_rejects_incoherent_shapes() {
5200        let pin = [9u8; 32];
5201        // count > 0 but no pin: unauditable.
5202        assert!(PaymentVerifier::binding_violation(500, None, &cp(500)).is_some());
5203        // count 0 but a pin: incoherent baseline.
5204        assert!(PaymentVerifier::binding_violation(0, Some(pin), &cp(0)).is_some());
5205    }
5206
5207    #[test]
5208    fn binding_rejects_count_above_cap() {
5209        let pin = [9u8; 32];
5210        let over = crate::replication::commitment::MAX_COMMITMENT_KEY_COUNT + 1;
5211        assert!(PaymentVerifier::binding_violation(over, Some(pin), &cp(over as usize)).is_some());
5212    }
5213
5214    #[test]
5215    fn cross_check_match_when_pin_and_count_agree() {
5216        let built = test_built_commitment(12);
5217        let outcome = PaymentVerifier::cross_check_binding(12, built.hash(), built.commitment());
5218        assert_eq!(outcome, CrossCheck::Match);
5219    }
5220
5221    #[test]
5222    fn cross_check_mismatch_when_count_inflated() {
5223        let built = test_built_commitment(12);
5224        // Quote claims 999 but the pinned commitment attests 12.
5225        let outcome = PaymentVerifier::cross_check_binding(999, built.hash(), built.commitment());
5226        assert_eq!(
5227            outcome,
5228            CrossCheck::Mismatch {
5229                quoted_key_count: 999,
5230                committed_key_count: 12,
5231            }
5232        );
5233    }
5234
5235    #[test]
5236    fn cross_check_unresolved_when_pin_wrong() {
5237        let built = test_built_commitment(12);
5238        // Pin does not match the supplied commitment's hash: not evidence.
5239        let outcome = PaymentVerifier::cross_check_binding(12, [0xFFu8; 32], built.commitment());
5240        assert_eq!(outcome, CrossCheck::PinDoesNotResolve);
5241    }
5242
5243    #[test]
5244    fn fresh_cached_commitment_honours_ttl_boundary() {
5245        use crate::replication::commitment_state::PeerCommitmentRecord;
5246        let built = test_built_commitment(5);
5247        let commitment = built.commitment().clone();
5248        let pin = built.hash();
5249        let ttl = std::time::Duration::from_secs(3 * 3600);
5250        let now = std::time::Instant::now();
5251
5252        // Fresh AND matching pin -> resolves to the commitment.
5253        let fresh = PeerCommitmentRecord::from_verified(commitment.clone(), now);
5254        assert!(
5255            PaymentVerifier::fresh_cached_commitment(&fresh, pin, now, ttl).is_some(),
5256            "a fresh cache entry whose hash matches the pin must resolve"
5257        );
5258
5259        // Fresh but a DIFFERENT pin -> treated as not-cached (None), so the
5260        // caller falls through to fetch the actually-quoted pin instead of
5261        // mis-resolving against the peer's latest (different) commitment.
5262        assert!(
5263            PaymentVerifier::fresh_cached_commitment(&fresh, [0xEEu8; 32], now, ttl).is_none(),
5264            "a fresh cache entry for a DIFFERENT pin must not resolve (fetch fallback runs)"
5265        );
5266
5267        // Stale: received older than the TTL -> treated as unknown (None), the
5268        // ADR-0004 false-positive guard against an aged cache entry.
5269        //
5270        // Advance the comparison clock PAST the TTL rather than subtracting the
5271        // TTL from `now`: on Windows the monotonic `Instant` epoch can be
5272        // younger than a multi-hour TTL, so `now.checked_sub(ttl + 1s)`
5273        // underflows to `None` and panics. `checked_add` from the receipt time
5274        // is always in range and is equivalent for the age comparison.
5275        let received_at = now;
5276        let now_after_ttl = received_at
5277            .checked_add(ttl + std::time::Duration::from_secs(1))
5278            .expect("instant in range");
5279        let stale = PeerCommitmentRecord::from_verified(commitment, received_at);
5280        assert!(
5281            PaymentVerifier::fresh_cached_commitment(&stale, pin, now_after_ttl, ttl).is_none(),
5282            "a cache entry older than the answerability TTL must be treated as unknown"
5283        );
5284    }
5285
5286    #[test]
5287    fn fetched_commitment_must_be_bound_to_the_queried_peer() {
5288        // A fetched commitment is accepted only when it is bound to the peer we
5289        // asked (sender_peer_id == peer_id) and hashes to the requested pin.
5290        let built = test_built_commitment(8);
5291        let commitment = built.commitment().clone();
5292        let pin = built.hash();
5293        let owner = PeerId::from_bytes(commitment.sender_peer_id);
5294
5295        // Correct owner + correct pin -> accepted.
5296        assert!(
5297            PaymentVerifier::fetched_commitment_is_valid(&commitment, &owner, pin),
5298            "a peer's own validly-signed commitment, hashing to the pin, must be accepted"
5299        );
5300
5301        // Same (validly signed) commitment but attributed to a DIFFERENT peer ->
5302        // rejected. This is the MAJOR fix: a peer must not be able to answer with
5303        // someone else's commitment and have it pass as its own.
5304        let other = PeerId::from_bytes([0xABu8; 32]);
5305        assert!(
5306            !PaymentVerifier::fetched_commitment_is_valid(&commitment, &other, pin),
5307            "another peer's commitment must be rejected for the queried peer"
5308        );
5309
5310        // Correct owner but wrong pin -> rejected.
5311        assert!(
5312            !PaymentVerifier::fetched_commitment_is_valid(&commitment, &owner, [0u8; 32]),
5313            "a commitment that does not hash to the requested pin must be rejected"
5314        );
5315    }
5316
5317    #[tokio::test]
5318    async fn emit_mismatch_evidence_without_p2p_does_not_panic() {
5319        // Guards the "always best-effort" degrade path: with no P2P handle there
5320        // is no trust engine to act on, so `emit_mismatch_evidence` must be a
5321        // no-op that never panics or errors on the payment path. This is a
5322        // no-panic guard on the degraded path — it does NOT exercise the
5323        // evidence->action mapping (that needs a live trust engine).
5324        let built = test_built_commitment(12);
5325        let evidence = crate::replication::types::FailureEvidence::QuoteCommitmentMismatch {
5326            peer: PeerId::from_bytes([1u8; 32]),
5327            pinned_commitment: [2u8; 32],
5328            quoted_key_count: 999,
5329            committed_key_count: 12,
5330            quote_artifact: vec![0xAA; 16],
5331            commitment: Box::new(built.commitment().clone()),
5332        };
5333        // No P2P -> no trust event even if enforce were on; must not panic.
5334        PaymentVerifier::emit_mismatch_evidence(&evidence, None).await;
5335    }
5336
5337    #[test]
5338    fn valid_sidecar_is_indexed_and_resolves_synchronously() {
5339        // A valid sidecar blob is indexed under its own (peer, pin) so the
5340        // cross-check resolves it synchronously — "the commitment arrived with
5341        // the quote", no gossip-cache hit or fetch needed.
5342        let built = test_built_commitment(9);
5343        let commitment = built.commitment().clone();
5344        let pin = built.hash();
5345        let owner = PeerId::from_bytes(commitment.sender_peer_id);
5346        let blob = rmp_serde::to_vec(&commitment).expect("serialize sidecar");
5347
5348        let map = PaymentVerifier::index_valid_sidecars(std::slice::from_ref(&blob));
5349        assert!(
5350            map.contains_key(&(owner, pin)),
5351            "a valid sidecar must be indexed under its own (peer, pin)"
5352        );
5353
5354        // A garbage blob is silently skipped (resolution falls back), never a
5355        // hard error.
5356        let map2 = PaymentVerifier::index_valid_sidecars(&[vec![0xFF; 8]]);
5357        assert!(map2.is_empty(), "an unparseable sidecar must be skipped");
5358    }
5359}