1use 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
34pub const MIN_PAYMENT_PROOF_SIZE_BYTES: usize = 32;
39
40pub 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
58const PAID_QUOTE_ISSUER_CLOSENESS_WIDTH: usize = K_BUCKET_SIZE;
62
63const PRICE_FLOOR_DEFAULT_TOLERANCE_PERCENT: u64 = 50;
70
71pub const PRICE_FLOOR_ENFORCE_ENV: &str = "ANT_PRICE_FLOOR_ENFORCE";
77
78pub const PRICE_FLOOR_TOLERANCE_ENV: &str = "ANT_PRICE_FLOOR_TOLERANCE_PERCENT";
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub struct PriceFloorConfig {
103 pub enforce: bool,
106 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 #[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 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
179fn 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
207fn 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(); 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#[derive(Debug, Clone)]
275pub struct EvmVerifierConfig {
276 pub network: EvmNetwork,
278}
279
280impl Default for EvmVerifierConfig {
281 fn default() -> Self {
282 Self {
283 network: EvmNetwork::ArbitrumOne,
284 }
285 }
286}
287
288#[derive(Debug, Clone)]
293pub struct PaymentVerifierConfig {
294 pub evm: EvmVerifierConfig,
296 pub cache_capacity: usize,
298 pub close_group_size: usize,
300 pub local_rewards_address: RewardsAddress,
305 pub price_floor: PriceFloorConfig,
307}
308
309#[derive(Debug, Clone, Copy, PartialEq, Eq)]
341pub enum VerificationContext {
342 ClientPut,
345 FreshReplication,
349 PaidListAdmission,
352}
353
354impl VerificationContext {
355 #[must_use]
360 pub fn is_store_admission(self) -> bool {
361 matches!(self, Self::ClientPut | Self::FreshReplication)
362 }
363}
364
365#[derive(Debug, Clone, Copy, PartialEq, Eq)]
367pub enum PaymentStatus {
368 CachedAsVerified,
370 PaymentRequired,
372 PaymentVerified,
374}
375
376#[derive(Debug, Clone, Copy, PartialEq, Eq)]
379pub enum CrossCheck {
380 Match,
382 Mismatch {
385 quoted_key_count: u32,
387 committed_key_count: u32,
389 },
390 PinDoesNotResolve,
393}
394
395impl PaymentStatus {
396 #[must_use]
398 pub fn can_store(&self) -> bool {
399 matches!(self, Self::CachedAsVerified | Self::PaymentVerified)
400 }
401
402 #[must_use]
404 pub fn is_cached(&self) -> bool {
405 matches!(self, Self::CachedAsVerified)
406 }
407}
408
409const DEFAULT_POOL_CACHE_CAPACITY: usize = 1_000;
411
412const MERKLE_PARITY_TELEMETRY_CACHE_CAPACITY: usize = 1_000;
428
429const MAX_SIDECARS_PER_BUNDLE: usize = evmlib::merkle_batch_payment::CANDIDATES_PER_POOL;
435
436type CommitmentCache = Arc<
441 tokio::sync::RwLock<
442 HashMap<PeerId, crate::replication::commitment_state::PeerCommitmentRecord>,
443 >,
444>;
445
446type PinFetchNegativeCache = Arc<Mutex<LruCache<(PeerId, [u8; 32]), ()>>>;
451
452#[cfg(any(test, feature = "test-utils"))]
455type TestSettlementOverride = (Amount, Option<[u8; 16]>);
456
457pub struct PaymentVerifier {
464 cache: VerifiedCache,
466 pool_cache: Mutex<LruCache<PoolHash, OnChainPaymentInfo>>,
468 closeness_pass_cache: Mutex<LruCache<PoolHash, ()>>,
472 inflight_closeness: Mutex<LruCache<PoolHash, Arc<ClosenessSlot>>>,
478 p2p_node: RwLock<Option<Arc<P2PNode>>>,
484 storage: RwLock<Option<Arc<LmdbStorage>>>,
494 #[cfg(any(test, feature = "test-utils"))]
498 test_paid_quote_k_closest_override: RwLock<Option<Vec<[u8; 32]>>>,
499 #[cfg(any(test, feature = "test-utils"))]
508 test_completed_payments_override: RwLock<HashMap<QuoteHash, TestSettlementOverride>>,
509 commitment_cache: RwLock<Option<CommitmentCache>>,
521 pin_fetch_negative_cache: PinFetchNegativeCache,
528 monetized_pin_tx:
533 RwLock<Option<tokio::sync::mpsc::Sender<crate::replication::MonetizedPinEvent>>>,
534 local_commitment_source: RwLock<Option<Arc<dyn crate::payment::quote::CommitmentSource>>>,
541 price_floor: RwLock<PriceFloorConfig>,
546 merkle_parity_from: RwLock<u64>,
557 merkle_parity_logged: Mutex<LruCache<PoolHash, ()>>,
566 merkle_parity_emissions: std::sync::atomic::AtomicUsize,
570 config: PaymentVerifierConfig,
572}
573
574struct ClosenessSlot {
579 notify: Arc<tokio::sync::Notify>,
580 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 fn notified_owned(&self) -> tokio::sync::futures::OwnedNotified {
599 Arc::clone(&self.notify).notified_owned()
600 }
601}
602
603struct InflightGuard<'a> {
612 slot_cache: &'a Mutex<LruCache<PoolHash, Arc<ClosenessSlot>>>,
613 pool_hash: PoolHash,
614 slot: Arc<ClosenessSlot>,
615}
616
617impl InflightGuard<'_> {
618 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 {
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 self.slot.notify.notify_waiters();
647 }
648}
649
650impl PaymentVerifier {
651 #[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 #[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 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 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 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 #[must_use]
752 pub fn close_group_size(&self) -> usize {
753 self.config.close_group_size
754 }
755
756 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 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 #[must_use]
786 pub fn price_floor_config(&self) -> PriceFloorConfig {
787 *self.price_floor.read()
788 }
789
790 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 pub fn check_payment_required(
898 &self,
899 xorname: &XorName,
900 context: VerificationContext,
901 ) -> PaymentStatus {
902 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 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 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 let status = self.check_payment_required(xorname, context);
998
999 match status {
1000 PaymentStatus::CachedAsVerified => {
1001 Ok(status)
1003 }
1004 PaymentStatus::PaymentRequired => {
1005 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 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 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 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 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 #[must_use]
1087 pub fn cache_stats(&self) -> CacheStats {
1088 self.cache.stats()
1089 }
1090
1091 #[must_use]
1093 pub fn cache_len(&self) -> usize {
1094 self.cache.len()
1095 }
1096
1097 #[cfg(any(test, feature = "test-utils"))]
1103 pub fn cache_insert(&self, xorname: XorName) {
1104 self.cache.insert(xorname);
1105 }
1106
1107 #[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 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 Self::validate_quote_arithmetic(payment)?;
1162 let candidates = Self::legacy_median_candidates(payment)?;
1163 let mut failures = Vec::with_capacity(candidates.len());
1164 let mut verified_paid_quote: Option<(Amount, Amount)> = None;
1167 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 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 self.enforce_price_floor(xorname, paid_price, settled_amount, context)?;
1214
1215 Self::log_off_curve_single_node(payment);
1220
1221 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 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 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 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 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("e_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 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("e_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("e.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 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 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 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 fn quote_arithmetic_violation(quote: &evmlib::PaymentQuote) -> Option<String> {
1661 Self::binding_violation(
1662 quote.committed_key_count,
1663 quote.commitment_pin,
1664 "e.price,
1665 )
1666 }
1667
1668 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 fn cross_check_binding(
1743 quoted_key_count: u32,
1744 quoted_pin: [u8; 32],
1745 commitment: &crate::replication::commitment::StorageCommitment,
1746 ) -> CrossCheck {
1747 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 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; }
1778 if rec.commitment_hash() != Some(pin) {
1785 return None;
1786 }
1787 rec.last_commitment().cloned()
1788 }
1789
1790 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 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 for blob in sidecars.iter().take(MAX_SIDECARS_PER_BUNDLE) {
1826 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; };
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 if Self::fetched_commitment_is_valid(&commitment, &peer_id, pin) {
1843 map.insert((peer_id, pin), commitment);
1844 }
1845 }
1846 map
1847 }
1848
1849 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 let sidecar_map = Self::index_valid_sidecars(commitment_sidecars);
1888
1889 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; };
1897 let peer_id = PeerId::from_bytes(*encoded_peer_id.as_bytes());
1898
1899 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 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 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 if unresolved.is_empty() {
1958 return;
1959 }
1960 let Some(p2p) = p2p else {
1961 return; };
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 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 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 neg_cache.lock().put((peer_id, pin), ());
2006 }
2007 }
2008 }
2009 }
2010
2011 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; };
2031 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 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 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; };
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 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; };
2132 Self::fetched_commitment_is_valid(&commitment, peer_id, pin).then_some(commitment)
2133 }
2134
2135 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 fn log_off_curve_single_node(payment: &ProofOfPayment) {
2159 if crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED {
2160 return; }
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 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 fn log_off_curve_merkle(pool: &evmlib::merkle_payments::MerklePaymentCandidatePool) {
2201 if crate::replication::config::QUOTE_ARITHMETIC_RECHECK_ENABLED {
2202 return; }
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 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 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 #[allow(dead_code)] fn quote_price_is_on_curve(price: &Amount) -> bool {
2312 Self::price_off_curve_diagnostics(price).is_none()
2313 }
2314
2315 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 fn candidate_count_to_usize(candidate_count: u64) -> usize {
2335 usize::try_from(candidate_count).unwrap_or(usize::MAX)
2336 }
2337
2338 const CANDIDATE_CLOSENESS_REQUIRED: usize = 9;
2362
2363 const CLOSENESS_LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(240);
2391
2392 const CLOSENESS_LOOKUP_WIDTH: usize = 2 * evmlib::merkle_payments::CANDIDATES_PER_POOL;
2425
2426 const MAX_LEADER_RETRIES: usize = 1;
2440
2441 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 async fn verify_merkle_candidate_closeness(
2495 &self,
2496 pool: &evmlib::merkle_payments::MerklePaymentCandidatePool,
2497 pool_hash: PoolHash,
2498 ) -> Result<()> {
2499 if self.closeness_pass_cache.lock().get(&pool_hash).is_some() {
2503 return Ok(());
2504 }
2505
2506 for attempt in 0..=Self::MAX_LEADER_RETRIES {
2524 #[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 let notified = slot.notified_owned();
2550 notified.await;
2551
2552 if let Some(result) = slot.result.get() {
2554 return result.clone().map_err(Error::Payment);
2555 }
2556 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 let Some(slot) = leader_slot else {
2574 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 Err(Error::Payment(
2597 "internal error: closeness retry loop exited without returning".into(),
2598 ))
2599 }
2600
2601 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 fn check_closeness_match(
2657 candidate_peer_ids: &[PeerId],
2658 network_peer_ids: &[PeerId],
2659 pool_address: &[u8; 32],
2660 ) -> Result<()> {
2661 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 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 let candidate_peer_ids = Self::derive_distinct_candidate_peer_ids(pool)?;
2729
2730 let attached = self.p2p_node.read().as_ref().map(Arc::clone);
2733 let Some(p2p_node) = attached else {
2734 #[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 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 #[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 let merkle_proof = deserialize_merkle_proof(proof_bytes)
2843 .map_err(|e| Error::Payment(format!("Failed to deserialize merkle proof: {e}")))?;
2844
2845 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 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 Self::validate_merkle_candidate_arithmetic(&merkle_proof.winner_pool)?;
2874 Self::log_off_curve_merkle(&merkle_proof.winner_pool);
2875
2876 self.verify_merkle_candidate_closeness(&merkle_proof.winner_pool, pool_hash)
2886 .await?;
2887
2888 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 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 {
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 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 let smart_contract_root = merkle_proof.winner_pool.midpoint_proof.root();
2952
2953 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 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 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 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 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 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 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 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; };
3129 let peer_id = PeerId::from_bytes(*blake3::hash(&candidate.pub_key).as_bytes());
3130
3131 if paid_indices.contains(&idx) {
3136 if let Some(ref tx) = monetized_pin_tx {
3137 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 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 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 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 fn prices_with_median(median: u64) -> Vec<Amount> {
3246 vec![Amount::from(median); 16]
3247 }
3248
3249 #[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 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 #[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 #[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, "e.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, "e, 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 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 verifier.cache.insert(xorname);
3506
3507 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 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 verifier.cache.insert(xorname);
3534
3535 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 assert_eq!(
3591 verifier.check_payment_required(&xorname, VerificationContext::ClientPut),
3592 PaymentStatus::PaymentRequired
3593 );
3594
3595 verifier.cache.insert(xorname);
3597
3598 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 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 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 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 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 #[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 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 #[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 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, "e, 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 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 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 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 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, "e, 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 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 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 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 #[test]
4020 fn price_floor_from_env_fails_closed_on_invalid_tolerance() {
4021 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 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 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 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, "e, 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 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 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 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 }
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 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 let target_xorname = [0xAAu8; 32];
4501
4502 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let mut quote = make_fake_quote(xorname, SystemTime::now(), rewards_addr);
4767 quote.pub_key = pub_key_bytes;
4768
4769 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 #[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 #[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 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 #[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 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 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 assert_eq!(
4931 crate::payment::proof::detect_proof_type(&tagged_bytes),
4932 Some(crate::payment::proof::ProofType::SingleNode)
4933 );
4934
4935 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 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 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 {
4972 let mut cache = verifier.pool_cache.lock();
4973 cache.put(pool_hash, payment_info);
4974 }
4975
4976 {
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 {
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 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 let verifier = create_test_verifier();
5010 let pool_hash = [0xAAu8; 32];
5011 verifier.closeness_pass_cache.lock().put(pool_hash, ());
5012
5013 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 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 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 for _ in 0..5 {
5104 tokio::task::yield_now().await;
5105 }
5106
5107 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 let verifier = create_test_verifier();
5132 let pool_hash = [0xDDu8; 32];
5133
5134 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 fn fake_midpoint_proof() -> evmlib::merkle_payments::MidpointProof {
5167 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 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 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 #[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 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 #[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 #[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 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 const MERKLE_PARITY_PER_NODE_DEPTH2: u64 = 6144;
5407
5408 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 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 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 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 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 for i in 0..DEFAULT_POOL_CACHE_CAPACITY {
5525 let mut hash: PoolHash = [0u8; 32];
5526 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 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 assert_eq!(
5557 verifier.pool_cache.lock().len(),
5558 DEFAULT_POOL_CACHE_CAPACITY
5559 );
5560
5561 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 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 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 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 let tampered_pool_hash = merkle_proof.winner_pool_hash();
5621
5622 {
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 {
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 {
5691 let info = evmlib::merkle_payments::OnChainPaymentInfo {
5692 depth: 2,
5693 merkle_payment_timestamp: ts,
5694 paid_node_addresses: vec![
5695 (
5698 RewardsAddress::new([0u8; 20]),
5699 0,
5700 Amount::from(MERKLE_PARITY_PER_NODE_DEPTH2),
5701 ),
5702 (
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 {
5740 let info = evmlib::merkle_payments::OnChainPaymentInfo {
5741 depth: 2,
5742 merkle_payment_timestamp: ts,
5743 paid_node_addresses: vec![
5744 (
5747 RewardsAddress::new([0u8; 20]),
5748 0,
5749 Amount::from(MERKLE_PARITY_PER_NODE_DEPTH2),
5750 ),
5751 (
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 {
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 {
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 #[tokio::test]
5861 async fn merkle_legacy_1x_settlement_rejected_after_the_parity_boundary() {
5862 let verifier = merkle_test_verifier(); 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 #[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 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 #[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 type TaggedProof = ([u8; 32], Vec<u8>);
5993
5994 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 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 #[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 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 #[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 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 #[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 #[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 #[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 #[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 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 #[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 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 #[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 #[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 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 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 #[test]
6417 fn closeness_lookup_timeout_is_240s() {
6418 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 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 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 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 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 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 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 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 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 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 let candidates = synthetic_peer_ids(15)
6542 .into_iter()
6543 .chain(std::iter::once(synthetic_peer_id(17)))
6544 .collect::<Vec<_>>();
6545 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 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 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 let mut candidates = synthetic_peer_ids(8);
6606 candidates.extend((100..=107).map(synthetic_peer_id)); 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 let mut candidates = synthetic_peer_ids(9);
6623 candidates.extend((100..=106).map(synthetic_peer_id)); 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 let candidates = synthetic_peer_ids(16);
6641 let network = synthetic_peer_ids(8); 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 #[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 #[test]
6677 fn adr0004_off_curve_prices_rejected_by_predicate() {
6678 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 #[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 #[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("e.price).is_none(),
6736 "every quote in honest bundle must be canonically on-curve"
6737 );
6738 }
6739 }
6740
6741 #[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 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 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 #[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 assert!(
6803 PaymentVerifier::price_off_curve_diagnostics(&on).is_none(),
6804 "on-curve price must yield no off-curve diagnostics"
6805 );
6806 }
6807
6808 #[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 #[test]
6829 fn adr0004_merkle_candidate_canonicality_matches_single_node() {
6830 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 #[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 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 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 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 use crate::payment::pricing::calculate_price as cp;
6910
6911 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 assert!(PaymentVerifier::binding_violation(0, None, &cp(0)).is_none());
6939 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 assert!(PaymentVerifier::binding_violation(500, Some(pin), &cp(500)).is_none());
6949 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 assert!(PaymentVerifier::binding_violation(500, None, &cp(500)).is_some());
6959 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 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 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 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 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 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 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 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 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 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 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 PaymentVerifier::emit_mismatch_evidence(&evidence, None).await;
7091 }
7092
7093 #[test]
7094 fn valid_sidecar_is_indexed_and_resolves_synchronously() {
7095 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 let map2 = PaymentVerifier::index_valid_sidecars(&[vec![0xFF; 8]]);
7113 assert!(map2.is_empty(), "an unparseable sidecar must be skipped");
7114 }
7115}