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