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