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