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