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