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::commitment::MAX_COMMITMENT_KEY_COUNT;
15use crate::replication::config::K_BUCKET_SIZE;
16use crate::storage::lmdb::LmdbStorage;
17use ant_protocol::payment::verify::{verify_quote_content, verify_quote_signature};
18use evmlib::common::{Amount, QuoteHash};
19use evmlib::contract::payment_vault;
20use evmlib::merkle_batch_payment::{OnChainPaymentInfo, PoolHash};
21use evmlib::Network as EvmNetwork;
22use evmlib::PaymentQuote;
23use evmlib::ProofOfPayment;
24use evmlib::RewardsAddress;
25use lru::LruCache;
26use parking_lot::{Mutex, RwLock};
27use saorsa_core::identity::node_identity::peer_id_from_public_key_bytes;
28use saorsa_core::identity::PeerId;
29use saorsa_core::P2PNode;
30use std::collections::HashMap;
31use std::num::NonZeroUsize;
32use std::sync::Arc;
33use std::time::Instant;
34
35/// Minimum allowed size for a payment proof in bytes.
36///
37/// This minimum ensures the proof contains at least a basic cryptographic hash or identifier.
38/// Proofs smaller than this are rejected as they cannot contain sufficient payment information.
39pub const MIN_PAYMENT_PROOF_SIZE_BYTES: usize = 32;
40
41/// Maximum allowed size for a payment proof in bytes (512 KB).
42///
43/// Single-node proofs with 7 ML-DSA-65 quotes reach ~40 KB; with ADR-0004
44/// commitment sidecars (one ~5.3 KB commitment per bound quote, ~13 KB each
45/// after rmp encoding) they reach ~150 KB.
46/// Merkle proofs include 16 candidate nodes (each with ~1,952-byte ML-DSA pub
47/// key and ~3,309-byte signature) plus merkle branch hashes, totaling ~130 KB.
48/// A merkle proof that ALSO ships all 16 commitment sidecars (clients built
49/// before the sidecars were dropped from the per-chunk bundle) reaches
50/// ~342 KB — the previous 256 KB cap rejected every such PUT the moment nodes
51/// carried live commitments, which is exactly how it was discovered.
52/// 512 KB accepts every shape above with headroom while still capping memory
53/// during verification.
54pub const MAX_PAYMENT_PROOF_SIZE_BYTES: usize = 524_288;
55
56const PAID_QUOTE_PAYMENT_MULTIPLIER: u64 = 3;
57const PAYMENT_VERIFY_SLOW_LOG_MS: u128 = 500;
58
59/// Number of nearest DHT peers accepted for paid-quote issuer locality.
60///
61/// This is the Kademlia K width, intentionally wider than `CLOSE_GROUP_SIZE`.
62const PAID_QUOTE_ISSUER_CLOSENESS_WIDTH: usize = K_BUCKET_SIZE;
63
64/// Default tolerance for the receiver-side price floor, as a percentage of the
65/// close group's MEDIAN commitment-bound price (see
66/// [`PaymentVerifier::group_reference_price`]).
67///
68/// Derived from production, not chosen: on ant-prod-01 over 2026-07-29..08-04,
69/// pricing each receiver against its OWN price rejected 0.377% of honest stores
70/// while still admitting the cheapest-of-K underpayment at 62.9% of receivers,
71/// because node prices span ~4x across the fleet and an honest client pays the
72/// group median. Against the group median instead, honest payments land near the
73/// reference and the underpayment lands well below it, so a tolerance separates
74/// them.
75///
76/// At the minimum permitted view, 65% rejects 0.140% of honest payments while
77/// catching ~90% of underpayment, against the own-price floor's measured 0.377%
78/// and 37.1%. Both axes improve, by roughly 2.7x on rejections rather than the
79/// order of magnitude an earlier revision claimed. 60% is the conservative
80/// alternative: 5x safer on honest traffic, at 66% detection.
81///
82/// The full sweep, the sample-size table and the simulation's assumptions live
83/// in ADR-0006 — deliberately in one place, because the same tables
84/// duplicated here and in the ADR had already drifted apart once. Tighten or
85/// loosen only from observed shadow telemetry, never speculatively.
86const PRICE_FLOOR_DEFAULT_TOLERANCE_PERCENT: u64 = 65;
87
88/// Minimum number of fresh NEIGHBOUR commitments (this node's own is counted
89/// separately) required before the price floor will evaluate at all.
90///
91/// Below this the local view is too thin for a median to mean anything (fresh
92/// start, post-churn, a gossip cache that has not filled), so the floor SKIPS
93/// rather than guessing. Skipping is the safe direction: the cost is a missed
94/// underpayment, whereas guessing from a handful of peers rejects honest stores
95/// whose payment already settled on-chain and cannot be refunded.
96///
97/// The value is not a round number chosen by feel. A median over a small sample
98/// of a distribution this wide is unstable, and the floor is *more* dangerous
99/// than the own-price reference it replaces until the sample is large: at 3
100/// neighbours it rejects 2.0% of honest stores, at 7 it rejects 0.6%, and only
101/// past about 11 does it beat the 0.377% the own-price floor measured in
102/// production. The gate therefore sits at 15 of the
103/// [`PAID_QUOTE_ISSUER_CLOSENESS_WIDTH`] closest, with the full table in
104/// ADR-0006.
105///
106/// Availability cost is expected to be small — the gossip TTL is hours against a
107/// much shorter sweep, so a settled node should normally know most of its
108/// neighbours — but that is an assumption, not a measurement, and the sample is
109/// drawn from peers close to the CHUNK while the cache is filled from peers
110/// close to THIS NODE, so edge-of-range chunks will skip more often. The
111/// `skipped=true` / `skip_reason` telemetry exists to measure that in shadow
112/// mode before anyone enforces.
113///
114/// A node that could suppress its neighbours' gossip can therefore disable this
115/// receiver's floor, but cannot make it reject honest traffic. That asymmetry is
116/// deliberate.
117const PRICE_FLOOR_MIN_NEIGHBOUR_COMMITMENTS: usize = 15;
118
119/// Why a price-floor evaluation did not produce a reference price.
120///
121/// Shadow mode exists to calibrate
122/// [`PRICE_FLOOR_MIN_NEIGHBOUR_COMMITMENTS`] from real deployments, and these
123/// three causes call for completely different responses: a mid-rotation node is
124/// expected and self-correcting, an unwired cache is a startup-order bug, and a
125/// persistently thin sample means the gate is set above what the network can
126/// supply. Collapsing them into one counter would make the telemetry unable to
127/// answer the only question it is there to answer.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129enum SkipReason {
130    /// The gossip commitment cache is not attached.
131    NoCommitmentCache,
132    /// No local routing view of the close group (no P2P handle attached).
133    NoRoutingView,
134    /// This node has no live commitment of its own.
135    NoOwnCommitment,
136    /// Fewer fresh neighbour commitments than the gate requires.
137    ThinSample,
138}
139
140impl SkipReason {
141    /// Only ever called from the price-floor telemetry, which compiles to
142    /// nothing without the `logging` feature.
143    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
144    const fn as_str(self) -> &'static str {
145        match self {
146            Self::NoCommitmentCache => "no_commitment_cache",
147            Self::NoRoutingView => "no_routing_view",
148            Self::NoOwnCommitment => "no_own_commitment",
149            Self::ThinSample => "thin_sample",
150        }
151    }
152}
153
154/// What the price floor could see of the close group on one admission.
155///
156/// `neighbours` is the quantity the gate actually tests; `total` includes this
157/// node's own commitment and is what the median is taken over. Both are logged
158/// because reporting only the total makes `group_sample=15, skipped=true` look
159/// like a contradiction when it is simply 14 neighbours plus self.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161struct GroupSample {
162    neighbours: usize,
163    total: usize,
164    skip_reason: Option<SkipReason>,
165}
166
167impl GroupSample {
168    const fn none(reason: SkipReason) -> Self {
169        Self {
170            neighbours: 0,
171            total: 0,
172            skip_reason: Some(reason),
173        }
174    }
175
176    const fn skipped(self, reason: SkipReason) -> Self {
177        Self {
178            skip_reason: Some(reason),
179            ..self
180        }
181    }
182
183    /// Only ever called from the price-floor telemetry, which compiles to
184    /// nothing without the `logging` feature.
185    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
186    fn skip_reason_str(self) -> &'static str {
187        self.skip_reason.map_or("none", SkipReason::as_str)
188    }
189}
190
191/// Environment variable enabling price-floor ENFORCEMENT (`1`/`true`).
192///
193/// Absent or any other value means shadow mode: the floor is computed and
194/// logged, never enforced. Per-node so enforcement can roll out canary-first;
195/// unsetting it (and restarting) is the kill switch.
196pub const PRICE_FLOOR_ENFORCE_ENV: &str = "ANT_PRICE_FLOOR_ENFORCE";
197
198/// Environment variable overriding the price-floor tolerance percentage
199/// (`0..=100`). Invalid or absent values use the default.
200pub const PRICE_FLOOR_TOLERANCE_ENV: &str = "ANT_PRICE_FLOOR_TOLERANCE_PERCENT";
201
202/// Receiver-side price floor for single-node store admissions.
203///
204/// ADR-0004 gives every quote a price CEILING (`price ==
205/// calculate_price(committed_key_count)`), but a ceiling is not a revenue
206/// floor: a modified client can fetch quotes from the whole neighbourhood and
207/// settle only the cheapest valid one in a 1-quote proof. This policy is the
208/// floor half: the settled amount must also clear the close group's MEDIAN
209/// commitment-bound price, scaled by a tolerance.
210///
211/// The reference is the group's median rather than this receiver's own price.
212/// A client pays `3x` the median of the quotes it collected, so comparing that
213/// to a single node's price compares a median to one draw from a distribution
214/// spanning ~4x — which in production rejected honest stores on the fullest
215/// nodes while admitting underpayment at the emptiest. The reference is built
216/// only from this node's own commitment and its neighbours' TTL-fresh gossiped
217/// ones, never from the payment bundle.
218///
219/// Rollout is shadow-first: with `enforce == false` (the default) the floor
220/// is evaluated and logged on every single-node store admission but never
221/// rejects. Enforcement is enabled per node via [`PRICE_FLOOR_ENFORCE_ENV`]
222/// for canary rollout. A floor rejection is an economic admission decision
223/// only — it must never feed trust/misbehaviour scoring.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub struct PriceFloorConfig {
226    /// When true, a below-floor settled payment is rejected. When false
227    /// (default), the verifier only logs would-reject telemetry.
228    pub enforce: bool,
229    /// Floor as a percentage of the close group's median commitment-bound
230    /// price (`0..=100`).
231    pub tolerance_percent: u64,
232}
233
234impl Default for PriceFloorConfig {
235    fn default() -> Self {
236        Self {
237            enforce: false,
238            tolerance_percent: PRICE_FLOOR_DEFAULT_TOLERANCE_PERCENT,
239        }
240    }
241}
242
243impl PriceFloorConfig {
244    /// Build from the environment (see [`PRICE_FLOOR_ENFORCE_ENV`] and
245    /// [`PRICE_FLOOR_TOLERANCE_ENV`]). Never panics.
246    ///
247    /// An unset tolerance uses the default. A tolerance that is *present but
248    /// invalid* (unparseable or `> 100`) is an operator error: rather than
249    /// silently enforce at the default, this **fails closed to shadow mode**
250    /// (`enforce = false`) and logs a prominent error, so a fat-fingered
251    /// tolerance can never enforce an unintended floor against real payments.
252    #[must_use]
253    pub fn from_env() -> Self {
254        let enforce_requested = std::env::var(PRICE_FLOOR_ENFORCE_ENV)
255            .is_ok_and(|v| matches!(v.trim(), "1" | "true" | "TRUE" | "True"));
256
257        let tolerance_raw = std::env::var(PRICE_FLOOR_TOLERANCE_ENV).ok();
258        let valid_tolerance = tolerance_raw
259            .as_deref()
260            .map(str::trim)
261            .and_then(|s| s.parse::<u64>().ok())
262            .filter(|percent| *percent <= 100);
263        // A tolerance that is set but does not parse to `0..=100` is an operator
264        // error. Fail CLOSED: never enforce a tolerance the operator did not
265        // actually specify.
266        let tolerance_present_but_invalid = tolerance_raw.is_some() && valid_tolerance.is_none();
267
268        if tolerance_present_but_invalid {
269            if enforce_requested {
270                crate::logging::error!(
271                    "{PRICE_FLOOR_TOLERANCE_ENV}={tolerance_raw:?} is not an integer in 0..=100; \
272                     refusing to enforce the price floor with an unspecified tolerance. \
273                     Price-floor enforcement DISABLED (shadow mode). Fix the value and restart \
274                     to enable enforcement."
275                );
276            } else {
277                crate::logging::warn!(
278                    "{PRICE_FLOOR_TOLERANCE_ENV}={tolerance_raw:?} is not an integer in 0..=100; \
279                     using the default {PRICE_FLOOR_DEFAULT_TOLERANCE_PERCENT}% for shadow-mode \
280                     telemetry."
281                );
282            }
283        }
284
285        Self {
286            enforce: enforce_requested && !tolerance_present_but_invalid,
287            tolerance_percent: valid_tolerance.unwrap_or(PRICE_FLOOR_DEFAULT_TOLERANCE_PERCENT),
288        }
289    }
290}
291
292#[derive(Clone, Copy)]
293struct LegacyMedianCandidate<'a> {
294    encoded_peer_id: &'a evmlib::EncodedPeerId,
295    quote: &'a PaymentQuote,
296    expected_amount: Amount,
297}
298
299fn median_quote_index(quote_count: usize) -> usize {
300    quote_count / 2
301}
302
303/// The settlement multiplier a merkle receipt must satisfy, from the instant it
304/// was stamped (ADR-0008).
305///
306/// `PAID_QUOTE_PAYMENT_MULTIPLIER` (3x, matching the single-node path) for a
307/// receipt stamped at or after `enforced_from`; the historic `1` for one
308/// stamped before it, which was bought under the previous rule and cannot be
309/// refunded.
310///
311/// The boundary needs no sunset logic because receipt expiry supplies it: a
312/// receipt older than one week is refused regardless, so once
313/// `enforced_from + one week` has passed no valid receipt can still reach the
314/// `1` branch.
315///
316/// Expiry bounds backdating rather than preventing it. The stamp is
317/// client-chosen and quoting nodes sign what they are asked for, so during the
318/// week after `enforced_from` a modified client can stamp just before the
319/// boundary and still settle at 1x — the same route honest in-flight receipts
320/// take. It closes when such stamps expire, at `enforced_from + one week`, and
321/// it cannot be narrowed without also refusing receipts bought in good faith
322/// under the previous rule.
323fn merkle_required_multiplier(receipt_timestamp: u64, enforced_from: u64) -> u64 {
324    if receipt_timestamp >= enforced_from {
325        PAID_QUOTE_PAYMENT_MULTIPLIER
326    } else {
327        1
328    }
329}
330
331/// Per-node payment implied by the merkle contract formula, for a given
332/// payment multiplier.
333///
334/// The contract settles `total = median16(amount) x 2^depth` and splits it
335/// evenly across the `depth` nodes it paid, so
336/// `per_node = multiplier x median16(price) x 2^depth / depth`.
337///
338/// `candidate_prices` are the candidates' **signed quoted** prices as they
339/// appear in the proof — always 1x, because the multiplier is applied by the
340/// client to the on-chain payable `amount` and never to the signed quote
341/// (ADR-0008). Passing `multiplier = 1` therefore reproduces the historic
342/// merkle expectation, and `PAID_QUOTE_PAYMENT_MULTIPLIER` the single-node
343/// parity expectation.
344///
345/// `median16` is the upper median (index `len / 2`), matching Solidity's
346/// `median16` with `k = 8`. Depth `0` yields zero: there is nothing to pay.
347///
348/// **Not linear in `multiplier`.** The trailing `/ depth` is integer division,
349/// so `expected(m)` is `floor(m x median x 2^depth / depth)`, which is NOT
350/// generally `m x expected(1)` — the two differ by up to `m - 1` wei whenever
351/// `depth` does not divide `median x 2^depth`. For example median 901 at depth
352/// 7 gives `expected(3) = 49426` but `3 x expected(1) = 49425`. Callers must
353/// therefore ask for the multiplier they mean and compare against that value;
354/// scaling a 1x result is wrong. The order here — multiply the total, then
355/// divide once — is deliberate, and matches the contract, which computes
356/// `totalAmount` before splitting it.
357fn merkle_expected_per_node(
358    candidate_prices: &[Amount],
359    depth: u8,
360    multiplier: u64,
361) -> Result<Amount> {
362    if depth == 0 {
363        return Ok(Amount::ZERO);
364    }
365
366    let mut sorted = candidate_prices.to_vec();
367    sorted.sort_unstable(); // ascending
368    let median_price = *sorted
369        .get(sorted.len() / 2)
370        .ok_or_else(|| Error::Payment("empty candidate pool in merkle proof".into()))?;
371
372    let leaves = 1u64
373        .checked_shl(u32::from(depth))
374        .ok_or_else(|| Error::Payment("merkle proof depth too large".into()))?;
375
376    let total_amount = median_price
377        .checked_mul(Amount::from(leaves))
378        .and_then(|total| total.checked_mul(Amount::from(multiplier)))
379        .ok_or_else(|| Error::Payment("merkle total payment overflow".into()))?;
380
381    Ok(total_amount / Amount::from(u64::from(depth)))
382}
383
384fn payment_proof_type_label(payment_proof: Option<&[u8]>) -> &'static str {
385    match payment_proof.and_then(detect_proof_type) {
386        Some(ProofType::Merkle) => "merkle",
387        Some(ProofType::SingleNode) => "single_node",
388        Some(_) => "unsupported",
389        None if payment_proof.is_some() => "unknown",
390        None => "none",
391    }
392}
393
394/// Configuration for EVM payment verification.
395///
396/// EVM verification is always on. All new data requires on-chain
397/// payment verification. The network field selects which EVM chain to use.
398#[derive(Debug, Clone)]
399pub struct EvmVerifierConfig {
400    /// EVM network to use (Arbitrum One, Arbitrum Sepolia, etc.)
401    pub network: EvmNetwork,
402}
403
404impl Default for EvmVerifierConfig {
405    fn default() -> Self {
406        Self {
407            network: EvmNetwork::ArbitrumOne,
408        }
409    }
410}
411
412/// Configuration for the payment verifier.
413///
414/// All new data requires EVM payment on Arbitrum. The cache stores
415/// previously verified payments to avoid redundant on-chain lookups.
416#[derive(Debug, Clone)]
417pub struct PaymentVerifierConfig {
418    /// EVM verifier configuration.
419    pub evm: EvmVerifierConfig,
420    /// Cache capacity (number of `XorName` values to cache).
421    pub cache_capacity: usize,
422    /// Close-group width exposed to storage and replication admission callers.
423    pub close_group_size: usize,
424    /// Local node's rewards address.
425    ///
426    /// Kept in the verifier config for payment policies that bind receipts to
427    /// this node's payout address.
428    pub local_rewards_address: RewardsAddress,
429    /// Receiver-side price floor policy (shadow mode by default).
430    pub price_floor: PriceFloorConfig,
431}
432
433/// The fresh admission path a payment proof is being verified for.
434///
435/// - **`ClientPut`** — the node is admitting a chunk store from a direct
436///   client PUT. The verifier applies store-strength cache semantics and live
437///   payment checks.
438/// - **`FreshReplication`** — the node is admitting a chunk store via the
439///   immediate fresh-write fan-out. The receiver is about to store the newly
440///   written chunk as if the client PUT it there directly, so this context is
441///   verified EXACTLY like `ClientPut` (store-strength cache semantics, same
442///   live checks, same price-floor policy). It exists as a separate variant so
443///   price-floor telemetry can distinguish direct ingress from fan-out — the
444///   two paths can legitimately diverge during commitment rotation, and the
445///   floor policy for fan-out must be tunable from observed data without
446///   touching direct-PUT behaviour.
447/// - **`PaidListAdmission`** — the node is admitting fresh paid-list metadata.
448///   It runs the same live payment checks, but writes a weaker cache entry
449///   that does not authorize future chunk stores. The price floor never
450///   applies here: paid-list records reprice no fresh economic decision.
451///
452/// The caller must check local receiver/admission membership before invoking
453/// the verifier for replication admission: fresh chunk replication requires
454/// local close-group responsibility, and fresh paid-list replication requires
455/// local paid-list close-group membership. Direct client PUT deliberately does
456/// not perform a receiver-responsibility gate. The verifier itself only checks
457/// payment proof validity and that the paid quote's issuer is in the K closest
458/// peers for the quoted chunk address.
459///
460/// Later neighbour-sync repair does not include proof-of-payment bytes and
461/// does not call this verifier. It authorizes repair from network evidence:
462/// majority storage among the configured close group, or majority paid-list
463/// membership among the closest K.
464#[derive(Debug, Clone, Copy, PartialEq, Eq)]
465pub enum VerificationContext {
466    /// The node is admitting a chunk store from a direct client PUT, with
467    /// store-strength cache semantics.
468    ClientPut,
469    /// The node is admitting a chunk store via immediate fresh replication —
470    /// verified identically to `ClientPut`, split out for price-floor
471    /// telemetry and policy.
472    FreshReplication,
473    /// The node is admitting fresh paid-list metadata with paid-list-strength
474    /// cache semantics.
475    PaidListAdmission,
476}
477
478impl VerificationContext {
479    /// True for contexts that admit chunk BYTES with store-strength cache
480    /// semantics: direct client PUT and immediate fresh replication. These two
481    /// are verified identically everywhere — the only policy that reads the
482    /// variant itself (rather than this predicate) is price-floor telemetry.
483    #[must_use]
484    pub fn is_store_admission(self) -> bool {
485        matches!(self, Self::ClientPut | Self::FreshReplication)
486    }
487}
488
489/// Status returned by payment verification.
490#[derive(Debug, Clone, Copy, PartialEq, Eq)]
491pub enum PaymentStatus {
492    /// Data was found in local cache - previously paid.
493    CachedAsVerified,
494    /// New data - payment required.
495    PaymentRequired,
496    /// Payment was provided and verified.
497    PaymentVerified,
498}
499
500/// Outcome of the ADR-0004 quote-vs-commitment cross-check (see
501/// [`PaymentVerifier::cross_check_binding`]).
502#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503pub enum CrossCheck {
504    /// Pin resolves to the commitment and the counts agree: nothing to report.
505    Match,
506    /// Pin resolves to the commitment but the claimed and committed counts
507    /// disagree: deterministic, first-occurrence contradiction (evidence).
508    Mismatch {
509        /// The key count the quote claimed.
510        quoted_key_count: u32,
511        /// The key count the pinned commitment actually attests.
512        committed_key_count: u32,
513    },
514    /// The supplied commitment does not hash to the quote's pin: the pin is
515    /// unresolved (treat as fetch/skip), never evidence.
516    PinDoesNotResolve,
517}
518
519impl PaymentStatus {
520    /// Returns true if the data can be stored (cached or payment verified).
521    #[must_use]
522    pub fn can_store(&self) -> bool {
523        matches!(self, Self::CachedAsVerified | Self::PaymentVerified)
524    }
525
526    /// Returns true if this status indicates the data was already paid for.
527    #[must_use]
528    pub fn is_cached(&self) -> bool {
529        matches!(self, Self::CachedAsVerified)
530    }
531}
532
533/// Default capacity for the merkle pool cache (number of pool hashes to cache).
534const DEFAULT_POOL_CACHE_CAPACITY: usize = 1_000;
535
536/// Capacity of the ADR-0008 parity-telemetry first-emission cache: how many
537/// recently measured pool hashes this node remembers in order to emit one
538/// sample per settlement instead of one per admitted chunk.
539///
540/// Bounded, and deliberately its own cache rather than a flag on the pool
541/// cache: the pool cache is populated as soon as the on-chain record is read,
542/// which happens *before* the paid indices, addresses and amounts are checked,
543/// so keying first-emission off it would let a proof that is rejected moments
544/// later suppress (or produce) a sample. This one is written only after full
545/// admission validation.
546///
547/// LRU eviction means a pool that goes quiet for more than
548/// `MERKLE_PARITY_TELEMETRY_CACHE_CAPACITY` distinct pools can be sampled a
549/// second time. That is the intended trade: the cache bounds memory, and the
550/// stream stays deduplicable by `pool` downstream.
551const MERKLE_PARITY_TELEMETRY_CACHE_CAPACITY: usize = 1_000;
552
553/// ADR-0004: max commitment sidecars processed per bundle. A legitimate bundle
554/// carries at most one commitment per quote/candidate — `CANDIDATES_PER_POOL`
555/// (16) is the larger of the single-node (`CLOSE_GROUP_SIZE` = 7) and merkle
556/// cases, so it covers both. Excess sidecars from a malicious client are
557/// ignored before any deserialize/verify work (bounds the hot-path cost).
558const MAX_SIDECARS_PER_BUNDLE: usize = evmlib::merkle_batch_payment::CANDIDATES_PER_POOL;
559
560/// Shared handle to the replication engine's gossip commitment cache
561/// (`last_commitment_by_peer`), used by the ADR-0004 cross-check to resolve a
562/// quote's pin against a neighbour's recently gossiped commitment. A `tokio`
563/// `RwLock` to match the engine's; read with `.await` on the async path.
564type CommitmentCache = Arc<
565    tokio::sync::RwLock<
566        HashMap<PeerId, crate::replication::commitment_state::PeerCommitmentRecord>,
567    >,
568>;
569
570/// Per-`(peer, pin)` negative cache for unresolved ADR-0004 pin fetches: a pin a
571/// peer answered `NotRetained` (or that timed out) is remembered so repeated
572/// bundles don't re-fetch it. Behind an `Arc` so the detached fetch task owns a
573/// handle without borrowing the verifier.
574type PinFetchNegativeCache = Arc<Mutex<LruCache<(PeerId, [u8; 32]), ()>>>;
575
576/// Test-override shape for one on-chain settlement: the settled amount and
577/// the recorded `bytes16` rewards-address prefix (`None` = matches the quote).
578#[cfg(any(test, feature = "test-utils"))]
579type TestSettlementOverride = (Amount, Option<[u8; 16]>);
580
581/// Main payment verifier for ant-node.
582///
583/// Uses:
584/// 1. LRU cache for fast lookups of previously verified `XorName` values
585/// 2. EVM payment verification for new data (always required)
586/// 3. Pool-level cache for merkle batch payments (avoids repeated on-chain queries)
587pub struct PaymentVerifier {
588    /// LRU cache of verified `XorName` values.
589    cache: VerifiedCache,
590    /// LRU cache of verified merkle pool hashes → on-chain payment info.
591    pool_cache: Mutex<LruCache<PoolHash, OnChainPaymentInfo>>,
592    /// LRU cache of pool hashes whose candidate closeness has already been
593    /// verified by this node. Collapses the per-chunk Kademlia lookup cost
594    /// within a batch (256 chunks × 1 pool = 1 lookup instead of 256).
595    closeness_pass_cache: Mutex<LruCache<PoolHash, ()>>,
596    /// In-flight closeness lookups, keyed by pool hash. Lets concurrent PUTs
597    /// for the same pool coalesce onto a single Kademlia lookup AND share
598    /// its result — on both success and failure — which bounds `DoS`
599    /// amplification to one lookup per unique `pool_hash` regardless of
600    /// concurrency.
601    inflight_closeness: Mutex<LruCache<PoolHash, Arc<ClosenessSlot>>>,
602    /// P2P node handle, attached post-construction so paid-quote verification
603    /// can check paid-quote issuer K-closeness, and merkle verification can
604    /// check that candidate `pub_keys` map to peers actually close to the pool
605    /// midpoint in the live DHT. `None` in unit tests that don't exercise
606    /// live-DHT checks; production startup MUST call [`attach_p2p_node`].
607    p2p_node: RwLock<Option<Arc<P2PNode>>>,
608    /// LMDB storage handle, attached post-construction. Retained for
609    /// store-backed verifier checks that need the authoritative on-disk record
610    /// count without depending on a side counter that may drift from
611    /// replication/repair/prune paths. NOTE: the ADR-0006 price floor does NOT
612    /// read this — it is bound to the live storage commitment via
613    /// [`Self::local_commitment_source`], not the on-disk count (the old floor
614    /// compared unlike counts and false-rejected honest quotes). `None` in unit
615    /// tests that don't exercise store-backed checks; production wires it via
616    /// [`Self::attach_storage`].
617    storage: RwLock<Option<Arc<LmdbStorage>>>,
618    /// Test-only override for the paid-quote issuer K-closest check.
619    ///
620    /// Production code derives closest peers from the attached [`P2PNode`].
621    #[cfg(any(test, feature = "test-utils"))]
622    test_paid_quote_k_closest_override: RwLock<Option<Vec<[u8; 32]>>>,
623    /// Test-only override for `completedPayments(quote_hash)`.
624    ///
625    /// Production always queries the payment vault; unit tests use this to
626    /// exercise the full verifier path without starting an EVM chain. Maps a
627    /// quote hash to the settled amount plus the recorded rewards-address
628    /// prefix (`None` means "matches the quote", the honest-settlement
629    /// default). The prefix is 16 bytes because the vault packs the address
630    /// as `bytes16` in the `completedPayments` slot.
631    #[cfg(any(test, feature = "test-utils"))]
632    test_completed_payments_override: RwLock<HashMap<QuoteHash, TestSettlementOverride>>,
633    // NOTE: the test-only own-peer-id override was removed with the ADR-retired
634    // quote-freshness/staleness gate (ADR-0004 binds price to the committed
635    // count instead), so it no longer has any reader.
636    /// ADR-0004 gossip commitment cache, shared with the replication engine
637    /// (`last_commitment_by_peer`). The cross-check resolves a quote's
638    /// `commitment_pin` against the neighbour's most recently gossiped
639    /// commitment held here, *only if seen within the answerability TTL*;
640    /// otherwise the pin is treated as unknown (fetch/skip), never a penalty.
641    /// A `tokio` `RwLock` to match the engine's; read with `.await` on the
642    /// async verification path. `None` until [`Self::attach_commitment_cache`]
643    /// (unit tests, or pre-replication startup).
644    commitment_cache: RwLock<Option<CommitmentCache>>,
645    /// ADR-0004 negative cache for unresolved pin fetches: a `(peer, pin)` that
646    /// resolved to `NotRetained` or timed out is remembered here so repeated
647    /// bundles citing the same unknown pin don't re-fetch (bounding the
648    /// amplification an attacker can drive). Keyed by `(PeerId, pin)`. Behind an
649    /// `Arc` so the detached background fetch task (which runs off the payment
650    /// hot path) can read and update it without borrowing the verifier.
651    pin_fetch_negative_cache: PinFetchNegativeCache,
652    /// ADR-0004: sender to surface monetized pins (commitments that backed a
653    /// payment) to the replication engine's deterministic first-audit drainer.
654    /// `None` until [`Self::attach_monetized_pin_sender`] (unit tests, or
655    /// pre-replication startup), in which case no first audit is scheduled.
656    monetized_pin_tx:
657        RwLock<Option<tokio::sync::mpsc::Sender<crate::replication::MonetizedPinEvent>>>,
658    /// Price-floor input: the SAME live commitment source the local
659    /// `QuoteGenerator` prices from, read via the non-mutating snapshot so the
660    /// floor never extends commitment answerability. `None` until
661    /// [`Self::attach_local_commitment_source`] (unit tests, or storage
662    /// disabled / pre-replication startup) — the floor then SKIPS the admission
663    /// entirely rather than pricing against anything, so a node in that state
664    /// never rejects.
665    local_commitment_source: RwLock<Option<Arc<dyn crate::payment::quote::CommitmentSource>>>,
666    /// Live price-floor policy, initialized from
667    /// [`PaymentVerifierConfig::price_floor`]. Behind a lock so tests (and any
668    /// future ops surface) can flip enforcement without rebuilding the
669    /// verifier.
670    price_floor: RwLock<PriceFloorConfig>,
671    /// ADR-0008: the instant from which a merkle receipt must settle at the
672    /// single-node 3x multiplier, defaulting to
673    /// [`crate::replication::config::MERKLE_PARITY_ENFORCED_FROM_UNIX`].
674    ///
675    /// Behind a lock purely so tests can pin it. Every merkle receipt is
676    /// necessarily stamped within one week of now (older ones are expired,
677    /// future ones refused), so a test that used the production boundary would
678    /// silently change which side of it the test data fell on as the wall clock
679    /// crossed that date. Pinning the boundary keeps those tests deterministic
680    /// forever.
681    merkle_parity_from: RwLock<u64>,
682    /// ADR-0008: pool hashes this node has already emitted a parity telemetry
683    /// line for. Bounded by
684    /// [`MERKLE_PARITY_TELEMETRY_CACHE_CAPACITY`]; see that constant for why
685    /// this is separate from [`Self::pool_cache`].
686    ///
687    /// Check-and-insert happens under this one lock, so concurrent admissions
688    /// of different chunks from the same batch emit exactly one line between
689    /// them rather than one each.
690    merkle_parity_logged: Mutex<LruCache<PoolHash, ()>>,
691    /// Count of ADR-0008 parity lines this verifier has actually emitted.
692    /// Incremented only on first emission for a pool, so it measures
693    /// settlements sampled rather than chunks admitted.
694    merkle_parity_emissions: std::sync::atomic::AtomicUsize,
695    /// Configuration.
696    config: PaymentVerifierConfig,
697}
698
699/// Shared state for an inflight closeness verification. The leader publishes
700/// its result via the `OnceLock`; waiters read that result directly instead
701/// of racing on a cache re-check. Wrapped in an `Arc` and held both by the
702/// leader's drop guard and by each waiting task.
703struct ClosenessSlot {
704    notify: Arc<tokio::sync::Notify>,
705    /// `Some(Ok(()))` on success, `Some(Err(msg))` on failure, `None` if the
706    /// leader disappeared without publishing (panic, cancellation).
707    result: std::sync::OnceLock<std::result::Result<(), String>>,
708}
709
710impl ClosenessSlot {
711    fn new() -> Self {
712        Self {
713            notify: Arc::new(tokio::sync::Notify::new()),
714            result: std::sync::OnceLock::new(),
715        }
716    }
717
718    /// Build an owned `Notified` future that snapshots the `notify_waiters`
719    /// counter at call time. Awaiting this future after dropping external
720    /// locks is race-free: if `notify_waiters` fires between construction
721    /// and the first poll, the snapshot mismatch resolves the future
722    /// immediately.
723    fn notified_owned(&self) -> tokio::sync::futures::OwnedNotified {
724        Arc::clone(&self.notify).notified_owned()
725    }
726}
727
728/// Drop guard that publishes the leader's result, clears the inflight slot,
729/// and wakes all waiters. Fires on every exit path: success, failure, panic,
730/// future-cancellation.
731///
732/// The guard owns its own `Arc<ClosenessSlot>` so `notify_waiters` still
733/// fires even if LRU pressure evicted the slot before the leader finished.
734/// Waiters see the published result via `result.get()`; the `Notify` is only
735/// the wake-up signal.
736struct InflightGuard<'a> {
737    slot_cache: &'a Mutex<LruCache<PoolHash, Arc<ClosenessSlot>>>,
738    pool_hash: PoolHash,
739    slot: Arc<ClosenessSlot>,
740}
741
742impl InflightGuard<'_> {
743    /// Publish the leader's result. Called exactly once by the leader on
744    /// every successful or explicit-error exit. If dropped without calling
745    /// (panic, cancellation) the guard still wakes waiters but leaves
746    /// `result` empty, which waiters treat as a transient failure and retry.
747    fn publish(&self, result: &Result<()>) {
748        let stored: std::result::Result<(), String> = match result {
749            Ok(()) => Ok(()),
750            Err(e) => Err(e.to_string()),
751        };
752        let _ = self.slot.result.set(stored);
753    }
754}
755
756impl Drop for InflightGuard<'_> {
757    fn drop(&mut self) {
758        // Remove the slot entry if it's still ours. A separate leader may
759        // have inserted a new slot for the same pool_hash after LRU
760        // eviction — don't pop someone else's entry.
761        {
762            let mut cache = self.slot_cache.lock();
763            if let Some(existing) = cache.peek(&self.pool_hash) {
764                if Arc::ptr_eq(existing, &self.slot) {
765                    cache.pop(&self.pool_hash);
766                }
767            }
768        }
769        // Wake every waiter registered against OUR slot, regardless of
770        // whether the cache entry is still ours.
771        self.slot.notify.notify_waiters();
772    }
773}
774
775impl PaymentVerifier {
776    /// Create a new payment verifier.
777    #[must_use]
778    pub fn new(config: PaymentVerifierConfig) -> Self {
779        const _: () = assert!(
780            DEFAULT_POOL_CACHE_CAPACITY > 0,
781            "pool cache capacity must be > 0"
782        );
783        let cache = VerifiedCache::with_capacity(config.cache_capacity);
784        let pool_cache_size =
785            NonZeroUsize::new(DEFAULT_POOL_CACHE_CAPACITY).unwrap_or(NonZeroUsize::MIN);
786        let pool_cache = Mutex::new(LruCache::new(pool_cache_size));
787        let closeness_pass_cache = Mutex::new(LruCache::new(pool_cache_size));
788        let inflight_closeness = Mutex::new(LruCache::new(pool_cache_size));
789
790        let cache_capacity = config.cache_capacity;
791        info!("Payment verifier initialized (cache_capacity={cache_capacity}, evm=always-on, pool_cache={DEFAULT_POOL_CACHE_CAPACITY})");
792
793        // Loud warning if a production binary was accidentally built with
794        // `test-utils`: that feature flips the live-DHT payment-check
795        // fail-open switches when P2PNode isn't attached. Safe in tests, never
796        // intended for prod.
797        #[cfg(feature = "test-utils")]
798        crate::logging::error!(
799            "PaymentVerifier: built with `test-utils` feature — payment live-DHT \
800             checks fall back to fail-open when no P2PNode is attached. This \
801             feature is for test binaries only; production nodes must be built \
802             without it."
803        );
804
805        Self {
806            cache,
807            pool_cache,
808            closeness_pass_cache,
809            inflight_closeness,
810            p2p_node: RwLock::new(None),
811            storage: RwLock::new(None),
812            #[cfg(any(test, feature = "test-utils"))]
813            test_paid_quote_k_closest_override: RwLock::new(None),
814            #[cfg(any(test, feature = "test-utils"))]
815            test_completed_payments_override: RwLock::new(HashMap::new()),
816            commitment_cache: RwLock::new(None),
817            pin_fetch_negative_cache: Arc::new(Mutex::new(LruCache::new(
818                NonZeroUsize::new(crate::replication::config::PIN_FETCH_NEGATIVE_CACHE_CAPACITY)
819                    .unwrap_or(NonZeroUsize::MIN),
820            ))),
821            monetized_pin_tx: RwLock::new(None),
822            local_commitment_source: RwLock::new(None),
823            price_floor: RwLock::new(config.price_floor),
824            merkle_parity_from: RwLock::new(
825                crate::replication::config::MERKLE_PARITY_ENFORCED_FROM_UNIX,
826            ),
827            merkle_parity_logged: Mutex::new(LruCache::new(
828                NonZeroUsize::new(MERKLE_PARITY_TELEMETRY_CACHE_CAPACITY)
829                    .unwrap_or(NonZeroUsize::MIN),
830            )),
831            merkle_parity_emissions: std::sync::atomic::AtomicUsize::new(0),
832            config,
833        }
834    }
835
836    /// Attach the ADR-0004 monetized-pin sender (the replication engine's
837    /// first-audit drainer channel) so the cross-check can route commitments
838    /// that backed a payment into a deterministic first audit. Idempotent;
839    /// absent (unit tests / pre-replication) no first audit is scheduled.
840    pub fn attach_monetized_pin_sender(
841        &self,
842        tx: tokio::sync::mpsc::Sender<crate::replication::MonetizedPinEvent>,
843    ) {
844        *self.monetized_pin_tx.write() = Some(tx);
845        debug!("PaymentVerifier: ADR-0004 monetized-pin sender attached");
846    }
847
848    /// Attach the ADR-0004 gossip commitment cache (the replication engine's
849    /// `last_commitment_by_peer`) so the cross-check can resolve a quote's
850    /// `commitment_pin` against the neighbour's recently gossiped commitment.
851    ///
852    /// Wired by the node once the replication engine exists, alongside the
853    /// quote generator's commitment source. Idempotent. Absent (unit tests,
854    /// pre-replication startup), the cross-check resolves no pins from gossip
855    /// and falls back to fetch/skip — never a penalty.
856    pub fn attach_commitment_cache(&self, cache: CommitmentCache) {
857        *self.commitment_cache.write() = Some(cache);
858        debug!("PaymentVerifier: ADR-0004 commitment cache attached");
859    }
860
861    /// Attach the node's [`P2PNode`] handle so paid-quote verification can
862    /// check issuer closeness, and merkle-payment verification can check
863    /// candidate `pub_keys` against the DHT's actual closest peers to the pool
864    /// midpoint.
865    ///
866    /// Production startup MUST call this once the `P2PNode` exists. Without
867    /// it, live-DHT payment checks fail CLOSED in release builds with a visible
868    /// error and fail open in test builds. Idempotent: calling twice replaces
869    /// the handle.
870    pub fn attach_p2p_node(&self, node: Arc<P2PNode>) {
871        *self.p2p_node.write() = Some(node);
872        debug!("PaymentVerifier: P2PNode attached for payment live-DHT checks");
873    }
874
875    /// Configured close-group width used by storage admission callers.
876    #[must_use]
877    pub fn close_group_size(&self) -> usize {
878        self.config.close_group_size
879    }
880
881    /// Attach the node's [`LmdbStorage`] handle for store-backed verifier
882    /// checks that read the authoritative on-disk record count.
883    ///
884    /// NOTE: the ADR-0006 price floor does NOT depend on this handle — it is
885    /// priced from the close group's gossiped commitments plus this node's own
886    /// ([`Self::attach_local_commitment_source`]), and a missing commitment
887    /// makes the floor skip rather than reject. So a node without storage
888    /// attached still admits PUTs; this
889    /// attachment only feeds any current/future store-count-backed checks.
890    /// Idempotent: calling twice replaces the handle.
891    pub fn attach_storage(&self, storage: Arc<LmdbStorage>) {
892        *self.storage.write() = Some(storage);
893        debug!("PaymentVerifier: LmdbStorage attached for paid-quote price-floor checks");
894    }
895
896    /// Attach the live commitment source for the price floor: the SAME
897    /// `ResponderCommitmentState` the local `QuoteGenerator` prices from, so
898    /// the floor and this node's own quotes read one pricing basis by
899    /// construction. Read via the non-mutating snapshot only. Idempotent.
900    /// Absent (unit tests, storage disabled, pre-replication startup), the
901    /// floor SKIPS the admission entirely with `skip_reason=no_own_commitment`
902    /// rather than pricing against anything, so a node in that state never
903    /// rejects.
904    pub fn attach_local_commitment_source(
905        &self,
906        source: Arc<dyn crate::payment::quote::CommitmentSource>,
907    ) {
908        *self.local_commitment_source.write() = Some(source);
909        debug!("PaymentVerifier: local commitment source attached for price-floor checks");
910    }
911
912    /// The live price-floor policy this verifier applies.
913    #[must_use]
914    pub fn price_floor_config(&self) -> PriceFloorConfig {
915        *self.price_floor.read()
916    }
917
918    /// Test-only setter for the price-floor policy, so enforcement and
919    /// tolerance can be exercised without environment variables.
920    #[cfg(any(test, feature = "test-utils"))]
921    pub fn set_price_floor_for_tests(&self, config: PriceFloorConfig) {
922        *self.price_floor.write() = config;
923    }
924
925    /// Test-only setter for the ADR-0008 merkle parity boundary, so both the
926    /// pre-boundary (historic 1x) and enforcing (3x) regimes can be exercised
927    /// against fixed receipt timestamps instead of the wall clock. `0` enforces
928    /// on every receipt; `u64::MAX` puts every receipt in the legacy window.
929    #[cfg(any(test, feature = "test-utils"))]
930    pub fn set_merkle_parity_from_for_tests(&self, enforced_from: u64) {
931        *self.merkle_parity_from.write() = enforced_from;
932    }
933
934    /// Number of ADR-0008 parity telemetry lines this verifier has emitted.
935    ///
936    /// One per settlement pool this node admitted a store for — not one per
937    /// chunk, and none at all for proofs that failed validation or for
938    /// non-store contexts. Test-only surface for the cardinality regression
939    /// tests; the production signal is the log line itself.
940    #[cfg(any(test, feature = "test-utils"))]
941    #[must_use]
942    pub fn merkle_parity_emission_count(&self) -> usize {
943        self.merkle_parity_emissions
944            .load(std::sync::atomic::Ordering::Relaxed)
945    }
946
947    /// Test-only setter for local closest peers used by the paid-quote
948    /// issuer K-closest check.
949    #[cfg(any(test, feature = "test-utils"))]
950    pub fn set_paid_quote_k_closest_for_tests(&self, peer_ids: Vec<[u8; 32]>) {
951        *self.test_paid_quote_k_closest_override.write() = Some(peer_ids);
952    }
953
954    /// Compatibility alias for older tests that called this the close group.
955    /// The check now accepts the K closest peers for the quoted chunk address.
956    #[cfg(any(test, feature = "test-utils"))]
957    pub fn set_paid_quote_close_group_for_tests(&self, peer_ids: Vec<[u8; 32]>) {
958        self.set_paid_quote_k_closest_for_tests(peer_ids);
959    }
960
961    /// Compatibility alias for older tests that called this the known-peer
962    /// set. The check now accepts the K closest peers for the quoted chunk
963    /// address.
964    #[cfg(any(test, feature = "test-utils"))]
965    pub fn set_paid_quote_known_peers_for_tests(&self, peer_ids: Vec<[u8; 32]>) {
966        self.set_paid_quote_k_closest_for_tests(peer_ids);
967    }
968
969    /// Test-only setter for an on-chain completed payment amount. The recorded
970    /// rewards address is treated as matching the quote (honest settlement).
971    #[cfg(any(test, feature = "test-utils"))]
972    pub fn set_completed_payment_for_tests(&self, quote_hash: QuoteHash, amount: Amount) {
973        self.test_completed_payments_override
974            .write()
975            .insert(quote_hash, (amount, None));
976    }
977
978    /// Test-only setter for an on-chain completed payment with an explicit
979    /// recorded rewards address, to exercise the settlement-redirect rejection.
980    #[cfg(any(test, feature = "test-utils"))]
981    pub fn set_completed_payment_with_address_for_tests(
982        &self,
983        quote_hash: QuoteHash,
984        amount: Amount,
985        rewards_address: evmlib::RewardsAddress,
986    ) {
987        self.test_completed_payments_override.write().insert(
988            quote_hash,
989            (amount, Some(Self::rewards_address_prefix(&rewards_address))),
990        );
991    }
992
993    /// The vault's `completedPayments` slot packs the payee as
994    /// `bytes16(bytes20(rewardsAddress))` — the leading 16 bytes of the
995    /// address (Solidity `bytesN` conversions truncate on the right). This is
996    /// the form the on-chain record is compared in.
997    fn rewards_address_prefix(rewards_address: &evmlib::RewardsAddress) -> [u8; 16] {
998        let mut prefix = [0u8; 16];
999        if let Some(head) = rewards_address.as_slice().get(..16) {
1000            prefix.copy_from_slice(head);
1001        }
1002        prefix
1003    }
1004
1005    /// Check if payment is required for the given `XorName`.
1006    ///
1007    /// This is the main entry point for payment verification:
1008    /// 1. Check LRU cache (fast path)
1009    /// 2. If not cached, payment is required
1010    ///
1011    /// The fast path is context-aware. A store-admission lookup (`ClientPut` /
1012    /// `FreshReplication`) is satisfied only by a close-group store
1013    /// verification. A `PaidListAdmission` lookup is satisfied by either a
1014    /// paid-list or client-PUT verification.
1015    ///
1016    /// # Arguments
1017    ///
1018    /// * `xorname` - The content-addressed name of the data
1019    /// * `context` - The verification context of the caller
1020    ///
1021    /// # Returns
1022    ///
1023    /// * `PaymentStatus::CachedAsVerified` - Found in local cache (previously paid)
1024    /// * `PaymentStatus::PaymentRequired` - Not cached (payment required)
1025    pub fn check_payment_required(
1026        &self,
1027        xorname: &XorName,
1028        context: VerificationContext,
1029    ) -> PaymentStatus {
1030        // Check LRU cache (fast path)
1031        let cached = if context.is_store_admission() {
1032            self.cache.contains_client_put_verified(xorname)
1033        } else {
1034            self.cache.contains_paid_list_verified(xorname)
1035        };
1036        if cached {
1037            if crate::logging::enabled!(crate::logging::Level::DEBUG) {
1038                debug!("Data {} found in verified cache", hex::encode(xorname));
1039            }
1040            return PaymentStatus::CachedAsVerified;
1041        }
1042
1043        // Not in cache - payment required
1044        if crate::logging::enabled!(crate::logging::Level::DEBUG) {
1045            debug!(
1046                "Data {} not in cache - payment required",
1047                hex::encode(xorname)
1048            );
1049        }
1050        PaymentStatus::PaymentRequired
1051    }
1052
1053    /// Verify that a PUT request has valid payment.
1054    ///
1055    /// This is the complete payment verification flow:
1056    /// 1. Check if data is in cache (previously paid)
1057    /// 2. If not, verify the provided payment proof
1058    ///
1059    /// # Arguments
1060    ///
1061    /// * `xorname` - The content-addressed name of the data
1062    /// * `payment_proof` - Optional payment proof (required if not in cache)
1063    /// * `context` - Which fresh admission path is verifying the proof — see
1064    ///   [`VerificationContext`] for cache-strength semantics
1065    ///
1066    /// # Returns
1067    ///
1068    /// * `Ok(PaymentStatus)` - Verification succeeded
1069    /// * `Err(Error::Payment)` - No payment and not cached, or payment invalid
1070    ///
1071    /// # Errors
1072    ///
1073    /// Returns an error if payment is required but not provided, or if payment is invalid.
1074    pub async fn verify_payment(
1075        &self,
1076        xorname: &XorName,
1077        payment_proof: Option<&[u8]>,
1078        context: VerificationContext,
1079    ) -> Result<PaymentStatus> {
1080        let started = Instant::now();
1081        let proof_type = payment_proof_type_label(payment_proof);
1082        let proof_bytes = payment_proof.map_or(0, <[u8]>::len);
1083        let result = self
1084            .verify_payment_inner(xorname, payment_proof, context)
1085            .await;
1086        let elapsed_ms = started.elapsed().as_millis();
1087
1088        match &result {
1089            Ok(status) if elapsed_ms >= PAYMENT_VERIFY_SLOW_LOG_MS => {
1090                info!(
1091                    target: "ant_node::payment::verify",
1092                    "Slow payment verification: context={context:?}, proof_type={proof_type}, proof_bytes={proof_bytes}, status={status:?}, elapsed_ms={elapsed_ms}",
1093                );
1094            }
1095            Ok(status) => {
1096                debug!(
1097                    target: "ant_node::payment::verify",
1098                    "Payment verification: context={context:?}, proof_type={proof_type}, proof_bytes={proof_bytes}, status={status:?}, elapsed_ms={elapsed_ms}",
1099                );
1100            }
1101            Err(e) if elapsed_ms >= PAYMENT_VERIFY_SLOW_LOG_MS => {
1102                warn!(
1103                    target: "ant_node::payment::verify",
1104                    "Slow payment verification failed: context={context:?}, proof_type={proof_type}, proof_bytes={proof_bytes}, elapsed_ms={elapsed_ms}: {e}",
1105                );
1106            }
1107            Err(e) => {
1108                debug!(
1109                    target: "ant_node::payment::verify",
1110                    "Payment verification failed: context={context:?}, proof_type={proof_type}, proof_bytes={proof_bytes}, elapsed_ms={elapsed_ms}: {e}",
1111                );
1112            }
1113        }
1114
1115        result
1116    }
1117
1118    async fn verify_payment_inner(
1119        &self,
1120        xorname: &XorName,
1121        payment_proof: Option<&[u8]>,
1122        context: VerificationContext,
1123    ) -> Result<PaymentStatus> {
1124        // First check if payment is required
1125        let status = self.check_payment_required(xorname, context);
1126
1127        match status {
1128            PaymentStatus::CachedAsVerified => {
1129                // No payment needed - already in cache
1130                Ok(status)
1131            }
1132            PaymentStatus::PaymentRequired => {
1133                // EVM verification is always on — verify the proof
1134                if let Some(proof) = payment_proof {
1135                    let proof_len = proof.len();
1136                    if proof_len < MIN_PAYMENT_PROOF_SIZE_BYTES {
1137                        return Err(Error::Payment(format!(
1138                            "Payment proof too small: {proof_len} bytes (min {MIN_PAYMENT_PROOF_SIZE_BYTES})"
1139                        )));
1140                    }
1141                    if proof_len > MAX_PAYMENT_PROOF_SIZE_BYTES {
1142                        return Err(Error::Payment(format!(
1143                            "Payment proof too large: {proof_len} bytes (max {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes)"
1144                        )));
1145                    }
1146
1147                    // Detect proof type from version tag byte
1148                    match detect_proof_type(proof) {
1149                        Some(ProofType::Merkle) => {
1150                            self.verify_merkle_payment(xorname, proof, context).await?;
1151                        }
1152                        Some(ProofType::SingleNode) => {
1153                            let parsed = deserialize_single_node_proof(proof).map_err(|e| {
1154                                Error::Payment(format!("Failed to deserialize payment proof: {e}"))
1155                            })?;
1156
1157                            if !parsed.tx_hashes.is_empty() {
1158                                debug!(
1159                                    "Proof includes {} transaction hash(es)",
1160                                    parsed.tx_hashes.len()
1161                                );
1162                            }
1163
1164                            self.verify_evm_payment(
1165                                xorname,
1166                                &parsed.proof_of_payment,
1167                                &parsed.commitment_sidecars,
1168                                context,
1169                            )
1170                            .await?;
1171                        }
1172                        None => {
1173                            let tag = proof.first().copied().unwrap_or(0);
1174                            return Err(Error::Payment(format!(
1175                                "Unknown payment proof type tag: 0x{tag:02x}"
1176                            )));
1177                        }
1178                        // ant-protocol marks `ProofType` as `#[non_exhaustive]`.
1179                        // A future proof variant that this node does not yet
1180                        // understand must be rejected, not silently accepted.
1181                        Some(_) => {
1182                            let tag = proof.first().copied().unwrap_or(0);
1183                            return Err(Error::Payment(format!(
1184                                "Unsupported payment proof type tag: 0x{tag:02x} (this node's protocol version does not handle it — upgrade ant-node)"
1185                            )));
1186                        }
1187                    }
1188
1189                    // Cache the verified xorname at the context's verification
1190                    // strength. Stronger entries satisfy weaker future lookups,
1191                    // but not the reverse.
1192                    if context.is_store_admission() {
1193                        self.cache.insert(*xorname);
1194                    } else {
1195                        self.cache.insert_paid_list_verified(*xorname);
1196                    }
1197
1198                    Ok(PaymentStatus::PaymentVerified)
1199                } else {
1200                    // No payment provided in production mode
1201                    let xorname_hex = hex::encode(xorname);
1202                    Err(Error::Payment(format!(
1203                        "Payment required for new data {xorname_hex}"
1204                    )))
1205                }
1206            }
1207            PaymentStatus::PaymentVerified => Err(Error::Payment(
1208                "Unexpected PaymentVerified status from check_payment_required".to_string(),
1209            )),
1210        }
1211    }
1212
1213    /// Get cache statistics.
1214    #[must_use]
1215    pub fn cache_stats(&self) -> CacheStats {
1216        self.cache.stats()
1217    }
1218
1219    /// Get the number of cached entries.
1220    #[must_use]
1221    pub fn cache_len(&self) -> usize {
1222        self.cache.len()
1223    }
1224
1225    /// Pre-populate the payment cache for a given address.
1226    ///
1227    /// This marks the address as already paid, so subsequent `verify_payment`
1228    /// calls will return `CachedAsVerified` without on-chain verification.
1229    /// Useful for test setups where real EVM payment is not needed.
1230    #[cfg(any(test, feature = "test-utils"))]
1231    pub fn cache_insert(&self, xorname: XorName) {
1232        self.cache.insert(xorname);
1233    }
1234
1235    /// Pre-populate the merkle pool cache. Testing helper that lets e2e tests
1236    /// bypass the on-chain `completedMerklePayments` lookup when the point of
1237    /// the test is to exercise merkle-verification logic BEFORE the on-chain
1238    /// call (e.g. the pay-yourself closeness check).
1239    #[cfg(any(test, feature = "test-utils"))]
1240    pub fn pool_cache_insert(&self, pool_hash: PoolHash, info: OnChainPaymentInfo) {
1241        let mut cache = self.pool_cache.lock();
1242        cache.put(pool_hash, info);
1243    }
1244
1245    /// Verify a single-node EVM payment proof.
1246    ///
1247    /// Verification steps:
1248    /// 1. Between 1 and `CLOSE_GROUP_SIZE` quotes are present
1249    /// 2. Median-priced candidate quotes are derived from the supplied bundle
1250    /// 3. Each candidate is checked for content binding, peer binding, and a
1251    ///    valid ML-DSA-65 signature
1252    /// 4. Each candidate must also come from a local K-close peer
1253    /// 5. A candidate is accepted only if `completedPayments(quoteHash)` is at
1254    ///    least 3x the median price
1255    ///
1256    /// Non-median quotes are parsed only to locate the median. Their content,
1257    /// peer bindings, and signatures are deliberately ignored: the paid
1258    /// quote's content hash, quote hash, signature, issuer
1259    /// K-closeness check, and on-chain settlement are the authority. A
1260    /// one-quote proof is valid when that single quote passes these checks and
1261    /// was paid 3x.
1262    async fn verify_evm_payment(
1263        &self,
1264        xorname: &XorName,
1265        payment: &ProofOfPayment,
1266        commitment_sidecars: &[Vec<u8>],
1267        context: VerificationContext,
1268    ) -> Result<()> {
1269        if crate::logging::enabled!(crate::logging::Level::DEBUG) {
1270            let xorname_hex = hex::encode(xorname);
1271            let quote_count = payment.peer_quotes.len();
1272            debug!(
1273                "Verifying EVM payment for {xorname_hex} with {quote_count} quotes ({context:?})"
1274            );
1275        }
1276
1277        Self::validate_quote_structure(payment)?;
1278        // ADR-0004: re-run the `price == calculate_price(committed_key_count)`
1279        // arithmetic/binding check on EVERY quote in the bundle (all single-node
1280        // quotes), per the ADR's "every storer re-runs the
1281        // price-equals-formula-of-count check on every quote in the bundle"
1282        // rule — bundle-level, before median selection (the candidate loop below
1283        // only sees median-priced quotes). This hard cutover also RETIRES the
1284        // percentage-based own-quote price-staleness gate: a quote's price is
1285        // now exactly bound to its committed count here (both the `(n>0, Some)`
1286        // and baseline `(0, None)` shapes), and the committed responsible count
1287        // legitimately differs from the on-disk count, so the old gate would
1288        // FALSE-REJECT healthy ADR quotes. The binding gate supersedes it.
1289        Self::validate_quote_arithmetic(payment)?;
1290        let candidates = Self::legacy_median_candidates(payment)?;
1291        let mut failures = Vec::with_capacity(candidates.len());
1292        // The paid (median) price and settled on-chain amount of the winning
1293        // candidate, kept for the receiver-side price-floor policy below.
1294        let mut verified_paid_quote: Option<(Amount, Amount)> = None;
1295        // ADR-0004 Amendment 2: remember WHICH candidate's on-chain settlement
1296        // verified — only that peer's commitment actually earned money, so only
1297        // its pin is nominated for a deterministic first audit below. The
1298        // non-median quotes merely locate the median and stay covered by the
1299        // gossip-lottery audit path.
1300        let mut paid_peer: Option<[u8; 32]> = None;
1301
1302        for candidate in candidates {
1303            let paid_price = candidate.quote.price;
1304            let candidate_peer = *candidate.encoded_peer_id.as_bytes();
1305            match self
1306                .verify_legacy_median_candidate(xorname, candidate)
1307                .await
1308            {
1309                Ok(settled_amount) => {
1310                    verified_paid_quote = Some((paid_price, settled_amount));
1311                    // First settlement-verified median candidate wins the paid
1312                    // slot and the sole first-audit nomination. If a client
1313                    // settled several TIED-median candidates, only this one is
1314                    // first-audited; gossiped extras keep the ADR-0002 lottery,
1315                    // sidecar-only extras are an accepted best-effort residual
1316                    // (ADR-0004 Amendment 2). The honest client pays one.
1317                    paid_peer = Some(candidate_peer);
1318                    break;
1319                }
1320                Err(err) => failures.push(err.to_string()),
1321            }
1322        }
1323
1324        let Some((paid_price, settled_amount)) = verified_paid_quote else {
1325            let xorname_hex = hex::encode(xorname);
1326            let details = if failures.is_empty() {
1327                "no median-priced candidates were available".to_string()
1328            } else {
1329                failures.join("; ")
1330            };
1331            return Err(Error::Payment(format!(
1332                "Median quote payment verification failed for {xorname_hex}: {details}"
1333            )));
1334        };
1335
1336        // Receiver-side price floor (single-node store admissions only). Runs
1337        // AFTER the paid quote's signature and settlement verified above, so
1338        // unauthenticated bundles can never poison floor telemetry. Shadow
1339        // mode logs; enforcement rejects — an economic admission decision
1340        // only, never trust/misbehaviour evidence.
1341        self.enforce_price_floor(xorname, paid_price, settled_amount, context)
1342            .await?;
1343
1344        // ADR-0004 observe-only telemetry: log off-curve quotes only AFTER the
1345        // paid (median) quote's ML-DSA-65 signature has verified above, so
1346        // unauthenticated senders cannot poison rollout logs. In enforce mode
1347        // `validate_quote_arithmetic` already rejected; this is a no-op there.
1348        Self::log_off_curve_single_node(payment);
1349
1350        // ADR-0004 cross-check + first-audit enqueue (store admissions only —
1351        // direct client PUT and immediate fresh replication, exactly the paths
1352        // that previously verified under `ClientPut`) runs ONLY after on-chain
1353        // payment verification has SUCCEEDED above, so an unpaid (but signed)
1354        // bundle can never enqueue audits or drive pin fetches — closing the
1355        // free-amplification path.
1356        if context.is_store_admission() {
1357            self.cross_check_quotes(payment, commitment_sidecars, paid_peer)
1358                .await;
1359        }
1360
1361        if crate::logging::enabled!(crate::logging::Level::INFO) {
1362            let xorname_hex = hex::encode(xorname);
1363            info!("EVM payment verified for {xorname_hex}");
1364        }
1365        Ok(())
1366    }
1367
1368    fn legacy_median_candidates(
1369        payment: &ProofOfPayment,
1370    ) -> Result<Vec<LegacyMedianCandidate<'_>>> {
1371        let mut sorted_quotes: Vec<(&evmlib::EncodedPeerId, &PaymentQuote)> = payment
1372            .peer_quotes
1373            .iter()
1374            .map(|(encoded_peer_id, quote)| (encoded_peer_id, quote))
1375            .collect();
1376        sorted_quotes.sort_by_key(|(_, quote)| quote.price);
1377        let quote_count = sorted_quotes.len();
1378        let median_index = median_quote_index(quote_count);
1379        let median_price = sorted_quotes
1380            .get(median_index)
1381            .ok_or_else(|| {
1382                Error::Payment(format!("Missing paid quote at median index {median_index}"))
1383            })?
1384            .1
1385            .price;
1386        let expected_amount = median_price
1387            .checked_mul(Amount::from(PAID_QUOTE_PAYMENT_MULTIPLIER))
1388            .ok_or_else(|| {
1389                Error::Payment(format!(
1390                    "Median quote payment amount overflow for price {median_price}"
1391                ))
1392            })?;
1393
1394        if expected_amount == Amount::ZERO || median_price == Amount::ZERO {
1395            return Err(Error::Payment(format!(
1396                "Median quote has zero price/amount (price={median_price}, amount={expected_amount}); refusing to verify as paid"
1397            )));
1398        }
1399
1400        Ok(sorted_quotes
1401            .into_iter()
1402            .filter(|(_, quote)| quote.price == median_price)
1403            .map(|(encoded_peer_id, quote)| LegacyMedianCandidate {
1404                encoded_peer_id,
1405                quote,
1406                expected_amount,
1407            })
1408            .collect())
1409    }
1410
1411    /// Fully validate one median-priced candidate. On success returns the
1412    /// settled on-chain amount for the candidate's quote hash, which the
1413    /// price-floor policy compares against the close group's median
1414    /// commitment price (the settled amount, not the quoted price, so an
1415    /// honest client may overpay a cheap quote to clear stricter receivers).
1416    async fn verify_legacy_median_candidate(
1417        &self,
1418        xorname: &XorName,
1419        candidate: LegacyMedianCandidate<'_>,
1420    ) -> Result<Amount> {
1421        Self::validate_paid_quote_content(xorname, candidate)?;
1422        let issuer_peer_id =
1423            Self::validate_paid_quote_peer_binding(candidate.encoded_peer_id, candidate.quote)?;
1424
1425        self.validate_paid_quote_issuer_k_closest(xorname, &issuer_peer_id)
1426            .await?;
1427
1428        Self::validate_paid_quote_signature(candidate).await?;
1429
1430        let (on_chain_amount, recorded_rewards_prefix) = self
1431            .completed_payment_settlement(candidate.quote.hash())
1432            .await?;
1433        // ADR-0004 Amendment 2: the settlement must be RECORDED FOR THE QUOTE'S
1434        // rewards address, not merely under its quote hash. The vault stores
1435        // whatever `(rewardsAddress, amount)` the payer supplied for the hash,
1436        // so an amount-only check would accept a payment the client redirected
1437        // to its own wallet — the issuer would be treated (and first-audited)
1438        // as "paid" without ever being compensated. Honest clients build the
1439        // payment from the quote itself, so this never rejects a legit upload.
1440        // The vault packs the payee as `bytes16`, so the comparison is on the
1441        // leading 16 bytes (128 bits — far beyond grinding range).
1442        if let Some(recorded) = recorded_rewards_prefix {
1443            let expected = Self::rewards_address_prefix(&candidate.quote.rewards_address);
1444            if recorded != expected {
1445                return Err(Error::Payment(format!(
1446                    "Median-priced quote settlement for peer {:?} was redirected: recorded rewards address prefix {} does not match the quote's {}",
1447                    candidate.encoded_peer_id,
1448                    hex::encode(recorded),
1449                    hex::encode(expected)
1450                )));
1451            }
1452        }
1453        if on_chain_amount >= candidate.expected_amount {
1454            return Ok(on_chain_amount);
1455        }
1456
1457        Err(Error::Payment(format!(
1458            "Median-priced quote for peer {:?} was not paid enough: expected at least {}, got {on_chain_amount}",
1459            candidate.encoded_peer_id, candidate.expected_amount
1460        )))
1461    }
1462
1463    /// The peer ids this node considers closest to `xorname`, by pure XOR
1464    /// distance, mirroring the selection the paid-quote closeness check uses.
1465    ///
1466    /// Returns an empty vec when the node is not wired to the P2P layer, which
1467    /// callers must treat as "no local view" rather than "no close peers".
1468    async fn local_k_closest_peer_ids(&self, xorname: &XorName) -> Vec<PeerId> {
1469        #[cfg(any(test, feature = "test-utils"))]
1470        if let Some(k_closest_peer_ids) = self.test_paid_quote_k_closest_override.read().as_ref() {
1471            return k_closest_peer_ids
1472                .iter()
1473                .map(|bytes| PeerId::from_bytes(*bytes))
1474                .collect();
1475        }
1476
1477        let Some(p2p_node) = self.p2p_node.read().as_ref().map(Arc::clone) else {
1478            return Vec::new();
1479        };
1480        p2p_node
1481            .dht_manager()
1482            .find_closest_nodes_local_by_distance_with_self(
1483                xorname,
1484                PAID_QUOTE_ISSUER_CLOSENESS_WIDTH,
1485            )
1486            .await
1487            .into_iter()
1488            .map(|node| node.peer_id)
1489            .collect()
1490    }
1491
1492    /// The close group's MEDIAN commitment-bound price for `xorname`, and the
1493    /// number of peers that median was taken over.
1494    ///
1495    /// This is the price floor's reference, and choosing the median of the group
1496    /// rather than this node's own price is the whole point of the policy.
1497    ///
1498    /// A client pays `3x` the MEDIAN of the quotes it collected. Pricing the
1499    /// floor against a receiver's OWN price compares that median to a single
1500    /// draw from a distribution that spans ~4x across the fleet, so the fullest
1501    /// receivers reject honest payments while the emptiest admit deep
1502    /// underpayment — measured on ant-prod-01, 0.377% of honest stores rejected
1503    /// with the cheapest-of-K underpayment still admitted by 62.9% of receivers.
1504    /// Both sides of that are the same defect: the reference is a sample, and
1505    /// the payment is a median. Comparing median to median removes it.
1506    ///
1507    /// The reference is built ONLY from state this node already holds:
1508    ///
1509    /// * the K peers closest to `xorname` in its own routing table, and
1510    /// * those peers' own signed commitments from the gossip cache, TTL-gated
1511    ///   by [`GOSSIP_ANSWERABILITY_TTL`], plus this node's own live commitment.
1512    ///
1513    /// Nothing in the payment bundle feeds it. A client cannot pad, prune or
1514    /// reorder quotes to move this number, which is what makes the floor
1515    /// resistant to the quote-selection games it exists to stop.
1516    ///
1517    /// The remaining lever is gossiping a false commitment, and it cuts BOTH
1518    /// ways, which is why the sample gate is set where it is:
1519    ///
1520    /// * **Understating** drags the median down and weakens the floor. The cost
1521    ///   is a missed underpayment.
1522    /// * **Overstating** drags it up and makes this node reject settled, honest
1523    ///   payments. That is the dangerous direction, because the money is already
1524    ///   spent and cannot be refunded, so a griefer would be spending nothing to
1525    ///   destroy someone else's payment.
1526    ///
1527    /// The bound is NOT "a majority of the group", and it is worth stating
1528    /// precisely because it is what an enforcement decision rests on. The floor
1529    /// does not need the median to reach the liars' value — only to move past
1530    /// the tolerance headroom. Each liar shifts the order statistic by one rank,
1531    /// and on the measured fleet spread one rank is worth roughly 15% of price
1532    /// while a 65% tolerance buys 1.54x. So **about a quarter of the sample**
1533    /// suffices in either direction: measured on this crate's own fixture, 4 of
1534    /// 15 overstating neighbours reject an honest payment sitting at the true
1535    /// median, and 4 of 15 understating ones (placed above the median, where an
1536    /// attacker would put them) admit a cheapest-of-K underpayment.
1537    ///
1538    /// Counts above `MAX_COMMITMENT_KEY_COUNT` are dropped outright, since
1539    /// gossip ingest authenticates the sender without bounding the count. That
1540    /// caps how far a single liar can reach but does not change the cardinality
1541    /// bound above. A signature proves who said a number, never that the number
1542    /// is true, and address grinding into a close group is a known adjacent
1543    /// problem. This is why the policy ships shadow-only: the ~25% bound is a
1544    /// reason not to enforce yet, not a property to rely on.
1545    ///
1546    /// Returns the reference price only when at least
1547    /// [`PRICE_FLOOR_MIN_NEIGHBOUR_COMMITMENTS`] neighbour commitments are
1548    /// fresh AND this node has its own live commitment; the `usize` is the
1549    /// sample size either way, so the caller can log how close it came. A `None`
1550    /// price means "do not evaluate".
1551    ///
1552    /// [`GOSSIP_ANSWERABILITY_TTL`]: crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL
1553    async fn group_reference_price(&self, xorname: &XorName) -> (Option<Amount>, GroupSample) {
1554        // This node's own live commitment. It is in the group whenever it is
1555        // being asked to store the chunk, so it belongs in the sample. Bound to
1556        // a local first so the source lock is released before the awaits below.
1557        //
1558        // It is counted separately from the neighbour tally: the gate below asks
1559        // "how much of the group do I actually know", and answering that with a
1560        // number that includes yourself overstates it by one, which matters most
1561        // exactly when the view is thinnest.
1562        // Wiring faults are reported before state faults, so a startup-order bug
1563        // is never mistaken for "this node is mid-rotation" or for "the gate is
1564        // above what the network supplies". Those three have three different
1565        // fixes and shadow mode exists to tell them apart.
1566        let Some(cache) = self.commitment_cache.read().as_ref().map(Arc::clone) else {
1567            return (None, GroupSample::none(SkipReason::NoCommitmentCache));
1568        };
1569        // Cache is checked first so a node without one does not pay for a
1570        // routing-table scan it will discard.
1571        let closest = self.local_k_closest_peer_ids(xorname).await;
1572        if closest.is_empty() {
1573            return (None, GroupSample::none(SkipReason::NoRoutingView));
1574        }
1575
1576        let own_source = self.local_commitment_source.read().as_ref().map(Arc::clone);
1577        // No own commitment means fresh, retired, or mid-rotation. Such a node
1578        // prices its OWN quotes at baseline, so letting it hold an incoming
1579        // payment to its neighbours' (higher) median would reject settlements it
1580        // would itself have quoted. Skip, which is also what ADR-0006 says a
1581        // receiver in this state does.
1582        let Some(own) = own_source.and_then(|source| source.current_binding_snapshot()) else {
1583            return (None, GroupSample::none(SkipReason::NoOwnCommitment));
1584        };
1585        let now = std::time::Instant::now();
1586        let ttl = crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
1587        let mut key_counts: Vec<u32> = {
1588            let guard = cache.read().await;
1589            closest
1590                .iter()
1591                .filter_map(|peer_id| {
1592                    let record = guard.get(peer_id)?;
1593                    // Stale gossip is treated as unknown rather than as a low
1594                    // price, so a peer going quiet can never drag the median
1595                    // down, nor count toward the minimum sample.
1596                    if now.saturating_duration_since(record.received_at) >= ttl {
1597                        return None;
1598                    }
1599                    record
1600                        .last_commitment()
1601                        .map(|c| c.key_count)
1602                        .filter(|count| *count <= MAX_COMMITMENT_KEY_COUNT)
1603                })
1604                .collect()
1605        };
1606
1607        let neighbours_known = key_counts.len();
1608        // Own count is held to the same cap as a neighbour's. Unreachable today
1609        // (the local builder refuses to build over-cap), but an asymmetry here
1610        // is the kind that quietly becomes a hole later.
1611        if own.key_count <= MAX_COMMITMENT_KEY_COUNT {
1612            key_counts.push(own.key_count);
1613        }
1614        let sample = GroupSample {
1615            neighbours: neighbours_known,
1616            total: key_counts.len(),
1617            skip_reason: None,
1618        };
1619
1620        if neighbours_known < PRICE_FLOOR_MIN_NEIGHBOUR_COMMITMENTS {
1621            return (None, sample.skipped(SkipReason::ThinSample));
1622        }
1623
1624        // Median of the PRICES, via the median key count. `calculate_price` is
1625        // monotonic in the key count, so the two orderings agree and taking the
1626        // median count avoids averaging two U256 prices.
1627        //
1628        // The LOWER median on even samples, deliberately: the upper median
1629        // rounds the reference UP, and a reference that is too high rejects
1630        // honest payments that have already settled on-chain and cannot be
1631        // refunded. (The merkle settlement path deliberately uses the UPPER
1632        // median instead: there it must match the on-chain contract's formula,
1633        // not choose a safe direction.) ADR-0006 carries the
1634        // measured difference.
1635        key_counts.sort_unstable();
1636        let median_key_count = key_counts
1637            .get((sample.total.saturating_sub(1)) / 2)
1638            .copied()
1639            .unwrap_or_default();
1640        let reference = calculate_price(usize::try_from(median_key_count).unwrap_or_default());
1641        (Some(reference), sample)
1642    }
1643
1644    /// Receiver-side price floor for single-node store admissions.
1645    ///
1646    /// Requires the settled on-chain amount to also clear
1647    /// `PAID_QUOTE_PAYMENT_MULTIPLIER × tolerance% ×` the close group's median
1648    /// commitment-bound price (see [`Self::group_reference_price`]). Together
1649    /// with the per-quote check above, the effective rule is
1650    /// `settled >= 3 × max(paid_price, tolerated_floor)`.
1651    ///
1652    /// When the group reference cannot be built — too few fresh commitments, no
1653    /// P2P handle, no gossip cache — the floor SKIPS the admission rather than
1654    /// falling back to this node's own price. Falling back is what the previous
1655    /// revision did, and it is precisely the comparison that rejected honest
1656    /// stores on the fullest nodes. A skipped evaluation is logged with its
1657    /// real `neighbours` / `group_sample` counts and a `skip_reason`, so shadow
1658    /// telemetry can separate an unwired node from one whose gate simply sits
1659    /// above what the network supplies.
1660    ///
1661    /// Always emits one telemetry line per evaluated admission (target
1662    /// `ant_node::payment::price_floor`) so shadow mode measures the exact
1663    /// rejections enforcement would cause. Rejects only when
1664    /// [`PriceFloorConfig::enforce`] is set.
1665    async fn enforce_price_floor(
1666        &self,
1667        xorname: &XorName,
1668        paid_price: Amount,
1669        settled_amount: Amount,
1670        context: VerificationContext,
1671    ) -> Result<()> {
1672        if !context.is_store_admission() {
1673            return Ok(());
1674        }
1675
1676        let floor = *self.price_floor.read();
1677        let tolerance_percent = floor.tolerance_percent.min(100);
1678
1679        let (reference, group_sample) = self.group_reference_price(xorname).await;
1680        let Some(reference_price) = reference else {
1681            // Not enough of the close group is known to price anything. Skip
1682            // rather than guess: see `group_reference_price`. The reason and
1683            // both counts are logged because shadow telemetry has to separate a
1684            // mid-rotation node from an unwired cache from a gate set above what
1685            // the network can supply — three causes with three different fixes.
1686            info!(
1687                target: "ant_node::payment::price_floor",
1688                "Price floor: context={context:?}, xorname={}, paid_price={paid_price}, \
1689                 settled={settled_amount}, neighbours={}, group_sample={}, reference_price=0, \
1690                 tolerance_percent={tolerance_percent}, required=0, below_floor=false, \
1691                 skipped=true, skip_reason={}, enforce={}",
1692                hex::encode(xorname),
1693                group_sample.neighbours,
1694                group_sample.total,
1695                group_sample.skip_reason_str(),
1696                floor.enforce,
1697            );
1698            return Ok(());
1699        };
1700
1701        // Amount is a U256: reference_price is bounded by the saturating pricing
1702        // curve and the multipliers are <= 300, so this arithmetic cannot
1703        // overflow; saturating keeps that a proof instead of an assumption.
1704        let tolerated_price =
1705            reference_price.saturating_mul(Amount::from(tolerance_percent)) / Amount::from(100u64);
1706        let required_amount =
1707            tolerated_price.saturating_mul(Amount::from(PAID_QUOTE_PAYMENT_MULTIPLIER));
1708        let below_floor = settled_amount < required_amount;
1709
1710        info!(
1711            target: "ant_node::payment::price_floor",
1712            "Price floor: context={context:?}, xorname={}, paid_price={paid_price}, \
1713             settled={settled_amount}, neighbours={}, group_sample={}, \
1714             reference_price={reference_price}, tolerance_percent={tolerance_percent}, \
1715             required={required_amount}, below_floor={below_floor}, skipped=false, \
1716             skip_reason=none, enforce={}",
1717            hex::encode(xorname),
1718            group_sample.neighbours,
1719            group_sample.total,
1720            floor.enforce,
1721        );
1722
1723        if below_floor && floor.enforce {
1724            return Err(Error::Payment(format!(
1725                "Settled payment {settled_amount} is below the close-group price floor \
1726                 {required_amount} ({PAID_QUOTE_PAYMENT_MULTIPLIER}x {tolerance_percent}% of \
1727                 the group median price {reference_price}, taken over {} peers)",
1728                group_sample.total
1729            )));
1730        }
1731
1732        Ok(())
1733    }
1734
1735    fn validate_paid_quote_content(
1736        xorname: &XorName,
1737        candidate: LegacyMedianCandidate<'_>,
1738    ) -> Result<()> {
1739        if verify_quote_content(candidate.quote, xorname) {
1740            return Ok(());
1741        }
1742
1743        let expected_hex = hex::encode(xorname);
1744        let actual_hex = hex::encode(candidate.quote.content.0);
1745        Err(Error::Payment(format!(
1746            "Paid quote content address mismatch for peer {:?}: expected {expected_hex}, got {actual_hex}",
1747            candidate.encoded_peer_id
1748        )))
1749    }
1750
1751    async fn validate_paid_quote_signature(candidate: LegacyMedianCandidate<'_>) -> Result<()> {
1752        let quote_for_signature = candidate.quote.clone();
1753        let peer_id_for_error = candidate.encoded_peer_id.clone();
1754        tokio::task::spawn_blocking(move || {
1755            if !verify_quote_signature(&quote_for_signature) {
1756                return Err(Error::Payment(format!(
1757                    "Paid quote ML-DSA-65 signature verification failed for peer {peer_id_for_error:?}"
1758                )));
1759            }
1760            Ok(())
1761        })
1762        .await
1763        .map_err(|e| Error::Payment(format!("Signature verification task failed: {e}")))?
1764    }
1765
1766    /// Look up the on-chain settlement recorded for `quote_hash`: the settled
1767    /// amount and the `bytes16` rewards-address prefix it was recorded for.
1768    /// The prefix is `None` only on the test-override path (meaning "matches
1769    /// the quote"); the production contract read always returns the recorded
1770    /// prefix so the caller's redirect check always applies.
1771    async fn completed_payment_settlement(
1772        &self,
1773        quote_hash: QuoteHash,
1774    ) -> Result<(Amount, Option<[u8; 16]>)> {
1775        #[cfg(any(test, feature = "test-utils"))]
1776        {
1777            let completed_payment_override = {
1778                self.test_completed_payments_override
1779                    .read()
1780                    .get(&quote_hash)
1781                    .copied()
1782            };
1783            if let Some((amount, recorded)) = completed_payment_override {
1784                return Ok((amount, recorded));
1785            }
1786        }
1787
1788        let provider = evmlib::utils::http_provider(self.config.evm.network.rpc_url().clone());
1789        let vault_address = *self.config.evm.network.payment_vault_address();
1790        let contract = payment_vault::interface::IPaymentVault::new(vault_address, provider);
1791
1792        let result = contract
1793            .completedPayments(quote_hash)
1794            .call()
1795            .await
1796            .map_err(|e| Error::Payment(format!("completedPayments lookup failed: {e}")))?;
1797
1798        Ok((Amount::from(result.amount), Some(result.rewardsAddress.0)))
1799    }
1800
1801    fn validate_paid_quote_peer_binding(
1802        encoded_peer_id: &evmlib::EncodedPeerId,
1803        quote: &PaymentQuote,
1804    ) -> Result<PeerId> {
1805        let expected_peer_id = peer_id_from_public_key_bytes(&quote.pub_key)
1806            .map_err(|e| Error::Payment(format!("Invalid ML-DSA public key in quote: {e}")))?;
1807
1808        if expected_peer_id.as_bytes() != encoded_peer_id.as_bytes() {
1809            let expected_hex = expected_peer_id.to_hex();
1810            let actual_hex = hex::encode(encoded_peer_id.as_bytes());
1811            return Err(Error::Payment(format!(
1812                "Paid quote pub_key does not belong to claimed peer {encoded_peer_id:?}: \
1813                 BLAKE3(pub_key) = {expected_hex}, peer_id = {actual_hex}"
1814            )));
1815        }
1816
1817        Ok(expected_peer_id)
1818    }
1819
1820    async fn validate_paid_quote_issuer_k_closest(
1821        &self,
1822        xorname: &XorName,
1823        issuer_peer_id: &PeerId,
1824    ) -> Result<()> {
1825        #[cfg(any(test, feature = "test-utils"))]
1826        if let Some(k_closest_peer_ids) = self.test_paid_quote_k_closest_override.read().as_ref() {
1827            if k_closest_peer_ids
1828                .iter()
1829                .any(|peer_id| peer_id == issuer_peer_id.as_bytes())
1830            {
1831                return Ok(());
1832            }
1833            let issuer_closeness_width = PAID_QUOTE_ISSUER_CLOSENESS_WIDTH;
1834            return Err(Error::Payment(format!(
1835                "Paid quote issuer {} is not among this node's local K={issuer_closeness_width} closest peers for {}",
1836                issuer_peer_id.to_hex(),
1837                hex::encode(xorname)
1838            )));
1839        }
1840
1841        let attached = self.p2p_node.read().as_ref().map(Arc::clone);
1842        let Some(p2p_node) = attached else {
1843            #[cfg(any(test, feature = "test-utils"))]
1844            {
1845                crate::logging::warn!(
1846                    "PaymentVerifier: no P2PNode attached; paid-quote issuer \
1847                     K-closest check SKIPPED (test build). Production startup MUST call \
1848                     PaymentVerifier::attach_p2p_node."
1849                );
1850                return Ok(());
1851            }
1852            #[cfg(not(any(test, feature = "test-utils")))]
1853            {
1854                crate::logging::error!(
1855                    "PaymentVerifier: no P2PNode attached; rejecting paid-quote \
1856                     payment. This is a node-startup bug — \
1857                     PaymentVerifier::attach_p2p_node must be called before \
1858                     any PUT handler runs."
1859                );
1860                return Err(Error::Payment(
1861                    "Paid quote rejected: verifier is not wired to the P2P \
1862                     layer; cannot verify issuer closeness."
1863                        .into(),
1864                ));
1865            }
1866        };
1867
1868        // Closeness *verification* must mirror the uploader's pure XOR-distance
1869        // peer selection. `find_closest_nodes_local_with_self` reranks the local
1870        // routing table by reachability (preferring directly-reachable peers,
1871        // XOR only as a tiebreaker), which demotes an XOR-close relay-only /
1872        // NAT'd peer out of the compared window and falsely rejects an honest
1873        // payment that legitimately quoted that peer. Use the XOR-only sibling
1874        // so this check matches how the client chose the quoted K-closest set.
1875        let issuer_closeness_width = PAID_QUOTE_ISSUER_CLOSENESS_WIDTH;
1876        let closest = p2p_node
1877            .dht_manager()
1878            .find_closest_nodes_local_by_distance_with_self(xorname, issuer_closeness_width)
1879            .await;
1880        if closest.iter().any(|node| node.peer_id == *issuer_peer_id) {
1881            return Ok(());
1882        }
1883
1884        Err(Error::Payment(format!(
1885            "Paid quote issuer {} is not among this node's local K={issuer_closeness_width} closest peers for {}",
1886            issuer_peer_id.to_hex(),
1887            hex::encode(xorname)
1888        )))
1889    }
1890
1891    /// Validate quote count, uniqueness, and basic structure.
1892    fn validate_quote_structure(payment: &ProofOfPayment) -> Result<()> {
1893        if payment.peer_quotes.is_empty() {
1894            return Err(Error::Payment("Payment has no quotes".to_string()));
1895        }
1896
1897        let quote_count = payment.peer_quotes.len();
1898        if quote_count > CLOSE_GROUP_SIZE {
1899            return Err(Error::Payment(format!(
1900                "Payment must have at most {CLOSE_GROUP_SIZE} quotes, got {quote_count}"
1901            )));
1902        }
1903
1904        let mut seen: Vec<&evmlib::EncodedPeerId> = Vec::with_capacity(quote_count);
1905        for (encoded_peer_id, _) in &payment.peer_quotes {
1906            if seen.contains(&encoded_peer_id) {
1907                return Err(Error::Payment(format!(
1908                    "Duplicate peer ID in payment quotes: {encoded_peer_id:?}"
1909                )));
1910            }
1911            seen.push(encoded_peer_id);
1912        }
1913
1914        Ok(())
1915    }
1916
1917    /// ADR-0004: enforce that every quoted price lies exactly on the public
1918    /// pricing curve.
1919    ///
1920    /// **Scope**: the price is forced by the quote's own signed
1921    /// `committed_key_count`, not merely required to be *somewhere* on the
1922    /// curve. `PaymentQuote` now carries `committed_key_count` and
1923    /// `commitment_pin`, both covered by the quote signature and the quote
1924    /// hash, so [`Self::binding_violation`] can hold the price to the count the
1925    /// quoter committed to. What this gate does not do is resolve the pin
1926    /// against the commitment the peer actually gossiped — a quoter can still
1927    /// commit to a count it does not store and price consistently with it.
1928    /// That cross-check is [`Self::cross_check_quotes`], gated separately by
1929    /// [`crate::replication::config::QUOTE_COMMITMENT_MISMATCH_TRUST_ENABLED`]
1930    /// because it carries a trust penalty rather than being reject-only.
1931    ///
1932    /// **Check**: exact recomputation, never price-inversion. The price is
1933    /// compared against `calculate_price(committed_key_count)` recomputed from
1934    /// the signed count. Inverting the price to a count would silently accept
1935    /// any value between two curve points, and would also let a quote price
1936    /// itself off one count while committing to another.
1937    ///
1938    /// **Where it runs**: in every [`VerificationContext`] over **every**
1939    /// quote in **both** quote types — all 7 single-node quotes
1940    /// ([`Self::validate_quote_arithmetic`]) and all 16 merkle candidates
1941    /// ([`Self::validate_merkle_candidate_arithmetic`]) — because the rule
1942    /// "every storer re-runs the price-equals-formula-of-count check on every
1943    /// quote in the bundle" (ADR-0004) needs no peer-specific state and depends
1944    /// only on the bundle itself, so every honest storer reaches the same
1945    /// verdict with no split-brain risk.
1946    ///
1947    /// **Reject-only**, per ADR-0004: no trust evidence is emitted, no audit
1948    /// is scheduled. The rejection is the consequence. The gate is
1949    /// rollout-gated by
1950    /// [`crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED`]; when
1951    /// `false`, off-curve quotes are accepted and only telemetered
1952    /// ([`Self::log_off_curve_single_node`] /
1953    /// [`Self::log_off_curve_merkle`]), matching ADR-0004's observe-only
1954    /// rollout. Telemetry is invoked **after** ML-DSA-65 signature
1955    /// verification so unauthenticated senders cannot poison the rollout
1956    /// logs.
1957    fn validate_quote_arithmetic(payment: &ProofOfPayment) -> Result<()> {
1958        if !crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED {
1959            return Ok(());
1960        }
1961        for (encoded_peer_id, quote) in &payment.peer_quotes {
1962            if let Some(detail) = Self::quote_arithmetic_violation(quote) {
1963                return Err(Error::Payment(format!(
1964                    "ADR-0004 off-curve quote rejected for peer {encoded_peer_id:?}: {detail}"
1965                )));
1966            }
1967        }
1968        Ok(())
1969    }
1970
1971    /// The ADR-0004 forced-price rule for a single quote, returning a human
1972    /// diagnostic iff the quote violates it. Shared by single-node quotes and
1973    /// merkle candidates via [`Self::binding_violation`].
1974    ///
1975    /// The rule is the ADR's exact one — `price == calculate_price(
1976    /// committed_key_count)`, recomputed, never inverted from the price (which
1977    /// rounds) — PLUS a binding-shape check. There is no "legacy degradation"
1978    /// that infers an old quote from its field values: a `(0, None)` quote is
1979    /// rejected unless its price is exactly `calculate_price(0)`, closing the
1980    /// bypass where a modified node strips the pin yet prices above baseline.
1981    /// Old-format quotes (which never carried these fields) are tolerated only
1982    /// at the *wire-decode* layer, where they decode as `(0, None)` and are then
1983    /// held to the same baseline rule; an explicit version negotiation, not
1984    /// field inference, is the sanctioned path if non-baseline legacy quotes
1985    /// must ever be accepted.
1986    fn quote_arithmetic_violation(quote: &evmlib::PaymentQuote) -> Option<String> {
1987        Self::binding_violation(
1988            quote.committed_key_count,
1989            quote.commitment_pin,
1990            &quote.price,
1991        )
1992    }
1993
1994    /// The shared ADR-0004 binding rule over a `(committed_key_count,
1995    /// commitment_pin, price)` triple, used for both quote types.
1996    ///
1997    /// Enforces, in order:
1998    /// 1. **Shape.** `(0, None)` baseline or `(n>0, Some(pin))` bound; the mixed
1999    ///    shapes `(n>0, None)` and `(0, Some(_))` are always rejected — a count
2000    ///    without a pin is unauditable, and a pin without a count is incoherent.
2001    /// 2. **Cap.** `committed_key_count <= MAX_COMMITMENT_KEY_COUNT`; a count a
2002    ///    commitment could never legitimately attest is rejected before pricing.
2003    /// 3. **Forced price.** `price == calculate_price(committed_key_count)`, by
2004    ///    exact recomputation.
2005    fn binding_violation(
2006        committed_key_count: u32,
2007        commitment_pin: Option<[u8; 32]>,
2008        price: &Amount,
2009    ) -> Option<String> {
2010        match (committed_key_count, commitment_pin.is_some()) {
2011            (0, false) | (1.., true) => {}
2012            (1.., false) => {
2013                return Some(format!(
2014                    "binding shape invalid: committed_key_count={committed_key_count} > 0 \
2015                     but commitment_pin is None (unauditable count)"
2016                ));
2017            }
2018            (0, true) => {
2019                return Some(
2020                    "binding shape invalid: committed_key_count=0 with a commitment_pin \
2021                     (incoherent baseline)"
2022                        .to_string(),
2023                );
2024            }
2025        }
2026        if committed_key_count > crate::replication::commitment::MAX_COMMITMENT_KEY_COUNT {
2027            return Some(format!(
2028                "committed_key_count={committed_key_count} exceeds MAX_COMMITMENT_KEY_COUNT={}",
2029                crate::replication::commitment::MAX_COMMITMENT_KEY_COUNT
2030            ));
2031        }
2032        let expected = calculate_price(Self::candidate_count_to_usize(u64::from(
2033            committed_key_count,
2034        )));
2035        if &expected == price {
2036            None
2037        } else {
2038            Some(format!(
2039                "price {price} does not equal calculate_price(committed_key_count={committed_key_count}) = {expected}"
2040            ))
2041        }
2042    }
2043
2044    /// Pure ADR-0004 cross-check: compare a quote's claimed `(key_count, pin)`
2045    /// against a resolved signed commitment.
2046    ///
2047    /// This is the decision core of "peers cross-check the original": given a
2048    /// quote's binding and the actual `StorageCommitment` the pin was resolved
2049    /// to (from the sidecar, the gossip cache, or a fetch), decide whether the
2050    /// quote contradicts the commitment. It is deliberately a pure function over
2051    /// the two artifacts so it is exhaustively unit-testable without any cache,
2052    /// network, or trust wiring; the caller owns resolution and emission.
2053    ///
2054    /// Outcomes:
2055    /// - [`CrossCheck::Match`] — the pin matches the commitment's hash and the
2056    ///   counts agree: nothing to report.
2057    /// - [`CrossCheck::Mismatch`] — the pin matches the commitment's hash but
2058    ///   the quote's `committed_key_count` differs from the commitment's
2059    ///   `key_count`. Two artifacts signed by the same key contradict each
2060    ///   other: this is the deterministic, first-occurrence evidence.
2061    /// - [`CrossCheck::PinDoesNotResolve`] — the supplied commitment's hash does
2062    ///   not equal the quote's pin (wrong/garbled resolution). NOT evidence: the
2063    ///   caller must treat it as an unresolved pin (fetch/skip), never a
2064    ///   penalty, exactly like an unanswerable pin.
2065    ///
2066    /// A baseline quote `(0, None)` is never cross-checked (it pins nothing);
2067    /// callers skip it before reaching here.
2068    fn cross_check_binding(
2069        quoted_key_count: u32,
2070        quoted_pin: [u8; 32],
2071        commitment: &crate::replication::commitment::StorageCommitment,
2072    ) -> CrossCheck {
2073        // The pin IS the commitment hash; if the resolved commitment hashes to
2074        // something else, this is not the artifact the quote pinned.
2075        match crate::replication::commitment::commitment_hash(commitment) {
2076            Some(h) if h == quoted_pin => {
2077                if commitment.key_count == quoted_key_count {
2078                    CrossCheck::Match
2079                } else {
2080                    CrossCheck::Mismatch {
2081                        quoted_key_count,
2082                        committed_key_count: commitment.key_count,
2083                    }
2084                }
2085            }
2086            _ => CrossCheck::PinDoesNotResolve,
2087        }
2088    }
2089
2090    /// Resolve a cached peer commitment record to its commitment *only if* it
2091    /// was seen within the answerability TTL; a staler entry is treated as
2092    /// unknown (ADR-0004: "a cached commitment older than the answerability TTL
2093    /// is treated as unknown"). Pure over `(record, now, ttl)` so the TTL
2094    /// boundary is unit-testable without the async cache/network path.
2095    fn fresh_cached_commitment(
2096        rec: &crate::replication::commitment_state::PeerCommitmentRecord,
2097        pin: [u8; 32],
2098        now: std::time::Instant,
2099        ttl: std::time::Duration,
2100    ) -> Option<crate::replication::commitment::StorageCommitment> {
2101        if now.saturating_duration_since(rec.received_at) >= ttl {
2102            return None; // stale cache entry -> treat as unknown
2103        }
2104        // Only resolve when the cached commitment is actually the one the quote
2105        // pinned. The auditor cache holds a peer's LATEST gossiped commitment,
2106        // which may be a DIFFERENT pin than this quote's; returning it would make
2107        // `cross_check_binding` yield `PinDoesNotResolve` and wrongly suppress
2108        // the fetch fallback for the quoted pin. A pin mismatch here means "not
2109        // cached" -> fall through to fetch.
2110        if rec.commitment_hash() != Some(pin) {
2111            return None;
2112        }
2113        rec.last_commitment().cloned()
2114    }
2115
2116    /// Resolve a `(peer, pin)` from the gossip commitment cache, if the cache is
2117    /// wired and holds a fresh entry whose hash matches the pin. Shared by the
2118    /// single-node and merkle cross-check paths.
2119    async fn cache_resolve(
2120        cache: Option<&CommitmentCache>,
2121        peer_id: PeerId,
2122        pin: [u8; 32],
2123        now: std::time::Instant,
2124        ttl: std::time::Duration,
2125    ) -> Option<crate::replication::commitment::StorageCommitment> {
2126        let cache = cache?;
2127        let guard = cache.read().await;
2128        guard
2129            .get(&peer_id)
2130            .and_then(|rec| Self::fresh_cached_commitment(rec, pin, now, ttl))
2131    }
2132
2133    /// Parse and validate ADR-0004 commitment sidecars into a `(peer, pin) ->
2134    /// commitment` map. Each blob is deserialized and held to the SAME gates as
2135    /// a gossip-ingested or fetched commitment (peer id derived from its own
2136    /// `sender_peer_id`, `BLAKE3(pubkey) == sender_peer_id`, valid signature),
2137    /// keyed by `(its own peer, its own hash)`. Resolution then matches a quote
2138    /// only when both the quote's peer AND pin equal the sidecar's, so a sidecar
2139    /// can never satisfy a different peer's or a different pin's quote. An
2140    /// unparseable or invalid sidecar is silently skipped (resolution falls back
2141    /// to gossip/fetch), never a hard error on the payment path.
2142    fn index_valid_sidecars(
2143        sidecars: &[Vec<u8>],
2144    ) -> HashMap<(PeerId, [u8; 32]), crate::replication::commitment::StorageCommitment> {
2145        use crate::replication::commitment::MAX_COMMITMENT_SIDECAR_BYTES;
2146        let mut map = HashMap::new();
2147        // Bound the number of sidecars we even look at: a legitimate bundle has
2148        // at most one commitment per quote/candidate. `MAX_SIDECARS_PER_BUNDLE`
2149        // (= CANDIDATES_PER_POOL, the larger of the two) caps the deserialize/
2150        // verify work a malicious client can force on the hot path.
2151        for blob in sidecars.iter().take(MAX_SIDECARS_PER_BUNDLE) {
2152            // Cap blob size before parsing: never attempt to deserialize an
2153            // oversized commitment.
2154            if blob.len() > MAX_COMMITMENT_SIDECAR_BYTES {
2155                continue;
2156            }
2157            let Ok(commitment) =
2158                rmp_serde::from_slice::<crate::replication::commitment::StorageCommitment>(blob)
2159            else {
2160                continue; // unparseable -> skip
2161            };
2162            let peer_id = PeerId::from_bytes(commitment.sender_peer_id);
2163            let Some(pin) = crate::replication::commitment::commitment_hash(&commitment) else {
2164                continue;
2165            };
2166            // Validate against its own (peer, pin): peer binding + pubkey
2167            // derivation + signature + hash==pin.
2168            if Self::fetched_commitment_is_valid(&commitment, &peer_id, pin) {
2169                map.insert((peer_id, pin), commitment);
2170            }
2171        }
2172        map
2173    }
2174
2175    /// ADR-0004 "peers cross-check the original": for each non-baseline quote in
2176    /// a client-put bundle, resolve its `commitment_pin` and report a count/pin
2177    /// contradiction.
2178    ///
2179    /// Resolution order: the sidecar first (the commitment arrived with the
2180    /// quote, validated synchronously — no state, no network), then the gossip
2181    /// cache (only if the neighbour's commitment was seen within
2182    /// `GOSSIP_ANSWERABILITY_TTL`; a staler entry is treated as unknown, per the
2183    /// ADR's "cached commitment older than the answerability TTL is treated as
2184    /// unknown"), then an off-hot-path `GetCommitmentByPin` fetch for pins still
2185    /// unresolved. A pin that resolves nowhere is simply skipped — an unresolved
2186    /// pin is never a penalty.
2187    ///
2188    /// A genuine [`CrossCheck::Mismatch`] is a deterministic, first-occurrence
2189    /// contradiction between two same-key-signed artifacts: when enforcing, it
2190    /// emits [`FailureEvidence::QuoteCommitmentMismatch`] to the trust engine
2191    /// (same lane as a confirmed deterministic audit failure — NOT the timeout
2192    /// silence lane); when observe-only, it only logs. Always best-effort: a
2193    /// missing cache or absent `P2PNode` degrades to "resolve nothing", never an
2194    /// error on the payment path — the synchronous arithmetic gate and the
2195    /// later audit remain the load-bearing checks.
2196    async fn cross_check_quotes(
2197        &self,
2198        payment: &ProofOfPayment,
2199        commitment_sidecars: &[Vec<u8>],
2200        paid_peer: Option<[u8; 32]>,
2201    ) {
2202        let now = std::time::Instant::now();
2203        let ttl = crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
2204        let p2p = self.p2p_node.read().as_ref().map(Arc::clone);
2205        let monetized_pin_tx = self.monetized_pin_tx.read().as_ref().cloned();
2206        let cache = self.commitment_cache.read().as_ref().map(Arc::clone);
2207
2208        // ADR-0004 "the commitment arrived with the quote": parse and FULLY
2209        // validate the sidecars (peer/pubkey/signature/hash gates, keyed by
2210        // `(peer, pin)`), so the cross-check resolves synchronously without a
2211        // gossip-cache hit or a post-payment fetch. An invalid sidecar is simply
2212        // dropped (resolution falls back to gossip/fetch), never a hard error.
2213        let sidecar_map = Self::index_valid_sidecars(commitment_sidecars);
2214
2215        // Inline pass: resolve from the sidecar first, then the gossip cache
2216        // (cheap, no network). Pins that don't resolve here are collected for
2217        // the off-hot-path fetch.
2218        let mut unresolved: Vec<(PeerId, [u8; 32], u32, Vec<u8>)> = Vec::new();
2219        for (encoded_peer_id, quote) in &payment.peer_quotes {
2220            let Some(pin) = quote.commitment_pin else {
2221                continue; // baseline quote pins nothing
2222            };
2223            let peer_id = PeerId::from_bytes(*encoded_peer_id.as_bytes());
2224
2225            // ADR-0004 Amendment 2: only the PAID candidate's commitment earned
2226            // money, so only its pin is routed for a deterministic first audit
2227            // (the drainer dedups, rate-budgets, and respects the cooldown).
2228            // Pre-amendment this fired for every pinned quote in the bundle —
2229            // up to CLOSE_GROUP_SIZE audits per proof for peers that were never
2230            // paid — a 7x term in the fleet-wide amplification that degraded
2231            // v0.14.3. Best-effort: a closed channel just means no first audit
2232            // is scheduled, never an error on the payment path.
2233            let is_paid = paid_peer.is_some_and(|paid| paid == *encoded_peer_id.as_bytes());
2234            if is_paid {
2235                if let Some(ref tx) = monetized_pin_tx {
2236                    // Bounded queue: drop on full (best-effort, penalty-free;
2237                    // the peer's next settled payment re-nominates it). Count a
2238                    // Full drop so ingress saturation is observable; a Closed
2239                    // channel just means the engine is shutting down.
2240                    if let Err(tokio::sync::mpsc::error::TrySendError::Full(_)) =
2241                        tx.try_send(crate::replication::MonetizedPinEvent {
2242                            peer: peer_id,
2243                            pin,
2244                            key_count: quote.committed_key_count,
2245                            quote_ts: quote.timestamp,
2246                        })
2247                    {
2248                        crate::replication::note_monetized_ingress_drop();
2249                    }
2250                }
2251            }
2252            // Resolution order: sidecar (synchronous, no state) -> gossip cache
2253            // (fresh within TTL) -> fetch fallback (collected as unresolved).
2254            let resolved = match sidecar_map.get(&(peer_id, pin)) {
2255                Some(c) => Some(c.clone()),
2256                None => Self::cache_resolve(cache.as_ref(), peer_id, pin, now, ttl).await,
2257            };
2258            match resolved {
2259                Some(commitment) => {
2260                    let artifact = rmp_serde::to_vec(quote).unwrap_or_default();
2261                    Self::handle_cross_check(
2262                        &peer_id,
2263                        pin,
2264                        quote.committed_key_count,
2265                        artifact,
2266                        &commitment,
2267                        p2p.as_ref(),
2268                    )
2269                    .await;
2270                }
2271                None => unresolved.push((
2272                    peer_id,
2273                    pin,
2274                    quote.committed_key_count,
2275                    rmp_serde::to_vec(quote).unwrap_or_default(),
2276                )),
2277            }
2278        }
2279
2280        // Off-hot-path fallback: fetch the unresolved pins via
2281        // `GetCommitmentByPin` and cross-check the results in a detached task,
2282        // so `verify_payment` does not block on the network.
2283        if unresolved.is_empty() {
2284            return;
2285        }
2286        let Some(p2p) = p2p else {
2287            return; // no P2P handle: cannot fetch, leave graced
2288        };
2289        let neg_cache = Arc::clone(&self.pin_fetch_negative_cache);
2290        tokio::spawn(async move {
2291            Self::drain_unresolved_pin_fetches(&p2p, &neg_cache, unresolved).await;
2292        });
2293    }
2294
2295    /// Fetch each unresolved pin via `GetCommitmentByPin` and cross-check the
2296    /// result. Bounded at [`MAX_PIN_FETCHES_PER_BUNDLE`] per call, negatively
2297    /// cached per `(peer, pin)`, and graced on any miss/timeout. Shared by the
2298    /// single-node and merkle cross-check paths; meant to run in a detached task
2299    /// off the payment hot path.
2300    async fn drain_unresolved_pin_fetches(
2301        p2p: &Arc<P2PNode>,
2302        neg_cache: &PinFetchNegativeCache,
2303        unresolved: Vec<(PeerId, [u8; 32], u32, Vec<u8>)>,
2304    ) {
2305        let mut fetched = 0usize;
2306        for (peer_id, pin, quoted_key_count, artifact) in unresolved {
2307            if fetched >= crate::replication::config::MAX_PIN_FETCHES_PER_BUNDLE {
2308                debug!("ADR-0004 pin-fetch cap reached for this bundle; leaving rest graced");
2309                break;
2310            }
2311            // Skip pins already known-unresolvable for this peer.
2312            if neg_cache.lock().get(&(peer_id, pin)).is_some() {
2313                continue;
2314            }
2315            fetched += 1;
2316            match Self::fetch_commitment_by_pin(p2p, &peer_id, pin).await {
2317                Some(commitment) => {
2318                    Self::handle_cross_check(
2319                        &peer_id,
2320                        pin,
2321                        quoted_key_count,
2322                        artifact,
2323                        &commitment,
2324                        Some(p2p),
2325                    )
2326                    .await;
2327                }
2328                None => {
2329                    // NotRetained / timeout / malformed: graced (never a
2330                    // penalty), but remembered so we don't re-fetch.
2331                    neg_cache.lock().put((peer_id, pin), ());
2332                }
2333            }
2334        }
2335    }
2336
2337    /// Apply the ADR-0004 cross-check verdict for one resolved `(peer, pin,
2338    /// quoted_count)` against `commitment`, emitting a trust failure on a
2339    /// genuine mismatch (when enforcing) or logging it (observe-only). Shared by
2340    /// the inline cache pass and the background fetch path so both reach the
2341    /// same verdict and emission.
2342    async fn handle_cross_check(
2343        peer_id: &PeerId,
2344        pin: [u8; 32],
2345        quoted_key_count: u32,
2346        quote_artifact: Vec<u8>,
2347        commitment: &crate::replication::commitment::StorageCommitment,
2348        p2p: Option<&Arc<P2PNode>>,
2349    ) {
2350        let CrossCheck::Mismatch {
2351            quoted_key_count,
2352            committed_key_count,
2353        } = Self::cross_check_binding(quoted_key_count, pin, commitment)
2354        else {
2355            return; // Match or PinDoesNotResolve: nothing to report
2356        };
2357        // The evidence is only meaningful if it carries the signed quote
2358        // artifact (one of the two contradicting same-key signatures). An empty
2359        // artifact — a re-serialization failure upstream — would produce
2360        // non-portable, unverifiable evidence, so grace it (log) instead of
2361        // emitting it: the deterministic first audit still convicts a genuine
2362        // inflater on the disk bytes.
2363        if quote_artifact.is_empty() {
2364            warn!(
2365                "ADR-0004 quote/commitment mismatch for {peer_id}: dropping evidence, \
2366                 quote artifact failed to serialize (graced; the audit still runs)"
2367            );
2368            return;
2369        }
2370        // Build the portable evidence variant — the two same-key-signed
2371        // artifacts that contradict each other, carried in full so any third
2372        // party can re-verify both signatures and recompute the contradiction.
2373        // This value IS the record; `emit_mismatch_evidence` turns it into the
2374        // trust action (or an observe-only log).
2375        let evidence = crate::replication::types::FailureEvidence::QuoteCommitmentMismatch {
2376            peer: *peer_id,
2377            pinned_commitment: pin,
2378            quoted_key_count,
2379            committed_key_count,
2380            quote_artifact,
2381            commitment: Box::new(commitment.clone()),
2382        };
2383        Self::emit_mismatch_evidence(&evidence, p2p).await;
2384    }
2385
2386    /// Route a `QuoteCommitmentMismatch` evidence record: when enforcing, report
2387    /// it to the trust engine as a confirmed deterministic failure (an
2388    /// `ApplicationFailure` — same lane as a confirmed audit failure, NOT the
2389    /// timeout silence lane); when observe-only, only log it. Separated so the
2390    /// evidence→action mapping is unit-testable independent of resolution.
2391    async fn emit_mismatch_evidence(
2392        evidence: &crate::replication::types::FailureEvidence,
2393        p2p: Option<&Arc<P2PNode>>,
2394    ) {
2395        let crate::replication::types::FailureEvidence::QuoteCommitmentMismatch {
2396            peer,
2397            quoted_key_count,
2398            committed_key_count,
2399            ..
2400        } = evidence
2401        else {
2402            return; // only this variant is handled here
2403        };
2404        let enforce = crate::replication::config::QUOTE_COMMITMENT_MISMATCH_TRUST_ENABLED;
2405        if enforce {
2406            warn!(
2407                "ADR-0004 quote/commitment mismatch (enforcing) for {peer}: quote claims \
2408                 {quoted_key_count} keys but pinned commitment attests {committed_key_count}"
2409            );
2410            if let Some(p2p) = p2p {
2411                p2p.report_trust_event(
2412                    peer,
2413                    saorsa_core::TrustEvent::ApplicationFailure(
2414                        crate::replication::config::AUDIT_FAILURE_TRUST_WEIGHT,
2415                    ),
2416                )
2417                .await;
2418            }
2419        } else {
2420            warn!(
2421                "ADR-0004 quote/commitment mismatch observed (not enforcing) for {peer}: quote \
2422                 claims {quoted_key_count} keys but pinned commitment attests {committed_key_count}"
2423            );
2424        }
2425    }
2426
2427    /// Fetch a peer's commitment by pin via `GetCommitmentByPin`, returning it
2428    /// only if the peer answered `Found` with a commitment that (a) is validly
2429    /// signed and peer-bound and (b) actually hashes to the requested pin.
2430    /// `None` on `NotRetained`, timeout, malformed, or any verification failure
2431    /// — all graced (the caller never penalises an unresolved pin).
2432    async fn fetch_commitment_by_pin(
2433        p2p: &Arc<P2PNode>,
2434        peer_id: &PeerId,
2435        pin: [u8; 32],
2436    ) -> Option<crate::replication::commitment::StorageCommitment> {
2437        use crate::replication::config::{PIN_FETCH_TIMEOUT, REPLICATION_PROTOCOL_ID};
2438        use crate::replication::protocol::{
2439            GetCommitmentByPin, GetCommitmentByPinResponse, ReplicationMessage,
2440            ReplicationMessageBody,
2441        };
2442        let msg = ReplicationMessage {
2443            request_id: 0,
2444            body: ReplicationMessageBody::GetCommitmentByPin(GetCommitmentByPin { pin }),
2445        };
2446        let encoded = msg.encode().ok()?;
2447        let resp = p2p
2448            .send_request(peer_id, REPLICATION_PROTOCOL_ID, encoded, PIN_FETCH_TIMEOUT)
2449            .await
2450            .ok()?;
2451        let decoded = ReplicationMessage::decode(&resp.data).ok()?;
2452        let ReplicationMessageBody::GetCommitmentByPinResponse(GetCommitmentByPinResponse::Found {
2453            commitment,
2454        }) = decoded.body
2455        else {
2456            return None; // NotRetained / unexpected -> graced
2457        };
2458        Self::fetched_commitment_is_valid(&commitment, peer_id, pin).then_some(commitment)
2459    }
2460
2461    /// The untrusted-fetched-commitment validation gates, pure over
2462    /// `(commitment, peer_id, pin)` so they are unit-testable. A fetched
2463    /// commitment is accepted only if it passes the SAME gates as a gossip
2464    /// ingest, so a peer cannot answer with another peer's (validly signed)
2465    /// commitment and have it pass as its own:
2466    ///   (a) it is bound to THIS peer (`sender_peer_id == peer_id`),
2467    ///   (b) the embedded pubkey derives that peer id (`BLAKE3(pk) == id`),
2468    ///   (c) its signature is valid (binds the pubkey),
2469    ///   (d) it actually hashes to the pin we asked for.
2470    fn fetched_commitment_is_valid(
2471        commitment: &crate::replication::commitment::StorageCommitment,
2472        peer_id: &PeerId,
2473        pin: [u8; 32],
2474    ) -> bool {
2475        commitment.sender_peer_id == *peer_id.as_bytes()
2476            && *blake3::hash(&commitment.sender_public_key).as_bytes() == commitment.sender_peer_id
2477            && crate::replication::commitment::verify_commitment_signature(commitment)
2478            && crate::replication::commitment::commitment_hash(commitment) == Some(pin)
2479    }
2480
2481    /// Single-node telemetry for off-curve quotes. Always returns; never
2482    /// errors. MUST be called only after ML-DSA-65 signature verification has
2483    /// passed, so unauthenticated peers cannot drive log volume.
2484    fn log_off_curve_single_node(payment: &ProofOfPayment) {
2485        if crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED {
2486            return; // enforce mode already rejected; no separate telemetry.
2487        }
2488        for (encoded_peer_id, quote) in &payment.peer_quotes {
2489            if let Some(detail) = Self::quote_arithmetic_violation(quote) {
2490                warn!(
2491                    "ADR-0004 off-curve single-node quote observed (not enforcing): \
2492                     peer {encoded_peer_id:?} {detail}"
2493                );
2494            }
2495        }
2496    }
2497
2498    /// ADR-0004 sister gate for the merkle batch path: every candidate's
2499    /// `price` field must lie on the pricing curve, by exact recomputation.
2500    /// See [`Self::validate_quote_arithmetic`] for the rationale; semantics
2501    /// (reject-only, rollout-gated, no trust evidence) are identical.
2502    fn validate_merkle_candidate_arithmetic(
2503        pool: &evmlib::merkle_payments::MerklePaymentCandidatePool,
2504    ) -> Result<()> {
2505        if !crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED {
2506            return Ok(());
2507        }
2508        for candidate in &pool.candidate_nodes {
2509            if let Some(detail) = Self::binding_violation(
2510                candidate.committed_key_count,
2511                candidate.commitment_pin,
2512                &candidate.price,
2513            ) {
2514                return Err(Error::Payment(format!(
2515                    "ADR-0004 merkle candidate rejected (reward {}): {detail}",
2516                    candidate.reward_address
2517                )));
2518            }
2519        }
2520        Ok(())
2521    }
2522
2523    /// Merkle batch telemetry for off-curve candidates. Always returns; never
2524    /// errors. MUST be called only after ML-DSA-65 signature verification has
2525    /// passed.
2526    fn log_off_curve_merkle(pool: &evmlib::merkle_payments::MerklePaymentCandidatePool) {
2527        if crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED {
2528            return; // enforce mode already rejected; no separate telemetry.
2529        }
2530        for candidate in &pool.candidate_nodes {
2531            if let Some(detail) = Self::binding_violation(
2532                candidate.committed_key_count,
2533                candidate.commitment_pin,
2534                &candidate.price,
2535            ) {
2536                warn!(
2537                    "ADR-0004 merkle candidate violation observed (not enforcing): \
2538                     reward {} {detail}",
2539                    candidate.reward_address
2540                );
2541            }
2542        }
2543    }
2544
2545    /// ADR-0008 merkle payment-parity telemetry.
2546    ///
2547    /// Records what a batch actually settled per paid node against what
2548    /// single-node parity requires, and which regime the receipt's timestamp put
2549    /// it in. Parity is enforced, so a post-boundary shortfall has already been
2550    /// rejected before this runs and cannot appear here; what this measures is
2551    /// how much traffic is still arriving on pre-boundary (1x) receipts, which
2552    /// is what tells us the compatibility window can be considered closed.
2553    /// Observational only: it never rejects and never feeds trust scoring — a
2554    /// client on a legacy receipt is running old code, not misbehaving.
2555    ///
2556    /// Two call-site requirements, both load-bearing for the signal:
2557    /// - **After full admission validation.** Every paid index, reward address
2558    ///   and amount must already have been checked. Logging earlier lets a
2559    ///   proof that is rejected moments later enter the rollout signal, which
2560    ///   would understate parity with samples that never resulted in a store.
2561    /// - **Store admissions only.** A paid-list admission reprices nothing and
2562    ///   would double-count a batch already measured when it was stored.
2563    ///
2564    /// Keyed by `pool_hash`, not by chunk address: one on-chain settlement
2565    /// covers up to 256 chunks, so a line per chunk would emit 256 duplicate
2566    /// samples of one economic event and let a big batch outvote a small one.
2567    ///
2568    /// Carrying the pool hash in the line is not enough on its own — it makes
2569    /// the stream *deduplicable* but leaves the emitted cardinality at one line
2570    /// per chunk. So the first emission for a pool is recorded in
2571    /// [`Self::merkle_parity_logged`] and later admissions from the same batch
2572    /// return without logging. The check-and-insert is a single locked
2573    /// operation, so concurrent admissions from one batch also produce exactly
2574    /// one line. "Once per pool" is per node/verifier: every storer that admits
2575    /// a chunk from the batch still contributes its own sample, which is what
2576    /// makes the signal a measure of traffic reaching the fleet.
2577    fn log_merkle_parity(
2578        &self,
2579        pool_hash: PoolHash,
2580        payment_info: &OnChainPaymentInfo,
2581        expected_bare: Amount,
2582        expected_parity: Amount,
2583        required_multiplier: u64,
2584    ) {
2585        // Check-and-insert under one lock: the loser of a race sees its own
2586        // insert report a prior entry and stays quiet.
2587        if self
2588            .merkle_parity_logged
2589            .lock()
2590            .put(pool_hash, ())
2591            .is_some()
2592        {
2593            return;
2594        }
2595        self.merkle_parity_emissions
2596            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2597
2598        let min_paid = payment_info
2599            .paid_node_addresses
2600            .iter()
2601            .map(|(_, _, amount)| *amount)
2602            .min()
2603            .unwrap_or(Amount::ZERO);
2604        let at_parity = min_paid >= expected_parity;
2605        let legacy_receipt = required_multiplier < PAID_QUOTE_PAYMENT_MULTIPLIER;
2606
2607        info!(
2608            target: "ant_node::payment::merkle_parity",
2609            "Merkle parity: pool={}, depth={}, paid_nodes={}, receipt_ts={}, \
2610             min_paid={min_paid}, expected_bare={expected_bare}, \
2611             expected_parity={expected_parity}, required_multiplier={required_multiplier}, \
2612             legacy_receipt={legacy_receipt}, at_parity={at_parity}",
2613            hex::encode(pool_hash),
2614            payment_info.depth,
2615            payment_info.paid_node_addresses.len(),
2616            payment_info.merkle_payment_timestamp,
2617        );
2618    }
2619
2620    /// Pure curve-canonicality predicate: does `price` lie exactly on the
2621    /// pricing curve? Equivalent to "there exists some non-negative integer
2622    /// `n` such that `calculate_price(n) == price`".
2623    ///
2624    /// Separated from the rollout-gated outer gates so the canonicality rule
2625    /// itself is unit-testable independent of the gate. Callers MUST use this
2626    /// and not `derive_records_stored_from_price` directly: the latter floors
2627    /// and is not a canonicality test.
2628    ///
2629    /// Saturation: `derive_records_stored_from_price` saturates to `u64::MAX`
2630    /// for prices beyond `calculate_price(u64::MAX)`, and
2631    /// [`Self::candidate_count_to_usize`] saturates to `usize::MAX` on 32-bit
2632    /// targets. Both saturation regimes converge on `calculate_price`'s own
2633    /// saturation ceiling; an honest in-range price (which can never approach
2634    /// these regions — `MAX_COMMITMENT_KEY_COUNT` is `1_000_000`) round-trips
2635    /// exactly.
2636    #[allow(dead_code)] // boolean convenience for tests + follow-up slices
2637    fn quote_price_is_on_curve(price: &Amount) -> bool {
2638        Self::price_off_curve_diagnostics(price).is_none()
2639    }
2640
2641    /// Returns `Some((candidate_count, recomputed))` iff `price` is off-curve;
2642    /// `None` iff `price` is on-curve. The tuple is the diagnostic detail used
2643    /// by both the rejection error message and the telemetry warning.
2644    fn price_off_curve_diagnostics(price: &Amount) -> Option<(u64, Amount)> {
2645        let candidate_count = derive_records_stored_from_price(*price);
2646        let recomputed = calculate_price(Self::candidate_count_to_usize(candidate_count));
2647        if recomputed == *price {
2648            None
2649        } else {
2650            Some((candidate_count, recomputed))
2651        }
2652    }
2653
2654    /// Narrow the canonicality predicate's `u64` candidate into `usize` for
2655    /// [`calculate_price`]. On every 64-bit target (the only supported
2656    /// production target) this is the identity; on 32-bit targets we saturate
2657    /// to `usize::MAX`, which matches `calculate_price`'s own
2658    /// `Amount::saturating_mul` behaviour so the round-trip still terminates
2659    /// in the same saturation regime rather than panicking.
2660    fn candidate_count_to_usize(candidate_count: u64) -> usize {
2661        usize::try_from(candidate_count).unwrap_or(usize::MAX)
2662    }
2663
2664    /// Minimum number of candidate `pub_keys` (out of 16) whose derived
2665    /// `PeerId` must be among the DHT's actual closest peers to the pool
2666    /// midpoint address for the pool to be accepted.
2667    ///
2668    /// Set to a simple majority (9/16). Two nodes' views of the closest set
2669    /// to a midpoint diverge on a young, high-churn, NAT-heavy network — by
2670    /// more than a near-unanimous threshold tolerates — so a stricter bar
2671    /// rejected honest pools whose candidates are genuinely drawn from the
2672    /// midpoint's close group but don't all reappear in this storer's own
2673    /// lookup. A majority absorbs that divergence while still requiring most
2674    /// candidates to be real peers the live DHT lists as closest.
2675    ///
2676    /// Security cost: a lower threshold widens the room for the "pay-yourself"
2677    /// attack — an attacker running real neighbourhood peers needs fewer of
2678    /// them to clear a majority than to clear a near-unanimous bar. No theft
2679    /// of funds is possible regardless (payment binds on-chain to the rewards
2680    /// address); the cost is that grinding storage payments back to your own
2681    /// nodes gets cheaper. Each counted candidate must still be a peer the
2682    /// live DHT actually returns as closest — a fabricated off-network key
2683    /// cannot satisfy this — so the floor is "run N real top-K Sybil nodes
2684    /// AND grind the midpoint", just with a smaller N. Pairs with the planned
2685    /// pool-midpoint consensus-anchor work, which removes the midpoint
2686    /// grinding freedom that makes a low threshold dangerous.
2687    const CANDIDATE_CLOSENESS_REQUIRED: usize = 9;
2688
2689    /// Timeout for the authoritative network lookup used by the closeness
2690    /// check.
2691    ///
2692    /// Iterative Kademlia lookups can cascade through `MAX_ITERATIONS = 20`
2693    /// rounds in saorsa-core's `find_closest_nodes_network`, and a single
2694    /// unresponsive peer's dial can take 20–30s before timing out. On a
2695    /// young network (e.g. fresh testnet, NAT-simulated peers in 30% of
2696    /// the swarm) iterations average ~10s each — captured trace from
2697    /// STG-01 EWR-3 ant-node-1 just before a pre-fix timeout:
2698    ///
2699    /// ```text
2700    /// Iter 0: +0.0s | Iter 1: +0.2s | Iter 2: +6.6s | Iter 3: +13.1s
2701    /// Iter 4: +20.9s | Iter 5: +39.8s | Iter 6: +50.8s | [60s wall]
2702    /// ```
2703    ///
2704    /// 60s caps the lookup at ~7 iterations and rejects honest pools whose
2705    /// candidates only emerge after iteration 7. 240s gives ~1.2× headroom
2706    /// over the ~200s natural worst-case runtime on a 1k-node testnet.
2707    ///
2708    /// `DoS` amplification stays bounded at roughly one in-flight lookup
2709    /// per unique `pool_hash` under typical load, via
2710    /// [`closeness_pass_cache`] + [`inflight_closeness`]. The bound is
2711    /// "typical" because `inflight_closeness` is an LRU and a sustained
2712    /// flood of unique `pool_hash` entries can evict an in-flight slot,
2713    /// at which point a second leader can race for the same pool (see
2714    /// [`InflightGuard::drop`]). At steady state the pool cache and pool
2715    /// signature verification gate keep this rare in practice.
2716    const CLOSENESS_LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(240);
2717
2718    /// Width of the storer's authoritative network lookup, in peers.
2719    ///
2720    /// The client over-queries `2 * CANDIDATES_PER_POOL = 32` peers via
2721    /// `find_closest_peers(addr, 32)` (see
2722    /// `ant-client/ant-core/src/data/client/merkle.rs::get_merkle_candidate_pool`)
2723    /// and selects 16 valid responders by XOR distance — so truly-close
2724    /// peers that are slow, NAT'd, or briefly unreachable get filtered
2725    /// out and replaced by peers from positions 17–32 of the network's
2726    /// actual ranking. The storer must therefore verify against the same
2727    /// wider window: a pool containing peers from positions 17–32 is
2728    /// honest (those peers really exist in the network's closest-32 set),
2729    /// it's just that the client's quote-collection step couldn't reach
2730    /// the peers at positions <17 in time.
2731    ///
2732    /// Empirical effect on STG-01 (1k-node testnet, 30% NAT-simulated):
2733    /// widening from K=16 to K=32 dropped client-side closeness
2734    /// mismatches from ~115 to ~31 per 5 min, a 73% reduction.
2735    ///
2736    /// Performance note: `count` does not just truncate the lookup —
2737    /// `find_closest_nodes_network` keeps iterating until either
2738    /// `MAX_ITERATIONS` is reached or `best_nodes.len() >= count`. K=32
2739    /// can therefore extend lookups by a few iterations on sparse
2740    /// networks vs K=16, which reinforces (rather than undermines) the
2741    /// timeout bump above.
2742    ///
2743    /// Security: the pay-yourself attack still requires the attacker's
2744    /// fabricated `PeerId`s to land in the storer's authoritative top-K, so
2745    /// the dominant cost is Sybil-grinding midpoint addresses or running real
2746    /// nodes near the target. The leniency for honest divergence comes from
2747    /// the `CANDIDATE_CLOSENESS_REQUIRED` majority threshold, not from this
2748    /// window; widening the window further was measured as too heavy on the
2749    /// lookup path.
2750    const CLOSENESS_LOOKUP_WIDTH: usize = 2 * evmlib::merkle_payments::CANDIDATES_PER_POOL;
2751
2752    /// Maximum waiter → leader retries when the leader's future was cancelled
2753    /// or panicked before publishing a result. Beyond this the waiter returns
2754    /// a visible error rather than spinning indefinitely through a
2755    /// cancellation cascade.
2756    ///
2757    /// Worst-case waiter wall-clock is `(MAX_LEADER_RETRIES + 1) *
2758    /// CLOSENESS_LOOKUP_TIMEOUT` (one wait per attempt). Kept low (1)
2759    /// because the only realistic trigger is leader future-cancellation,
2760    /// which should be extraordinarily rare; under sustained adversarial
2761    /// cancellation a higher cap doesn't add resilience, it just hides
2762    /// the symptom. With `CLOSENESS_LOOKUP_TIMEOUT = 240s` this caps a
2763    /// single user-visible verification at ~8 min worst case (vs ~20 min
2764    /// at the previous value of 4).
2765    const MAX_LEADER_RETRIES: usize = 1;
2766
2767    /// Compute the storer's authoritative-lookup width for a candidate pool.
2768    ///
2769    /// Returns `max(CLOSENESS_LOOKUP_WIDTH, pool_len)`: matches the client's
2770    /// over-query width today, and scales with the pool if a future protocol
2771    /// bump grows pool size beyond `CLOSENESS_LOOKUP_WIDTH`. Truncating to
2772    /// `CLOSENESS_LOOKUP_WIDTH` in that future case would re-open the
2773    /// K-too-small failure mode (the storer would reject honest pools whose
2774    /// candidates legitimately span a wider XOR range than the storer
2775    /// fetched). Pinned by `closeness_lookup_count_uses_max_of_width_and_pool_len`.
2776    const fn closeness_lookup_count(pool_len: usize) -> usize {
2777        if Self::CLOSENESS_LOOKUP_WIDTH > pool_len {
2778            Self::CLOSENESS_LOOKUP_WIDTH
2779        } else {
2780            pool_len
2781        }
2782    }
2783
2784    /// Verify that the candidate pool's `pub_keys` correspond to peers that
2785    /// are actually XOR-closest to the pool midpoint address, by querying
2786    /// the DHT for its closest peers to that address and requiring that a
2787    /// majority of the candidates match.
2788    ///
2789    /// **What this blocks**: the "pay yourself" attack. Candidate signatures
2790    /// only cover `(price, reward_address, timestamp)` and the `pub_key` bytes —
2791    /// nothing ties a candidate to a network-registered identity or to the
2792    /// pool neighbourhood. Without this check an attacker can generate 16
2793    /// ML-DSA keypairs locally, point all 16 `reward_address` fields at a
2794    /// single attacker-controlled wallet, submit the merkle payment, and drain
2795    /// their own payment back out.
2796    ///
2797    /// **How it blocks**: each candidate's `PeerId = BLAKE3(pub_key)`; the DHT
2798    /// is the authoritative source of "which peers exist at this XOR
2799    /// coordinate". If the attacker's 16 fabricated `PeerId`s are not among
2800    /// the peers the network actually lists as closest to the pool address,
2801    /// the pool is forged.
2802    ///
2803    /// **Scope**: a `MerklePaymentProof` carries exactly one `winner_pool`
2804    /// (the pool the smart contract selected for the batch). Every storing
2805    /// node that receives the proof independently re-runs this check against
2806    /// that same pool, so a forged pool is rejected at every node it
2807    /// reaches.
2808    ///
2809    /// **Known limitation — Sybil-grinding**: `midpoint_proof.address()` is a
2810    /// BLAKE3 hash of attacker-controllable inputs (leaf bytes, tree root,
2811    /// timestamp). A determined attacker who *also* runs Sybil DHT nodes can
2812    /// grind the midpoint until it lands in a region where a majority of
2813    /// their Sybil keys are the true network-closest — at which point this check
2814    /// passes for the attacker. Closing that gap requires binding the
2815    /// midpoint to an attacker-uncontrolled value (e.g. a block hash at
2816    /// payment time or an on-chain VRF) or a Sybil-resistant identity
2817    /// layer. This defence raises the attack cost from "free" to "run N
2818    /// Sybil nodes AND grind", which is a meaningful but not complete
2819    /// improvement.
2820    async fn verify_merkle_candidate_closeness(
2821        &self,
2822        pool: &evmlib::merkle_payments::MerklePaymentCandidatePool,
2823        pool_hash: PoolHash,
2824    ) -> Result<()> {
2825        // Fast path: this node already verified this pool successfully.
2826        // A batch of 256 chunks shares one winner_pool, so without this cache
2827        // we'd pay a Kademlia lookup per chunk.
2828        if self.closeness_pass_cache.lock().get(&pool_hash).is_some() {
2829            return Ok(());
2830        }
2831
2832        // Single-flight: on each attempt, either claim leadership by
2833        // inserting a fresh `ClosenessSlot`, or wait on an existing leader
2834        // and read its published result. The leader holds an `Arc` to the
2835        // slot independent of the LruCache so waiters are still woken if
2836        // eviction pressure kicked the cache entry.
2837        //
2838        // The `notified_owned()` future snapshots the `notify_waiters`
2839        // counter at the moment of construction (while we hold the lock),
2840        // which makes the subsequent `.await` race-free: if the leader
2841        // calls `notify_waiters` between our construction and our poll, the
2842        // counter has advanced and the future resolves immediately on first
2843        // poll.
2844        //
2845        // Bounded retry: if we're a waiter and the leader gets cancelled or
2846        // panics (slot.result.get() == None after wake-up), we loop back to
2847        // claim leadership. `MAX_LEADER_RETRIES` bounds the attempts so
2848        // adversarial cancellation cascades cannot spin this indefinitely.
2849        for attempt in 0..=Self::MAX_LEADER_RETRIES {
2850            // Release the mutex guard explicitly before any await below.
2851            // Clippy wants `if let ... else` written as `map_or_else`, but
2852            // any such rewrite re-borrows the locked `inflight` inside the
2853            // closure and fails the borrow checker — so the lint is
2854            // silenced here.
2855            #[allow(clippy::option_if_let_else)]
2856            let (waiter_slot, leader_slot) = {
2857                let mut inflight = self.inflight_closeness.lock();
2858                let chosen = if let Some(existing) = inflight.get(&pool_hash) {
2859                    (Some(Arc::clone(existing)), None)
2860                } else {
2861                    let slot = Arc::new(ClosenessSlot::new());
2862                    inflight.put(pool_hash, Arc::clone(&slot));
2863                    (None, Some(slot))
2864                };
2865                drop(inflight);
2866                chosen
2867            };
2868
2869            if let Some(slot) = waiter_slot {
2870                // Build the owned-notified future BEFORE awaiting, so it
2871                // snapshots the `notify_waiters` counter now. The slot
2872                // already existed when we locked, so the leader is either
2873                // running or finished; in both cases the snapshot + counter
2874                // check ensures we wake up correctly.
2875                let notified = slot.notified_owned();
2876                notified.await;
2877
2878                // Leader published a result — use it directly.
2879                if let Some(result) = slot.result.get() {
2880                    return result.clone().map_err(Error::Payment);
2881                }
2882                // Leader disappeared without publishing (panic or
2883                // cancellation). Slot was cleared by the leader's drop
2884                // guard; loop to become the new leader — unless we've
2885                // hit the retry bound (see MAX_LEADER_RETRIES).
2886                if attempt == Self::MAX_LEADER_RETRIES {
2887                    return Err(Error::Payment(
2888                        "Merkle candidate pool rejected: closeness leader \
2889                         repeatedly failed to publish a result (likely \
2890                         repeated cancellation or panic)."
2891                            .into(),
2892                    ));
2893                }
2894                continue;
2895            }
2896
2897            // Leader path. Drop guard clears the slot and wakes waiters on
2898            // every exit (success, failure, panic, cancellation).
2899            let Some(slot) = leader_slot else {
2900                // Unreachable by construction.
2901                return Err(Error::Payment(
2902                    "internal error: neither leader nor waiter in closeness check".into(),
2903                ));
2904            };
2905            let guard = InflightGuard {
2906                slot_cache: &self.inflight_closeness,
2907                pool_hash,
2908                slot,
2909            };
2910
2911            let result = self.verify_merkle_candidate_closeness_inner(pool).await;
2912            guard.publish(&result);
2913            if result.is_ok() {
2914                self.closeness_pass_cache.lock().put(pool_hash, ());
2915            }
2916            return result;
2917        }
2918        // Unreachable: the for-loop body always either `return`s or `continue`s,
2919        // and the waiter branch's `continue` only runs when `attempt <
2920        // Self::MAX_LEADER_RETRIES`. The last iteration's waiter branch returns
2921        // via the retry-bound check; the leader branch always returns.
2922        Err(Error::Payment(
2923            "internal error: closeness retry loop exited without returning".into(),
2924        ))
2925    }
2926
2927    /// Inner closeness check: the actual DHT lookup + set-membership test.
2928    /// Wrapped by [`verify_merkle_candidate_closeness`] with a pass-cache and
2929    /// single-flight guard so a batch of chunks and a storm of forged PUTs
2930    /// don't multiply the lookup cost.
2931    /// Derive each candidate's `PeerId` from its `pub_key` and reject the
2932    /// pool if any `PeerId` appears more than once.
2933    ///
2934    /// This is a pure-validation pre-check, runnable without a `P2PNode`:
2935    /// catches the case where one real peer's `pub_key` is repeated to
2936    /// inflate the closeness match count, without paying for a Kademlia
2937    /// lookup. An honest pool has [`evmlib::merkle_payments::CANDIDATES_PER_POOL`]
2938    /// distinct candidate `pub_keys` by construction.
2939    fn derive_distinct_candidate_peer_ids(
2940        pool: &evmlib::merkle_payments::MerklePaymentCandidatePool,
2941    ) -> Result<Vec<PeerId>> {
2942        let mut candidate_peer_ids = Vec::with_capacity(pool.candidate_nodes.len());
2943        let mut seen = std::collections::HashSet::with_capacity(pool.candidate_nodes.len());
2944        for candidate in &pool.candidate_nodes {
2945            let pid = peer_id_from_public_key_bytes(&candidate.pub_key).map_err(|e| {
2946                Error::Payment(format!(
2947                    "Invalid ML-DSA public key in merkle candidate: {e}"
2948                ))
2949            })?;
2950            if !seen.insert(pid) {
2951                return Err(Error::Payment(
2952                    "Merkle candidate pool rejected: duplicate candidate PeerId. An \
2953                     honest pool has 16 distinct candidate pub_keys; duplicates would \
2954                     let a single real peer satisfy the closeness threshold by being \
2955                     counted multiple times."
2956                        .into(),
2957                ));
2958            }
2959            candidate_peer_ids.push(pid);
2960        }
2961        Ok(candidate_peer_ids)
2962    }
2963
2964    /// Pure-logic closeness check: given the pool's candidate peer IDs and
2965    /// the storer's authoritative network view (closest peers to the pool
2966    /// midpoint), decide whether the pool passes the
2967    /// `CANDIDATE_CLOSENESS_REQUIRED`-of-N threshold.
2968    ///
2969    /// A candidate counts only if its `PeerId` is one of the peers the
2970    /// storer's own network lookup returned (exact set membership). This is
2971    /// the property that makes the gate meaningful: a passing candidate must
2972    /// be a real, reachable peer the live DHT actually routes to and lists
2973    /// among the closest — it cannot be a key fabricated off-network. The
2974    /// leniency in this check is purely the lowered threshold (a majority
2975    /// rather than near-unanimity), which tolerates the closest-set
2976    /// divergence between two nodes' views without admitting fabricated keys.
2977    ///
2978    /// Extracted from `verify_merkle_candidate_closeness_inner` so tests
2979    /// can exercise the matching logic without standing up a real DHT.
2980    /// Mirrors the runtime path exactly: same sparse-network short-circuit,
2981    /// same set-membership check, same error strings.
2982    fn check_closeness_match(
2983        candidate_peer_ids: &[PeerId],
2984        network_peer_ids: &[PeerId],
2985        pool_address: &[u8; 32],
2986    ) -> Result<()> {
2987        // Sparse-network short-circuit: if the DHT itself returned fewer
2988        // peers than the closeness threshold, the proof can never pass —
2989        // not because the candidates are forged, but because we don't
2990        // have an authoritative view to compare against. Surface this
2991        // distinct cause so operators can tell "retry once the network
2992        // settles" apart from "this peer sent a forged pool".
2993        if network_peer_ids.len() < Self::CANDIDATE_CLOSENESS_REQUIRED {
2994            debug!(
2995                "Merkle closeness deferred: network lookup returned {} peers \
2996                 for pool midpoint {} (need at least {} to verify)",
2997                network_peer_ids.len(),
2998                hex::encode(pool_address),
2999                Self::CANDIDATE_CLOSENESS_REQUIRED,
3000            );
3001            return Err(Error::Payment(format!(
3002                "Merkle candidate pool rejected: authoritative DHT lookup returned \
3003                 only {} peers, less than the {} required to verify candidate \
3004                 closeness. Retry once the routing table populates further.",
3005                network_peer_ids.len(),
3006                Self::CANDIDATE_CLOSENESS_REQUIRED,
3007            )));
3008        }
3009
3010        // Exact-match membership against the returned closest peers.
3011        // Candidate `PeerId`s are deduplicated upstream, so each match
3012        // corresponds to a distinct peer.
3013        let network_set: std::collections::HashSet<PeerId> =
3014            network_peer_ids.iter().copied().collect();
3015        let matched = candidate_peer_ids
3016            .iter()
3017            .filter(|pid| network_set.contains(pid))
3018            .count();
3019
3020        if matched < Self::CANDIDATE_CLOSENESS_REQUIRED {
3021            debug!(
3022                "Merkle closeness rejected: {matched}/{} candidates match the DHT's closest peers \
3023                 for pool midpoint {} (required: {}, network returned {} peers)",
3024                candidate_peer_ids.len(),
3025                hex::encode(pool_address),
3026                Self::CANDIDATE_CLOSENESS_REQUIRED,
3027                network_peer_ids.len(),
3028            );
3029            return Err(Error::Payment(
3030                "Merkle candidate pool rejected: candidate pub_keys do not match the \
3031                 network's closest peers to the pool midpoint address. Pools must be \
3032                 collected from the pool-address close group, not fabricated off-network."
3033                    .into(),
3034            ));
3035        }
3036
3037        debug!(
3038            "Merkle closeness passed: {matched}/{} candidates matched the DHT's closest peers \
3039             for pool midpoint {}",
3040            candidate_peer_ids.len(),
3041            hex::encode(pool_address),
3042        );
3043        Ok(())
3044    }
3045
3046    #[allow(clippy::too_many_lines)]
3047    async fn verify_merkle_candidate_closeness_inner(
3048        &self,
3049        pool: &evmlib::merkle_payments::MerklePaymentCandidatePool,
3050    ) -> Result<()> {
3051        // Pre-check: catch malformed/hostile pools (duplicate candidate
3052        // PeerIds) before paying for the Kademlia lookup. Runs in unit
3053        // tests without a P2PNode too.
3054        let candidate_peer_ids = Self::derive_distinct_candidate_peer_ids(pool)?;
3055
3056        // Release the RwLock guard before any await to avoid holding it
3057        // across an iterative Kademlia lookup.
3058        let attached = self.p2p_node.read().as_ref().map(Arc::clone);
3059        let Some(p2p_node) = attached else {
3060            // Production must call attach_p2p_node at startup. Fail CLOSED
3061            // to avoid silently disabling the defence if a startup path
3062            // regresses and loses the attach call. Unit-test builds that
3063            // construct a PaymentVerifier directly without exercising merkle
3064            // verification are opted-in via `test-utils` to fall back to
3065            // fail-open.
3066            #[cfg(any(test, feature = "test-utils"))]
3067            {
3068                crate::logging::warn!(
3069                    "PaymentVerifier: no P2PNode attached; merkle pay-yourself \
3070                     defence SKIPPED (test build). Production startup MUST call \
3071                     PaymentVerifier::attach_p2p_node."
3072                );
3073                return Ok(());
3074            }
3075            #[cfg(not(any(test, feature = "test-utils")))]
3076            {
3077                crate::logging::error!(
3078                    "PaymentVerifier: no P2PNode attached; rejecting merkle \
3079                     payment. This is a node-startup bug — \
3080                     PaymentVerifier::attach_p2p_node must be called before \
3081                     any PUT handler runs."
3082                );
3083                return Err(Error::Payment(
3084                    "Merkle candidate pool rejected: verifier is not wired to \
3085                     the P2P layer; cannot verify candidate closeness."
3086                        .into(),
3087                ));
3088            }
3089        };
3090
3091        let pool_address = pool.midpoint_proof.address();
3092        // Match the client's over-query width. The client's
3093        // `get_merkle_candidate_pool` queries 2 × `CANDIDATES_PER_POOL` peers
3094        // and picks the 16 closest *valid responders* — so legitimate pools
3095        // routinely include peers from positions 17–32 of the network's true
3096        // ranking when the closer peers are slow or NAT-stuck. The storer
3097        // must look at the same window or it will reject honest pools with
3098        // no security benefit.
3099        //
3100        // `pool.candidate_nodes` is currently a fixed-size array of length
3101        // `CANDIDATES_PER_POOL` (= 16), so `.max(...)` always evaluates to
3102        // `CLOSENESS_LOOKUP_WIDTH` today. The compile-time
3103        // `const _: () = assert!(WIDTH >= CANDIDATES_PER_POOL)` in the test
3104        // module pins that invariant. The `.max(...)` form is belt-and-braces
3105        // for a hypothetical future protocol that grows pool size to a
3106        // `Vec`-typed candidate set: the storer would scale its lookup with
3107        // the pool rather than truncating, which would otherwise re-open the
3108        // K-too-small failure mode.
3109        let lookup_count = Self::closeness_lookup_count(pool.candidate_nodes.len());
3110        let network_lookup = p2p_node
3111            .dht_manager()
3112            .find_closest_nodes_network(&pool_address.0, lookup_count);
3113        let network_peers =
3114            match tokio::time::timeout(Self::CLOSENESS_LOOKUP_TIMEOUT, network_lookup).await {
3115                Ok(Ok(peers)) => peers,
3116                Ok(Err(e)) => {
3117                    debug!(
3118                        "Merkle closeness network-lookup failed for pool midpoint {}: {e}",
3119                        hex::encode(pool_address.0),
3120                    );
3121                    return Err(Error::Payment(
3122                        "Merkle candidate pool rejected: could not verify candidate \
3123                     closeness against the authoritative network view."
3124                            .into(),
3125                    ));
3126                }
3127                Err(_) => {
3128                    debug!(
3129                        "Merkle closeness network-lookup timeout ({:?}) for pool midpoint {}",
3130                        Self::CLOSENESS_LOOKUP_TIMEOUT,
3131                        hex::encode(pool_address.0),
3132                    );
3133                    return Err(Error::Payment(
3134                        "Merkle candidate pool rejected: authoritative network lookup \
3135                     timed out. Retry once the network lookup completes."
3136                            .into(),
3137                    ));
3138                }
3139            };
3140
3141        let network_peer_ids: Vec<PeerId> = network_peers.iter().map(|n| n.peer_id).collect();
3142        Self::check_closeness_match(&candidate_peer_ids, &network_peer_ids, &pool_address.0)
3143    }
3144
3145    /// Verify a merkle batch payment proof.
3146    ///
3147    /// This verification flow:
3148    /// 1. Deserialize the `MerklePaymentProof`
3149    /// 2. Check pool cache for previously verified pool hash
3150    /// 3. If not cached, query on-chain for payment info
3151    /// 4. Validate the proof against on-chain data
3152    /// 5. Cache the pool hash for subsequent chunk verifications in the same batch
3153    #[allow(clippy::too_many_lines)]
3154    async fn verify_merkle_payment(
3155        &self,
3156        xorname: &XorName,
3157        proof_bytes: &[u8],
3158        context: VerificationContext,
3159    ) -> Result<()> {
3160        if crate::logging::enabled!(crate::logging::Level::DEBUG) {
3161            debug!(
3162                "Verifying merkle payment for {} ({context:?})",
3163                hex::encode(xorname)
3164            );
3165        }
3166
3167        // Deserialize the merkle proof
3168        let merkle_proof = deserialize_merkle_proof(proof_bytes)
3169            .map_err(|e| Error::Payment(format!("Failed to deserialize merkle proof: {e}")))?;
3170
3171        // Verify the address in the proof matches the xorname being stored
3172        if merkle_proof.address.0 != *xorname {
3173            let proof_hex = hex::encode(merkle_proof.address.0);
3174            let store_hex = hex::encode(xorname);
3175            return Err(Error::Payment(format!(
3176                "Merkle proof address mismatch: proof is for {proof_hex}, but storing {store_hex}"
3177            )));
3178        }
3179
3180        let pool_hash = merkle_proof.winner_pool_hash();
3181
3182        // Run cheap local checks BEFORE expensive on-chain queries.
3183        // This prevents DoS via garbage proofs that trigger RPC lookups.
3184        for candidate in &merkle_proof.winner_pool.candidate_nodes {
3185            if !crate::payment::verify_merkle_candidate_signature(candidate) {
3186                return Err(Error::Payment(format!(
3187                    "Invalid ML-DSA-65 signature on merkle candidate node (reward: {})",
3188                    candidate.reward_address
3189                )));
3190            }
3191        }
3192
3193        // ADR-0004: every storer re-runs the price-equals-formula-of-count
3194        // check on every merkle candidate, in every context, before median
3195        // reconstruction. Runs AFTER signature verification so observe-only
3196        // telemetry cannot be spoofed by unauthenticated senders. Reject-only
3197        // when enforcement is enabled; no trust evidence emitted in either
3198        // mode.
3199        Self::validate_merkle_candidate_arithmetic(&merkle_proof.winner_pool)?;
3200        Self::log_off_curve_merkle(&merkle_proof.winner_pool);
3201
3202        // Pay-yourself defence: the candidate pub_keys must map to peers the
3203        // live DHT actually considers closest to the pool midpoint. Without
3204        // this, an attacker can point all 16 reward_address fields at a
3205        // self-owned wallet and drain their own payment. Every storing node
3206        // runs this check against the single `winner_pool` in the proof, so a
3207        // forged pool is rejected everywhere it lands. The pass cache and
3208        // single-flight keyed on pool_hash collapse the Kademlia lookup cost
3209        // within a batch and across concurrent PUTs for the same pool.
3210        //
3211        self.verify_merkle_candidate_closeness(&merkle_proof.winner_pool, pool_hash)
3212            .await?;
3213
3214        // Check pool cache first
3215        let cached_info = {
3216            let mut pool_cache = self.pool_cache.lock();
3217            pool_cache.get(&pool_hash).cloned()
3218        };
3219
3220        let payment_info = if let Some(info) = cached_info {
3221            debug!("Pool cache hit for hash {}", hex::encode(pool_hash));
3222            info
3223        } else {
3224            // Query on-chain for completed merkle payment
3225            let info =
3226                payment_vault::get_completed_merkle_payment(&self.config.evm.network, pool_hash)
3227                    .await
3228                    .map_err(|e| {
3229                        let pool_hex = hex::encode(pool_hash);
3230                        Error::Payment(format!(
3231                            "Failed to query merkle payment info for pool {pool_hex}: {e}"
3232                        ))
3233                    })?;
3234
3235            let paid_node_addresses: Vec<_> = info
3236                .paidNodeAddresses
3237                .iter()
3238                .map(|pna| (pna.rewardsAddress, usize::from(pna.poolIndex), pna.amount))
3239                .collect();
3240
3241            let on_chain_info = OnChainPaymentInfo {
3242                depth: info.depth,
3243                merkle_payment_timestamp: info.merklePaymentTimestamp,
3244                paid_node_addresses,
3245            };
3246
3247            // Cache the pool info for subsequent chunks in the same batch
3248            {
3249                let mut pool_cache = self.pool_cache.lock();
3250                pool_cache.put(pool_hash, on_chain_info.clone());
3251            }
3252
3253            debug!(
3254                "Queried on-chain merkle payment info for pool {}: depth={}, timestamp={}, paid_nodes={}",
3255                hex::encode(pool_hash),
3256                on_chain_info.depth,
3257                on_chain_info.merkle_payment_timestamp,
3258                on_chain_info.paid_node_addresses.len()
3259            );
3260
3261            on_chain_info
3262        };
3263
3264        // Verify timestamp consistency (signatures already checked above before RPC).
3265        for candidate in &merkle_proof.winner_pool.candidate_nodes {
3266            if candidate.merkle_payment_timestamp != payment_info.merkle_payment_timestamp {
3267                return Err(Error::Payment(format!(
3268                    "Candidate timestamp mismatch: expected {}, got {} (reward: {})",
3269                    payment_info.merkle_payment_timestamp,
3270                    candidate.merkle_payment_timestamp,
3271                    candidate.reward_address
3272                )));
3273            }
3274        }
3275
3276        // Get the root from the winner pool's midpoint proof
3277        let smart_contract_root = merkle_proof.winner_pool.midpoint_proof.root();
3278
3279        // Verify the cryptographic merkle proofs (address belongs to tree,
3280        // midpoint belongs to tree, roots match, timestamps valid).
3281        evmlib::merkle_payments::verify_merkle_proof(
3282            &merkle_proof.address,
3283            &merkle_proof.data_proof,
3284            &merkle_proof.winner_pool.midpoint_proof,
3285            payment_info.depth,
3286            smart_contract_root,
3287            payment_info.merkle_payment_timestamp,
3288        )
3289        .map_err(|e| {
3290            let xorname_hex = hex::encode(xorname);
3291            Error::Payment(format!(
3292                "Merkle proof verification failed for {xorname_hex}: {e}"
3293            ))
3294        })?;
3295
3296        // Verify paid node count matches depth
3297        let expected_depth = payment_info.depth as usize;
3298        let actual_paid = payment_info.paid_node_addresses.len();
3299        if actual_paid != expected_depth {
3300            return Err(Error::Payment(format!(
3301                "Wrong number of paid nodes: expected {expected_depth}, got {actual_paid}"
3302            )));
3303        }
3304
3305        // Expected per-node payment from the contract formula. ADR-0008: which
3306        // multiplier is REQUIRED depends on when the receipt was stamped —
3307        // 3x from the parity boundary onward, the historic 1x before it, since
3308        // that money was already spent under the old rule. The expiry check
3309        // above bounds the legacy branch: no receipt older than a week is
3310        // valid, so the branch is unreachable one week past the boundary.
3311        let candidate_prices: Vec<Amount> = merkle_proof
3312            .winner_pool
3313            .candidate_nodes
3314            .iter()
3315            .map(|c| c.price)
3316            .collect();
3317        let parity_from = *self.merkle_parity_from.read();
3318        let required_multiplier =
3319            merkle_required_multiplier(payment_info.merkle_payment_timestamp, parity_from);
3320        let expected_per_node_bare =
3321            merkle_expected_per_node(&candidate_prices, payment_info.depth, 1)?;
3322        let expected_per_node_parity = merkle_expected_per_node(
3323            &candidate_prices,
3324            payment_info.depth,
3325            PAID_QUOTE_PAYMENT_MULTIPLIER,
3326        )?;
3327        let expected_per_node =
3328            merkle_expected_per_node(&candidate_prices, payment_info.depth, required_multiplier)?;
3329
3330        // Verify paid node indices, addresses, and amounts against the candidate pool.
3331        //
3332        // Each paid node must:
3333        // 1. Have a valid index within the candidate pool
3334        // 2. Match the expected reward address at that index
3335        // 3. Have been paid at least `expected_per_node`, which is the contract
3336        //    formula `median16(prices) * 2^depth / depth` at the multiplier the
3337        //    receipt's own timestamp selects (3x from the parity boundary, the
3338        //    historic 1x before it). Do NOT re-assume the 1x formula here —
3339        //    read `expected_per_node` rather than recomputing it.
3340        //
3341        // Note: unlike single-node payments, merkle proofs are NOT bound to a
3342        // specific storing node. The contract pays `depth` random nodes from the
3343        // winner pool; the storing node is whichever close-group peer the client
3344        // routes the chunk to. There is no local-recipient check here because
3345        // any node that can verify the merkle proof is allowed to store the chunk.
3346        // Replay protection comes from the per-address proof binding (each proof
3347        // is for a specific XorName in the paid tree).
3348        for (addr, idx, paid_amount) in &payment_info.paid_node_addresses {
3349            let node = merkle_proof
3350                .winner_pool
3351                .candidate_nodes
3352                .get(*idx)
3353                .ok_or_else(|| {
3354                    Error::Payment(format!(
3355                        "Paid node index {idx} out of bounds for pool size {}",
3356                        merkle_proof.winner_pool.candidate_nodes.len()
3357                    ))
3358                })?;
3359            if node.reward_address != *addr {
3360                return Err(Error::Payment(format!(
3361                    "Paid node address mismatch at index {idx}: expected {addr}, got {}",
3362                    node.reward_address
3363                )));
3364            }
3365            if *paid_amount < expected_per_node {
3366                return Err(Error::Payment(format!(
3367                    "Underpayment for node at index {idx}: paid {paid_amount}, \
3368                     expected at least {expected_per_node} \
3369                     (median16 formula, depth={}, {required_multiplier}x required for a \
3370                     receipt stamped {} vs parity boundary {parity_from})",
3371                    payment_info.depth, payment_info.merkle_payment_timestamp
3372                )));
3373            }
3374        }
3375
3376        if crate::logging::enabled!(crate::logging::Level::INFO) {
3377            info!(
3378                "Merkle payment verified for {} (pool: {})",
3379                hex::encode(xorname),
3380                hex::encode(pool_hash)
3381            );
3382        }
3383
3384        // ADR-0008 parity telemetry, emitted only now: every paid index, reward
3385        // address and amount above has been validated, so a proof that is
3386        // rejected later in this function can never enter the rollout signal.
3387        // Store admissions only, matching the cross-check below — a paid-list
3388        // receipt reprices no fresh economic decision and would otherwise
3389        // double-count a batch already measured at its store admission.
3390        // `log_merkle_parity` itself drops all but the first admission per
3391        // pool, so a 256-chunk batch contributes one line here, not 256.
3392        if context.is_store_admission() {
3393            self.log_merkle_parity(
3394                pool_hash,
3395                &payment_info,
3396                expected_per_node_bare,
3397                expected_per_node_parity,
3398                required_multiplier,
3399            );
3400        }
3401
3402        // ADR-0004: route the merkle-batch candidates through the SAME
3403        // cross-check + first-audit funnel as single-node quotes, AFTER on-chain
3404        // verification has succeeded (so an unpaid pool cannot drive audits or
3405        // fetches). Store admissions only (direct PUT + immediate fresh
3406        // replication, the paths that previously verified under `ClientPut`) —
3407        // a paid-list receipt's pins have aged out.
3408        // Amendment 2: only the candidates the contract actually PAID
3409        // (`paid_node_addresses` indices, verified above) are nominated for
3410        // first audits; the rest of the pool merely established the median.
3411        if context.is_store_admission() {
3412            let paid_indices: std::collections::HashSet<usize> = payment_info
3413                .paid_node_addresses
3414                .iter()
3415                .map(|(_, idx, _)| *idx)
3416                .collect();
3417            self.cross_check_merkle_candidates(
3418                &merkle_proof.winner_pool,
3419                &merkle_proof.commitment_sidecars,
3420                &paid_indices,
3421            )
3422            .await;
3423        }
3424
3425        Ok(())
3426    }
3427
3428    /// ADR-0004 cross-check for the merkle-batch path: every candidate carries
3429    /// the same signed `(committed_key_count, commitment_pin)` binding as a
3430    /// single-node quote, so each non-baseline candidate is resolved against the
3431    /// gossip cache (or fetched) and routed into the deterministic first audit,
3432    /// exactly like [`Self::cross_check_quotes`]. The candidate's peer id is
3433    /// derived from its `pub_key` (`PeerId = BLAKE3(pub_key)`), matching how the
3434    /// network binds identities.
3435    async fn cross_check_merkle_candidates(
3436        &self,
3437        pool: &evmlib::merkle_payments::MerklePaymentCandidatePool,
3438        commitment_sidecars: &[Vec<u8>],
3439        paid_indices: &std::collections::HashSet<usize>,
3440    ) {
3441        let now = std::time::Instant::now();
3442        let ttl = crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
3443        let p2p = self.p2p_node.read().as_ref().map(Arc::clone);
3444        let monetized_pin_tx = self.monetized_pin_tx.read().as_ref().cloned();
3445        let cache = self.commitment_cache.read().as_ref().map(Arc::clone);
3446        // ADR-0004 "the commitment arrived with the quote" for the merkle path:
3447        // validate sidecars exactly as the single-node path does.
3448        let sidecar_map = Self::index_valid_sidecars(commitment_sidecars);
3449
3450        let mut unresolved: Vec<(PeerId, [u8; 32], u32, Vec<u8>)> = Vec::new();
3451        for (idx, candidate) in pool.candidate_nodes.iter().enumerate() {
3452            let Some(pin) = candidate.commitment_pin else {
3453                continue; // baseline candidate pins nothing
3454            };
3455            let peer_id = PeerId::from_bytes(*blake3::hash(&candidate.pub_key).as_bytes());
3456
3457            // ADR-0004 Amendment 2: nominate only the candidates the contract
3458            // actually paid — the unpaid pool members earned nothing and stay
3459            // covered by the gossip-lottery audit path. Pre-amendment every
3460            // pool candidate (16) was nominated per verified proof.
3461            if paid_indices.contains(&idx) {
3462                if let Some(ref tx) = monetized_pin_tx {
3463                    // Bounded queue: drop on full (best-effort, penalty-free;
3464                    // the peer's next settled payment re-nominates it). Count a
3465                    // Full drop so ingress saturation is observable; a Closed
3466                    // channel just means the engine is shutting down.
3467                    if let Err(tokio::sync::mpsc::error::TrySendError::Full(_)) =
3468                        tx.try_send(crate::replication::MonetizedPinEvent {
3469                            peer: peer_id,
3470                            pin,
3471                            key_count: candidate.committed_key_count,
3472                            quote_ts: std::time::UNIX_EPOCH
3473                                .checked_add(std::time::Duration::from_secs(
3474                                    candidate.merkle_payment_timestamp,
3475                                ))
3476                                .unwrap_or(std::time::UNIX_EPOCH),
3477                        })
3478                    {
3479                        crate::replication::note_monetized_ingress_drop();
3480                    }
3481                }
3482            }
3483
3484            let resolved = match sidecar_map.get(&(peer_id, pin)) {
3485                Some(c) => Some(c.clone()),
3486                None => Self::cache_resolve(cache.as_ref(), peer_id, pin, now, ttl).await,
3487            };
3488            match resolved {
3489                Some(commitment) => {
3490                    let artifact = rmp_serde::to_vec(candidate).unwrap_or_default();
3491                    Self::handle_cross_check(
3492                        &peer_id,
3493                        pin,
3494                        candidate.committed_key_count,
3495                        artifact,
3496                        &commitment,
3497                        p2p.as_ref(),
3498                    )
3499                    .await;
3500                }
3501                None => unresolved.push((
3502                    peer_id,
3503                    pin,
3504                    candidate.committed_key_count,
3505                    rmp_serde::to_vec(candidate).unwrap_or_default(),
3506                )),
3507            }
3508        }
3509
3510        if unresolved.is_empty() {
3511            return;
3512        }
3513        let Some(p2p) = p2p else {
3514            return;
3515        };
3516        let neg_cache = Arc::clone(&self.pin_fetch_negative_cache);
3517        tokio::spawn(async move {
3518            Self::drain_unresolved_pin_fetches(&p2p, &neg_cache, unresolved).await;
3519        });
3520    }
3521}
3522
3523#[cfg(test)]
3524#[allow(clippy::expect_used, clippy::panic)]
3525mod tests {
3526    use super::*;
3527    use evmlib::merkle_payments::MerklePaymentCandidatePool;
3528    use evmlib::PaymentQuote;
3529    use saorsa_core::MlDsa65;
3530    use saorsa_pqc::pqc::types::MlDsaSecretKey;
3531    use saorsa_pqc::pqc::MlDsaOperations;
3532    use std::time::SystemTime;
3533
3534    /// Create a verifier for unit tests. EVM is always on, but tests can
3535    /// pre-populate the cache to bypass on-chain verification.
3536    fn create_test_verifier() -> PaymentVerifier {
3537        let config = PaymentVerifierConfig {
3538            evm: EvmVerifierConfig::default(),
3539            cache_capacity: 100,
3540            close_group_size: CLOSE_GROUP_SIZE,
3541            local_rewards_address: RewardsAddress::new([1u8; 20]),
3542            price_floor: PriceFloorConfig::default(),
3543        };
3544        PaymentVerifier::new(config)
3545    }
3546
3547    #[test]
3548    fn paid_quote_issuer_closeness_width_uses_k() {
3549        let issuer_closeness_width = PAID_QUOTE_ISSUER_CLOSENESS_WIDTH;
3550        let k_bucket_size = K_BUCKET_SIZE;
3551        let close_group_size = CLOSE_GROUP_SIZE;
3552
3553        assert_eq!(issuer_closeness_width, k_bucket_size);
3554        assert!(issuer_closeness_width > close_group_size);
3555    }
3556
3557    /// 16 candidate prices 100..=1600; the upper median (index 8) is 900.
3558    fn varied_candidate_prices() -> Vec<Amount> {
3559        (1..=16u64).map(|i| Amount::from(i * 100)).collect()
3560    }
3561
3562    #[test]
3563    fn merkle_expected_per_node_reproduces_the_contract_formula() {
3564        // total = median16 x 2^depth = 900 x 16 = 14400, over depth=4 nodes.
3565        let per_node = merkle_expected_per_node(&varied_candidate_prices(), 4, 1)
3566            .expect("depth 4 pool is payable");
3567        assert_eq!(per_node, Amount::from(3_600u64));
3568    }
3569
3570    /// 16 identical candidate prices, so the upper median is exactly `median`.
3571    fn prices_with_median(median: u64) -> Vec<Amount> {
3572        vec![Amount::from(median); 16]
3573    }
3574
3575    /// The parity expectation is the floor of the multiplied total, which is
3576    /// **not** the bare expectation times the multiplier.
3577    ///
3578    /// `expected(m) = floor(m x median x 2^depth / depth)` sits in
3579    /// `[m x expected(1), m x expected(1) + (m - 1)]`: equal when `depth`
3580    /// divides the total, up to `m - 1` wei above it when it does not.
3581    /// Asserting exact equality would encode `floor(3x/d) == 3 x floor(x/d)`,
3582    /// which is false in general and only happened to hold for the
3583    /// evenly-dividing case the first version of this test used.
3584    #[test]
3585    fn merkle_expected_per_node_scales_within_the_division_remainder() {
3586        let multiplier = PAID_QUOTE_PAYMENT_MULTIPLIER;
3587
3588        for median in [1u64, 899, 900, 901, 6_000, 1_000_003] {
3589            for depth in 1..=8u8 {
3590                let prices = prices_with_median(median);
3591                let bare = merkle_expected_per_node(&prices, depth, 1)
3592                    .expect("bare expectation is payable");
3593                let parity = merkle_expected_per_node(&prices, depth, multiplier)
3594                    .expect("parity expectation is payable");
3595
3596                let scaled_bare = bare * Amount::from(multiplier);
3597                let slack = Amount::from(multiplier - 1);
3598
3599                assert!(
3600                    parity >= scaled_bare && parity <= scaled_bare + slack,
3601                    "median {median} depth {depth}: parity {parity} must lie in \
3602                     [{scaled_bare}, {}]",
3603                    scaled_bare + slack
3604                );
3605
3606                // And it is exactly the floor of the multiplied total.
3607                let leaves = 1u64 << u32::from(depth);
3608                let expected =
3609                    Amount::from(median * leaves * multiplier) / Amount::from(u64::from(depth));
3610                assert_eq!(parity, expected, "median {median} depth {depth}");
3611            }
3612        }
3613    }
3614
3615    /// Regression for the arithmetic order: the helper multiplies the total and
3616    /// then divides once, as the contract does. Median 901 at depth 7 is a case
3617    /// where that differs from scaling a 1x result by one wei, so a refactor
3618    /// that divided first would fail here.
3619    #[test]
3620    fn merkle_expected_per_node_multiplies_before_dividing() {
3621        let prices = prices_with_median(901);
3622        let bare = merkle_expected_per_node(&prices, 7, 1).expect("bare expectation is payable");
3623        let parity = merkle_expected_per_node(&prices, 7, PAID_QUOTE_PAYMENT_MULTIPLIER)
3624            .expect("parity expectation is payable");
3625
3626        assert_eq!(bare, Amount::from(16_475u64));
3627        assert_eq!(parity, Amount::from(49_426u64));
3628        assert_eq!(
3629            parity,
3630            bare * Amount::from(PAID_QUOTE_PAYMENT_MULTIPLIER) + Amount::from(1u64),
3631            "dividing before multiplying would lose this wei"
3632        );
3633    }
3634
3635    /// The economic invariant ADR-0008 restores: a merkle **leaf** settles
3636    /// for what the single-node path settles — 3x the median quote — up to
3637    /// the contract's integer division.
3638    ///
3639    /// Leaf, not chunk: the tree pads to `2^ceil(log2(N))` and the contract
3640    /// charges for every leaf, so a batch whose size is not a power of two
3641    /// pays a padding premium on top. That premium is a property of the
3642    /// contract formula, not of the multiplier under test here.
3643    ///
3644    /// `amountPerNode = totalAmount / depth` discards a remainder whenever
3645    /// `depth` does not divide `median x 2^depth` (e.g. depth 7). The loss is
3646    /// strictly under one wei per paid node, spread across `2^depth` chunks,
3647    /// so it is economically irrelevant — but the invariant is "within
3648    /// rounding", not exact equality, and the test says so rather than
3649    /// picking depths that happen to divide evenly.
3650    #[test]
3651    fn merkle_parity_per_chunk_equals_single_node_settlement() {
3652        let prices = varied_candidate_prices();
3653        let median = Amount::from(900u64);
3654
3655        for depth in 1..=8u8 {
3656            let per_node = merkle_expected_per_node(&prices, depth, PAID_QUOTE_PAYMENT_MULTIPLIER)
3657                .expect("every supported depth is payable");
3658            let required_total = per_node * Amount::from(u64::from(depth));
3659
3660            let leaves = Amount::from(1u64 << u32::from(depth));
3661            let ideal_total = median * Amount::from(PAID_QUOTE_PAYMENT_MULTIPLIER) * leaves;
3662
3663            assert!(
3664                required_total <= ideal_total,
3665                "at depth {depth} the required total {required_total} must not \
3666                 exceed the 3x-median ideal {ideal_total}"
3667            );
3668            assert!(
3669                ideal_total - required_total < Amount::from(u64::from(depth)),
3670                "at depth {depth} the shortfall {} must be pure division \
3671                 remainder (< depth wei), not a missing multiplier",
3672                ideal_total - required_total
3673            );
3674        }
3675    }
3676
3677    #[test]
3678    fn merkle_expected_per_node_is_zero_at_depth_zero() {
3679        let per_node = merkle_expected_per_node(&varied_candidate_prices(), 0, 3)
3680            .expect("depth zero is a valid no-op, not an error");
3681        assert_eq!(per_node, Amount::ZERO);
3682    }
3683
3684    #[test]
3685    fn merkle_expected_per_node_rejects_an_empty_pool() {
3686        let Err(err) = merkle_expected_per_node(&[], 4, 3) else {
3687            panic!("an empty candidate pool has no median and must not be payable");
3688        };
3689        let err = err.to_string();
3690        assert!(err.contains("empty candidate pool"), "got: {err}");
3691    }
3692
3693    fn make_signed_quote(
3694        xorname: XorName,
3695        price: Amount,
3696        rewards_seed: u8,
3697    ) -> (evmlib::EncodedPeerId, PaymentQuote) {
3698        let ml_dsa = MlDsa65::new();
3699        let (public_key, secret_key) = ml_dsa.generate_keypair().expect("keygen");
3700        let pub_key_bytes = public_key.as_bytes().to_vec();
3701        let peer_id = encoded_peer_id_for_pub_key(&pub_key_bytes);
3702        // Derive the ADR-0004 binding from the price rather than hardcoding
3703        // `(0, None)`: a quote priced at `calculate_price(n)` must also claim
3704        // `committed_key_count = n`, or it charges as though it stored `n` keys
3705        // while committing to nothing and is rejected by the arithmetic gate
3706        // before the test's own assertion is reached. Prices that are not on
3707        // the curve at all (`ZERO`, small literals) keep the baseline shape and
3708        // stay off-curve, which is what the tests exercising bad prices want.
3709        let (committed_key_count, commitment_pin) =
3710            match PaymentVerifier::price_off_curve_diagnostics(&price) {
3711                None => {
3712                    let records = derive_records_stored_from_price(price);
3713                    let count = u32::try_from(records).unwrap_or(u32::MAX);
3714                    let pin = if count == 0 { None } else { Some([0xA5u8; 32]) };
3715                    (count, pin)
3716                }
3717                Some(_) => (0, None),
3718            };
3719        let mut quote = PaymentQuote {
3720            content: xor_name::XorName(xorname),
3721            timestamp: SystemTime::now(),
3722            price,
3723            rewards_address: RewardsAddress::new([rewards_seed; 20]),
3724            committed_key_count,
3725            commitment_pin,
3726            pub_key: pub_key_bytes,
3727            signature: Vec::new(),
3728        };
3729        let secret_key = MlDsaSecretKey::from_bytes(secret_key.as_bytes()).expect("secret key");
3730        quote.signature = ml_dsa
3731            .sign(&secret_key, &quote.bytes_for_sig())
3732            .expect("sign quote")
3733            .as_bytes()
3734            .to_vec();
3735        (peer_id, quote)
3736    }
3737
3738    fn make_signed_legacy_bundle(
3739        xorname: XorName,
3740        prices: [Amount; CLOSE_GROUP_SIZE],
3741    ) -> Vec<(evmlib::EncodedPeerId, PaymentQuote)> {
3742        prices
3743            .into_iter()
3744            .enumerate()
3745            .map(|(index, price)| {
3746                let rewards_seed = u8::try_from(index + 1).expect("small test index");
3747                make_signed_quote(xorname, price, rewards_seed)
3748            })
3749            .collect()
3750    }
3751
3752    fn price_at_records(records: usize) -> Amount {
3753        crate::payment::pricing::calculate_price(records)
3754    }
3755
3756    fn unique_test_prices() -> [Amount; CLOSE_GROUP_SIZE] {
3757        [
3758            price_at_records(0),
3759            price_at_records(1),
3760            price_at_records(2),
3761            price_at_records(3),
3762            price_at_records(4),
3763            price_at_records(5),
3764            price_at_records(6),
3765        ]
3766    }
3767
3768    fn tied_median_test_prices() -> [Amount; CLOSE_GROUP_SIZE] {
3769        [
3770            price_at_records(0),
3771            price_at_records(1),
3772            price_at_records(2),
3773            price_at_records(3),
3774            price_at_records(3),
3775            price_at_records(4),
3776            price_at_records(5),
3777        ]
3778    }
3779
3780    fn median_test_candidates(
3781        peer_quotes: &[(evmlib::EncodedPeerId, PaymentQuote)],
3782    ) -> Vec<(evmlib::EncodedPeerId, PaymentQuote)> {
3783        let mut sorted_quotes: Vec<_> = peer_quotes.iter().collect();
3784        sorted_quotes.sort_by_key(|(_, quote)| quote.price);
3785        let median_index = median_quote_index(sorted_quotes.len());
3786        let median_price = sorted_quotes
3787            .get(median_index)
3788            .expect("median quote")
3789            .1
3790            .price;
3791
3792        sorted_quotes
3793            .into_iter()
3794            .filter(|(_, quote)| quote.price == median_price)
3795            .map(|(peer_id, quote)| (peer_id.clone(), quote.clone()))
3796            .collect()
3797    }
3798
3799    fn expected_median_payment(peer_quotes: &[(evmlib::EncodedPeerId, PaymentQuote)]) -> Amount {
3800        let median_price = median_test_candidates(peer_quotes)
3801            .first()
3802            .expect("median candidate")
3803            .1
3804            .price;
3805        median_price * Amount::from(PAID_QUOTE_PAYMENT_MULTIPLIER)
3806    }
3807
3808    fn mark_k_closest_paid_candidates(
3809        verifier: &PaymentVerifier,
3810        peer_quotes: &[(evmlib::EncodedPeerId, PaymentQuote)],
3811    ) {
3812        let k_closest_peers = median_test_candidates(peer_quotes)
3813            .iter()
3814            .map(|(peer_id, _)| *peer_id.as_bytes())
3815            .collect();
3816        verifier.set_paid_quote_k_closest_for_tests(k_closest_peers);
3817    }
3818
3819    fn mark_candidate_paid(verifier: &PaymentVerifier, quote: &PaymentQuote, amount: Amount) {
3820        verifier.set_completed_payment_for_tests(quote.hash(), amount);
3821    }
3822
3823    fn mark_all_median_candidates_unpaid(
3824        verifier: &PaymentVerifier,
3825        peer_quotes: &[(evmlib::EncodedPeerId, PaymentQuote)],
3826    ) {
3827        for (_, quote) in median_test_candidates(peer_quotes) {
3828            mark_candidate_paid(verifier, &quote, Amount::ZERO);
3829        }
3830    }
3831
3832    #[test]
3833    fn test_payment_required_for_new_data() {
3834        let verifier = create_test_verifier();
3835        let xorname = [1u8; 32];
3836
3837        // All uncached data requires payment
3838        let status = verifier.check_payment_required(&xorname, VerificationContext::ClientPut);
3839        assert_eq!(status, PaymentStatus::PaymentRequired);
3840    }
3841
3842    #[test]
3843    fn test_cache_hit() {
3844        let verifier = create_test_verifier();
3845        let xorname = [1u8; 32];
3846
3847        // Manually add to cache
3848        verifier.cache.insert(xorname);
3849
3850        // Should return CachedAsVerified
3851        let status = verifier.check_payment_required(&xorname, VerificationContext::ClientPut);
3852        assert_eq!(status, PaymentStatus::CachedAsVerified);
3853    }
3854
3855    #[tokio::test]
3856    async fn test_verify_payment_without_proof_rejected() {
3857        let verifier = create_test_verifier();
3858        let xorname = [1u8; 32];
3859
3860        // No proof provided => should return an error (EVM is always on)
3861        let result = verifier
3862            .verify_payment(&xorname, None, VerificationContext::ClientPut)
3863            .await;
3864        assert!(
3865            result.is_err(),
3866            "Expected Err without proof, got: {result:?}"
3867        );
3868    }
3869
3870    #[tokio::test]
3871    async fn test_verify_payment_cached() {
3872        let verifier = create_test_verifier();
3873        let xorname = [1u8; 32];
3874
3875        // Add to cache — simulates previously-paid data
3876        verifier.cache.insert(xorname);
3877
3878        // Should succeed without payment (cached)
3879        let result = verifier
3880            .verify_payment(&xorname, None, VerificationContext::ClientPut)
3881            .await;
3882        assert!(result.is_ok());
3883        assert_eq!(result.expect("cached"), PaymentStatus::CachedAsVerified);
3884    }
3885
3886    #[tokio::test]
3887    async fn test_paid_list_cache_entry_does_not_satisfy_client_put() {
3888        let verifier = create_test_verifier();
3889        let xorname = [0xB8u8; 32];
3890        verifier.cache.insert_paid_list_verified(xorname);
3891
3892        assert_eq!(
3893            verifier.check_payment_required(&xorname, VerificationContext::PaidListAdmission),
3894            PaymentStatus::CachedAsVerified,
3895            "paid-list lookups must hit a paid-list-verified entry"
3896        );
3897        assert_eq!(
3898            verifier.check_payment_required(&xorname, VerificationContext::ClientPut),
3899            PaymentStatus::PaymentRequired,
3900            "client PUT must not fast-path on a paid-list-verified entry"
3901        );
3902
3903        let err = verifier
3904            .verify_payment(&xorname, None, VerificationContext::ClientPut)
3905            .await
3906            .expect_err("proof-less client PUT must not ride the paid-list entry");
3907        assert!(
3908            format!("{err}").contains("Payment required"),
3909            "client PUT must still demand payment: {err}"
3910        );
3911    }
3912
3913    #[test]
3914    fn test_payment_status_can_store() {
3915        assert!(PaymentStatus::CachedAsVerified.can_store());
3916        assert!(PaymentStatus::PaymentVerified.can_store());
3917        assert!(!PaymentStatus::PaymentRequired.can_store());
3918    }
3919
3920    #[test]
3921    fn test_payment_status_is_cached() {
3922        assert!(PaymentStatus::CachedAsVerified.is_cached());
3923        assert!(!PaymentStatus::PaymentVerified.is_cached());
3924        assert!(!PaymentStatus::PaymentRequired.is_cached());
3925    }
3926
3927    #[tokio::test]
3928    async fn test_cache_preload_bypasses_evm() {
3929        let verifier = create_test_verifier();
3930        let xorname = [42u8; 32];
3931
3932        // Not yet cached — should require payment
3933        assert_eq!(
3934            verifier.check_payment_required(&xorname, VerificationContext::ClientPut),
3935            PaymentStatus::PaymentRequired
3936        );
3937
3938        // Pre-populate cache (simulates a previous successful payment)
3939        verifier.cache.insert(xorname);
3940
3941        // Now the xorname should be cached
3942        assert_eq!(
3943            verifier.check_payment_required(&xorname, VerificationContext::ClientPut),
3944            PaymentStatus::CachedAsVerified
3945        );
3946    }
3947
3948    #[tokio::test]
3949    async fn test_proof_too_small() {
3950        let verifier = create_test_verifier();
3951        let xorname = [1u8; 32];
3952
3953        // Proof smaller than MIN_PAYMENT_PROOF_SIZE_BYTES
3954        let small_proof = vec![0u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
3955        let result = verifier
3956            .verify_payment(&xorname, Some(&small_proof), VerificationContext::ClientPut)
3957            .await;
3958        assert!(result.is_err());
3959        let err_msg = format!("{}", result.expect_err("should fail"));
3960        assert!(
3961            err_msg.contains("too small"),
3962            "Error should mention 'too small': {err_msg}"
3963        );
3964    }
3965
3966    #[tokio::test]
3967    async fn test_proof_too_large() {
3968        let verifier = create_test_verifier();
3969        let xorname = [2u8; 32];
3970
3971        // Proof larger than MAX_PAYMENT_PROOF_SIZE_BYTES
3972        let large_proof = vec![0u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
3973        let result = verifier
3974            .verify_payment(&xorname, Some(&large_proof), VerificationContext::ClientPut)
3975            .await;
3976        assert!(result.is_err());
3977        let err_msg = format!("{}", result.expect_err("should fail"));
3978        assert!(
3979            err_msg.contains("too large"),
3980            "Error should mention 'too large': {err_msg}"
3981        );
3982    }
3983
3984    #[tokio::test]
3985    async fn test_proof_at_min_boundary_unknown_tag() {
3986        let verifier = create_test_verifier();
3987        let xorname = [3u8; 32];
3988
3989        // Exactly MIN_PAYMENT_PROOF_SIZE_BYTES with unknown tag — rejected
3990        let boundary_proof = vec![0xFFu8; MIN_PAYMENT_PROOF_SIZE_BYTES];
3991        let result = verifier
3992            .verify_payment(
3993                &xorname,
3994                Some(&boundary_proof),
3995                VerificationContext::ClientPut,
3996            )
3997            .await;
3998        assert!(result.is_err());
3999        let err_msg = format!("{}", result.expect_err("should fail"));
4000        assert!(
4001            err_msg.contains("Unknown payment proof type tag"),
4002            "Error should mention unknown tag: {err_msg}"
4003        );
4004    }
4005
4006    #[tokio::test]
4007    async fn test_proof_at_max_boundary_unknown_tag() {
4008        let verifier = create_test_verifier();
4009        let xorname = [4u8; 32];
4010
4011        // Exactly MAX_PAYMENT_PROOF_SIZE_BYTES with unknown tag — rejected
4012        let boundary_proof = vec![0xFFu8; MAX_PAYMENT_PROOF_SIZE_BYTES];
4013        let result = verifier
4014            .verify_payment(
4015                &xorname,
4016                Some(&boundary_proof),
4017                VerificationContext::ClientPut,
4018            )
4019            .await;
4020        assert!(result.is_err());
4021        let err_msg = format!("{}", result.expect_err("should fail"));
4022        assert!(
4023            err_msg.contains("Unknown payment proof type tag"),
4024            "Error should mention unknown tag: {err_msg}"
4025        );
4026    }
4027
4028    /// Regression pin for the DEV-01 (2026-07-06) outage: a merkle proof that
4029    /// ships all 16 ADR-0004 commitment sidecars serializes to ~342 KB, and the
4030    /// old 256 KB cap size-rejected every merkle PUT as soon as nodes carried
4031    /// live commitments. The cap must keep accepting that legacy client shape;
4032    /// a proof of that size must fail on content, never on size.
4033    #[tokio::test]
4034    async fn test_sidecar_bearing_merkle_proof_size_is_accepted() {
4035        const LEGACY_SIDECAR_PROOF_BYTES: usize = 342_171;
4036
4037        let verifier = create_test_verifier();
4038        let xorname = [6u8; 32];
4039
4040        let legacy_sized_proof = vec![0xFFu8; LEGACY_SIDECAR_PROOF_BYTES];
4041        let result = verifier
4042            .verify_payment(
4043                &xorname,
4044                Some(&legacy_sized_proof),
4045                VerificationContext::ClientPut,
4046            )
4047            .await;
4048        assert!(result.is_err());
4049        let err_msg = format!("{}", result.expect_err("should fail"));
4050        assert!(
4051            !err_msg.contains("too large"),
4052            "A {LEGACY_SIDECAR_PROOF_BYTES}-byte proof must not be size-rejected \
4053             (sidecar-bearing merkle proofs from pre-fix clients): {err_msg}"
4054        );
4055    }
4056
4057    #[tokio::test]
4058    async fn test_malformed_single_node_proof() {
4059        let verifier = create_test_verifier();
4060        let xorname = [5u8; 32];
4061
4062        // Valid tag (0x01) but garbage payload — should fail deserialization
4063        let mut garbage = vec![crate::ant_protocol::PROOF_TAG_SINGLE_NODE];
4064        garbage.extend_from_slice(&[0xAB; 63]);
4065        let result = verifier
4066            .verify_payment(&xorname, Some(&garbage), VerificationContext::ClientPut)
4067            .await;
4068        assert!(result.is_err());
4069        let err_msg = format!("{}", result.expect_err("should fail"));
4070        assert!(
4071            err_msg.contains("deserialize") || err_msg.contains("Failed"),
4072            "Error should mention deserialization failure: {err_msg}"
4073        );
4074    }
4075
4076    #[tokio::test]
4077    async fn test_legacy_paid_median_full_path_accepted() {
4078        let verifier = create_test_verifier();
4079        let xorname = [0xA1u8; 32];
4080        let peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
4081        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
4082        let expected_amount = expected_median_payment(&peer_quotes);
4083        let paid_quote = median_test_candidates(&peer_quotes)
4084            .first()
4085            .expect("median candidate")
4086            .1
4087            .clone();
4088        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
4089
4090        let proof_bytes = serialize_proof(peer_quotes);
4091        let result = verifier
4092            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4093            .await;
4094
4095        assert_eq!(
4096            result.expect("paid median should verify"),
4097            PaymentStatus::PaymentVerified
4098        );
4099    }
4100
4101    /// ADR-0004 Amendment 2: a settlement recorded under the median quote's
4102    /// hash but redirected to a DIFFERENT rewards address must be rejected —
4103    /// otherwise a client could "pay" its own wallet while the issuer is
4104    /// treated (and first-audited) as paid without ever being compensated.
4105    #[tokio::test]
4106    async fn test_legacy_paid_median_redirected_settlement_rejected() {
4107        let verifier = create_test_verifier();
4108        let xorname = [0xA2u8; 32];
4109        let peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
4110        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
4111        let expected_amount = expected_median_payment(&peer_quotes);
4112        let paid_quote = median_test_candidates(&peer_quotes)
4113            .first()
4114            .expect("median candidate")
4115            .1
4116            .clone();
4117        // Full amount, but recorded for an address that is not the quote's.
4118        let attacker_address = RewardsAddress::new([0xEEu8; 20]);
4119        assert_ne!(attacker_address, paid_quote.rewards_address);
4120        verifier.set_completed_payment_with_address_for_tests(
4121            paid_quote.hash(),
4122            expected_amount,
4123            attacker_address,
4124        );
4125
4126        let proof_bytes = serialize_proof(peer_quotes);
4127        let result = verifier
4128            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4129            .await;
4130
4131        let err = result.expect_err("redirected settlement must be rejected");
4132        assert!(
4133            format!("{err}").contains("redirected"),
4134            "Error should mention the settlement redirect: {err}"
4135        );
4136    }
4137
4138    #[tokio::test]
4139    async fn test_legacy_single_quote_proof_accepted() {
4140        let verifier = create_test_verifier();
4141        let xorname = [0xB1u8; 32];
4142        let (peer_id, quote) = make_signed_quote(xorname, price_at_records(0), 1);
4143        let peer_quotes = vec![(peer_id, quote.clone())];
4144        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
4145        mark_candidate_paid(&verifier, &quote, expected_median_payment(&peer_quotes));
4146
4147        let proof_bytes = serialize_proof(peer_quotes);
4148        let result = verifier
4149            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4150            .await;
4151
4152        assert_eq!(
4153            result.expect("single paid quote should verify"),
4154            PaymentStatus::PaymentVerified
4155        );
4156    }
4157
4158    /// Fixed-count [`crate::payment::quote::CommitmentSource`] standing in for
4159    /// the receiver's live commitment state in price-floor tests.
4160    struct FixedFloorSource {
4161        key_count: u32,
4162    }
4163
4164    impl crate::payment::quote::CommitmentSource for FixedFloorSource {
4165        fn current_binding_for_quote(&self) -> Option<crate::payment::quote::QuoteBinding> {
4166            self.current_binding_snapshot()
4167        }
4168
4169        fn current_binding_snapshot(&self) -> Option<crate::payment::quote::QuoteBinding> {
4170            Some(crate::payment::quote::QuoteBinding {
4171                key_count: self.key_count,
4172                pin: [0u8; 32],
4173            })
4174        }
4175
4176        fn commitment_blob_for_pin(&self, _pin: [u8; 32]) -> Option<Vec<u8>> {
4177            None
4178        }
4179    }
4180
4181    /// Receiver commitment count for floor tests, chosen so the local price is
4182    /// comfortably more than double the baseline (the 50% floor then rejects a
4183    /// baseline-priced settlement). Asserted in each test so a pricing-curve
4184    /// change fails loudly instead of silently weakening the tests.
4185    const FLOOR_TEST_LOCAL_KEY_COUNT: u32 = 1_000_000;
4186
4187    fn floor_test_verifier(enforce: bool) -> PaymentVerifier {
4188        let verifier = create_test_verifier();
4189        verifier.attach_local_commitment_source(Arc::new(FixedFloorSource {
4190            key_count: FLOOR_TEST_LOCAL_KEY_COUNT,
4191        }));
4192        verifier.set_price_floor_for_tests(PriceFloorConfig {
4193            enforce,
4194            tolerance_percent: PRICE_FLOOR_DEFAULT_TOLERANCE_PERCENT,
4195        });
4196        let local_price = price_at_records(FLOOR_TEST_LOCAL_KEY_COUNT as usize);
4197        assert!(
4198            local_price > price_at_records(0) * Amount::from(2u64),
4199            "floor tests need a local price above twice baseline, got {local_price}"
4200        );
4201        verifier
4202    }
4203
4204    /// The settled amount the floor requires: 3x the tolerated fraction of the
4205    /// close group's median commitment-bound price.
4206    fn group_floor_required_amount() -> Amount {
4207        let tolerated = price_at_records(GROUP_TEST_MEDIAN_KEY_COUNT as usize)
4208            * Amount::from(PRICE_FLOOR_DEFAULT_TOLERANCE_PERCENT)
4209            / Amount::from(100u64);
4210        tolerated * Amount::from(PAID_QUOTE_PAYMENT_MULTIPLIER)
4211    }
4212
4213    /// One cheap (baseline-priced) quote paid `settled`: the cheapest-of-K
4214    /// omission shape a modified client can always produce.
4215    fn cheap_single_quote_proof(
4216        verifier: &PaymentVerifier,
4217        xorname: XorName,
4218        settled: Amount,
4219    ) -> Vec<u8> {
4220        let (peer_id, quote) = make_signed_quote(xorname, price_at_records(0), 1);
4221        let peer_quotes = vec![(peer_id, quote.clone())];
4222        mark_k_closest_paid_candidates(verifier, &peer_quotes);
4223        mark_candidate_paid(verifier, &quote, settled);
4224        serialize_proof(peer_quotes)
4225    }
4226
4227    /// Close-group commitment counts used by the group-median floor tests.
4228    ///
4229    /// Exactly [`PRICE_FLOOR_MIN_NEIGHBOUR_COMMITMENTS`] entries, so these tests
4230    /// sit on the gate rather than comfortably past it: drop one and the floor
4231    /// must skip. Spread widely enough that the cheapest sits below the tolerated
4232    /// fraction of the median (asserted in the rejection test), and kept in the
4233    /// low thousands because each entry builds a real signed merkle commitment.
4234    const GROUP_TEST_KEY_COUNTS: [u32; 15] = [
4235        500, 800, 1_100, 1_400, 1_700, 2_000, 2_300, 2_600, 2_900, 3_200, 3_500, 3_800, 4_100,
4236        4_400, 4_700,
4237    ];
4238
4239    /// The LOWER median of [`GROUP_TEST_KEY_COUNTS`] plus this node's own
4240    /// [`FLOOR_TEST_LOCAL_KEY_COUNT`].
4241    ///
4242    /// Sixteen samples, so the lower median is the eighth smallest: `2_600`. The
4243    /// receiver's own count is an extreme outlier at the top and does not move
4244    /// it, which is exactly the robustness a median buys. An even sample is
4245    /// deliberate — it is the case where upper and lower median differ, and the
4246    /// lower one is what production safety depends on.
4247    const GROUP_TEST_MEDIAN_KEY_COUNT: u32 = 2_600;
4248
4249    /// Build a gossip commitment cache holding one fresh commitment per entry of
4250    /// `key_counts`, attach it, and return the peer ids so the caller can put
4251    /// them in the K-closest set.
4252    ///
4253    /// `age` ages every record equally, for the staleness test.
4254    fn attach_group_commitments(
4255        verifier: &PaymentVerifier,
4256        key_counts: &[u32],
4257        age: std::time::Duration,
4258    ) -> Vec<[u8; 32]> {
4259        use crate::replication::commitment_state::PeerCommitmentRecord;
4260
4261        let received_at = std::time::Instant::now()
4262            .checked_sub(age)
4263            .unwrap_or_else(std::time::Instant::now);
4264        let mut cache_map = HashMap::new();
4265        let mut peer_ids = Vec::with_capacity(key_counts.len());
4266        for (index, count) in key_counts.iter().enumerate() {
4267            let built = test_built_commitment(*count);
4268            let mut raw = [0u8; 32];
4269            // Distinct, stable id per neighbour; the id only has to match
4270            // between the cache key and the K-closest set.
4271            raw[0] = u8::try_from(index + 1).unwrap_or(u8::MAX);
4272            peer_ids.push(raw);
4273            cache_map.insert(
4274                PeerId::from_bytes(raw),
4275                PeerCommitmentRecord::from_verified(built.commitment().clone(), received_at),
4276            );
4277        }
4278        verifier.attach_commitment_cache(Arc::new(tokio::sync::RwLock::new(cache_map)));
4279        peer_ids
4280    }
4281
4282    /// A one-quote proof priced at `quote_records`, settled at `3 x
4283    /// price(settle_records)`, with the K-closest set covering both the quote
4284    /// issuer and the supplied close-group neighbours.
4285    fn group_floor_proof(
4286        verifier: &PaymentVerifier,
4287        xorname: XorName,
4288        quote_records: usize,
4289        settled: Amount,
4290        neighbours: &[[u8; 32]],
4291    ) -> Vec<u8> {
4292        let (peer_id, quote) = make_signed_quote(xorname, price_at_records(quote_records), 1);
4293        let mut k_closest: Vec<[u8; 32]> = neighbours.to_vec();
4294        k_closest.push(*peer_id.as_bytes());
4295        let peer_quotes = vec![(peer_id, quote.clone())];
4296        verifier.set_paid_quote_k_closest_for_tests(k_closest);
4297        mark_candidate_paid(verifier, &quote, settled);
4298        serialize_proof(peer_quotes)
4299    }
4300
4301    fn three_times(price: Amount) -> Amount {
4302        price * Amount::from(PAID_QUOTE_PAYMENT_MULTIPLIER)
4303    }
4304
4305    /// Overwrite the signed key count on cached commitments for `peer_ids`.
4306    ///
4307    /// Models a modified node: the honest builder refuses to construct a
4308    /// commitment at these counts, and building real ones at the protocol cap
4309    /// costs about a second and 200 MB apiece. The signature no longer matches,
4310    /// which is fine — the floor reads the cached count and never re-verifies.
4311    ///
4312    /// Asserts that every requested mutation landed. Callers assert ADMISSION,
4313    /// so a helper that silently no-opped would make those tests pass without
4314    /// ever forging anything.
4315    async fn forge_key_counts(
4316        verifier: &PaymentVerifier,
4317        peer_ids: Option<&[[u8; 32]]>,
4318        key_count: u32,
4319    ) {
4320        use crate::replication::commitment_state::PeerCommitmentRecord;
4321
4322        let peer_ids = peer_ids.expect("caller must supply a valid peer id slice");
4323        let cache = verifier
4324            .commitment_cache
4325            .read()
4326            .as_ref()
4327            .map(Arc::clone)
4328            .expect("commitment cache must be attached before forging counts");
4329        let mut mutated = 0usize;
4330        {
4331            let mut guard = cache.write().await;
4332            for raw in peer_ids {
4333                if let Some(record) = guard.get_mut(&PeerId::from_bytes(*raw)) {
4334                    if let Some(mut forged) = record.last_commitment().cloned() {
4335                        forged.key_count = key_count;
4336                        *record =
4337                            PeerCommitmentRecord::from_verified(forged, std::time::Instant::now());
4338                        mutated += 1;
4339                    }
4340                }
4341            }
4342        }
4343        assert_eq!(
4344            mutated,
4345            peer_ids.len(),
4346            "every forged count must land, or the test asserting admission proves nothing"
4347        );
4348    }
4349
4350    #[test]
4351    fn store_admission_contexts_cover_puts_and_fresh_replication_only() {
4352        assert!(VerificationContext::ClientPut.is_store_admission());
4353        assert!(VerificationContext::FreshReplication.is_store_admission());
4354        assert!(!VerificationContext::PaidListAdmission.is_store_admission());
4355    }
4356
4357    /// Pins the reference itself: the sample includes this node, the median is
4358    /// taken over the whole close group, and the receiver's own extreme count
4359    /// does not move it.
4360    #[tokio::test]
4361    async fn group_reference_price_is_the_close_group_median() {
4362        let verifier = floor_test_verifier(true);
4363        let xorname = [0xD0u8; 32];
4364        let neighbours =
4365            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
4366        verifier.set_paid_quote_k_closest_for_tests(neighbours);
4367
4368        let (reference, sample) = verifier.group_reference_price(&xorname).await;
4369        let reference = reference.expect("a fully populated group must produce a reference");
4370
4371        assert_eq!(
4372            sample.neighbours,
4373            GROUP_TEST_KEY_COUNTS.len(),
4374            "the gated count is neighbours only"
4375        );
4376        assert_eq!(
4377            sample.total,
4378            GROUP_TEST_KEY_COUNTS.len() + 1,
4379            "the median is taken over the neighbours plus this node's own commitment"
4380        );
4381        assert!(
4382            sample.skip_reason.is_none(),
4383            "a fully populated group must not report a skip reason"
4384        );
4385        assert_eq!(
4386            reference,
4387            price_at_records(GROUP_TEST_MEDIAN_KEY_COUNT as usize),
4388            "the reference must be the group median price, not this node's own"
4389        );
4390        assert!(
4391            reference < price_at_records(FLOOR_TEST_LOCAL_KEY_COUNT as usize),
4392            "this node's own price is far above the median and must not be the reference"
4393        );
4394    }
4395
4396    /// The production false-rejection case, encoded.
4397    ///
4398    /// This receiver holds far more than anyone else in its group, so its own
4399    /// price is enormous. An honest client paying 3x the GROUP MEDIAN must still
4400    /// be admitted. Pricing the floor against the receiver's own commitment
4401    /// rejected exactly this shape on ant-prod-01, 0.377% of honest stores, all
4402    /// of them on the fullest nodes.
4403    #[tokio::test]
4404    async fn price_floor_prices_against_the_group_median_not_the_receiver() {
4405        let verifier = floor_test_verifier(true);
4406        let xorname = [0xD1u8; 32];
4407        let neighbours =
4408            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
4409
4410        let median_price = price_at_records(GROUP_TEST_MEDIAN_KEY_COUNT as usize);
4411        let own_price = price_at_records(FLOOR_TEST_LOCAL_KEY_COUNT as usize);
4412        assert!(
4413            own_price > median_price * Amount::from(2u64),
4414            "this test is only meaningful when the receiver is far above the group median"
4415        );
4416
4417        // Honest: the client paid 3x the median of the quotes it collected.
4418        let settled = three_times(median_price);
4419        let proof_bytes = group_floor_proof(
4420            &verifier,
4421            xorname,
4422            GROUP_TEST_MEDIAN_KEY_COUNT as usize,
4423            settled,
4424            &neighbours,
4425        );
4426
4427        let result = verifier
4428            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4429            .await;
4430
4431        assert_eq!(
4432            result.expect("an honest median payment must clear the group-median floor"),
4433            PaymentStatus::PaymentVerified
4434        );
4435    }
4436
4437    /// The attack the floor exists to stop: collect the neighbourhood's quotes,
4438    /// settle only the cheapest one, submit it as a one-quote proof.
4439    #[tokio::test]
4440    async fn price_floor_rejects_cheapest_of_group_payment() {
4441        let verifier = floor_test_verifier(true);
4442        let xorname = [0xD2u8; 32];
4443        let neighbours =
4444            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
4445
4446        let cheapest = GROUP_TEST_KEY_COUNTS.first().copied().unwrap_or(0) as usize;
4447        let cheapest_price = price_at_records(cheapest);
4448        let tolerated = price_at_records(GROUP_TEST_MEDIAN_KEY_COUNT as usize)
4449            * Amount::from(PRICE_FLOOR_DEFAULT_TOLERANCE_PERCENT)
4450            / Amount::from(100u64);
4451        assert!(
4452            cheapest_price < tolerated,
4453            "the cheapest group price must sit below the tolerated floor for this test to bite"
4454        );
4455
4456        let proof_bytes = group_floor_proof(
4457            &verifier,
4458            xorname,
4459            cheapest,
4460            three_times(cheapest_price),
4461            &neighbours,
4462        );
4463
4464        let err = verifier
4465            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4466            .await
4467            .expect_err("settling only the cheapest group quote must not clear the floor");
4468
4469        assert!(
4470            format!("{err}").contains("below the close-group price floor"),
4471            "Error should name the group price floor: {err}"
4472        );
4473    }
4474
4475    /// The anti-manipulation property: the reference price is built from this
4476    /// node's own routing view and the neighbours' signed gossip, never from the
4477    /// bundle. Padding the bundle with cheap quotes (the median-padding shape)
4478    /// must not move the floor.
4479    #[tokio::test]
4480    async fn price_floor_reference_ignores_client_supplied_quotes() {
4481        let verifier = floor_test_verifier(true);
4482        let xorname = [0xD3u8; 32];
4483        let neighbours =
4484            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
4485
4486        // A bundle stuffed with baseline-priced quotes: the client's own median
4487        // is now the floor price, which is exactly what it would want.
4488        let cheapest = GROUP_TEST_KEY_COUNTS.first().copied().unwrap_or(0) as usize;
4489        let mut peer_quotes = Vec::new();
4490        let mut k_closest: Vec<[u8; 32]> = neighbours.clone();
4491        for seed in 1..=CLOSE_GROUP_SIZE {
4492            let seed_u8 = u8::try_from(seed).unwrap_or(u8::MAX);
4493            let (peer_id, quote) = make_signed_quote(xorname, price_at_records(cheapest), seed_u8);
4494            k_closest.push(*peer_id.as_bytes());
4495            peer_quotes.push((peer_id, quote));
4496        }
4497        verifier.set_paid_quote_k_closest_for_tests(k_closest);
4498        // Settle the padded median honestly for that padded bundle.
4499        for (_, quote) in &peer_quotes {
4500            mark_candidate_paid(&verifier, quote, three_times(price_at_records(cheapest)));
4501        }
4502        let proof_bytes = serialize_proof(peer_quotes);
4503
4504        let err = verifier
4505            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4506            .await
4507            .expect_err("a bundle padded with cheap quotes must not lower this node's floor");
4508
4509        assert!(
4510            format!("{err}").contains("below the close-group price floor"),
4511            "Error should name the group price floor: {err}"
4512        );
4513    }
4514
4515    /// Too thin a local view must SKIP, never reject. A settled payment cannot
4516    /// be refunded, so guessing a reference from a handful of peers would burn
4517    /// user money on a startup or post-churn window.
4518    ///
4519    /// One neighbour short of the gate, and built from the DEAREST counts on
4520    /// purpose: if the gate were deleted, the surviving sample would price the
4521    /// floor ABOVE the settled amount and the payment would be rejected, so this
4522    /// test fails rather than passing vacuously. Building it from the cheapest
4523    /// counts (the obvious choice) would pass either way and prove nothing.
4524    #[tokio::test]
4525    async fn price_floor_skips_when_group_view_is_too_thin() {
4526        let verifier = floor_test_verifier(true);
4527        let xorname = [0xD4u8; 32];
4528        let thin: Vec<u32> = GROUP_TEST_KEY_COUNTS
4529            .iter()
4530            .rev()
4531            .copied()
4532            .take(PRICE_FLOOR_MIN_NEIGHBOUR_COMMITMENTS - 1)
4533            .collect();
4534        assert_eq!(thin.len(), PRICE_FLOOR_MIN_NEIGHBOUR_COMMITMENTS - 1);
4535        let neighbours = attach_group_commitments(&verifier, &thin, std::time::Duration::ZERO);
4536
4537        // Deep underpayment that this sample, if it were used, would reject.
4538        let settled = three_times(price_at_records(0));
4539        let would_be_median = thin.get(thin.len() / 2).copied().unwrap_or_default();
4540        assert!(
4541            settled
4542                < price_at_records(would_be_median as usize)
4543                    * Amount::from(PRICE_FLOOR_DEFAULT_TOLERANCE_PERCENT)
4544                    / Amount::from(100u64)
4545                    * Amount::from(PAID_QUOTE_PAYMENT_MULTIPLIER),
4546            "the thin sample must price ABOVE the settlement, so deleting the gate fails this test"
4547        );
4548        let proof_bytes = group_floor_proof(&verifier, xorname, 0, settled, &neighbours);
4549
4550        let result = verifier
4551            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4552            .await;
4553
4554        assert_eq!(
4555            result.expect("a thin group view must skip the floor, not reject"),
4556            PaymentStatus::PaymentVerified
4557        );
4558    }
4559
4560    /// Exactly ON the gate must evaluate, so the boundary is pinned from both
4561    /// sides alongside the one-short test above.
4562    #[tokio::test]
4563    async fn price_floor_evaluates_at_exactly_the_minimum_sample() {
4564        let verifier = floor_test_verifier(true);
4565        let xorname = [0xDAu8; 32];
4566        assert_eq!(
4567            GROUP_TEST_KEY_COUNTS.len(),
4568            PRICE_FLOOR_MIN_NEIGHBOUR_COMMITMENTS,
4569            "the fixture must sit exactly on the gate for this boundary test"
4570        );
4571        let neighbours =
4572            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
4573
4574        let proof_bytes = group_floor_proof(
4575            &verifier,
4576            xorname,
4577            0,
4578            three_times(price_at_records(0)),
4579            &neighbours,
4580        );
4581
4582        let err = verifier
4583            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4584            .await
4585            .expect_err("exactly at the minimum sample the floor must evaluate and reject");
4586        assert!(format!("{err}").contains("below the close-group price floor"));
4587    }
4588
4589    /// A receiver with no live commitment of its own must skip.
4590    ///
4591    /// Such a node prices its OWN quotes at baseline, so holding an incoming
4592    /// payment to its neighbours' higher median would reject settlements it
4593    /// would itself have quoted. The gossip cache is fully populated here, so
4594    /// only the missing own commitment can cause the skip.
4595    #[tokio::test]
4596    async fn price_floor_skips_when_this_node_has_no_commitment() {
4597        let verifier = create_test_verifier();
4598        verifier.set_price_floor_for_tests(PriceFloorConfig {
4599            enforce: true,
4600            tolerance_percent: PRICE_FLOOR_DEFAULT_TOLERANCE_PERCENT,
4601        });
4602        let xorname = [0xDBu8; 32];
4603        let neighbours =
4604            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
4605
4606        let proof_bytes = group_floor_proof(
4607            &verifier,
4608            xorname,
4609            0,
4610            three_times(price_at_records(0)),
4611            &neighbours,
4612        );
4613
4614        let result = verifier
4615            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4616            .await;
4617
4618        assert_eq!(
4619            result.expect("a receiver with no commitment of its own must skip the floor"),
4620            PaymentStatus::PaymentVerified
4621        );
4622    }
4623
4624    /// A neighbour gossiping a count no honest node could hold must be dropped,
4625    /// not priced against.
4626    ///
4627    /// Gossip ingest authenticates the sender but does not bound the count,
4628    /// while quote validation rejects anything above `MAX_COMMITMENT_KEY_COUNT`.
4629    /// Without the filter, one such commitment inflates the reference and the
4630    /// floor becomes a way to reject other people's settled payments.
4631    #[tokio::test]
4632    async fn price_floor_ignores_commitments_above_the_protocol_cap() {
4633        let verifier = floor_test_verifier(true);
4634        let xorname = [0xDCu8; 32];
4635        // The honest builder refuses to construct an over-cap commitment, so
4636        // forge one the way a modified node would: build a valid commitment and
4637        // overwrite the signed count. Dropping it leaves the sample one short of
4638        // the gate, so the floor skips — that cardinality change is what this
4639        // test detects if the filter is removed. One over-cap value alone would
4640        // NOT move a 16-sample median; inflating the reference that way needs
4641        // about a quarter of the sample, which is the cardinality bound on
4642        // `group_reference_price` rather than something this filter fixes.
4643        let neighbours =
4644            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
4645        let over_cap = crate::replication::commitment::MAX_COMMITMENT_KEY_COUNT + 1;
4646        {
4647            let cache = verifier
4648                .commitment_cache
4649                .read()
4650                .as_ref()
4651                .map(Arc::clone)
4652                .expect("cache attached above");
4653            let mut guard = cache.write().await;
4654            let victim = neighbours.last().copied().unwrap_or_default();
4655            if let Some(record) = guard.get_mut(&PeerId::from_bytes(victim)) {
4656                let mut forged = record
4657                    .last_commitment()
4658                    .cloned()
4659                    .expect("fixture record holds a commitment");
4660                forged.key_count = over_cap;
4661                *record = crate::replication::commitment_state::PeerCommitmentRecord::from_verified(
4662                    forged,
4663                    std::time::Instant::now(),
4664                );
4665            }
4666        }
4667
4668        let proof_bytes = group_floor_proof(
4669            &verifier,
4670            xorname,
4671            0,
4672            three_times(price_at_records(0)),
4673            &neighbours,
4674        );
4675
4676        let result = verifier
4677            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4678            .await;
4679
4680        assert_eq!(
4681            result.expect("an over-cap gossiped count must be dropped, leaving too thin a sample"),
4682            PaymentStatus::PaymentVerified
4683        );
4684    }
4685
4686    /// Pins the other KNOWN LIMIT: four of fifteen OVERSTATING neighbours push
4687    /// the reference up far enough to reject an honest payment sitting at the
4688    /// true group median.
4689    ///
4690    /// This is the griefing direction, and the more serious of the two: the
4691    /// attacker spends nothing and the victim's money is already settled and
4692    /// unrefundable. Like its understating sibling this test asserts a weakness
4693    /// deliberately. If a future change improves the bound it will fail and must
4694    /// be re-derived rather than deleted.
4695    #[tokio::test]
4696    async fn group_median_is_griefed_by_four_overstated_commitments() {
4697        let verifier = floor_test_verifier(true);
4698        let xorname = [0xE0u8; 32];
4699        let neighbours =
4700            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
4701        forge_key_counts(&verifier, neighbours.get(..4), MAX_COMMITMENT_KEY_COUNT).await;
4702
4703        // A completely honest payment, priced at the TRUE group median.
4704        let honest = three_times(price_at_records(GROUP_TEST_MEDIAN_KEY_COUNT as usize));
4705        let proof_bytes = group_floor_proof(
4706            &verifier,
4707            xorname,
4708            GROUP_TEST_MEDIAN_KEY_COUNT as usize,
4709            honest,
4710            &neighbours,
4711        );
4712
4713        let err = verifier
4714            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4715            .await
4716            .expect_err(
4717                "KNOWN LIMIT: four overstated neighbours reject an honest at-median payment. \
4718                 If this now succeeds, the bound improved — re-derive it and update the docs.",
4719            );
4720        assert!(format!("{err}").contains("below the close-group price floor"));
4721    }
4722
4723    /// Pins the KNOWN LIMIT, so it is a fact in the test suite rather than a
4724    /// claim in a comment: four of fifteen understating neighbours DISARM the
4725    /// floor, admitting the cheapest-of-K underpayment it exists to reject.
4726    ///
4727    /// This test asserts a weakness on purpose. It is the concrete reason
4728    /// enforcement stays off, and if a future change improves the bound this
4729    /// test will fail and must be re-derived rather than quietly deleted.
4730    #[tokio::test]
4731    async fn group_median_is_disarmed_by_four_understated_commitments() {
4732        let verifier = floor_test_verifier(true);
4733        let xorname = [0xDFu8; 32];
4734        let mut counts: Vec<u32> = GROUP_TEST_KEY_COUNTS.to_vec();
4735        for slot in counts.iter_mut().rev().take(4) {
4736            *slot = 1;
4737        }
4738        let neighbours = attach_group_commitments(&verifier, &counts, std::time::Duration::ZERO);
4739
4740        let proof_bytes = group_floor_proof(
4741            &verifier,
4742            xorname,
4743            0,
4744            three_times(price_at_records(0)),
4745            &neighbours,
4746        );
4747
4748        let result = verifier
4749            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4750            .await;
4751
4752        assert_eq!(
4753            result.expect(
4754                "KNOWN LIMIT: four understated neighbours disarm the floor. If this now \
4755                 rejects, the bound improved — re-derive it and update the docs."
4756            ),
4757            PaymentStatus::PaymentVerified
4758        );
4759    }
4760
4761    /// The griefing direction: a small minority gossiping OVERSTATED
4762    /// commitments must not push the reference up far enough to make this node
4763    /// reject an honest, already settled payment.
4764    ///
4765    /// This is the dangerous direction of a false commitment. Understating only
4766    /// costs a missed underpayment; overstating destroys someone else's money,
4767    /// and the attacker spends nothing to do it.
4768    ///
4769    /// The bound is real but partial, and worth stating precisely rather than
4770    /// claiming immunity. Each liar shifts the order statistic up by one rank,
4771    /// so what protects the payment is the tolerance headroom, not the median
4772    /// itself. In this fixture three liars move the reference `2_600` ->
4773    /// `3_500` and an at-median payment still clears, by only 1.9%; four move it
4774    /// to `3_800`
4775    /// and the same payment is REJECTED (pinned by
4776    /// `group_median_is_griefed_by_four_overstated_commitments`). The griefing
4777    /// bound is therefore about a quarter of the sample, the same as the
4778    /// disarming one — NOT "roughly half", which was the incorrect claim this
4779    /// policy originally rested on.
4780    ///
4781    /// Estimator coverage: this case fails under a 25th percentile, and its
4782    /// disarming sibling fails under a mean and under the upper median, so the
4783    /// pair pins the estimator jointly. Neither does so alone.
4784    #[tokio::test]
4785    async fn group_median_resists_three_overstated_commitments() {
4786        let verifier = floor_test_verifier(true);
4787        let xorname = [0xDDu8; 32];
4788        // Three of fifteen neighbours claim the protocol maximum. Forged by
4789        // overwriting the signed count rather than building real 1,000,000-leaf
4790        // commitments, which cost about a second and 200 MB each.
4791        let neighbours =
4792            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
4793        forge_key_counts(&verifier, neighbours.get(..3), MAX_COMMITMENT_KEY_COUNT).await;
4794
4795        // An honest payment at the TRUE group median must still be admitted.
4796        let honest = three_times(price_at_records(GROUP_TEST_MEDIAN_KEY_COUNT as usize));
4797        let proof_bytes = group_floor_proof(
4798            &verifier,
4799            xorname,
4800            GROUP_TEST_MEDIAN_KEY_COUNT as usize,
4801            honest,
4802            &neighbours,
4803        );
4804
4805        let result = verifier
4806            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4807            .await;
4808
4809        assert_eq!(
4810            result.expect("a minority of overstated commitments must not reject honest payments"),
4811            PaymentStatus::PaymentVerified
4812        );
4813    }
4814
4815    /// Stale gossip is treated as unknown rather than as a low price, so a peer
4816    /// going quiet can neither drag the median down nor be counted toward the
4817    /// minimum sample.
4818    ///
4819    /// Every neighbour is stale, so the sample collapses below the gate and the
4820    /// floor skips instead of pricing against this node's own (huge) count.
4821    #[tokio::test]
4822    async fn price_floor_ignores_stale_group_commitments() {
4823        let verifier = floor_test_verifier(true);
4824        let xorname = [0xD5u8; 32];
4825        let stale_age = crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL
4826            + std::time::Duration::from_secs(60);
4827        let neighbours = attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, stale_age);
4828
4829        let proof_bytes = group_floor_proof(
4830            &verifier,
4831            xorname,
4832            0,
4833            three_times(price_at_records(0)),
4834            &neighbours,
4835        );
4836
4837        let result = verifier
4838            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4839            .await;
4840
4841        assert_eq!(
4842            result.expect("stale gossip must not be priced against"),
4843            PaymentStatus::PaymentVerified
4844        );
4845    }
4846
4847    /// A MIXED cache must exclude only the stale entries and price against the
4848    /// fresh ones.
4849    ///
4850    /// The all-stale test above collapses to the sample gate, so it would still
4851    /// pass if the TTL filter let stale counts through whenever enough fresh
4852    /// ones existed. This one pins the filter itself, and asserts on the
4853    /// reference directly rather than end-to-end.
4854    ///
4855    /// Going through `verify_payment` would need enough stale entries to move
4856    /// the median past the tolerance — more neighbours than production can ever
4857    /// present, since the K-closest scan returns at most 20 including self. The
4858    /// reference and the gated neighbour count are the precise observations
4859    /// anyway: if the TTL filter were removed, both would change.
4860    #[tokio::test]
4861    async fn price_floor_excludes_only_the_stale_entries_from_a_mixed_cache() {
4862        use crate::replication::commitment_state::PeerCommitmentRecord;
4863
4864        let verifier = floor_test_verifier(true);
4865        let xorname = [0xDEu8; 32];
4866        let stale_age = crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL
4867            + std::time::Duration::from_secs(60);
4868
4869        // Fresh: the full fixture, exactly on the gate.
4870        let fresh =
4871            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
4872
4873        // Stale: four cheap counts, keeping the total within the 19 neighbours a
4874        // real routing view can supply.
4875        let stale_counts = [1u32; 4];
4876        let stale_received = std::time::Instant::now()
4877            .checked_sub(stale_age)
4878            .expect("test clock must support the TTL offset");
4879        let mut all = fresh.clone();
4880        {
4881            let cache = verifier
4882                .commitment_cache
4883                .read()
4884                .as_ref()
4885                .map(Arc::clone)
4886                .expect("cache attached above");
4887            let mut guard = cache.write().await;
4888            for (index, count) in stale_counts.iter().enumerate() {
4889                let built = test_built_commitment(*count);
4890                let mut raw = [0u8; 32];
4891                raw[0] = 0xF0;
4892                raw[1] = u8::try_from(index).unwrap_or(u8::MAX);
4893                all.push(raw);
4894                guard.insert(
4895                    PeerId::from_bytes(raw),
4896                    PeerCommitmentRecord::from_verified(built.commitment().clone(), stale_received),
4897                );
4898            }
4899        }
4900        verifier.set_paid_quote_k_closest_for_tests(all);
4901
4902        let (reference, sample) = verifier.group_reference_price(&xorname).await;
4903
4904        assert_eq!(
4905            sample.neighbours,
4906            GROUP_TEST_KEY_COUNTS.len(),
4907            "stale entries must not count toward the gate"
4908        );
4909        assert_eq!(
4910            reference,
4911            Some(price_at_records(GROUP_TEST_MEDIAN_KEY_COUNT as usize)),
4912            "the reference must be the fresh-only median; counting the stale cheap \
4913             entries would drag it below"
4914        );
4915    }
4916
4917    /// Understated commitments pull the reference DOWN and weaken the floor.
4918    ///
4919    /// Three adversarially-placed liars leave it standing; four disarm it. The
4920    /// placement matters and is easy to get wrong: understating a peer that was
4921    /// already below the median changes nothing, so a test that rewrites the
4922    /// CHEAPEST entries passes while testing nothing. These rewrite the DEAREST
4923    /// ones, which is where an attacker would sit, and the count is set to the
4924    /// largest that still holds rather than to an aspirational majority.
4925    #[tokio::test]
4926    async fn group_median_resists_three_understated_commitments() {
4927        let verifier = floor_test_verifier(true);
4928        let xorname = [0xD6u8; 32];
4929        // Three of fifteen neighbours claim to store almost nothing. `1`, not
4930        // `0`: a commitment over an empty key set cannot be built at all, so one
4931        // key is the least a peer can honestly (or dishonestly) commit to.
4932        let mut counts: Vec<u32> = GROUP_TEST_KEY_COUNTS.to_vec();
4933        for slot in counts.iter_mut().rev().take(3) {
4934            *slot = 1;
4935        }
4936        let neighbours = attach_group_commitments(&verifier, &counts, std::time::Duration::ZERO);
4937
4938        let cheapest_price = price_at_records(0);
4939        let proof_bytes = group_floor_proof(
4940            &verifier,
4941            xorname,
4942            0,
4943            three_times(cheapest_price),
4944            &neighbours,
4945        );
4946
4947        let err = verifier
4948            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4949            .await
4950            .expect_err("a minority of understated commitments must not disarm the floor");
4951
4952        assert!(
4953            format!("{err}").contains("below the close-group price floor"),
4954            "Error should name the group price floor: {err}"
4955        );
4956    }
4957
4958    #[tokio::test]
4959    async fn test_price_floor_shadow_mode_accepts_below_floor_settlement() {
4960        let verifier = floor_test_verifier(false);
4961        let xorname = [0xC1u8; 32];
4962        let neighbours =
4963            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
4964        let settled = three_times(price_at_records(0));
4965        assert!(
4966            settled < group_floor_required_amount(),
4967            "shadow mode is only meaningful on a settlement that WOULD be rejected"
4968        );
4969        let proof_bytes = group_floor_proof(&verifier, xorname, 0, settled, &neighbours);
4970
4971        let result = verifier
4972            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4973            .await;
4974
4975        assert_eq!(
4976            result.expect("shadow mode must never reject on the floor"),
4977            PaymentStatus::PaymentVerified
4978        );
4979    }
4980
4981    #[tokio::test]
4982    async fn test_price_floor_enforced_rejects_cheapest_of_k_settlement() {
4983        let verifier = floor_test_verifier(true);
4984        let xorname = [0xC2u8; 32];
4985        let neighbours =
4986            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
4987        let settled = three_times(price_at_records(0));
4988        let proof_bytes = group_floor_proof(&verifier, xorname, 0, settled, &neighbours);
4989
4990        let err = verifier
4991            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
4992            .await
4993            .expect_err("a 3x-baseline settlement must not clear the group-median floor");
4994
4995        assert!(
4996            format!("{err}").contains("below the close-group price floor"),
4997            "Error should name the price floor: {err}"
4998        );
4999    }
5000
5001    #[tokio::test]
5002    async fn test_price_floor_enforced_accepts_exactly_at_floor_overpayment() {
5003        // An honest client may OVERPAY a cheap quote to clear stricter
5004        // receivers: the floor compares the settled amount, not the quote
5005        // price, and exactly-at-floor must pass.
5006        let verifier = floor_test_verifier(true);
5007        let xorname = [0xC3u8; 32];
5008        let neighbours =
5009            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
5010        let proof_bytes = group_floor_proof(
5011            &verifier,
5012            xorname,
5013            0,
5014            group_floor_required_amount(),
5015            &neighbours,
5016        );
5017
5018        let result = verifier
5019            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5020            .await;
5021
5022        assert_eq!(
5023            result.expect("an exactly-at-floor settlement must pass"),
5024            PaymentStatus::PaymentVerified
5025        );
5026    }
5027
5028    #[tokio::test]
5029    async fn test_price_floor_enforced_applies_to_fresh_replication() {
5030        // Fresh replication is the same fresh economic event as a direct PUT;
5031        // exempting it would let one cheap accepting node fan the proof out
5032        // around every other storer's floor.
5033        let verifier = floor_test_verifier(true);
5034        let xorname = [0xC4u8; 32];
5035        let neighbours =
5036            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
5037        let settled = three_times(price_at_records(0));
5038        let proof_bytes = group_floor_proof(&verifier, xorname, 0, settled, &neighbours);
5039
5040        let err = verifier
5041            .verify_payment(
5042                &xorname,
5043                Some(&proof_bytes),
5044                VerificationContext::FreshReplication,
5045            )
5046            .await
5047            .expect_err("fresh replication must enforce the same floor as direct PUTs");
5048
5049        assert!(
5050            format!("{err}").contains("below the close-group price floor"),
5051            "Error should name the price floor: {err}"
5052        );
5053    }
5054
5055    #[tokio::test]
5056    async fn test_price_floor_never_reprices_paid_list_admission() {
5057        let verifier = floor_test_verifier(true);
5058        let xorname = [0xC5u8; 32];
5059        let neighbours =
5060            attach_group_commitments(&verifier, &GROUP_TEST_KEY_COUNTS, std::time::Duration::ZERO);
5061        let settled = three_times(price_at_records(0));
5062        let proof_bytes = group_floor_proof(&verifier, xorname, 0, settled, &neighbours);
5063
5064        let result = verifier
5065            .verify_payment(
5066                &xorname,
5067                Some(&proof_bytes),
5068                VerificationContext::PaidListAdmission,
5069            )
5070            .await;
5071
5072        assert_eq!(
5073            result.expect("paid-list admission reprices no fresh economic decision"),
5074            PaymentStatus::PaymentVerified
5075        );
5076    }
5077
5078    /// A node that HAS its own commitment but no gossip cache must skip.
5079    ///
5080    /// This is the case that actually distinguishes the new behaviour from the
5081    /// old: under the withdrawn own-price rule this receiver priced the floor at
5082    /// its own enormous count and rejected the settlement. Now it has no group
5083    /// view, so it does not evaluate. Using a verifier with no commitment source
5084    /// at all (the obvious setup) would have passed under both rules and proved
5085    /// nothing.
5086    #[tokio::test]
5087    async fn test_price_floor_without_any_group_view_skips() {
5088        let verifier = floor_test_verifier(true);
5089        let xorname = [0xC6u8; 32];
5090        let settled = three_times(price_at_records(0));
5091        assert!(
5092            settled
5093                < price_at_records(FLOOR_TEST_LOCAL_KEY_COUNT as usize)
5094                    * Amount::from(PRICE_FLOOR_DEFAULT_TOLERANCE_PERCENT)
5095                    / Amount::from(100u64)
5096                    * Amount::from(PAID_QUOTE_PAYMENT_MULTIPLIER),
5097            "the old own-price rule would have rejected this settlement, so the skip is load-bearing"
5098        );
5099        let proof_bytes = cheap_single_quote_proof(&verifier, xorname, settled);
5100
5101        let result = verifier
5102            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5103            .await;
5104
5105        assert_eq!(
5106            result.expect("no group view must skip the floor, never reject"),
5107            PaymentStatus::PaymentVerified
5108        );
5109    }
5110
5111    /// `from_env` must fail CLOSED: a present-but-invalid tolerance can never
5112    /// leave enforcement on with a tolerance the operator did not specify.
5113    /// (This test owns the `PRICE_FLOOR_*` env vars — no other test reads them.)
5114    #[test]
5115    fn price_floor_from_env_fails_closed_on_invalid_tolerance() {
5116        // Defaults with nothing set.
5117        std::env::remove_var(PRICE_FLOOR_ENFORCE_ENV);
5118        std::env::remove_var(PRICE_FLOOR_TOLERANCE_ENV);
5119        let cfg = PriceFloorConfig::from_env();
5120        assert!(!cfg.enforce);
5121        assert_eq!(cfg.tolerance_percent, PRICE_FLOOR_DEFAULT_TOLERANCE_PERCENT);
5122
5123        // Enforce on, valid tolerance: honoured.
5124        std::env::set_var(PRICE_FLOOR_ENFORCE_ENV, "1");
5125        std::env::set_var(PRICE_FLOOR_TOLERANCE_ENV, "80");
5126        let cfg = PriceFloorConfig::from_env();
5127        assert!(cfg.enforce);
5128        assert_eq!(cfg.tolerance_percent, 80);
5129
5130        // Enforce on, out-of-range tolerance: enforcement DISABLED (fail closed).
5131        std::env::set_var(PRICE_FLOOR_TOLERANCE_ENV, "150");
5132        let cfg = PriceFloorConfig::from_env();
5133        assert!(
5134            !cfg.enforce,
5135            "an out-of-range tolerance must not silently enforce a default"
5136        );
5137
5138        // Enforce on, unparseable tolerance: also disabled.
5139        std::env::set_var(PRICE_FLOOR_TOLERANCE_ENV, "loose");
5140        let cfg = PriceFloorConfig::from_env();
5141        assert!(!cfg.enforce);
5142
5143        std::env::remove_var(PRICE_FLOOR_ENFORCE_ENV);
5144        std::env::remove_var(PRICE_FLOOR_TOLERANCE_ENV);
5145    }
5146
5147    #[tokio::test]
5148    async fn test_legacy_single_quote_proof_requires_three_x_payment() {
5149        let verifier = create_test_verifier();
5150        let xorname = [0xB2u8; 32];
5151        let (peer_id, quote) = make_signed_quote(xorname, price_at_records(0), 1);
5152        let peer_quotes = vec![(peer_id, quote.clone())];
5153        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
5154        mark_candidate_paid(&verifier, &quote, quote.price);
5155
5156        let proof_bytes = serialize_proof(peer_quotes);
5157        let err = verifier
5158            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5159            .await
5160            .expect_err("single quote paid less than 3x should be rejected");
5161
5162        assert!(
5163            format!("{err}").contains("not paid enough"),
5164            "Error should mention underpayment: {err}"
5165        );
5166    }
5167
5168    #[tokio::test]
5169    async fn test_legacy_too_many_quotes_rejected() {
5170        let verifier = create_test_verifier();
5171        let xorname = [0xB3u8; 32];
5172        let mut peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
5173        peer_quotes.push(make_signed_quote(xorname, price_at_records(7), 8));
5174
5175        let proof_bytes = serialize_proof(peer_quotes);
5176        let err = verifier
5177            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5178            .await
5179            .expect_err("proof with more than close-group quotes should be rejected");
5180
5181        assert!(
5182            format!("{err}").contains("at most"),
5183            "Error should mention max quote count: {err}"
5184        );
5185    }
5186
5187    #[tokio::test]
5188    async fn test_legacy_structural_majority_price_at_median_accepted() {
5189        let verifier = create_test_verifier();
5190        let xorname = [0xA2u8; 32];
5191        let peer_quotes = make_signed_legacy_bundle(
5192            xorname,
5193            [
5194                crate::payment::pricing::calculate_price(0),
5195                crate::payment::pricing::calculate_price(100),
5196                crate::payment::pricing::calculate_price(500),
5197                crate::payment::pricing::calculate_price(1000),
5198                crate::payment::pricing::calculate_price(2000),
5199                crate::payment::pricing::calculate_price(4000),
5200                crate::payment::pricing::calculate_price(6000),
5201            ],
5202        );
5203        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
5204        let expected_amount = expected_median_payment(&peer_quotes);
5205        let paid_quote = median_test_candidates(&peer_quotes)
5206            .first()
5207            .expect("median candidate")
5208            .1
5209            .clone();
5210        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
5211
5212        let proof_bytes = serialize_proof(peer_quotes);
5213        let result = verifier
5214            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5215            .await;
5216
5217        assert_eq!(
5218            result.expect("median-priced verifier should accept"),
5219            PaymentStatus::PaymentVerified
5220        );
5221    }
5222
5223    #[tokio::test]
5224    async fn test_legacy_paid_median_issuer_k_closest_rejection() {
5225        let verifier = create_test_verifier();
5226        verifier.set_paid_quote_k_closest_for_tests(vec![rand::random()]);
5227        let xorname = [0xA4u8; 32];
5228        let peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
5229        let expected_amount = expected_median_payment(&peer_quotes);
5230        let paid_quote = median_test_candidates(&peer_quotes)
5231            .first()
5232            .expect("median candidate")
5233            .1
5234            .clone();
5235        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
5236
5237        let proof_bytes = serialize_proof(peer_quotes);
5238        let err = verifier
5239            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5240            .await
5241            .expect_err("out-of-K paid issuer should be rejected");
5242
5243        assert!(
5244            format!("{err}").contains("not among this node's local"),
5245            "Error should mention local K-closest peers: {err}"
5246        );
5247    }
5248
5249    /// A zero-priced median must never be admitted.
5250    ///
5251    /// Which check rejects it depends on the ADR-0004 rollout gate. `Amount::ZERO`
5252    /// is not a point on the pricing curve (the curve's minimum is
5253    /// `calculate_price(0)`), so with
5254    /// [`crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED`] on, the
5255    /// arithmetic gate rejects the bundle before median selection runs and the
5256    /// dedicated zero-price check is no longer reachable for single-node quotes.
5257    /// The gate subsumes it rather than replacing it, so both messages are
5258    /// accepted here and the invariant under test stays "this is rejected".
5259    #[tokio::test]
5260    async fn test_legacy_zero_price_median_rejected() {
5261        let verifier = create_test_verifier();
5262        let xorname = [0xA6u8; 32];
5263        let peer_quotes = make_signed_legacy_bundle(
5264            xorname,
5265            [
5266                Amount::ZERO,
5267                Amount::ZERO,
5268                Amount::ZERO,
5269                Amount::ZERO,
5270                Amount::from(1u64),
5271                Amount::from(2u64),
5272                Amount::from(3u64),
5273            ],
5274        );
5275
5276        let proof_bytes = serialize_proof(peer_quotes);
5277        let err = verifier
5278            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5279            .await
5280            .expect_err("zero median must be rejected");
5281
5282        let msg = format!("{err}");
5283        assert!(
5284            msg.contains("zero price") || msg.contains("off-curve quote rejected"),
5285            "Error must reject the zero-priced median, by either the zero-price \
5286             check or the ADR-0004 arithmetic gate: {msg}"
5287        );
5288    }
5289
5290    #[tokio::test]
5291    async fn test_legacy_paid_quote_content_mismatch_rejected() {
5292        let verifier = create_test_verifier();
5293        let xorname = [0xA7u8; 32];
5294        let mut peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
5295        let median_index = median_quote_index(peer_quotes.len());
5296        peer_quotes[median_index].1.content = xor_name::XorName([0xE7u8; 32]);
5297        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
5298
5299        let proof_bytes = serialize_proof(peer_quotes);
5300        let err = verifier
5301            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5302            .await
5303            .expect_err("paid quote content mismatch should be rejected");
5304
5305        assert!(
5306            format!("{err}").contains("content address mismatch"),
5307            "Error should mention content mismatch: {err}"
5308        );
5309    }
5310
5311    #[tokio::test]
5312    async fn test_legacy_unpaid_quote_content_mismatch_accepted() {
5313        let verifier = create_test_verifier();
5314        let xorname = [0xA8u8; 32];
5315        let mut peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
5316        peer_quotes[0].1.content = xor_name::XorName([0xE8u8; 32]);
5317        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
5318        let expected_amount = expected_median_payment(&peer_quotes);
5319        let paid_quote = median_test_candidates(&peer_quotes)
5320            .first()
5321            .expect("median candidate")
5322            .1
5323            .clone();
5324        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
5325
5326        let proof_bytes = serialize_proof(peer_quotes);
5327        let result = verifier
5328            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5329            .await;
5330
5331        assert_eq!(
5332            result.expect("unpaid content mismatch should be ignored"),
5333            PaymentStatus::PaymentVerified
5334        );
5335    }
5336
5337    #[tokio::test]
5338    async fn test_legacy_paid_quote_bad_signature_rejected() {
5339        let verifier = create_test_verifier();
5340        let xorname = [0xA9u8; 32];
5341        let mut peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
5342        let median_index = median_quote_index(peer_quotes.len());
5343        peer_quotes[median_index].1.signature.push(0xFF);
5344        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
5345        let expected_amount = expected_median_payment(&peer_quotes);
5346        let paid_quote = median_test_candidates(&peer_quotes)
5347            .first()
5348            .expect("median candidate")
5349            .1
5350            .clone();
5351        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
5352
5353        let proof_bytes = serialize_proof(peer_quotes);
5354        let err = verifier
5355            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5356            .await
5357            .expect_err("paid bad signature should be rejected");
5358
5359        assert!(
5360            format!("{err}").contains("signature verification failed"),
5361            "Error should mention signature failure: {err}"
5362        );
5363    }
5364
5365    #[tokio::test]
5366    async fn test_legacy_unpaid_quote_bad_signature_accepted() {
5367        let verifier = create_test_verifier();
5368        let xorname = [0xAAu8; 32];
5369        let mut peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
5370        peer_quotes[0].1.signature.push(0xFF);
5371        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
5372        let expected_amount = expected_median_payment(&peer_quotes);
5373        let paid_quote = median_test_candidates(&peer_quotes)
5374            .first()
5375            .expect("median candidate")
5376            .1
5377            .clone();
5378        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
5379
5380        let proof_bytes = serialize_proof(peer_quotes);
5381        let result = verifier
5382            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5383            .await;
5384
5385        assert_eq!(
5386            result.expect("unpaid bad signature should be ignored"),
5387            PaymentStatus::PaymentVerified
5388        );
5389    }
5390
5391    #[tokio::test]
5392    async fn test_legacy_unpaid_peer_binding_mismatch_accepted() {
5393        let verifier = create_test_verifier();
5394        let xorname = [0xABu8; 32];
5395        let mut peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
5396        peer_quotes[0].0 = evmlib::EncodedPeerId::new(rand::random());
5397        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
5398        let expected_amount = expected_median_payment(&peer_quotes);
5399        let paid_quote = median_test_candidates(&peer_quotes)
5400            .first()
5401            .expect("median candidate")
5402            .1
5403            .clone();
5404        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
5405
5406        let proof_bytes = serialize_proof(peer_quotes);
5407        let result = verifier
5408            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5409            .await;
5410
5411        assert_eq!(
5412            result.expect("unpaid peer binding mismatch should be ignored"),
5413            PaymentStatus::PaymentVerified
5414        );
5415    }
5416
5417    #[tokio::test]
5418    async fn test_legacy_median_tie_accepts_paid_candidate() {
5419        let verifier = create_test_verifier();
5420        let xorname = [0xACu8; 32];
5421        let peer_quotes = make_signed_legacy_bundle(xorname, tied_median_test_prices());
5422        mark_k_closest_paid_candidates(&verifier, &peer_quotes);
5423        mark_all_median_candidates_unpaid(&verifier, &peer_quotes);
5424        let expected_amount = expected_median_payment(&peer_quotes);
5425        let paid_quote = median_test_candidates(&peer_quotes)
5426            .get(1)
5427            .expect("second tied median candidate")
5428            .1
5429            .clone();
5430        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
5431
5432        let proof_bytes = serialize_proof(peer_quotes);
5433        let result = verifier
5434            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5435            .await;
5436
5437        assert_eq!(
5438            result.expect("one paid tied median candidate should verify"),
5439            PaymentStatus::PaymentVerified
5440        );
5441    }
5442
5443    #[tokio::test]
5444    async fn test_legacy_paid_list_admission_enforces_issuer_k_closest() {
5445        let verifier = create_test_verifier();
5446        verifier.set_paid_quote_k_closest_for_tests(Vec::new());
5447        let xorname = [0xB5u8; 32];
5448        let peer_quotes = make_signed_legacy_bundle(xorname, unique_test_prices());
5449        let expected_amount = expected_median_payment(&peer_quotes);
5450        let paid_quote = median_test_candidates(&peer_quotes)
5451            .first()
5452            .expect("median candidate")
5453            .1
5454            .clone();
5455        mark_candidate_paid(&verifier, &paid_quote, expected_amount);
5456
5457        let proof_bytes = serialize_proof(peer_quotes);
5458        let err = verifier
5459            .verify_payment(
5460                &xorname,
5461                Some(&proof_bytes),
5462                VerificationContext::PaidListAdmission,
5463            )
5464            .await
5465            .expect_err("paid-list admission must enforce the paid issuer K-closest check");
5466
5467        assert!(
5468            format!("{err}").contains("not among this node's local"),
5469            "Error should mention local K-closest peers: {err}"
5470        );
5471    }
5472
5473    #[test]
5474    fn test_cache_len_getter() {
5475        let verifier = create_test_verifier();
5476        assert_eq!(verifier.cache_len(), 0);
5477
5478        verifier.cache.insert([10u8; 32]);
5479        assert_eq!(verifier.cache_len(), 1);
5480
5481        verifier.cache.insert([20u8; 32]);
5482        assert_eq!(verifier.cache_len(), 2);
5483    }
5484
5485    #[test]
5486    fn test_cache_stats_after_operations() {
5487        let verifier = create_test_verifier();
5488        let xorname = [7u8; 32];
5489
5490        // Miss
5491        verifier.check_payment_required(&xorname, VerificationContext::ClientPut);
5492        let stats = verifier.cache_stats();
5493        assert_eq!(stats.misses, 1);
5494        assert_eq!(stats.hits, 0);
5495
5496        // Insert and hit
5497        verifier.cache.insert(xorname);
5498        verifier.check_payment_required(&xorname, VerificationContext::ClientPut);
5499        let stats = verifier.cache_stats();
5500        assert_eq!(stats.hits, 1);
5501        assert_eq!(stats.misses, 1);
5502        assert_eq!(stats.additions, 1);
5503    }
5504
5505    #[tokio::test]
5506    async fn test_concurrent_cache_lookups() {
5507        let verifier = std::sync::Arc::new(create_test_verifier());
5508
5509        // Pre-populate cache for all 10 xornames
5510        for i in 0..10u8 {
5511            verifier.cache.insert([i; 32]);
5512        }
5513
5514        let mut handles = Vec::new();
5515        for i in 0..10u8 {
5516            let v = verifier.clone();
5517            handles.push(tokio::spawn(async move {
5518                let xorname = [i; 32];
5519                v.verify_payment(&xorname, None, VerificationContext::ClientPut)
5520                    .await
5521            }));
5522        }
5523
5524        for handle in handles {
5525            let result = handle.await.expect("task panicked");
5526            assert!(result.is_ok());
5527            assert_eq!(result.expect("cached"), PaymentStatus::CachedAsVerified);
5528        }
5529
5530        assert_eq!(verifier.cache_len(), 10);
5531    }
5532
5533    #[test]
5534    fn test_default_evm_config() {
5535        let _config = EvmVerifierConfig::default();
5536        // EVM is always on — default network is ArbitrumOne
5537    }
5538
5539    #[test]
5540    fn test_real_ml_dsa_proof_size_within_limits() {
5541        use crate::payment::metrics::QuotingMetricsTracker;
5542        use crate::payment::proof::PaymentProof;
5543        use crate::payment::quote::{QuoteGenerator, XorName};
5544        use alloy::primitives::FixedBytes;
5545        use evmlib::{EncodedPeerId, RewardsAddress};
5546        use saorsa_core::MlDsa65;
5547        use saorsa_pqc::pqc::types::MlDsaSecretKey;
5548        use saorsa_pqc::pqc::MlDsaOperations;
5549
5550        let ml_dsa = MlDsa65::new();
5551        let mut peer_quotes = Vec::new();
5552
5553        for i in 0..5u8 {
5554            let (public_key, secret_key) = ml_dsa.generate_keypair().expect("keygen");
5555
5556            let rewards_address = RewardsAddress::new([i; 20]);
5557            let metrics_tracker = QuotingMetricsTracker::new(0);
5558            let mut generator = QuoteGenerator::new(rewards_address, metrics_tracker);
5559
5560            let pub_key_bytes = public_key.as_bytes().to_vec();
5561            let sk_bytes = secret_key.as_bytes().to_vec();
5562            generator.set_signer(pub_key_bytes, move |msg| {
5563                let sk = MlDsaSecretKey::from_bytes(&sk_bytes).expect("sk parse");
5564                let ml_dsa = MlDsa65::new();
5565                ml_dsa.sign(&sk, msg).expect("sign").as_bytes().to_vec()
5566            });
5567
5568            let content: XorName = [i; 32];
5569            let quote = generator.create_quote(content, 4096, 0).expect("quote");
5570
5571            peer_quotes.push((EncodedPeerId::new(rand::random()), quote));
5572        }
5573
5574        let proof = PaymentProof {
5575            proof_of_payment: ProofOfPayment { peer_quotes },
5576            tx_hashes: vec![FixedBytes::from([0xABu8; 32])],
5577            commitment_sidecars: vec![],
5578        };
5579
5580        let proof_bytes =
5581            crate::payment::proof::serialize_single_node_proof(&proof).expect("serialize");
5582
5583        // 7 ML-DSA-65 quotes with ~1952-byte pub keys and ~3309-byte signatures
5584        // should produce a proof in the 30-80 KB range
5585        assert!(
5586            proof_bytes.len() > 20_000,
5587            "Real 7-quote ML-DSA proof should be > 20 KB, got {} bytes",
5588            proof_bytes.len()
5589        );
5590        assert!(
5591            proof_bytes.len() < MAX_PAYMENT_PROOF_SIZE_BYTES,
5592            "Real 7-quote ML-DSA proof ({} bytes) should fit within {} byte limit",
5593            proof_bytes.len(),
5594            MAX_PAYMENT_PROOF_SIZE_BYTES
5595        );
5596    }
5597
5598    #[tokio::test]
5599    async fn test_content_address_mismatch_rejected() {
5600        use crate::payment::proof::{serialize_single_node_proof, PaymentProof};
5601        use evmlib::{EncodedPeerId, PaymentQuote, RewardsAddress};
5602        use std::time::SystemTime;
5603
5604        let verifier = create_test_verifier();
5605
5606        // The xorname we're trying to store
5607        let target_xorname = [0xAAu8; 32];
5608
5609        // Create a quote for a DIFFERENT xorname
5610        let wrong_xorname = [0xBBu8; 32];
5611        let quote = PaymentQuote {
5612            content: xor_name::XorName(wrong_xorname),
5613            timestamp: SystemTime::now(),
5614            // Baseline-priced so the quote is on-curve: this test is about the
5615            // content binding, and an off-curve price would be rejected by the
5616            // ADR-0004 arithmetic gate first, never reaching that check.
5617            price: crate::payment::pricing::calculate_price(0),
5618            rewards_address: RewardsAddress::new([1u8; 20]),
5619            committed_key_count: 0,
5620            commitment_pin: None,
5621            pub_key: vec![0u8; 64],
5622            signature: vec![0u8; 64],
5623        };
5624
5625        // Build CLOSE_GROUP_SIZE quotes with distinct peer IDs
5626        let mut peer_quotes = Vec::new();
5627        for _ in 0..CLOSE_GROUP_SIZE {
5628            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
5629        }
5630
5631        let proof = PaymentProof {
5632            proof_of_payment: ProofOfPayment { peer_quotes },
5633            tx_hashes: vec![],
5634            commitment_sidecars: vec![],
5635        };
5636
5637        let proof_bytes = serialize_single_node_proof(&proof).expect("serialize proof");
5638
5639        let result = verifier
5640            .verify_payment(
5641                &target_xorname,
5642                Some(&proof_bytes),
5643                VerificationContext::ClientPut,
5644            )
5645            .await;
5646
5647        assert!(result.is_err(), "Should reject mismatched content address");
5648        let err_msg = format!("{}", result.expect_err("should be error"));
5649        assert!(
5650            err_msg.contains("content address mismatch"),
5651            "Error should mention 'content address mismatch': {err_msg}"
5652        );
5653    }
5654
5655    /// Helper: create a fake quote with the given xorname and timestamp.
5656    fn make_fake_quote(
5657        xorname: [u8; 32],
5658        timestamp: SystemTime,
5659        rewards_address: RewardsAddress,
5660    ) -> evmlib::PaymentQuote {
5661        use evmlib::PaymentQuote;
5662
5663        PaymentQuote {
5664            content: xor_name::XorName(xorname),
5665            timestamp,
5666            // Baseline quote: `(committed_key_count = 0, commitment_pin = None)`
5667            // must be priced at `calculate_price(0)` to satisfy the ADR-0004
5668            // binding rule. An arbitrary placeholder price here is off-curve and
5669            // is rejected outright once
5670            // [`crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED`] is
5671            // on, which would mask whatever a test actually means to assert.
5672            price: crate::payment::pricing::calculate_price(0),
5673            rewards_address,
5674            committed_key_count: 0,
5675            commitment_pin: None,
5676            pub_key: vec![0u8; 64],
5677            signature: vec![0u8; 64],
5678        }
5679    }
5680
5681    /// Helper: create a fake quote priced on-curve at `records` stored records
5682    /// (price = `calculate_price(records)`), reusing [`make_fake_quote`] for the
5683    /// remaining fields. Used by the ADR-0004 arithmetic-gate tests.
5684    ///
5685    /// Sets the whole binding, not just the price: ADR-0004 requires `price ==
5686    /// calculate_price(committed_key_count)` AND the `(n > 0, Some(pin))` /
5687    /// `(0, None)` shape, so pricing at `records` while leaving the count at `0`
5688    /// produces a quote that claims to store nothing yet charges as though it
5689    /// stored `records` keys. That is exactly what the gate rejects.
5690    fn make_fake_quote_at_records(
5691        xorname: [u8; 32],
5692        timestamp: SystemTime,
5693        rewards_address: RewardsAddress,
5694        records: usize,
5695    ) -> evmlib::PaymentQuote {
5696        let mut quote = make_fake_quote(xorname, timestamp, rewards_address);
5697        quote.price = crate::payment::pricing::calculate_price(records);
5698        quote.committed_key_count = u32::try_from(records).unwrap_or(u32::MAX);
5699        quote.commitment_pin = if records == 0 {
5700            None
5701        } else {
5702            // Any stable non-zero pin: these fixtures never resolve it to a real
5703            // commitment, they only need the binding shape to be coherent.
5704            Some([0xA5u8; 32])
5705        };
5706        quote
5707    }
5708
5709    /// Helper: wrap quotes into a tagged serialized `PaymentProof`.
5710    fn serialize_proof(peer_quotes: Vec<(evmlib::EncodedPeerId, evmlib::PaymentQuote)>) -> Vec<u8> {
5711        use crate::payment::proof::{serialize_single_node_proof, PaymentProof};
5712
5713        let proof = PaymentProof {
5714            proof_of_payment: ProofOfPayment { peer_quotes },
5715            tx_hashes: vec![],
5716            commitment_sidecars: vec![],
5717        };
5718        serialize_single_node_proof(&proof).expect("serialize proof")
5719    }
5720
5721    #[tokio::test]
5722    async fn test_old_quote_uses_storage_delta_not_timestamp() {
5723        use evmlib::{EncodedPeerId, RewardsAddress};
5724        use std::time::Duration;
5725
5726        let verifier = create_test_verifier();
5727        let xorname = [0xCCu8; 32];
5728        let rewards_addr = RewardsAddress::new([1u8; 20]);
5729
5730        // Create a quote that's 25 hours old (exceeds 24-hour max)
5731        let old_timestamp = SystemTime::now() - Duration::from_secs(25 * 3600);
5732        let quote = make_fake_quote(xorname, old_timestamp, rewards_addr);
5733
5734        let mut peer_quotes = Vec::new();
5735        for _ in 0..CLOSE_GROUP_SIZE {
5736            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
5737        }
5738
5739        let proof_bytes = serialize_proof(peer_quotes);
5740        let result = verifier
5741            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5742            .await;
5743
5744        let err_msg = format!("{}", result.expect_err("should fail at later check"));
5745        assert!(
5746            !err_msg.contains("expired"),
5747            "Should not reject by timestamp age: {err_msg}"
5748        );
5749    }
5750
5751    #[tokio::test]
5752    async fn test_future_quote_uses_storage_delta_not_timestamp() {
5753        use evmlib::{EncodedPeerId, RewardsAddress};
5754        use std::time::Duration;
5755
5756        let verifier = create_test_verifier();
5757        let xorname = [0xDDu8; 32];
5758        let rewards_addr = RewardsAddress::new([1u8; 20]);
5759
5760        // Create a quote with a timestamp 1 hour in the future
5761        let future_timestamp = SystemTime::now() + Duration::from_secs(3600);
5762        let quote = make_fake_quote(xorname, future_timestamp, rewards_addr);
5763
5764        let mut peer_quotes = Vec::new();
5765        for _ in 0..CLOSE_GROUP_SIZE {
5766            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
5767        }
5768
5769        let proof_bytes = serialize_proof(peer_quotes);
5770        let result = verifier
5771            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5772            .await;
5773
5774        let err_msg = format!("{}", result.expect_err("should fail at later check"));
5775        assert!(
5776            !err_msg.contains("future"),
5777            "Should not reject by future timestamp: {err_msg}"
5778        );
5779    }
5780
5781    #[tokio::test]
5782    async fn test_quote_within_clock_skew_tolerance_accepted() {
5783        use evmlib::{EncodedPeerId, RewardsAddress};
5784        use std::time::Duration;
5785
5786        let verifier = create_test_verifier();
5787        let xorname = [0xD1u8; 32];
5788        let rewards_addr = RewardsAddress::new([1u8; 20]);
5789
5790        // Quote 30 seconds in the future — well within 300s tolerance
5791        let future_timestamp = SystemTime::now() + Duration::from_secs(30);
5792        let quote = make_fake_quote(xorname, future_timestamp, rewards_addr);
5793
5794        let mut peer_quotes = Vec::new();
5795        for _ in 0..CLOSE_GROUP_SIZE {
5796            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
5797        }
5798
5799        let proof_bytes = serialize_proof(peer_quotes);
5800        let result = verifier
5801            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5802            .await;
5803
5804        // Should NOT fail at timestamp check (will fail later at pub_key binding)
5805        let err_msg = format!("{}", result.expect_err("should fail at later check"));
5806        assert!(
5807            !err_msg.contains("future"),
5808            "Should pass timestamp check (within tolerance), but got: {err_msg}"
5809        );
5810    }
5811
5812    #[tokio::test]
5813    async fn test_quote_beyond_clock_skew_still_uses_storage_delta() {
5814        use evmlib::{EncodedPeerId, RewardsAddress};
5815        use std::time::Duration;
5816
5817        let verifier = create_test_verifier();
5818        let xorname = [0xD2u8; 32];
5819        let rewards_addr = RewardsAddress::new([1u8; 20]);
5820
5821        // Quote 360 seconds in the future — exceeds 300s tolerance
5822        let future_timestamp = SystemTime::now() + Duration::from_secs(360);
5823        let quote = make_fake_quote(xorname, future_timestamp, rewards_addr);
5824
5825        let mut peer_quotes = Vec::new();
5826        for _ in 0..CLOSE_GROUP_SIZE {
5827            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
5828        }
5829
5830        let proof_bytes = serialize_proof(peer_quotes);
5831        let result = verifier
5832            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5833            .await;
5834
5835        let err_msg = format!("{}", result.expect_err("should fail at later check"));
5836        assert!(
5837            !err_msg.contains("future"),
5838            "Should not reject by future timestamp: {err_msg}"
5839        );
5840    }
5841
5842    #[tokio::test]
5843    async fn test_quote_23h_old_still_accepted() {
5844        use evmlib::{EncodedPeerId, RewardsAddress};
5845        use std::time::Duration;
5846
5847        let verifier = create_test_verifier();
5848        let xorname = [0xD3u8; 32];
5849        let rewards_addr = RewardsAddress::new([1u8; 20]);
5850
5851        // Quote 23 hours old — within 24h max age
5852        let old_timestamp = SystemTime::now() - Duration::from_secs(23 * 3600);
5853        let quote = make_fake_quote(xorname, old_timestamp, rewards_addr);
5854
5855        let mut peer_quotes = Vec::new();
5856        for _ in 0..CLOSE_GROUP_SIZE {
5857            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
5858        }
5859
5860        let proof_bytes = serialize_proof(peer_quotes);
5861        let result = verifier
5862            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5863            .await;
5864
5865        // Should NOT fail at timestamp check (will fail later at pub_key binding)
5866        let err_msg = format!("{}", result.expect_err("should fail at later check"));
5867        assert!(
5868            !err_msg.contains("expired"),
5869            "Should pass expiry check (23h < 24h), but got: {err_msg}"
5870        );
5871    }
5872
5873    /// Helper: build an `EncodedPeerId` that matches the BLAKE3 hash of an ML-DSA public key.
5874    fn encoded_peer_id_for_pub_key(pub_key: &[u8]) -> evmlib::EncodedPeerId {
5875        let ant_peer_id = peer_id_from_public_key_bytes(pub_key).expect("valid ML-DSA pub key");
5876        evmlib::EncodedPeerId::new(*ant_peer_id.as_bytes())
5877    }
5878
5879    #[tokio::test]
5880    async fn test_wrong_peer_binding_rejected() {
5881        use evmlib::{EncodedPeerId, RewardsAddress};
5882        use saorsa_core::MlDsa65;
5883        use saorsa_pqc::pqc::MlDsaOperations;
5884
5885        let verifier = create_test_verifier();
5886        let xorname = [0xFFu8; 32];
5887        let rewards_addr = RewardsAddress::new([1u8; 20]);
5888
5889        // Generate a real ML-DSA keypair so pub_key is valid
5890        let ml_dsa = MlDsa65::new();
5891        let (public_key, _secret_key) = ml_dsa.generate_keypair().expect("keygen");
5892        let pub_key_bytes = public_key.as_bytes().to_vec();
5893
5894        // Create a quote with a real pub_key but attach it to a random peer ID
5895        // whose identity multihash does NOT match BLAKE3(pub_key)
5896        let mut quote = make_fake_quote(xorname, SystemTime::now(), rewards_addr);
5897        quote.pub_key = pub_key_bytes;
5898
5899        // Use random ed25519 peer IDs — they won't match BLAKE3(pub_key)
5900        let mut peer_quotes = Vec::new();
5901        for _ in 0..CLOSE_GROUP_SIZE {
5902            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
5903        }
5904
5905        let proof_bytes = serialize_proof(peer_quotes);
5906        let result = verifier
5907            .verify_payment(&xorname, Some(&proof_bytes), VerificationContext::ClientPut)
5908            .await;
5909
5910        assert!(result.is_err(), "Should reject wrong peer binding");
5911        let err_msg = format!("{}", result.expect_err("should fail"));
5912        assert!(
5913            err_msg.contains("pub_key does not belong to claimed peer"),
5914            "Error should mention binding mismatch: {err_msg}"
5915        );
5916    }
5917
5918    // =========================================================================
5919    // VerificationContext tests — both contexts verify fresh proof admissions.
5920    // Later neighbour-sync repair has no proof-of-payment and is authorized by
5921    // closest-7 storage quorum or closest-K paid-list quorum instead.
5922    // =========================================================================
5923
5924    /// Content binding is required for every fresh proof context. A receipt for
5925    /// chunk A cannot admit chunk B as either a direct/fresh store or a fresh
5926    /// paid-list update.
5927    #[tokio::test]
5928    async fn test_fresh_contexts_reject_content_mismatch() {
5929        let verifier = create_test_verifier();
5930        let stored_xorname = [0xD2u8; 32];
5931        let quoted_xorname = [0xD3u8; 32];
5932        let rewards = RewardsAddress::new([1u8; 20]);
5933
5934        let mut peer_quotes = Vec::new();
5935        for _ in 0..CLOSE_GROUP_SIZE {
5936            let quote = make_fake_quote(quoted_xorname, SystemTime::now(), rewards);
5937            peer_quotes.push((evmlib::EncodedPeerId::new(rand::random()), quote));
5938        }
5939        let proof_bytes = serialize_proof(peer_quotes);
5940
5941        for context in [
5942            VerificationContext::ClientPut,
5943            VerificationContext::FreshReplication,
5944            VerificationContext::PaidListAdmission,
5945        ] {
5946            let err = verifier
5947                .verify_payment(&stored_xorname, Some(&proof_bytes), context)
5948                .await
5949                .expect_err("content binding must hold in every context");
5950            assert!(
5951                format!("{err}").contains("content address mismatch"),
5952                "{context:?} must reject a receipt for a different address: {err}"
5953            );
5954        }
5955    }
5956
5957    /// The merkle pay-yourself closeness defence (including its duplicate-
5958    /// candidate pre-check, which runs without a `P2PNode`) applies to every
5959    /// proof verification context because every context is a fresh admission.
5960    #[tokio::test]
5961    async fn test_fresh_contexts_enforce_merkle_closeness() {
5962        let verifier = create_test_verifier();
5963
5964        let (mut merkle_proof, _pool_hash, xorname, _timestamp) = make_valid_merkle_proof();
5965
5966        // 16 copies of one real candidate: every self-signature is valid, but
5967        // the candidate PeerIds are duplicates — the closeness pre-check
5968        // rejects this pool on a client PUT.
5969        let shared = merkle_proof
5970            .winner_pool
5971            .candidate_nodes
5972            .first()
5973            .expect("candidates")
5974            .clone();
5975        for c in &mut merkle_proof.winner_pool.candidate_nodes {
5976            *c = shared.clone();
5977        }
5978        let tagged =
5979            crate::payment::proof::serialize_merkle_proof(&merkle_proof).expect("serialize");
5980
5981        for context in [
5982            VerificationContext::ClientPut,
5983            VerificationContext::FreshReplication,
5984            VerificationContext::PaidListAdmission,
5985        ] {
5986            let err = verifier
5987                .verify_payment(&xorname, Some(&tagged), context)
5988                .await
5989                .expect_err("duplicate candidate PeerIds must fail fresh admission closeness");
5990            assert!(
5991                format!("{err}").contains("duplicate candidate PeerId"),
5992                "{context:?} must fail at the closeness pre-check: {err}"
5993            );
5994        }
5995    }
5996
5997    // =========================================================================
5998    // Merkle-tagged proof tests
5999    // =========================================================================
6000
6001    #[tokio::test]
6002    async fn test_merkle_tagged_proof_invalid_data_rejected() {
6003        use crate::ant_protocol::PROOF_TAG_MERKLE;
6004
6005        let verifier = merkle_test_verifier();
6006        let xorname = [0xA1u8; 32];
6007
6008        // Build a merkle-tagged proof with garbage body.
6009        // The tag byte is correct but the body is not valid msgpack.
6010        let mut merkle_garbage = Vec::with_capacity(64);
6011        merkle_garbage.push(PROOF_TAG_MERKLE);
6012        merkle_garbage.extend_from_slice(&[0xAB; 63]);
6013
6014        let result = verifier
6015            .verify_payment(
6016                &xorname,
6017                Some(&merkle_garbage),
6018                VerificationContext::ClientPut,
6019            )
6020            .await;
6021
6022        assert!(
6023            result.is_err(),
6024            "Should reject merkle proof with invalid body"
6025        );
6026        let err_msg = format!("{}", result.expect_err("should fail"));
6027        assert!(
6028            err_msg.contains("deserialize") || err_msg.contains("merkle proof"),
6029            "Error should mention deserialization failure: {err_msg}"
6030        );
6031    }
6032
6033    #[tokio::test]
6034    async fn test_single_node_tagged_proof_deserialization() {
6035        use crate::payment::proof::serialize_single_node_proof;
6036        use evmlib::{EncodedPeerId, RewardsAddress};
6037
6038        let verifier = create_test_verifier();
6039        let xorname = [0xA2u8; 32];
6040        let rewards_addr = RewardsAddress::new([1u8; 20]);
6041
6042        // Build a valid tagged single-node proof
6043        let quote = make_fake_quote(xorname, SystemTime::now(), rewards_addr);
6044        let mut peer_quotes = Vec::new();
6045        for _ in 0..CLOSE_GROUP_SIZE {
6046            peer_quotes.push((EncodedPeerId::new(rand::random()), quote.clone()));
6047        }
6048
6049        let proof = crate::payment::proof::PaymentProof {
6050            proof_of_payment: ProofOfPayment {
6051                peer_quotes: peer_quotes.clone(),
6052            },
6053            tx_hashes: vec![],
6054            commitment_sidecars: vec![],
6055        };
6056
6057        let tagged_bytes = serialize_single_node_proof(&proof).expect("serialize tagged proof");
6058
6059        // detect_proof_type should identify it as SingleNode
6060        assert_eq!(
6061            crate::payment::proof::detect_proof_type(&tagged_bytes),
6062            Some(crate::payment::proof::ProofType::SingleNode)
6063        );
6064
6065        // verify_payment should process it through the single-node path.
6066        // It will fail at quote validation (fake pub_key), but we verify
6067        // it passes the deserialization stage by checking the error type.
6068        let result = verifier
6069            .verify_payment(
6070                &xorname,
6071                Some(&tagged_bytes),
6072                VerificationContext::ClientPut,
6073            )
6074            .await;
6075
6076        assert!(result.is_err(), "Should fail at quote validation stage");
6077        let err_msg = format!("{}", result.expect_err("should fail"));
6078        // It should NOT be a deserialization error — it should get further
6079        assert!(
6080            !err_msg.contains("deserialize"),
6081            "Should pass deserialization but fail later: {err_msg}"
6082        );
6083    }
6084
6085    #[test]
6086    fn test_pool_cache_insert_and_lookup() {
6087        use evmlib::merkle_batch_payment::PoolHash;
6088
6089        // Verify the pool_cache field exists and works correctly.
6090        // Insert a pool hash, then verify it's present on lookup.
6091        let verifier = create_test_verifier();
6092
6093        let pool_hash: PoolHash = [0xBBu8; 32];
6094        let payment_info = evmlib::merkle_payments::OnChainPaymentInfo {
6095            depth: 4,
6096            merkle_payment_timestamp: 1_700_000_000,
6097            paid_node_addresses: vec![],
6098        };
6099
6100        // Insert into pool cache
6101        {
6102            let mut cache = verifier.pool_cache.lock();
6103            cache.put(pool_hash, payment_info);
6104        }
6105
6106        // First lookup — should find it
6107        {
6108            let found = verifier.pool_cache.lock().get(&pool_hash).cloned();
6109            assert!(found.is_some(), "Pool hash should be in cache after insert");
6110            let info = found.expect("cached info");
6111            assert_eq!(info.depth, 4);
6112            assert_eq!(info.merkle_payment_timestamp, 1_700_000_000);
6113        }
6114
6115        // Second lookup — same result (no double-query needed)
6116        {
6117            let found = verifier.pool_cache.lock().get(&pool_hash).cloned();
6118            assert!(
6119                found.is_some(),
6120                "Pool hash should still be in cache on second lookup"
6121            );
6122        }
6123
6124        // Different pool hash — should NOT be found
6125        let other_hash: PoolHash = [0xCCu8; 32];
6126        {
6127            let found = verifier.pool_cache.lock().get(&other_hash).cloned();
6128            assert!(found.is_none(), "Unknown pool hash should not be in cache");
6129        }
6130    }
6131
6132    #[tokio::test]
6133    async fn closeness_pass_cache_short_circuits_second_call() {
6134        // When a pool_hash is in the closeness_pass_cache, the outer
6135        // verify_merkle_candidate_closeness must return Ok(()) without
6136        // running the inner lookup — even if no P2PNode is attached.
6137        // That second half (no-p2p → would normally fail-closed in release)
6138        // is the proof the cache short-circuit ran first.
6139        let verifier = create_test_verifier();
6140        let pool_hash = [0xAAu8; 32];
6141        verifier.closeness_pass_cache.lock().put(pool_hash, ());
6142
6143        // Construct a dummy pool — contents don't matter because the cache
6144        // hit means we never look at them.
6145        let pool = MerklePaymentCandidatePool {
6146            midpoint_proof: fake_midpoint_proof(),
6147            candidate_nodes: make_candidate_nodes(1_700_000_000),
6148        };
6149
6150        let result = verifier
6151            .verify_merkle_candidate_closeness(&pool, pool_hash)
6152            .await;
6153        assert!(
6154            result.is_ok(),
6155            "cached pool hash must bypass the inner check and return Ok(()), got: {result:?}"
6156        );
6157    }
6158
6159    #[tokio::test]
6160    async fn closeness_single_flight_concurrent_readers_share_one_verification() {
6161        // Two concurrent callers for the same pool_hash should produce the
6162        // same outcome, and the cache should end up populated exactly once.
6163        // We use the test-utils fail-open path to short-circuit the inner
6164        // DHT lookup; the purpose of this test is the single-flight
6165        // plumbing, not the lookup itself.
6166        let verifier = Arc::new(create_test_verifier());
6167        let pool_hash = [0x77u8; 32];
6168        let pool = MerklePaymentCandidatePool {
6169            midpoint_proof: fake_midpoint_proof(),
6170            candidate_nodes: make_candidate_nodes(1_700_000_000),
6171        };
6172
6173        let v1 = Arc::clone(&verifier);
6174        let p1 = pool.clone();
6175        let v2 = Arc::clone(&verifier);
6176        let p2 = pool.clone();
6177
6178        let (r1, r2) = tokio::join!(
6179            async move { v1.verify_merkle_candidate_closeness(&p1, pool_hash).await },
6180            async move { v2.verify_merkle_candidate_closeness(&p2, pool_hash).await },
6181        );
6182
6183        assert_eq!(r1.is_ok(), r2.is_ok(), "concurrent callers must agree");
6184        assert!(
6185            r1.is_ok(),
6186            "both callers must succeed on the test-utils path"
6187        );
6188        assert!(
6189            verifier
6190                .closeness_pass_cache
6191                .lock()
6192                .get(&pool_hash)
6193                .is_some(),
6194            "success path must populate the pass cache"
6195        );
6196        assert!(
6197            verifier.inflight_closeness.lock().get(&pool_hash).is_none(),
6198            "inflight slot must be cleared after the leader finishes"
6199        );
6200    }
6201
6202    #[tokio::test]
6203    async fn closeness_waiter_reads_leaders_published_failure() {
6204        // Prove the waiter path actually surfaces a failure published by a
6205        // concurrent leader, without running its own inner check. Insert a
6206        // slot, spawn a waiter (which will park on notified_owned), then
6207        // publish failure + notify from the outside — simulating what the
6208        // leader's `publish` + drop-guard pair does.
6209        let verifier = Arc::new(create_test_verifier());
6210        let pool_hash = [0x55u8; 32];
6211        let slot = Arc::new(ClosenessSlot::new());
6212        verifier
6213            .inflight_closeness
6214            .lock()
6215            .put(pool_hash, Arc::clone(&slot));
6216
6217        let pool = MerklePaymentCandidatePool {
6218            midpoint_proof: fake_midpoint_proof(),
6219            candidate_nodes: make_candidate_nodes(1_700_000_000),
6220        };
6221
6222        let verifier_c = Arc::clone(&verifier);
6223        let pool_c = pool.clone();
6224        let waiter = tokio::spawn(async move {
6225            verifier_c
6226                .verify_merkle_candidate_closeness(&pool_c, pool_hash)
6227                .await
6228        });
6229
6230        // Yield so the waiter can run up to its `notified_owned().await`.
6231        // A few yields cover both single-threaded and multi-threaded tokio
6232        // runtimes regardless of scheduling.
6233        for _ in 0..5 {
6234            tokio::task::yield_now().await;
6235        }
6236
6237        // Simulate the leader's `publish` + drop-guard: publish the result,
6238        // clear the slot, wake waiters.
6239        slot.result
6240            .set(Err("forged pool: not close enough".to_string()))
6241            .expect("set once");
6242        verifier.inflight_closeness.lock().pop(&pool_hash);
6243        slot.notify.notify_waiters();
6244
6245        let result = waiter.await.expect("task panicked");
6246        let err = result.expect_err("waiter must return the leader's published failure");
6247        assert!(
6248            err.to_string().contains("forged pool"),
6249            "waiter must surface the leader's error message, got: {err}"
6250        );
6251    }
6252
6253    #[tokio::test]
6254    async fn closeness_rejects_pool_with_duplicate_candidate_pub_keys() {
6255        // An attacker who submits 16 copies of the same real peer's pub_key
6256        // would otherwise satisfy the closeness threshold trivially:
6257        // that one peer's membership in the DHT-returned set would count
6258        // 16 times. The dedupe check in verify_merkle_candidate_closeness_inner
6259        // must reject the pool BEFORE the network lookup runs (so this test
6260        // works even with no P2PNode attached).
6261        let verifier = create_test_verifier();
6262        let pool_hash = [0xDDu8; 32];
6263
6264        // Build a normal pool, then overwrite every candidate's pub_key
6265        // with a single shared key so all 16 derive to the same PeerId.
6266        let mut candidates = make_candidate_nodes(1_700_000_000);
6267        let shared_pub_key = candidates
6268            .first()
6269            .expect("make_candidate_nodes returns CANDIDATES_PER_POOL entries")
6270            .pub_key
6271            .clone();
6272        for c in &mut candidates {
6273            c.pub_key = shared_pub_key.clone();
6274        }
6275        let pool = MerklePaymentCandidatePool {
6276            midpoint_proof: fake_midpoint_proof(),
6277            candidate_nodes: candidates,
6278        };
6279
6280        let result = verifier
6281            .verify_merkle_candidate_closeness(&pool, pool_hash)
6282            .await;
6283        let err = result.expect_err("duplicate candidate PeerIds must be rejected");
6284        let msg = err.to_string();
6285        assert!(
6286            msg.contains("duplicate candidate PeerId"),
6287            "rejection must be the duplicate-PeerId branch, got: {msg}"
6288        );
6289    }
6290
6291    /// Build a deterministic but otherwise-unused `MidpointProof` so unit
6292    /// tests can construct a `MerklePaymentCandidatePool` without spinning
6293    /// up a real merkle tree. The closeness path only calls `.address()`
6294    /// on it, which is a pure BLAKE3 of the branch's leaf/root/timestamp —
6295    /// the values don't need to be tree-valid for these tests.
6296    fn fake_midpoint_proof() -> evmlib::merkle_payments::MidpointProof {
6297        // Build a minimal tree of two leaves so we get a real branch.
6298        let leaves = vec![xor_name::XorName([1u8; 32]), xor_name::XorName([2u8; 32])];
6299        let tree = evmlib::merkle_payments::MerkleTree::from_xornames(leaves).expect("tree");
6300        let candidates = tree.reward_candidates(1_700_000_000).expect("candidates");
6301        candidates.first().expect("at least one").clone()
6302    }
6303
6304    // =========================================================================
6305    // Merkle verification unit tests
6306    // =========================================================================
6307
6308    /// Helper: build 16 validly-signed ML-DSA-65 candidate nodes.
6309    fn make_candidate_nodes(
6310        timestamp: u64,
6311    ) -> [evmlib::merkle_payments::MerklePaymentCandidateNode;
6312           evmlib::merkle_payments::CANDIDATES_PER_POOL] {
6313        use evmlib::merkle_payments::{MerklePaymentCandidateNode, CANDIDATES_PER_POOL};
6314        use saorsa_core::MlDsa65;
6315        use saorsa_pqc::pqc::types::MlDsaSecretKey;
6316        use saorsa_pqc::pqc::MlDsaOperations;
6317
6318        std::array::from_fn::<_, CANDIDATES_PER_POOL, _>(|i| {
6319            let ml_dsa = MlDsa65::new();
6320            let (pub_key, secret_key) = ml_dsa.generate_keypair().expect("keygen");
6321            // Baseline candidate: `(committed_key_count = 0, commitment_pin =
6322            // None)` below, so the price must be `calculate_price(0)` to satisfy
6323            // the ADR-0004 binding rule. A placeholder price is off-curve and is
6324            // rejected before the check each test actually exercises.
6325            let price = crate::payment::pricing::calculate_price(0);
6326            #[allow(clippy::cast_possible_truncation)]
6327            let reward_address = RewardsAddress::new([i as u8; 20]);
6328            let msg = MerklePaymentCandidateNode::bytes_to_sign(
6329                &price,
6330                &reward_address,
6331                timestamp,
6332                0,
6333                &None,
6334            );
6335            let sk = MlDsaSecretKey::from_bytes(secret_key.as_bytes()).expect("sk");
6336            let signature = ml_dsa.sign(&sk, &msg).expect("sign").as_bytes().to_vec();
6337
6338            MerklePaymentCandidateNode {
6339                pub_key: pub_key.as_bytes().to_vec(),
6340                price,
6341                reward_address,
6342                merkle_payment_timestamp: timestamp,
6343                committed_key_count: 0,
6344                commitment_pin: None,
6345                signature,
6346            }
6347        })
6348    }
6349
6350    /// Helper: build a valid `MerklePaymentProof` with real ML-DSA-65
6351    /// signatures. Returns the raw proof, pool hash, xorname, and timestamp.
6352    fn make_valid_merkle_proof() -> (
6353        evmlib::merkle_payments::MerklePaymentProof,
6354        evmlib::merkle_batch_payment::PoolHash,
6355        [u8; 32],
6356        u64,
6357    ) {
6358        use evmlib::merkle_payments::{MerklePaymentCandidatePool, MerklePaymentProof, MerkleTree};
6359
6360        let timestamp = std::time::SystemTime::now()
6361            .duration_since(std::time::UNIX_EPOCH)
6362            .expect("system time")
6363            .as_secs();
6364
6365        let addresses: Vec<xor_name::XorName> = (0..4u8)
6366            .map(|i| xor_name::XorName::from_content(&[i]))
6367            .collect();
6368        let tree = MerkleTree::from_xornames(addresses.clone()).expect("tree");
6369
6370        let candidate_nodes = make_candidate_nodes(timestamp);
6371
6372        let reward_candidates = tree
6373            .reward_candidates(timestamp)
6374            .expect("reward candidates");
6375        let midpoint_proof = reward_candidates
6376            .first()
6377            .expect("at least one candidate")
6378            .clone();
6379
6380        let pool = MerklePaymentCandidatePool {
6381            midpoint_proof,
6382            candidate_nodes,
6383        };
6384
6385        let first_address = *addresses.first().expect("first address");
6386        let address_proof = tree
6387            .generate_address_proof(0, first_address)
6388            .expect("proof");
6389
6390        let merkle_proof = MerklePaymentProof::new(first_address, address_proof, pool);
6391        let pool_hash = merkle_proof.winner_pool_hash();
6392        let xorname = first_address.0;
6393
6394        (merkle_proof, pool_hash, xorname, timestamp)
6395    }
6396
6397    /// ADR-0004 Amendment 2: only the PAID (settlement-verified) quote's pin is
6398    /// nominated for a deterministic first audit; the unpaid bundle quotes are
6399    /// cross-checked but never enqueue audits.
6400    #[tokio::test]
6401    async fn adr0004_first_audit_nominates_only_paid_single_node_quote() {
6402        use evmlib::{EncodedPeerId, RewardsAddress};
6403
6404        let verifier = create_test_verifier();
6405        let (tx, mut rx) = tokio::sync::mpsc::channel(8);
6406        verifier.attach_monetized_pin_sender(tx);
6407
6408        let ids: Vec<[u8; 32]> = (1..=3u8).map(|b| [b; 32]).collect();
6409        let payment = ProofOfPayment {
6410            peer_quotes: ids
6411                .iter()
6412                .enumerate()
6413                .map(|(i, id)| {
6414                    let pin_byte = u8::try_from(i).expect("small bundle") + 1;
6415                    let mut quote = make_fake_quote(
6416                        [0xD0; 32],
6417                        SystemTime::now(),
6418                        RewardsAddress::new([pin_byte; 20]),
6419                    );
6420                    quote.commitment_pin = Some([pin_byte; 32]);
6421                    quote.committed_key_count = 100;
6422                    (EncodedPeerId::new(*id), quote)
6423                })
6424                .collect(),
6425        };
6426
6427        // The middle quote is the candidate whose on-chain settlement verified.
6428        let paid = ids.get(1).copied().expect("paid id");
6429        verifier.cross_check_quotes(&payment, &[], Some(paid)).await;
6430
6431        let event = rx.try_recv().expect("the paid quote must be nominated");
6432        assert_eq!(event.peer, PeerId::from_bytes(paid));
6433        assert_eq!(event.pin, [2u8; 32]);
6434        assert!(
6435            rx.try_recv().is_err(),
6436            "unpaid bundle quotes must not be nominated for first audits"
6437        );
6438    }
6439
6440    /// ADR-0004 Amendment 2: with no verified paid candidate, nothing is
6441    /// nominated (defensive: the caller never reaches the cross-check on a
6442    /// failed verification, but the emission itself must also fail closed).
6443    #[tokio::test]
6444    async fn adr0004_first_audit_nominates_nothing_without_paid_peer() {
6445        use evmlib::{EncodedPeerId, RewardsAddress};
6446
6447        let verifier = create_test_verifier();
6448        let (tx, mut rx) = tokio::sync::mpsc::channel(8);
6449        verifier.attach_monetized_pin_sender(tx);
6450
6451        let mut quote =
6452            make_fake_quote([0xD1; 32], SystemTime::now(), RewardsAddress::new([1; 20]));
6453        quote.commitment_pin = Some([1u8; 32]);
6454        let payment = ProofOfPayment {
6455            peer_quotes: vec![(EncodedPeerId::new([1u8; 32]), quote)],
6456        };
6457
6458        verifier.cross_check_quotes(&payment, &[], None).await;
6459        assert!(rx.try_recv().is_err(), "no paid peer, no nomination");
6460    }
6461
6462    /// ADR-0004 Amendment 2, merkle path: only the candidates at the
6463    /// contract-verified PAID indices are nominated; the rest of the pool
6464    /// merely established the median and must not enqueue audits.
6465    #[tokio::test]
6466    async fn adr0004_first_audit_nominates_only_paid_merkle_candidates() {
6467        use evmlib::merkle_payments::{MerklePaymentCandidatePool, MerkleTree};
6468
6469        let verifier = create_test_verifier();
6470        let (tx, mut rx) = tokio::sync::mpsc::channel(8);
6471        verifier.attach_monetized_pin_sender(tx);
6472
6473        let timestamp = std::time::SystemTime::now()
6474            .duration_since(std::time::UNIX_EPOCH)
6475            .expect("system time")
6476            .as_secs();
6477        let mut candidate_nodes = make_candidate_nodes(timestamp);
6478        for (i, candidate) in candidate_nodes.iter_mut().enumerate() {
6479            candidate.commitment_pin = Some([u8::try_from(i & 0xFF).expect("byte"); 32]);
6480            candidate.committed_key_count = 50;
6481        }
6482        let addresses: Vec<xor_name::XorName> = (0..4u8)
6483            .map(|i| xor_name::XorName::from_content(&[i]))
6484            .collect();
6485        let tree = MerkleTree::from_xornames(addresses).expect("tree");
6486        let midpoint_proof = tree
6487            .reward_candidates(timestamp)
6488            .expect("reward candidates")
6489            .first()
6490            .expect("at least one candidate")
6491            .clone();
6492        let pool = MerklePaymentCandidatePool {
6493            midpoint_proof,
6494            candidate_nodes,
6495        };
6496
6497        let paid_indices: std::collections::HashSet<usize> = [1usize, 3].into_iter().collect();
6498        verifier
6499            .cross_check_merkle_candidates(&pool, &[], &paid_indices)
6500            .await;
6501
6502        let mut nominated = Vec::new();
6503        while let Ok(event) = rx.try_recv() {
6504            nominated.push(event);
6505        }
6506        assert_eq!(
6507            nominated.len(),
6508            2,
6509            "only the PAID candidates are nominated, not the whole pool"
6510        );
6511        for (event, idx) in nominated.iter().zip([1usize, 3]) {
6512            let candidate = pool.candidate_nodes.get(idx).expect("paid candidate");
6513            assert_eq!(
6514                event.peer,
6515                PeerId::from_bytes(*blake3::hash(&candidate.pub_key).as_bytes())
6516            );
6517            assert_eq!(event.pin, [u8::try_from(idx).expect("byte"); 32]);
6518        }
6519    }
6520
6521    /// Helper: build a minimal valid `MerklePaymentProof` with real ML-DSA-65
6522    /// signatures. Returns `(xorname, serialized_tagged_proof, pool_hash, timestamp)`.
6523    /// Verifier for merkle admission tests, pinned to the **enforcing** side of
6524    /// the ADR-0008 parity boundary.
6525    ///
6526    /// Merkle receipts must be stamped within one week of now or they are
6527    /// expired, so these tests necessarily build near-`now` timestamps. Left on
6528    /// the production boundary they would sit in the legacy 1x window today and
6529    /// silently switch to the 3x rule when the wall clock crossed that date,
6530    /// changing what each assertion means. Pinning to `0` means "every receipt
6531    /// is post-boundary", which is the rule the release ships with.
6532    fn merkle_test_verifier() -> PaymentVerifier {
6533        let verifier = create_test_verifier();
6534        verifier.set_merkle_parity_from_for_tests(0);
6535        verifier
6536    }
6537
6538    /// Per-node amount a depth-2 pool of baseline-priced candidates must settle
6539    /// under parity: `median * 2^2 * 3 / 2`, i.e. six times the candidate price.
6540    ///
6541    /// Derived from the curve rather than hardcoded: the candidates are priced
6542    /// at `calculate_price(0)` so they satisfy the ADR-0004 binding rule, and a
6543    /// literal would silently stop matching the formula if the curve moves.
6544    fn merkle_parity_per_node_depth2() -> Amount {
6545        crate::payment::pricing::calculate_price(0) * Amount::from(6u64)
6546    }
6547
6548    /// The same pool's historic pre-parity amount: `median * 2^2 / 2`, i.e.
6549    /// twice the candidate price.
6550    fn merkle_legacy_per_node_depth2() -> Amount {
6551        crate::payment::pricing::calculate_price(0) * Amount::from(2u64)
6552    }
6553
6554    fn make_valid_merkle_proof_bytes() -> (
6555        [u8; 32],
6556        Vec<u8>,
6557        evmlib::merkle_batch_payment::PoolHash,
6558        u64,
6559    ) {
6560        let (merkle_proof, pool_hash, xorname, timestamp) = make_valid_merkle_proof();
6561        let tagged = crate::payment::proof::serialize_merkle_proof(&merkle_proof)
6562            .expect("serialize merkle proof");
6563        (xorname, tagged, pool_hash, timestamp)
6564    }
6565
6566    #[tokio::test]
6567    async fn test_merkle_address_mismatch_rejected() {
6568        let verifier = merkle_test_verifier();
6569        let (_correct_xorname, tagged_proof, _pool_hash, _ts) = make_valid_merkle_proof_bytes();
6570
6571        // Use a DIFFERENT xorname than what the proof was built for
6572        let wrong_xorname = [0xFFu8; 32];
6573
6574        let result = verifier
6575            .verify_payment(
6576                &wrong_xorname,
6577                Some(&tagged_proof),
6578                VerificationContext::ClientPut,
6579            )
6580            .await;
6581
6582        assert!(
6583            result.is_err(),
6584            "Should reject merkle proof address mismatch"
6585        );
6586        let err_msg = format!("{}", result.expect_err("should fail"));
6587        assert!(
6588            err_msg.contains("address mismatch") || err_msg.contains("Merkle proof address"),
6589            "Error should mention address mismatch: {err_msg}"
6590        );
6591    }
6592
6593    #[tokio::test]
6594    async fn test_merkle_malformed_body_rejected() {
6595        let verifier = merkle_test_verifier();
6596        let xorname = [0xA3u8; 32];
6597
6598        // Valid merkle tag but truncated/corrupted msgpack body
6599        let mut bad_proof = vec![crate::ant_protocol::PROOF_TAG_MERKLE];
6600        bad_proof.extend_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF]);
6601        bad_proof.extend_from_slice(&[0x00; 10]);
6602        // pad to minimum size
6603        while bad_proof.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
6604            bad_proof.push(0x00);
6605        }
6606
6607        let result = verifier
6608            .verify_payment(&xorname, Some(&bad_proof), VerificationContext::ClientPut)
6609            .await;
6610
6611        assert!(result.is_err(), "Should reject malformed merkle body");
6612        let err_msg = format!("{}", result.expect_err("should fail"));
6613        assert!(
6614            err_msg.contains("deserialize") || err_msg.contains("Failed"),
6615            "Error should mention deserialization: {err_msg}"
6616        );
6617    }
6618
6619    #[test]
6620    fn test_merkle_proof_serialized_size_within_limits() {
6621        let (_xorname, tagged_proof, _pool_hash, _ts) = make_valid_merkle_proof_bytes();
6622
6623        // 16 ML-DSA-65 candidates (~1952 pub key + ~3309 sig each) ≈ 84 KB + tree data
6624        assert!(
6625            tagged_proof.len() >= MIN_PAYMENT_PROOF_SIZE_BYTES,
6626            "Merkle proof ({} bytes) should be >= min {} bytes",
6627            tagged_proof.len(),
6628            MIN_PAYMENT_PROOF_SIZE_BYTES
6629        );
6630        assert!(
6631            tagged_proof.len() <= MAX_PAYMENT_PROOF_SIZE_BYTES,
6632            "Merkle proof ({} bytes) should be <= max {} bytes",
6633            tagged_proof.len(),
6634            MAX_PAYMENT_PROOF_SIZE_BYTES
6635        );
6636    }
6637
6638    #[test]
6639    fn test_merkle_proof_tag_is_correct() {
6640        let (_xorname, tagged_proof, _pool_hash, _ts) = make_valid_merkle_proof_bytes();
6641
6642        assert_eq!(
6643            tagged_proof.first().copied(),
6644            Some(crate::ant_protocol::PROOF_TAG_MERKLE),
6645            "First byte must be the merkle tag"
6646        );
6647        assert_eq!(
6648            crate::payment::proof::detect_proof_type(&tagged_proof),
6649            Some(crate::payment::proof::ProofType::Merkle)
6650        );
6651    }
6652
6653    #[test]
6654    fn test_pool_cache_eviction() {
6655        use evmlib::merkle_batch_payment::PoolHash;
6656
6657        let config = PaymentVerifierConfig {
6658            evm: EvmVerifierConfig::default(),
6659            cache_capacity: 100,
6660            close_group_size: CLOSE_GROUP_SIZE,
6661            local_rewards_address: RewardsAddress::new([1u8; 20]),
6662            price_floor: PriceFloorConfig::default(),
6663        };
6664        let verifier = PaymentVerifier::new(config);
6665
6666        // Fill the pool cache to capacity (DEFAULT_POOL_CACHE_CAPACITY = 1000)
6667        for i in 0..DEFAULT_POOL_CACHE_CAPACITY {
6668            let mut hash: PoolHash = [0u8; 32];
6669            // Write index bytes into the hash
6670            let idx_bytes = i.to_le_bytes();
6671            for (j, b) in idx_bytes.iter().enumerate() {
6672                if j < 32 {
6673                    hash[j] = *b;
6674                }
6675            }
6676            let info = evmlib::merkle_payments::OnChainPaymentInfo {
6677                depth: 4,
6678                merkle_payment_timestamp: 1_700_000_000,
6679                paid_node_addresses: vec![],
6680            };
6681            verifier.pool_cache.lock().put(hash, info);
6682        }
6683
6684        assert_eq!(
6685            verifier.pool_cache.lock().len(),
6686            DEFAULT_POOL_CACHE_CAPACITY
6687        );
6688
6689        // Insert one more — should evict the oldest
6690        let overflow_hash: PoolHash = [0xFFu8; 32];
6691        let info = evmlib::merkle_payments::OnChainPaymentInfo {
6692            depth: 8,
6693            merkle_payment_timestamp: 1_800_000_000,
6694            paid_node_addresses: vec![],
6695        };
6696        verifier.pool_cache.lock().put(overflow_hash, info);
6697
6698        // Size should still be at capacity (not capacity + 1)
6699        assert_eq!(
6700            verifier.pool_cache.lock().len(),
6701            DEFAULT_POOL_CACHE_CAPACITY
6702        );
6703
6704        // The new entry should be present
6705        let found = verifier.pool_cache.lock().get(&overflow_hash).cloned();
6706        assert!(
6707            found.is_some(),
6708            "Newly inserted pool hash should be present"
6709        );
6710        assert_eq!(found.expect("info").depth, 8);
6711    }
6712
6713    #[test]
6714    fn test_pool_cache_concurrent_access() {
6715        use evmlib::merkle_batch_payment::PoolHash;
6716        use std::sync::Arc;
6717
6718        let verifier = Arc::new(create_test_verifier());
6719
6720        let mut handles = Vec::new();
6721        for i in 0..20u8 {
6722            let v = verifier.clone();
6723            handles.push(std::thread::spawn(move || {
6724                let hash: PoolHash = [i; 32];
6725                let info = evmlib::merkle_payments::OnChainPaymentInfo {
6726                    depth: i,
6727                    merkle_payment_timestamp: u64::from(i) * 1000,
6728                    paid_node_addresses: vec![],
6729                };
6730                v.pool_cache.lock().put(hash, info);
6731
6732                // Read back
6733                let found = v.pool_cache.lock().get(&hash).cloned();
6734                assert!(found.is_some(), "Entry {i} should be readable after insert");
6735            }));
6736        }
6737
6738        for handle in handles {
6739            handle.join().expect("thread panicked");
6740        }
6741
6742        // All 20 entries should be present (well under 1000 capacity)
6743        assert_eq!(verifier.pool_cache.lock().len(), 20);
6744    }
6745
6746    #[tokio::test]
6747    async fn test_merkle_tampered_candidate_signature_rejected() {
6748        let verifier = merkle_test_verifier();
6749
6750        let (mut merkle_proof, _pool_hash, xorname, timestamp) = make_valid_merkle_proof();
6751
6752        // Tamper the first candidate's signature
6753        if let Some(byte) = merkle_proof
6754            .winner_pool
6755            .candidate_nodes
6756            .first_mut()
6757            .and_then(|c| c.signature.first_mut())
6758        {
6759            *byte ^= 0xFF;
6760        }
6761
6762        // Recompute pool hash after tampering (signature change alters the hash)
6763        let tampered_pool_hash = merkle_proof.winner_pool_hash();
6764
6765        // Pre-populate pool cache so we skip the on-chain query
6766        {
6767            let info = evmlib::merkle_payments::OnChainPaymentInfo {
6768                depth: 4,
6769                merkle_payment_timestamp: timestamp,
6770                paid_node_addresses: vec![],
6771            };
6772            verifier.pool_cache.lock().put(tampered_pool_hash, info);
6773        }
6774
6775        let tagged =
6776            crate::payment::proof::serialize_merkle_proof(&merkle_proof).expect("serialize");
6777
6778        let result = verifier
6779            .verify_payment(&xorname, Some(&tagged), VerificationContext::ClientPut)
6780            .await;
6781
6782        assert!(
6783            result.is_err(),
6784            "Should reject merkle proof with tampered candidate signature"
6785        );
6786        let err_msg = format!("{}", result.expect_err("should fail"));
6787        assert!(
6788            err_msg.contains("Invalid ML-DSA-65 signature"),
6789            "Error should mention invalid signature: {err_msg}"
6790        );
6791    }
6792
6793    #[tokio::test]
6794    async fn test_merkle_timestamp_mismatch_rejected() {
6795        let verifier = merkle_test_verifier();
6796
6797        let (xorname, tagged, pool_hash, timestamp) = make_valid_merkle_proof_bytes();
6798
6799        // Pre-populate pool cache with a DIFFERENT timestamp than the candidates
6800        {
6801            let mismatched_ts = timestamp + 9999;
6802            let info = evmlib::merkle_payments::OnChainPaymentInfo {
6803                depth: 4,
6804                merkle_payment_timestamp: mismatched_ts,
6805                paid_node_addresses: vec![],
6806            };
6807            verifier.pool_cache.lock().put(pool_hash, info);
6808        }
6809
6810        let result = verifier
6811            .verify_payment(&xorname, Some(&tagged), VerificationContext::ClientPut)
6812            .await;
6813
6814        assert!(
6815            result.is_err(),
6816            "Should reject merkle proof with timestamp mismatch"
6817        );
6818        let err_msg = format!("{}", result.expect_err("should fail"));
6819        assert!(
6820            err_msg.contains("timestamp mismatch"),
6821            "Error should mention timestamp mismatch: {err_msg}"
6822        );
6823    }
6824
6825    #[tokio::test]
6826    async fn test_merkle_paid_node_index_out_of_bounds_rejected() {
6827        let verifier = merkle_test_verifier();
6828        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
6829
6830        // The test tree has 4 addresses → depth 2. We must match the tree depth
6831        // so verify_merkle_proof passes the depth check, then the paid node
6832        // index out-of-bounds check fires.
6833        {
6834            let info = evmlib::merkle_payments::OnChainPaymentInfo {
6835                depth: 2,
6836                merkle_payment_timestamp: ts,
6837                paid_node_addresses: vec![
6838                    // First paid node: valid (matches candidate 0, amount clears
6839                    // the parity formula so the test reaches the index check)
6840                    (
6841                        RewardsAddress::new([0u8; 20]),
6842                        0,
6843                        merkle_parity_per_node_depth2(),
6844                    ),
6845                    // Second paid node: index 999 is way beyond CANDIDATES_PER_POOL (16)
6846                    (
6847                        RewardsAddress::new([1u8; 20]),
6848                        999,
6849                        merkle_parity_per_node_depth2(),
6850                    ),
6851                ],
6852            };
6853            verifier.pool_cache.lock().put(pool_hash, info);
6854        }
6855
6856        let result = verifier
6857            .verify_payment(
6858                &xorname,
6859                Some(&tagged_proof),
6860                VerificationContext::ClientPut,
6861            )
6862            .await;
6863
6864        assert!(
6865            result.is_err(),
6866            "Should reject paid node index out of bounds"
6867        );
6868        let err_msg = format!("{}", result.expect_err("should fail"));
6869        assert!(
6870            err_msg.contains("out of bounds"),
6871            "Error should mention out of bounds: {err_msg}"
6872        );
6873    }
6874
6875    #[tokio::test]
6876    async fn test_merkle_paid_node_address_mismatch_rejected() {
6877        let verifier = merkle_test_verifier();
6878        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
6879
6880        // Tree has depth 2, so provide 2 paid node entries.
6881        // Both use valid indices but the second has a wrong reward address.
6882        {
6883            let info = evmlib::merkle_payments::OnChainPaymentInfo {
6884                depth: 2,
6885                merkle_payment_timestamp: ts,
6886                paid_node_addresses: vec![
6887                    // Index 0 with matching address [0x00; 20], paid enough to
6888                    // clear the parity formula so the test reaches index 1
6889                    (
6890                        RewardsAddress::new([0u8; 20]),
6891                        0,
6892                        merkle_parity_per_node_depth2(),
6893                    ),
6894                    // Index 1 with WRONG address — candidate 1's address is [0x01; 20]
6895                    (
6896                        RewardsAddress::new([0xFF; 20]),
6897                        1,
6898                        merkle_parity_per_node_depth2(),
6899                    ),
6900                ],
6901            };
6902            verifier.pool_cache.lock().put(pool_hash, info);
6903        }
6904
6905        let result = verifier
6906            .verify_payment(
6907                &xorname,
6908                Some(&tagged_proof),
6909                VerificationContext::ClientPut,
6910            )
6911            .await;
6912
6913        assert!(result.is_err(), "Should reject paid node address mismatch");
6914        let err_msg = format!("{}", result.expect_err("should fail"));
6915        assert!(
6916            err_msg.contains("address mismatch"),
6917            "Error should mention address mismatch: {err_msg}"
6918        );
6919    }
6920
6921    #[tokio::test]
6922    async fn test_merkle_wrong_depth_rejected() {
6923        let verifier = merkle_test_verifier();
6924        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
6925
6926        // Pre-populate pool cache with depth=3 but only 1 paid node address
6927        // (depth must equal paid_node_addresses.len())
6928        {
6929            let info = evmlib::merkle_payments::OnChainPaymentInfo {
6930                depth: 3,
6931                merkle_payment_timestamp: ts,
6932                paid_node_addresses: vec![(
6933                    RewardsAddress::new([0u8; 20]),
6934                    0,
6935                    Amount::from(1024u64),
6936                )],
6937            };
6938            verifier.pool_cache.lock().put(pool_hash, info);
6939        }
6940
6941        let result = verifier
6942            .verify_payment(
6943                &xorname,
6944                Some(&tagged_proof),
6945                VerificationContext::ClientPut,
6946            )
6947            .await;
6948
6949        assert!(
6950            result.is_err(),
6951            "Should reject mismatched depth vs paid node count"
6952        );
6953        let err_msg = format!("{}", result.expect_err("should fail"));
6954        assert!(
6955            err_msg.contains("Wrong number of paid nodes")
6956                || err_msg.contains("verification failed"),
6957            "Error should mention depth/count mismatch: {err_msg}"
6958        );
6959    }
6960
6961    #[tokio::test]
6962    async fn test_merkle_underpayment_rejected() {
6963        let verifier = merkle_test_verifier();
6964        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
6965
6966        // Tree depth=2, so 2 paid nodes required. Candidates all quote price=1024.
6967        // Expected per-node: median(1024) * 2^2 / 2 = 2048.
6968        // Pay only 1 wei per node — far below the expected amount.
6969        {
6970            let info = evmlib::merkle_payments::OnChainPaymentInfo {
6971                depth: 2,
6972                merkle_payment_timestamp: ts,
6973                paid_node_addresses: vec![
6974                    (RewardsAddress::new([0u8; 20]), 0, Amount::from(1u64)),
6975                    (RewardsAddress::new([1u8; 20]), 1, Amount::from(1u64)),
6976                ],
6977            };
6978            verifier.pool_cache.lock().put(pool_hash, info);
6979        }
6980
6981        let result = verifier
6982            .verify_payment(
6983                &xorname,
6984                Some(&tagged_proof),
6985                VerificationContext::ClientPut,
6986            )
6987            .await;
6988
6989        assert!(
6990            result.is_err(),
6991            "Should reject merkle payment where paid amount < expected per-node amount"
6992        );
6993        let err_msg = format!("{}", result.expect_err("should fail"));
6994        assert!(
6995            err_msg.contains("Underpayment"),
6996            "Error should mention underpayment: {err_msg}"
6997        );
6998    }
6999
7000    /// A batch settled at the historic 1x is refused once its receipt is stamped
7001    /// at or after the parity boundary. This is the fix being active by default:
7002    /// no flag, no shadow mode.
7003    #[tokio::test]
7004    async fn merkle_legacy_1x_settlement_rejected_after_the_parity_boundary() {
7005        let verifier = merkle_test_verifier(); // boundary pinned at 0 = always enforcing
7006        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
7007
7008        {
7009            let info = evmlib::merkle_payments::OnChainPaymentInfo {
7010                depth: 2,
7011                merkle_payment_timestamp: ts,
7012                paid_node_addresses: vec![
7013                    (
7014                        RewardsAddress::new([0u8; 20]),
7015                        0,
7016                        merkle_legacy_per_node_depth2(),
7017                    ),
7018                    (
7019                        RewardsAddress::new([1u8; 20]),
7020                        1,
7021                        merkle_legacy_per_node_depth2(),
7022                    ),
7023                ],
7024            };
7025            verifier.pool_cache.lock().put(pool_hash, info);
7026        }
7027
7028        let err_msg = format!(
7029            "{}",
7030            verifier
7031                .verify_payment(
7032                    &xorname,
7033                    Some(&tagged_proof),
7034                    VerificationContext::ClientPut,
7035                )
7036                .await
7037                .expect_err("a 1x settlement must be refused past the boundary")
7038        );
7039        assert!(
7040            err_msg.contains("Underpayment") && err_msg.contains("3x required"),
7041            "Error should name the required multiplier: {err_msg}"
7042        );
7043    }
7044
7045    /// A receipt stamped BEFORE the boundary keeps its 1x price. The money was
7046    /// already spent under the old rule and cannot be refunded, so refusing it
7047    /// would destroy value. This is the compatibility half of the cutover.
7048    #[tokio::test]
7049    async fn merkle_legacy_1x_settlement_accepted_before_the_parity_boundary() {
7050        let verifier = create_test_verifier();
7051        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
7052        // Boundary just after this receipt's stamp: the receipt is legacy.
7053        verifier.set_merkle_parity_from_for_tests(ts + 1);
7054
7055        {
7056            let info = evmlib::merkle_payments::OnChainPaymentInfo {
7057                depth: 2,
7058                merkle_payment_timestamp: ts,
7059                paid_node_addresses: vec![
7060                    (
7061                        RewardsAddress::new([0u8; 20]),
7062                        0,
7063                        merkle_legacy_per_node_depth2(),
7064                    ),
7065                    (
7066                        RewardsAddress::new([1u8; 20]),
7067                        1,
7068                        merkle_legacy_per_node_depth2(),
7069                    ),
7070                ],
7071            };
7072            verifier.pool_cache.lock().put(pool_hash, info);
7073        }
7074
7075        let result = verifier
7076            .verify_payment(
7077                &xorname,
7078                Some(&tagged_proof),
7079                VerificationContext::ClientPut,
7080            )
7081            .await;
7082        assert!(
7083            result.is_ok(),
7084            "a receipt stamped before the boundary keeps the 1x rule: {result:?}"
7085        );
7086    }
7087
7088    /// An upgraded client's 3x settlement is accepted on both sides of the
7089    /// boundary. This is what makes the client-first rollout work: the client
7090    /// pays 3x from the day it ships, and neither a node that predates the
7091    /// boundary nor one enforcing past it has any reason to refuse.
7092    #[tokio::test]
7093    async fn merkle_parity_settlement_accepted_in_both_regimes() {
7094        for parity_from in [0u64, u64::MAX] {
7095            let verifier = create_test_verifier();
7096            verifier.set_merkle_parity_from_for_tests(parity_from);
7097            let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
7098
7099            {
7100                let info = evmlib::merkle_payments::OnChainPaymentInfo {
7101                    depth: 2,
7102                    merkle_payment_timestamp: ts,
7103                    paid_node_addresses: vec![
7104                        (
7105                            RewardsAddress::new([0u8; 20]),
7106                            0,
7107                            merkle_parity_per_node_depth2(),
7108                        ),
7109                        (
7110                            RewardsAddress::new([1u8; 20]),
7111                            1,
7112                            merkle_parity_per_node_depth2(),
7113                        ),
7114                    ],
7115                };
7116                verifier.pool_cache.lock().put(pool_hash, info);
7117            }
7118
7119            let result = verifier
7120                .verify_payment(
7121                    &xorname,
7122                    Some(&tagged_proof),
7123                    VerificationContext::ClientPut,
7124                )
7125                .await;
7126            assert!(
7127                result.is_ok(),
7128                "3x must be accepted with boundary {parity_from}: {result:?}"
7129            );
7130        }
7131    }
7132
7133    /// One chunk's payment proof as the verifier receives it: the stored
7134    /// address and the tagged, serialized proof bytes.
7135    type TaggedProof = ([u8; 32], Vec<u8>);
7136
7137    /// Build valid proofs for several addresses of ONE tree, all resolving to
7138    /// the same winner pool hash — the shape a real batch upload has, and the
7139    /// case the ADR-0008 parity telemetry must collapse to a single sample.
7140    /// Returns `(Vec<(xorname, tagged_proof)>, pool_hash, timestamp)`.
7141    fn make_valid_merkle_proofs_for_one_pool(
7142        indices: &[usize],
7143    ) -> (
7144        Vec<TaggedProof>,
7145        evmlib::merkle_batch_payment::PoolHash,
7146        u64,
7147    ) {
7148        use evmlib::merkle_payments::{MerklePaymentCandidatePool, MerklePaymentProof, MerkleTree};
7149
7150        let timestamp = std::time::SystemTime::now()
7151            .duration_since(std::time::UNIX_EPOCH)
7152            .expect("system time")
7153            .as_secs();
7154
7155        let addresses: Vec<xor_name::XorName> = (0..4u8)
7156            .map(|i| xor_name::XorName::from_content(&[i]))
7157            .collect();
7158        let tree = MerkleTree::from_xornames(addresses.clone()).expect("tree");
7159
7160        let midpoint_proof = tree
7161            .reward_candidates(timestamp)
7162            .expect("reward candidates")
7163            .first()
7164            .expect("at least one candidate")
7165            .clone();
7166        let pool = MerklePaymentCandidatePool {
7167            midpoint_proof,
7168            candidate_nodes: make_candidate_nodes(timestamp),
7169        };
7170
7171        let mut proofs = Vec::with_capacity(indices.len());
7172        let mut pool_hash = None;
7173        for &index in indices {
7174            let address = *addresses.get(index).expect("address index within the tree");
7175            let address_proof = tree
7176                .generate_address_proof(index, address)
7177                .expect("address proof");
7178            let proof = MerklePaymentProof::new(address, address_proof, pool.clone());
7179            let hash = proof.winner_pool_hash();
7180            match pool_hash {
7181                None => pool_hash = Some(hash),
7182                Some(first) => assert_eq!(
7183                    hash, first,
7184                    "every address in one tree must share one winner pool"
7185                ),
7186            }
7187            let tagged =
7188                crate::payment::proof::serialize_merkle_proof(&proof).expect("serialize proof");
7189            proofs.push((address.0, tagged));
7190        }
7191
7192        (proofs, pool_hash.expect("at least one proof"), timestamp)
7193    }
7194
7195    /// The depth-2 test pool's on-chain record, settled at 3x parity so the
7196    /// proof is admitted and the telemetry call site is actually reached.
7197    fn parity_settled_pool_info(ts: u64) -> evmlib::merkle_payments::OnChainPaymentInfo {
7198        evmlib::merkle_payments::OnChainPaymentInfo {
7199            depth: 2,
7200            merkle_payment_timestamp: ts,
7201            paid_node_addresses: vec![
7202                (
7203                    RewardsAddress::new([0u8; 20]),
7204                    0,
7205                    merkle_parity_per_node_depth2(),
7206                ),
7207                (
7208                    RewardsAddress::new([1u8; 20]),
7209                    1,
7210                    merkle_parity_per_node_depth2(),
7211                ),
7212            ],
7213        }
7214    }
7215
7216    // =========================================================================
7217    // ADR-0008 parity telemetry: what may enter the rollout signal, and at what
7218    // cardinality. The signal is read to decide when the pre-boundary (1x)
7219    // compatibility window has drained, so a sample from a proof that was
7220    // rejected — or 256 samples from one settlement — would mislead that call.
7221    // =========================================================================
7222
7223    /// A proof naming a paid index outside the pool is rejected in the paid-node
7224    /// loop, before the telemetry call site. Nothing may be measured.
7225    #[tokio::test]
7226    async fn parity_telemetry_silent_when_a_paid_index_is_invalid() {
7227        let verifier = merkle_test_verifier();
7228        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
7229
7230        {
7231            let mut info = parity_settled_pool_info(ts);
7232            // Second entry points past CANDIDATES_PER_POOL (16).
7233            if let Some(entry) = info.paid_node_addresses.get_mut(1) {
7234                entry.1 = 999;
7235            }
7236            verifier.pool_cache.lock().put(pool_hash, info);
7237        }
7238
7239        let result = verifier
7240            .verify_payment(
7241                &xorname,
7242                Some(&tagged_proof),
7243                VerificationContext::ClientPut,
7244            )
7245            .await;
7246
7247        assert!(
7248            result.is_err(),
7249            "an out-of-bounds paid index must be refused"
7250        );
7251        assert_eq!(
7252            verifier.merkle_parity_emission_count(),
7253            0,
7254            "a refused proof must not enter the parity signal"
7255        );
7256    }
7257
7258    /// A paid entry whose reward address does not match the candidate at that
7259    /// index is rejected before the telemetry call site.
7260    #[tokio::test]
7261    async fn parity_telemetry_silent_when_a_reward_address_is_wrong() {
7262        let verifier = merkle_test_verifier();
7263        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
7264
7265        {
7266            let mut info = parity_settled_pool_info(ts);
7267            // Candidate 1's address is [0x01; 20], not [0xFF; 20].
7268            if let Some(entry) = info.paid_node_addresses.get_mut(1) {
7269                entry.0 = RewardsAddress::new([0xFF; 20]);
7270            }
7271            verifier.pool_cache.lock().put(pool_hash, info);
7272        }
7273
7274        let result = verifier
7275            .verify_payment(
7276                &xorname,
7277                Some(&tagged_proof),
7278                VerificationContext::ClientPut,
7279            )
7280            .await;
7281
7282        assert!(result.is_err(), "a redirected payee must be refused");
7283        assert_eq!(
7284            verifier.merkle_parity_emission_count(),
7285            0,
7286            "a refused proof must not enter the parity signal"
7287        );
7288    }
7289
7290    /// An underpaid batch is the case the signal most obviously must not
7291    /// contain: it is rejected, so it never became a store.
7292    #[tokio::test]
7293    async fn parity_telemetry_silent_on_underpayment() {
7294        let verifier = merkle_test_verifier();
7295        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
7296
7297        {
7298            let info = evmlib::merkle_payments::OnChainPaymentInfo {
7299                depth: 2,
7300                merkle_payment_timestamp: ts,
7301                paid_node_addresses: vec![
7302                    (RewardsAddress::new([0u8; 20]), 0, Amount::from(1u64)),
7303                    (RewardsAddress::new([1u8; 20]), 1, Amount::from(1u64)),
7304                ],
7305            };
7306            verifier.pool_cache.lock().put(pool_hash, info);
7307        }
7308
7309        let result = verifier
7310            .verify_payment(
7311                &xorname,
7312                Some(&tagged_proof),
7313                VerificationContext::ClientPut,
7314            )
7315            .await;
7316
7317        assert!(result.is_err(), "an underpaid batch must be refused");
7318        assert_eq!(
7319            verifier.merkle_parity_emission_count(),
7320            0,
7321            "a refused proof must not enter the parity signal"
7322        );
7323    }
7324
7325    /// A paid-list admission verifies the same proof but reprices nothing. It
7326    /// must not be measured, or a batch already sampled at its store admission
7327    /// would be counted twice.
7328    #[tokio::test]
7329    async fn parity_telemetry_silent_for_paid_list_admission() {
7330        let verifier = merkle_test_verifier();
7331        let (xorname, tagged_proof, pool_hash, ts) = make_valid_merkle_proof_bytes();
7332        verifier
7333            .pool_cache
7334            .lock()
7335            .put(pool_hash, parity_settled_pool_info(ts));
7336
7337        let result = verifier
7338            .verify_payment(
7339                &xorname,
7340                Some(&tagged_proof),
7341                VerificationContext::PaidListAdmission,
7342            )
7343            .await;
7344
7345        assert!(result.is_ok(), "the proof itself is valid: {result:?}");
7346        assert_eq!(
7347            verifier.merkle_parity_emission_count(),
7348            0,
7349            "only store admissions may be measured"
7350        );
7351    }
7352
7353    /// Two chunks of one batch are one economic event. The pool hash in the
7354    /// line makes the stream deduplicable; the first-emission cache is what
7355    /// keeps the emitted cardinality at one.
7356    #[tokio::test]
7357    async fn parity_telemetry_emits_once_for_two_chunks_of_one_pool() {
7358        let verifier = merkle_test_verifier();
7359        let (proofs, pool_hash, ts) = make_valid_merkle_proofs_for_one_pool(&[0, 1]);
7360        verifier
7361            .pool_cache
7362            .lock()
7363            .put(pool_hash, parity_settled_pool_info(ts));
7364
7365        for (xorname, tagged) in &proofs {
7366            let result = verifier
7367                .verify_payment(xorname, Some(tagged), VerificationContext::ClientPut)
7368                .await;
7369            assert!(result.is_ok(), "both chunks must be admitted: {result:?}");
7370        }
7371
7372        assert_eq!(
7373            verifier.merkle_parity_emission_count(),
7374            1,
7375            "one settlement is one sample, however many chunks it covers"
7376        );
7377    }
7378
7379    /// Deduplication is per pool, not a global mute: a genuinely separate
7380    /// settlement is a separate sample.
7381    #[tokio::test]
7382    async fn parity_telemetry_emits_once_more_for_a_second_pool() {
7383        let verifier = merkle_test_verifier();
7384
7385        let (first, first_pool, first_ts) = make_valid_merkle_proofs_for_one_pool(&[0, 1]);
7386        verifier
7387            .pool_cache
7388            .lock()
7389            .put(first_pool, parity_settled_pool_info(first_ts));
7390        for (xorname, tagged) in &first {
7391            verifier
7392                .verify_payment(xorname, Some(tagged), VerificationContext::ClientPut)
7393                .await
7394                .expect("first pool admitted");
7395        }
7396        assert_eq!(verifier.merkle_parity_emission_count(), 1);
7397
7398        // A fresh batch: new candidate keypairs and leaf salts give it a
7399        // different pool hash. Its chunk is one the first batch did not carry,
7400        // so this exercises verification rather than the verified-address cache.
7401        let (second, second_pool, second_ts) = make_valid_merkle_proofs_for_one_pool(&[2]);
7402        let (second_xorname, second_tagged) = second.first().expect("one proof").clone();
7403        assert_ne!(first_pool, second_pool, "the second batch is a new pool");
7404        verifier
7405            .pool_cache
7406            .lock()
7407            .put(second_pool, parity_settled_pool_info(second_ts));
7408        verifier
7409            .verify_payment(
7410                &second_xorname,
7411                Some(&second_tagged),
7412                VerificationContext::ClientPut,
7413            )
7414            .await
7415            .expect("second pool admitted");
7416
7417        assert_eq!(
7418            verifier.merkle_parity_emission_count(),
7419            2,
7420            "a second settlement contributes a second sample"
7421        );
7422    }
7423
7424    /// Concurrent admissions of one batch — the normal case, since a client
7425    /// PUTs a batch's chunks in parallel — must still emit once. The
7426    /// check-and-insert is a single locked operation for exactly this reason.
7427    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
7428    async fn parity_telemetry_emits_once_under_concurrent_admissions() {
7429        let verifier = Arc::new(merkle_test_verifier());
7430        let (proofs, pool_hash, ts) = make_valid_merkle_proofs_for_one_pool(&[0, 1, 2, 3]);
7431        verifier
7432            .pool_cache
7433            .lock()
7434            .put(pool_hash, parity_settled_pool_info(ts));
7435
7436        let mut handles = Vec::new();
7437        for (xorname, tagged) in proofs {
7438            // Two racing admissions per address, as replication and the direct
7439            // PUT can both arrive for the same chunk.
7440            for _ in 0..2 {
7441                let verifier = Arc::clone(&verifier);
7442                let tagged = tagged.clone();
7443                handles.push(tokio::spawn(async move {
7444                    verifier
7445                        .verify_payment(&xorname, Some(&tagged), VerificationContext::ClientPut)
7446                        .await
7447                }));
7448            }
7449        }
7450
7451        for handle in handles {
7452            let result = handle.await.expect("task panicked");
7453            assert!(
7454                result.is_ok(),
7455                "every concurrent admission must succeed: {result:?}"
7456            );
7457        }
7458
7459        assert_eq!(
7460            verifier.merkle_parity_emission_count(),
7461            1,
7462            "concurrent admissions of one pool must not race into extra samples"
7463        );
7464    }
7465
7466    /// The first-emission cache is bounded, so a node admitting an unbounded
7467    /// stream of distinct pools cannot grow it without limit.
7468    #[test]
7469    fn parity_telemetry_first_emission_cache_is_bounded() {
7470        let verifier = create_test_verifier();
7471        for i in 0..(MERKLE_PARITY_TELEMETRY_CACHE_CAPACITY + 50) {
7472            let mut hash: PoolHash = [0u8; 32];
7473            for (j, b) in i.to_le_bytes().iter().enumerate() {
7474                if let Some(slot) = hash.get_mut(j) {
7475                    *slot = *b;
7476                }
7477            }
7478            verifier.merkle_parity_logged.lock().put(hash, ());
7479        }
7480
7481        assert_eq!(
7482            verifier.merkle_parity_logged.lock().len(),
7483            MERKLE_PARITY_TELEMETRY_CACHE_CAPACITY,
7484            "the telemetry cache must stay at its capacity"
7485        );
7486    }
7487
7488    #[test]
7489    fn merkle_required_multiplier_switches_exactly_at_the_boundary() {
7490        let boundary = 1_785_855_600u64;
7491
7492        assert_eq!(merkle_required_multiplier(boundary - 1, boundary), 1);
7493        assert_eq!(
7494            merkle_required_multiplier(boundary, boundary),
7495            PAID_QUOTE_PAYMENT_MULTIPLIER,
7496            "the boundary instant itself is enforcing"
7497        );
7498        assert_eq!(
7499            merkle_required_multiplier(boundary + 1, boundary),
7500            PAID_QUOTE_PAYMENT_MULTIPLIER
7501        );
7502    }
7503
7504    /// The legacy branch cannot outlive the receipt lifetime, which is what
7505    /// makes the cutover self-completing.
7506    ///
7507    /// It bounds backdating rather than preventing it: mid-window, a stamp just
7508    /// before the boundary is both unexpired and eligible for 1x, so a modified
7509    /// client can take that route until it expires. Both halves are asserted
7510    /// here so neither claim drifts.
7511    #[test]
7512    fn merkle_legacy_window_closes_one_receipt_lifetime_after_the_boundary() {
7513        let boundary = 1_785_855_600u64;
7514        let expiry = evmlib::merkle_payments::MERKLE_PAYMENT_EXPIRATION;
7515
7516        // Mid-window: a deliberately backdated stamp is still unexpired, and
7517        // still gets the 1x rule. This route is open for exactly one week.
7518        let mid_window = boundary + expiry / 2;
7519        let backdated = boundary - 1;
7520        assert!(
7521            mid_window - backdated < expiry,
7522            "the backdated stamp is still within its lifetime"
7523        );
7524        assert_eq!(
7525            merkle_required_multiplier(backdated, boundary),
7526            1,
7527            "backdating is bounded by expiry, not blocked outright"
7528        );
7529
7530        // Once now is a full receipt lifetime past the boundary, the oldest
7531        // still-valid stamp is itself at or after the boundary.
7532        let now = boundary + expiry;
7533        let oldest_valid_stamp = now - expiry;
7534        assert_eq!(
7535            merkle_required_multiplier(oldest_valid_stamp, boundary),
7536            PAID_QUOTE_PAYMENT_MULTIPLIER,
7537            "no unexpired receipt can still claim the 1x rule"
7538        );
7539    }
7540
7541    //
7542    // These constants are load-bearing for both correctness (the storer
7543    // must look at the same window the client picks from, otherwise honest
7544    // pools are rejected) and DoS resistance (the timeout caps lookup
7545    // amplification per forged pool_hash). Pinning them with tests gives
7546    // future patches a one-line failure if either is silently changed
7547    // without updating the security argument in the doc comments.
7548    //
7549    // Empirical justification, captured during STG-01 investigation on
7550    // 2026-05-01:
7551    //
7552    //   - 60s timeout cut iterative lookups off after ~7 of 20 iterations
7553    //     (trace from EWR-3 ant-node-1 in CLOSENESS_LOOKUP_TIMEOUT doc).
7554    //   - K=16 storer window vs K=32 client over-query produced 73%
7555    //     false-positive mismatch rejections under realistic load
7556    //     (115 → 31 client mismatches per 5min after K=32 deploy).
7557    // =========================================================================
7558
7559    #[test]
7560    fn closeness_lookup_timeout_is_240s() {
7561        // Pin the timeout. If a future change drops it back to 60s the
7562        // failure mode from the trace in the doc comment will return.
7563        assert_eq!(
7564            PaymentVerifier::CLOSENESS_LOOKUP_TIMEOUT,
7565            std::time::Duration::from_secs(240),
7566            "CLOSENESS_LOOKUP_TIMEOUT must be 240s; if changing this, update \
7567             the iteration trace in the doc comment and re-validate on a \
7568             fresh testnet"
7569        );
7570    }
7571
7572    #[test]
7573    fn closeness_lookup_width_is_32() {
7574        // Pin the storer's lookup width. Must equal the client's
7575        // over-query factor (CANDIDATES_PER_POOL * 2 = 32) so the storer
7576        // sees the same peers the client legitimately picks from.
7577        assert_eq!(
7578            PaymentVerifier::CLOSENESS_LOOKUP_WIDTH,
7579            2 * evmlib::merkle_payments::CANDIDATES_PER_POOL,
7580            "CLOSENESS_LOOKUP_WIDTH must equal 2 * CANDIDATES_PER_POOL to \
7581             match the client's over-query in get_merkle_candidate_pool"
7582        );
7583    }
7584
7585    #[test]
7586    fn closeness_required_threshold_is_majority() {
7587        // Pin the threshold so a future change can't silently move it. This
7588        // is the security knob: a 9/16 majority tolerates closest-set
7589        // divergence between two nodes' views while still requiring most
7590        // candidates to be real peers the live DHT lists as closest.
7591        assert_eq!(
7592            PaymentVerifier::CANDIDATE_CLOSENESS_REQUIRED,
7593            9,
7594            "closeness threshold is a 9/16 majority"
7595        );
7596    }
7597
7598    #[test]
7599    fn closeness_lookup_count_uses_max_of_width_and_pool_len() {
7600        // The honest case: a 16-candidate pool must trigger a 32-peer
7601        // network lookup. This is the K=16-rejects-honest-pool fix from
7602        // the STG-01 investigation — without it, the storer never
7603        // observes the peers at network-true positions 17–32 that the
7604        // client legitimately picks from.
7605        let standard =
7606            PaymentVerifier::closeness_lookup_count(evmlib::merkle_payments::CANDIDATES_PER_POOL);
7607        assert_eq!(
7608            standard, 32,
7609            "honest 16-candidate pool must trigger a 32-peer DHT lookup"
7610        );
7611
7612        // Future-proof: if a protocol bump ever produces a pool larger
7613        // than CLOSENESS_LOOKUP_WIDTH, lookup_count must scale with the
7614        // pool — not truncate to WIDTH. Truncating would let an attacker
7615        // hide candidates by padding the pool past the storer's window.
7616        assert_eq!(
7617            PaymentVerifier::closeness_lookup_count(64),
7618            64,
7619            "lookup_count must scale up if pool exceeds CLOSENESS_LOOKUP_WIDTH"
7620        );
7621
7622        // Lower bound (also covered by the const-assert below; pin the
7623        // runtime path too in case the const-assert is ever removed).
7624        assert_eq!(
7625            PaymentVerifier::closeness_lookup_count(1),
7626            PaymentVerifier::CLOSENESS_LOOKUP_WIDTH,
7627            "lookup_count must never drop below CLOSENESS_LOOKUP_WIDTH"
7628        );
7629    }
7630
7631    // Compile-time invariant: the `closeness_lookup_count` formula relies
7632    // on WIDTH being ≥ CANDIDATES_PER_POOL so we never request fewer peers
7633    // than the pool itself contains.
7634    const _: () = assert!(
7635        PaymentVerifier::CLOSENESS_LOOKUP_WIDTH >= evmlib::merkle_payments::CANDIDATES_PER_POOL,
7636        "CLOSENESS_LOOKUP_WIDTH must be ≥ CANDIDATES_PER_POOL",
7637    );
7638
7639    // =========================================================================
7640    // Closeness-match logic tests
7641    //
7642    // These tests use the extracted `check_closeness_match` helper to
7643    // exercise the matching logic directly with synthetic peer-ID sets,
7644    // without standing up a real DHT. They cover:
7645    //
7646    //   - the 9/16 majority threshold (accept at exactly 9, reject below);
7647    //   - that a candidate counts only via exact membership in the storer's
7648    //     returned closest peers, so off-network fabrications are rejected;
7649    //   - the sparse-network short-circuit.
7650    //
7651    // Synthetic PeerIds put the tag in `bytes[0]`, so a candidate is in or
7652    // out of the network's returned set purely by tag value.
7653    // =========================================================================
7654
7655    /// Build a deterministic `PeerId` from a single byte tag.
7656    fn synthetic_peer_id(tag: u8) -> PeerId {
7657        let mut bytes = [0u8; 32];
7658        bytes[0] = tag;
7659        PeerId::from_bytes(bytes)
7660    }
7661
7662    /// Build a vector of synthetic `PeerId`s tagged with bytes 1..=n.
7663    fn synthetic_peer_ids(n: u8) -> Vec<PeerId> {
7664        (1..=n).map(synthetic_peer_id).collect()
7665    }
7666
7667    #[test]
7668    fn closeness_match_passes_when_all_16_candidates_in_top_16() {
7669        // Trivial case: every candidate is in the network's top-16.
7670        // Asserts the happy path still works after the refactor.
7671        let candidates = synthetic_peer_ids(16);
7672        let network = synthetic_peer_ids(16);
7673        let pool_address = [0u8; 32];
7674        let result = PaymentVerifier::check_closeness_match(&candidates, &network, &pool_address);
7675        assert!(result.is_ok(), "all-in-top-16 pool must pass: {result:?}");
7676    }
7677
7678    #[test]
7679    fn closeness_match_passes_when_candidates_span_positions_1_to_15_and_17() {
7680        // The client's pool contains 16 candidates, 15 at network-true
7681        // positions 1..=15 plus one at position 17 (the position-16 peer was
7682        // unresponsive when the client over-queried). Under K=32 all 16 are
7683        // exact matches, comfortably ≥ the 9/16 majority.
7684        let candidates = synthetic_peer_ids(15)
7685            .into_iter()
7686            .chain(std::iter::once(synthetic_peer_id(17)))
7687            .collect::<Vec<_>>();
7688        // Lookup window = 32, includes position 17.
7689        let network: Vec<PeerId> = (1..=32).map(synthetic_peer_id).collect();
7690        let pool_address = [0u8; 32];
7691        let result = PaymentVerifier::check_closeness_match(&candidates, &network, &pool_address);
7692        assert!(
7693            result.is_ok(),
7694            "pool with one candidate at position 17 must pass: {result:?}"
7695        );
7696    }
7697
7698    #[test]
7699    fn closeness_match_accepts_honest_skew_via_exact_matches() {
7700        // Honest skew: the client's 16 candidates span network-true positions
7701        // {1..=12, 17, 19, 21, 23}. The lookup window of 32 covers all of
7702        // them, so all 16 are exact matches — trivially ≥ the 9/16 majority.
7703        let candidates: Vec<PeerId> = (1..=12u8)
7704            .chain([17u8, 19, 21, 23])
7705            .map(synthetic_peer_id)
7706            .collect();
7707        let pool_address = [0u8; 32];
7708        let network: Vec<PeerId> = (1..=32).map(synthetic_peer_id).collect();
7709
7710        let result = PaymentVerifier::check_closeness_match(&candidates, &network, &pool_address);
7711        assert!(
7712            result.is_ok(),
7713            "honest pool fully inside the lookup window must pass: {result:?}"
7714        );
7715    }
7716
7717    #[test]
7718    fn closeness_match_rejects_forged_pool() {
7719        // Security floor: a fully-forged pool whose candidate PeerIds are
7720        // disjoint from the network's returned closest peers must be
7721        // rejected. The lowered majority threshold must NOT let off-network
7722        // fabrications pass — every counted candidate has to be a peer the
7723        // live DHT actually returned.
7724        let forged_candidates: Vec<PeerId> = (100..=115).map(synthetic_peer_id).collect();
7725        let network: Vec<PeerId> = (1..=32).map(synthetic_peer_id).collect();
7726        let pool_address = [0u8; 32];
7727
7728        let result =
7729            PaymentVerifier::check_closeness_match(&forged_candidates, &network, &pool_address);
7730        match result {
7731            Err(Error::Payment(msg)) => {
7732                assert!(
7733                    msg.contains("candidate pub_keys do not match"),
7734                    "expected forged-pool rejection message, got: {msg}"
7735                );
7736            }
7737            other => {
7738                panic!("forged pool disjoint from the network set must be rejected: {other:?}")
7739            }
7740        }
7741    }
7742
7743    #[test]
7744    fn closeness_match_rejects_pool_below_majority() {
7745        // Threshold sanity: 8 candidates are exact matches (tags 1..=8) and
7746        // the other 8 are off-network fabrications (tags 100..=107). 8 < 9
7747        // → reject.
7748        let mut candidates = synthetic_peer_ids(8);
7749        candidates.extend((100..=107).map(synthetic_peer_id)); // 8 fabrications
7750        let network: Vec<PeerId> = (1..=32).map(synthetic_peer_id).collect();
7751        let pool_address = [0u8; 32];
7752
7753        let result = PaymentVerifier::check_closeness_match(&candidates, &network, &pool_address);
7754        assert!(
7755            result.is_err(),
7756            "8 matches < majority of 9/16 must reject: {result:?}"
7757        );
7758    }
7759
7760    #[test]
7761    fn closeness_match_accepts_at_exactly_majority() {
7762        // Threshold sanity: exactly 9 candidates are exact matches (tags
7763        // 1..=9), the other 7 are off-network fabrications (tags 100..=106).
7764        // 9 ≥ 9 → accept.
7765        let mut candidates = synthetic_peer_ids(9);
7766        candidates.extend((100..=106).map(synthetic_peer_id)); // 7 fabrications
7767        let network: Vec<PeerId> = (1..=32).map(synthetic_peer_id).collect();
7768        let pool_address = [0u8; 32];
7769
7770        let result = PaymentVerifier::check_closeness_match(&candidates, &network, &pool_address);
7771        assert!(
7772            result.is_ok(),
7773            "9/16 ≥ majority threshold must accept: {result:?}"
7774        );
7775    }
7776
7777    #[test]
7778    fn closeness_match_returns_sparse_dht_error_when_lookup_too_small() {
7779        // The sparse-DHT short-circuit fires when the lookup returned
7780        // fewer peers than the threshold itself — even an all-matching
7781        // candidate set can't pass because the storer doesn't have an
7782        // authoritative view to compare against.
7783        let candidates = synthetic_peer_ids(16);
7784        let network = synthetic_peer_ids(8); // < CANDIDATE_CLOSENESS_REQUIRED (9)
7785        let pool_address = [0u8; 32];
7786
7787        let result = PaymentVerifier::check_closeness_match(&candidates, &network, &pool_address);
7788        match result {
7789            Err(Error::Payment(msg)) => {
7790                assert!(
7791                    msg.contains("authoritative DHT lookup returned only 8"),
7792                    "expected sparse-DHT error message, got: {msg}"
7793                );
7794            }
7795            other => panic!("expected sparse-DHT rejection, got: {other:?}"),
7796        }
7797    }
7798
7799    // ---------- ADR-0004: quote arithmetic re-check ----------
7800
7801    /// Curve canonicality: any price produced by `calculate_price(n)` is
7802    /// on-curve by construction. We exercise a spread of `n` covering the
7803    /// baseline floor (n=0), small counts, the pricing-curve knee
7804    /// (`n=PRICING_DIVISOR=6000`), and a saturating-arithmetic regime.
7805    #[test]
7806    fn adr0004_on_curve_prices_round_trip() {
7807        for &n in &[0usize, 1, 2, 100, 5999, 6000, 6001, 50_000, 1_000_000] {
7808            let price = crate::payment::pricing::calculate_price(n);
7809            assert!(
7810                PaymentVerifier::quote_price_is_on_curve(&price),
7811                "calculate_price({n}) = {price} must be on-curve"
7812            );
7813        }
7814    }
7815
7816    /// Off-curve canonicality: a price one wei above or below an on-curve
7817    /// point is between two adjacent curve values and must fail the
7818    /// canonicality predicate. The check IS exact equality, not a tolerance.
7819    #[test]
7820    fn adr0004_off_curve_prices_rejected_by_predicate() {
7821        // n=100 is well above baseline so price ± 1 is non-saturating.
7822        let on = crate::payment::pricing::calculate_price(100);
7823        let just_above = on + Amount::from(1u64);
7824        let just_below = on - Amount::from(1u64);
7825        assert!(
7826            !PaymentVerifier::quote_price_is_on_curve(&just_above),
7827            "price one wei above an on-curve point must be off-curve"
7828        );
7829        assert!(
7830            !PaymentVerifier::quote_price_is_on_curve(&just_below),
7831            "price one wei below an on-curve point must be off-curve"
7832        );
7833    }
7834
7835    /// A price strictly below the baseline floor is off-curve: the formula's
7836    /// minimum value is `calculate_price(0) = BASELINE`, so any smaller value
7837    /// has no corresponding `n`.
7838    #[test]
7839    fn adr0004_sub_baseline_price_is_off_curve() {
7840        let baseline = crate::payment::pricing::calculate_price(0);
7841        let sub_baseline = baseline - Amount::from(1u64);
7842        assert!(
7843            !PaymentVerifier::quote_price_is_on_curve(&sub_baseline),
7844            "price strictly below baseline must be off-curve"
7845        );
7846    }
7847
7848    /// ADR-0004 storer-side gate: a bundle in which every quote is on-curve
7849    /// passes the gate **and** the per-quote canonicality predicate. Runs in
7850    /// every context (no `ClientPut` split): the rule depends only on the
7851    /// bundle, not on per-peer state. The outer `validate_quote_arithmetic`
7852    /// short-circuits to `Ok` under the observe-only rollout const, so the
7853    /// per-quote diagnostics assertion is what proves the bundle is genuinely
7854    /// on-curve regardless of how the const ships.
7855    #[test]
7856    fn adr0004_validate_quote_arithmetic_passes_for_honest_bundle() {
7857        use evmlib::{EncodedPeerId, RewardsAddress};
7858
7859        let payment = ProofOfPayment {
7860            peer_quotes: (0..crate::ant_protocol::CLOSE_GROUP_SIZE)
7861                .map(|i| {
7862                    let id: [u8; 32] = rand::random();
7863                    let byte = u8::try_from(i & 0xFF).unwrap_or(0);
7864                    let quote = make_fake_quote_at_records(
7865                        [0xC0u8; 32],
7866                        SystemTime::now(),
7867                        RewardsAddress::new([byte; 20]),
7868                        100 * (i + 1),
7869                    );
7870                    (EncodedPeerId::new(id), quote)
7871                })
7872                .collect(),
7873        };
7874        PaymentVerifier::validate_quote_arithmetic(&payment)
7875            .expect("honest on-curve bundle must pass the gate (any const value)");
7876        for (_, quote) in &payment.peer_quotes {
7877            assert!(
7878                PaymentVerifier::price_off_curve_diagnostics(&quote.price).is_none(),
7879                "every quote in honest bundle must be canonically on-curve"
7880            );
7881        }
7882    }
7883
7884    /// Off-curve quote behaviour follows the rollout gate
7885    /// [`QUOTE_ARITHMETIC_RECHECK_ENABLED`]. The gate now ships enforcing, so
7886    /// an off-curve quote must be rejected; the observe-only branch is kept so
7887    /// the test still documents the semantics if the gate is ever rolled back.
7888    /// The rejection payload itself is exercised separately by
7889    /// `adr0004_off_curve_diagnostics_yields_reject_payload`.
7890    #[test]
7891    fn adr0004_off_curve_quote_follows_rollout_gate() {
7892        use evmlib::{EncodedPeerId, RewardsAddress};
7893
7894        let mut quote = make_fake_quote_at_records(
7895            [0xC1u8; 32],
7896            SystemTime::now(),
7897            RewardsAddress::new([1u8; 20]),
7898            100,
7899        );
7900        // Bump one wei off the curve.
7901        quote.price += Amount::from(1u64);
7902
7903        let id: [u8; 32] = rand::random();
7904        let payment = ProofOfPayment {
7905            peer_quotes: vec![(EncodedPeerId::new(id), quote)],
7906        };
7907
7908        // Both branches of the const-gated split are asserted, so the test
7909        // keeps its meaning whichever way the gate is set rather than going
7910        // silently vacuous when it flips.
7911        if crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED {
7912            assert!(
7913                PaymentVerifier::validate_quote_arithmetic(&payment).is_err(),
7914                "enforcing rollout must reject off-curve quotes"
7915            );
7916        } else {
7917            assert!(
7918                PaymentVerifier::validate_quote_arithmetic(&payment).is_ok(),
7919                "observe-only rollout must not reject off-curve quotes"
7920            );
7921        }
7922    }
7923
7924    /// Enforcement-branch coverage: the rejection payload (peer id, candidate
7925    /// `n`, recomputed price) is produced for off-curve prices independently
7926    /// of the rollout const, so CI exercises the rejection code path even
7927    /// while [`QUOTE_ARITHMETIC_RECHECK_ENABLED`] ships as `false`. Flipping
7928    /// the const to `true` then merely wires this diagnostic into the outer
7929    /// `Err` return, which is what `validate_quote_arithmetic` does.
7930    #[test]
7931    fn adr0004_off_curve_diagnostics_yields_reject_payload() {
7932        let on = crate::payment::pricing::calculate_price(100);
7933        let off = on + Amount::from(1u64);
7934
7935        let diag = PaymentVerifier::price_off_curve_diagnostics(&off)
7936            .expect("off-curve price must produce diagnostics");
7937        let (candidate_count, recomputed) = diag;
7938        assert_eq!(candidate_count, 100, "floor candidate must be n=100");
7939        assert_eq!(
7940            recomputed, on,
7941            "recomputed price must equal the floor curve point"
7942        );
7943        assert!(
7944            recomputed < off,
7945            "off-curve diagnostics' recomputed price must be strictly below the off-curve input"
7946        );
7947
7948        // And an on-curve price must produce no diagnostics.
7949        assert!(
7950            PaymentVerifier::price_off_curve_diagnostics(&on).is_none(),
7951            "on-curve price must yield no off-curve diagnostics"
7952        );
7953    }
7954
7955    /// Saturation regime: a price strictly above
7956    /// `calculate_price(u64::MAX-equivalent saturating ceiling)` is rejected.
7957    /// We do not have direct access to that ceiling, but `Amount::MAX` is
7958    /// guaranteed above it (since `calculate_price(usize::MAX)` saturates to
7959    /// some value strictly less than `Amount::MAX` due to the additive
7960    /// baseline). The gate must reject it.
7961    #[test]
7962    fn adr0004_amount_max_price_is_off_curve() {
7963        let price = Amount::MAX;
7964        assert!(
7965            !PaymentVerifier::quote_price_is_on_curve(&price),
7966            "Amount::MAX must not be a valid on-curve price"
7967        );
7968    }
7969
7970    /// Merkle gate, predicate-level: the same canonicality rule applies to
7971    /// `MerklePaymentCandidateNode.price`. We don't construct a full merkle
7972    /// proof here (the test fixtures for that live elsewhere); we prove the
7973    /// underlying decision matches the single-node side, so the Merkle gate
7974    /// inherits the same correctness as `validate_quote_arithmetic`.
7975    #[test]
7976    fn adr0004_merkle_candidate_canonicality_matches_single_node() {
7977        // Every on-curve `n` produces a price the predicate accepts; one wei
7978        // off produces a price the predicate rejects. This is the entire
7979        // contract; the Merkle gate's outer wrapper enforces the same const
7980        // as the single-node gate, so the wrappers are mechanically
7981        // equivalent.
7982        for &n in &[0usize, 1, 100, 6000, 1_000_000] {
7983            let on = crate::payment::pricing::calculate_price(n);
7984            assert!(
7985                PaymentVerifier::quote_price_is_on_curve(&on),
7986                "merkle candidate price for n={n} must be on-curve"
7987            );
7988            if n > 0 {
7989                let off = on + Amount::from(1u64);
7990                assert!(
7991                    !PaymentVerifier::quote_price_is_on_curve(&off),
7992                    "merkle candidate price one wei above n={n} must be off-curve"
7993                );
7994            }
7995        }
7996    }
7997
7998    /// Merkle gate, pool-level: build a real signed candidate pool, set every
7999    /// candidate's price to the same on-curve value, and assert the gate
8000    /// passes. Then bump one candidate's price one wei off-curve and assert
8001    /// the per-candidate diagnostics correctly identify it. We use the
8002    /// diagnostics predicate rather than the outer `validate_merkle_candidate_arithmetic`
8003    /// because the outer wrapper short-circuits to `Ok` under the observe-only
8004    /// rollout const; the diagnostics path is what carries the rejection
8005    /// information when enforcement flips on.
8006    #[test]
8007    fn adr0004_merkle_pool_off_curve_candidate_caught_by_diagnostics() {
8008        use evmlib::merkle_payments::MerklePaymentCandidatePool;
8009
8010        let timestamp = 1_700_000_000u64;
8011        let mut candidates = make_candidate_nodes(timestamp);
8012
8013        // Set every candidate price to calculate_price(500) so the pool is
8014        // honestly on-curve to start. The binding must move with the price:
8015        // ADR-0004 requires `price == calculate_price(committed_key_count)`, so
8016        // repricing at 500 records while leaving the count at 0 would make the
8017        // pool dishonest rather than honest.
8018        let on_curve = crate::payment::pricing::calculate_price(500);
8019        for c in &mut candidates {
8020            c.price = on_curve;
8021            c.committed_key_count = 500;
8022            c.commitment_pin = Some([0xA5u8; 32]);
8023        }
8024        let pool = MerklePaymentCandidatePool {
8025            midpoint_proof: fake_midpoint_proof(),
8026            candidate_nodes: candidates,
8027        };
8028        // The outer wrapper is rollout-gated, but a fully on-curve pool must
8029        // pass it under any const value because the loop finds no off-curve
8030        // candidate to reject.
8031        PaymentVerifier::validate_merkle_candidate_arithmetic(&pool)
8032            .expect("honest on-curve pool must pass merkle gate (any const value)");
8033        for c in &pool.candidate_nodes {
8034            assert!(
8035                PaymentVerifier::price_off_curve_diagnostics(&c.price).is_none(),
8036                "every honest candidate must be canonically on-curve"
8037            );
8038        }
8039
8040        // Now bump exactly one candidate off-curve and check that the
8041        // diagnostics path catches it. (The outer wrapper still short-circuits
8042        // under observe-only; this proves the underlying detection works
8043        // independently of the rollout const, exercising the rejection-payload
8044        // path in CI.)
8045        let mut tampered = pool;
8046        tampered.candidate_nodes[3].price += Amount::from(1u64);
8047        let mut off_curve_seen = 0;
8048        for c in &tampered.candidate_nodes {
8049            if PaymentVerifier::price_off_curve_diagnostics(&c.price).is_some() {
8050                off_curve_seen += 1;
8051            }
8052        }
8053        assert_eq!(
8054            off_curve_seen, 1,
8055            "exactly one tampered candidate must register as off-curve"
8056        );
8057    }
8058
8059    // === ADR-0004 binding-shape + cross-check unit tests ===
8060
8061    use crate::payment::pricing::calculate_price as cp;
8062
8063    /// Build a real signed commitment over `n` synthetic keys for tests.
8064    fn test_built_commitment(n: u32) -> crate::replication::commitment_state::BuiltCommitment {
8065        use saorsa_pqc::api::sig::ml_dsa_65;
8066        let (pk, sk) = ml_dsa_65().generate_keypair().expect("keypair");
8067        let pk_bytes = pk.to_bytes();
8068        let peer_id = blake3::hash(&pk_bytes);
8069        let entries: Vec<([u8; 32], [u8; 32])> = (0..n)
8070            .map(|i| {
8071                let mut k = [0u8; 32];
8072                k[..4].copy_from_slice(&i.to_le_bytes());
8073                let mut b = [1u8; 32];
8074                b[..4].copy_from_slice(&i.to_le_bytes());
8075                (k, b)
8076            })
8077            .collect();
8078        crate::replication::commitment_state::BuiltCommitment::build(
8079            entries,
8080            peer_id.as_bytes(),
8081            &sk,
8082            &pk_bytes,
8083        )
8084        .expect("build commitment")
8085    }
8086
8087    #[test]
8088    fn binding_baseline_ok_only_at_baseline_price() {
8089        // (0, None) with calculate_price(0) is the valid baseline.
8090        assert!(PaymentVerifier::binding_violation(0, None, &cp(0)).is_none());
8091        // (0, None) with a non-baseline price is REJECTED — this is the BLOCKER
8092        // bypass the round-1 review found (unpinned quote priced above baseline).
8093        assert!(PaymentVerifier::binding_violation(0, None, &cp(500)).is_some());
8094    }
8095
8096    #[test]
8097    fn binding_bound_ok_only_with_pin_and_exact_price() {
8098        let pin = [9u8; 32];
8099        // (n>0, Some(pin)) priced exactly is valid.
8100        assert!(PaymentVerifier::binding_violation(500, Some(pin), &cp(500)).is_none());
8101        // (n>0, Some(pin)) priced for a DIFFERENT count is rejected (on-curve
8102        // but wrong count — stronger than canonicality).
8103        assert!(PaymentVerifier::binding_violation(500, Some(pin), &cp(499)).is_some());
8104    }
8105
8106    #[test]
8107    fn binding_rejects_incoherent_shapes() {
8108        let pin = [9u8; 32];
8109        // count > 0 but no pin: unauditable.
8110        assert!(PaymentVerifier::binding_violation(500, None, &cp(500)).is_some());
8111        // count 0 but a pin: incoherent baseline.
8112        assert!(PaymentVerifier::binding_violation(0, Some(pin), &cp(0)).is_some());
8113    }
8114
8115    #[test]
8116    fn binding_rejects_count_above_cap() {
8117        let pin = [9u8; 32];
8118        let over = crate::replication::commitment::MAX_COMMITMENT_KEY_COUNT + 1;
8119        assert!(PaymentVerifier::binding_violation(over, Some(pin), &cp(over as usize)).is_some());
8120    }
8121
8122    #[test]
8123    fn cross_check_match_when_pin_and_count_agree() {
8124        let built = test_built_commitment(12);
8125        let outcome = PaymentVerifier::cross_check_binding(12, built.hash(), built.commitment());
8126        assert_eq!(outcome, CrossCheck::Match);
8127    }
8128
8129    #[test]
8130    fn cross_check_mismatch_when_count_inflated() {
8131        let built = test_built_commitment(12);
8132        // Quote claims 999 but the pinned commitment attests 12.
8133        let outcome = PaymentVerifier::cross_check_binding(999, built.hash(), built.commitment());
8134        assert_eq!(
8135            outcome,
8136            CrossCheck::Mismatch {
8137                quoted_key_count: 999,
8138                committed_key_count: 12,
8139            }
8140        );
8141    }
8142
8143    #[test]
8144    fn cross_check_unresolved_when_pin_wrong() {
8145        let built = test_built_commitment(12);
8146        // Pin does not match the supplied commitment's hash: not evidence.
8147        let outcome = PaymentVerifier::cross_check_binding(12, [0xFFu8; 32], built.commitment());
8148        assert_eq!(outcome, CrossCheck::PinDoesNotResolve);
8149    }
8150
8151    #[test]
8152    fn fresh_cached_commitment_honours_ttl_boundary() {
8153        use crate::replication::commitment_state::PeerCommitmentRecord;
8154        let built = test_built_commitment(5);
8155        let commitment = built.commitment().clone();
8156        let pin = built.hash();
8157        let ttl = std::time::Duration::from_secs(3 * 3600);
8158        let now = std::time::Instant::now();
8159
8160        // Fresh AND matching pin -> resolves to the commitment.
8161        let fresh = PeerCommitmentRecord::from_verified(commitment.clone(), now);
8162        assert!(
8163            PaymentVerifier::fresh_cached_commitment(&fresh, pin, now, ttl).is_some(),
8164            "a fresh cache entry whose hash matches the pin must resolve"
8165        );
8166
8167        // Fresh but a DIFFERENT pin -> treated as not-cached (None), so the
8168        // caller falls through to fetch the actually-quoted pin instead of
8169        // mis-resolving against the peer's latest (different) commitment.
8170        assert!(
8171            PaymentVerifier::fresh_cached_commitment(&fresh, [0xEEu8; 32], now, ttl).is_none(),
8172            "a fresh cache entry for a DIFFERENT pin must not resolve (fetch fallback runs)"
8173        );
8174
8175        // Stale: received older than the TTL -> treated as unknown (None), the
8176        // ADR-0004 false-positive guard against an aged cache entry.
8177        //
8178        // Advance the comparison clock PAST the TTL rather than subtracting the
8179        // TTL from `now`: on Windows the monotonic `Instant` epoch can be
8180        // younger than a multi-hour TTL, so `now.checked_sub(ttl + 1s)`
8181        // underflows to `None` and panics. `checked_add` from the receipt time
8182        // is always in range and is equivalent for the age comparison.
8183        let received_at = now;
8184        let now_after_ttl = received_at
8185            .checked_add(ttl + std::time::Duration::from_secs(1))
8186            .expect("instant in range");
8187        let stale = PeerCommitmentRecord::from_verified(commitment, received_at);
8188        assert!(
8189            PaymentVerifier::fresh_cached_commitment(&stale, pin, now_after_ttl, ttl).is_none(),
8190            "a cache entry older than the answerability TTL must be treated as unknown"
8191        );
8192    }
8193
8194    #[test]
8195    fn fetched_commitment_must_be_bound_to_the_queried_peer() {
8196        // A fetched commitment is accepted only when it is bound to the peer we
8197        // asked (sender_peer_id == peer_id) and hashes to the requested pin.
8198        let built = test_built_commitment(8);
8199        let commitment = built.commitment().clone();
8200        let pin = built.hash();
8201        let owner = PeerId::from_bytes(commitment.sender_peer_id);
8202
8203        // Correct owner + correct pin -> accepted.
8204        assert!(
8205            PaymentVerifier::fetched_commitment_is_valid(&commitment, &owner, pin),
8206            "a peer's own validly-signed commitment, hashing to the pin, must be accepted"
8207        );
8208
8209        // Same (validly signed) commitment but attributed to a DIFFERENT peer ->
8210        // rejected. This is the MAJOR fix: a peer must not be able to answer with
8211        // someone else's commitment and have it pass as its own.
8212        let other = PeerId::from_bytes([0xABu8; 32]);
8213        assert!(
8214            !PaymentVerifier::fetched_commitment_is_valid(&commitment, &other, pin),
8215            "another peer's commitment must be rejected for the queried peer"
8216        );
8217
8218        // Correct owner but wrong pin -> rejected.
8219        assert!(
8220            !PaymentVerifier::fetched_commitment_is_valid(&commitment, &owner, [0u8; 32]),
8221            "a commitment that does not hash to the requested pin must be rejected"
8222        );
8223    }
8224
8225    #[tokio::test]
8226    async fn emit_mismatch_evidence_without_p2p_does_not_panic() {
8227        // Guards the "always best-effort" degrade path: with no P2P handle there
8228        // is no trust engine to act on, so `emit_mismatch_evidence` must be a
8229        // no-op that never panics or errors on the payment path. This is a
8230        // no-panic guard on the degraded path — it does NOT exercise the
8231        // evidence->action mapping (that needs a live trust engine).
8232        let built = test_built_commitment(12);
8233        let evidence = crate::replication::types::FailureEvidence::QuoteCommitmentMismatch {
8234            peer: PeerId::from_bytes([1u8; 32]),
8235            pinned_commitment: [2u8; 32],
8236            quoted_key_count: 999,
8237            committed_key_count: 12,
8238            quote_artifact: vec![0xAA; 16],
8239            commitment: Box::new(built.commitment().clone()),
8240        };
8241        // No P2P -> no trust event even if enforce were on; must not panic.
8242        PaymentVerifier::emit_mismatch_evidence(&evidence, None).await;
8243    }
8244
8245    #[test]
8246    fn valid_sidecar_is_indexed_and_resolves_synchronously() {
8247        // A valid sidecar blob is indexed under its own (peer, pin) so the
8248        // cross-check resolves it synchronously — "the commitment arrived with
8249        // the quote", no gossip-cache hit or fetch needed.
8250        let built = test_built_commitment(9);
8251        let commitment = built.commitment().clone();
8252        let pin = built.hash();
8253        let owner = PeerId::from_bytes(commitment.sender_peer_id);
8254        let blob = rmp_serde::to_vec(&commitment).expect("serialize sidecar");
8255
8256        let map = PaymentVerifier::index_valid_sidecars(std::slice::from_ref(&blob));
8257        assert!(
8258            map.contains_key(&(owner, pin)),
8259            "a valid sidecar must be indexed under its own (peer, pin)"
8260        );
8261
8262        // A garbage blob is silently skipped (resolution falls back), never a
8263        // hard error.
8264        let map2 = PaymentVerifier::index_valid_sidecars(&[vec![0xFF; 8]]);
8265        assert!(map2.is_empty(), "an unparseable sidecar must be skipped");
8266    }
8267}