Skip to main content

ant_node/payment/
verifier.rs

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