1#![allow(clippy::significant_drop_tightening)]
16
17pub mod admission;
18pub mod audit;
19pub mod audit_coordinator;
20pub(crate) mod audit_metrics;
21pub mod bootstrap;
22pub mod commitment;
23pub mod commitment_state;
24pub mod config;
25pub mod fresh;
26pub mod neighbor_sync;
27pub mod paid_list;
28pub mod possession;
29pub mod protocol;
30pub mod pruning;
31pub mod quorum;
32pub mod recent_provers;
33pub mod scheduling;
34pub mod slice;
35pub mod storage_commitment_audit;
36pub mod subtree;
37pub mod types;
38
39use std::collections::{HashMap, HashSet, VecDeque};
40use std::fmt;
41use std::num::NonZeroUsize;
42use std::ops::ControlFlow;
43use std::path::{Path, PathBuf};
44use std::sync::atomic::{AtomicU64, Ordering};
45use std::sync::Arc;
46use std::time::{Duration, Instant, SystemTime};
47
48use lru::LruCache;
49use std::pin::Pin;
50
51use crate::logging::{debug, error, info, warn};
52use futures::stream::FuturesUnordered;
53use futures::{future::join_all, Future, StreamExt};
54use parking_lot::Mutex;
55use rand::rngs::StdRng;
56use rand::{Rng, SeedableRng};
57use tokio::sync::broadcast::error::RecvError;
58use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
59use tokio::task::JoinHandle;
60use tokio_util::sync::CancellationToken;
61use tokio_util::task::TaskTracker;
62
63use crate::ant_protocol::XorName;
64use crate::error::{Error, Result};
65use crate::payment::{
66 PaymentVerifier, VerificationContext, MAX_PAYMENT_PROOF_SIZE_BYTES,
67 MIN_PAYMENT_PROOF_SIZE_BYTES,
68};
69use crate::replication::audit::AuditTickResult;
70use crate::replication::audit_coordinator::AuditChallengeCoordinator;
71use crate::replication::audit_metrics::{
72 AuditResponderClass, AuditResponderDropReason, AuditResponderMetrics,
73 ReplicationResponderClass, ResponderAdmissionCeiling,
74};
75use crate::replication::commitment::{commitment_hash, StorageCommitment};
76use crate::replication::commitment_state::{
77 PeerCommitmentRecord, PersistedRetention, ResponderCommitmentState, GOSSIP_ANSWERABILITY_TTL,
78};
79use crate::replication::config::{
80 max_parallel_fetch, storage_admission_width, ReplicationConfig, MAX_AUDIT_RESPONSES_PER_PEER,
81 MAX_CONCURRENT_AUDIT_RESPONSES, MAX_CONCURRENT_REPLICATION_SENDS,
82 MAX_DIGEST_AUDIT_RESPONSES_PER_PEER, MAX_INCOMING_VERIFICATION_KEYS,
83 MAX_SUBTREE_ROUND1_PER_PEER, MAX_SUBTREE_SESSIONS, MAX_VERIFICATION_KEYS_PER_CYCLE,
84 REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID, SUBTREE_ROUND1_WORK_BURST_BYTES,
85 SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, SUBTREE_SESSION_TTL,
86};
87use crate::replication::paid_list::PaidList;
88use crate::replication::protocol::{
89 FreshReplicationResponse, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
90 VerificationResponse,
91};
92use crate::replication::quorum::KeyVerificationOutcome;
93use crate::replication::recent_provers::RecentProvers;
94use crate::replication::scheduling::{CapacityDisplacement, ReplicationQueues};
95use crate::replication::types::{
96 AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence,
97 NeighborSyncState, PeerSyncRecord, PresenceEvidence, RepairProofs, VerificationEntry,
98 VerificationState,
99};
100use crate::storage::LmdbStorage;
101use saorsa_core::identity::{NodeIdentity, PeerId};
102use saorsa_core::{DhtNetworkEvent, P2PEvent, P2PNode, TrustEvent};
103use saorsa_pqc::api::sig::{MlDsaSecretKey, MlDsaVariant};
104
105static FIRST_AUDIT_INGRESS_DROPPED: AtomicU64 = AtomicU64::new(0);
113
114pub(crate) fn note_monetized_ingress_drop() {
117 FIRST_AUDIT_INGRESS_DROPPED.fetch_add(1, Ordering::Relaxed);
118}
119
120#[derive(Default)]
121struct FirstAuditObservability {
122 received: AtomicU64,
123 queued: AtomicU64,
124 coalesced: AtomicU64,
125 duplicates: AtomicU64,
126 capacity_evicted: AtomicU64,
127 self_target_skipped: AtomicU64,
130 suppressed_lower: AtomicU64,
134 cooldown_deferred_attempts: AtomicU64,
135 rate_deferred_attempts: AtomicU64,
136 window_deduped: AtomicU64,
137 launched: AtomicU64,
138 passed: AtomicU64,
139 timed_out: AtomicU64,
140 failed: AtomicU64,
141 bootstrap_claims: AtomicU64,
142 idle: AtomicU64,
143 insufficient_keys: AtomicU64,
144 outside_answerability_window: AtomicU64,
145 inflight: AtomicU64,
146}
147
148#[cfg(any(test, feature = "test-utils"))]
154#[derive(Debug, Clone, Copy)]
155pub struct FirstAuditStats {
156 pub received: u64,
158 pub queued: u64,
160 pub self_target_skipped: u64,
162 pub launched: u64,
164 pub passed: u64,
166 pub timed_out: u64,
168 pub failed: u64,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173enum FirstAuditTerminalOutcome {
174 Passed,
175 Timeout,
176 Failed,
177 BootstrapClaim,
178 Idle,
179 InsufficientKeys,
180}
181
182impl FirstAuditTerminalOutcome {
183 #[cfg(any(feature = "logging", test))]
184 const fn as_str(self) -> &'static str {
185 match self {
186 Self::Passed => "passed",
187 Self::Timeout => "timeout",
188 Self::Failed => "failed",
189 Self::BootstrapClaim => "bootstrap_claim",
190 Self::Idle => "idle",
191 Self::InsufficientKeys => "insufficient_keys",
192 }
193 }
194}
195
196fn first_audit_terminal_outcome(result: &AuditTickResult) -> FirstAuditTerminalOutcome {
197 match result {
198 AuditTickResult::Passed { .. } => FirstAuditTerminalOutcome::Passed,
199 AuditTickResult::Failed {
200 evidence:
201 FailureEvidence::AuditFailure {
202 reason: AuditFailureReason::Timeout,
203 ..
204 },
205 ..
206 } => FirstAuditTerminalOutcome::Timeout,
207 AuditTickResult::Failed { .. } => FirstAuditTerminalOutcome::Failed,
208 AuditTickResult::BootstrapClaim { .. } => FirstAuditTerminalOutcome::BootstrapClaim,
209 AuditTickResult::Idle => FirstAuditTerminalOutcome::Idle,
210 AuditTickResult::InsufficientKeys => FirstAuditTerminalOutcome::InsufficientKeys,
211 }
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215enum FirstAuditQueueOutcome {
216 Queued,
218 Coalesced,
221 SuppressedLower,
225 RetainedOnTie,
229 CapacityEvicted { peer: PeerId, pin: [u8; 32] },
232}
233
234fn coalesce_first_audit_event(
250 pending: &mut LruCache<PeerId, MonetizedPinEvent>,
251 incoming: MonetizedPinEvent,
252 incoming_is_newer: bool,
253 rng: &mut StdRng,
254) -> FirstAuditQueueOutcome {
255 if let Some(existing) = pending.peek(&incoming.peer) {
256 if incoming.key_count < existing.key_count {
259 return FirstAuditQueueOutcome::SuppressedLower;
260 }
261 if incoming.key_count == existing.key_count && !incoming_is_newer {
263 return FirstAuditQueueOutcome::RetainedOnTie;
264 }
265 let _ = pending.push(incoming.peer, incoming);
269 return FirstAuditQueueOutcome::Coalesced;
270 }
271 if pending.len() >= pending.cap().get() {
280 let victim = {
281 let idx = rng.gen_range(0..pending.len());
282 pending.iter().nth(idx).map(|(p, _)| *p)
283 };
284 if let Some(victim_peer) = victim {
285 if let Some(evicted) = pending.pop(&victim_peer) {
286 let _ = pending.push(incoming.peer, incoming);
287 return FirstAuditQueueOutcome::CapacityEvicted {
288 peer: victim_peer,
289 pin: evicted.pin,
290 };
291 }
292 }
293 }
294 match pending.push(incoming.peer, incoming) {
295 None => FirstAuditQueueOutcome::Queued,
296 Some((evicted_peer, evicted)) => FirstAuditQueueOutcome::CapacityEvicted {
302 peer: evicted_peer,
303 pin: evicted.pin,
304 },
305 }
306}
307
308const FIRST_AUDIT_SEND_LATENCY_SLACK: Duration = Duration::from_secs(1);
314
315#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318struct RecentFirstAudit {
319 launched_at: Instant,
320 key_count: u32,
321}
322
323struct FirstAuditInflightSlot(Arc<FirstAuditObservability>);
327
328impl FirstAuditInflightSlot {
329 fn acquire(observability: &Arc<FirstAuditObservability>) -> Self {
330 observability.inflight.fetch_add(1, Ordering::Relaxed);
331 Self(Arc::clone(observability))
332 }
333}
334
335impl Drop for FirstAuditInflightSlot {
336 fn drop(&mut self) {
337 self.0.inflight.fetch_sub(1, Ordering::Relaxed);
338 }
339}
340
341const fn first_audit_count_jump(audited_count: u32, new_count: u32) -> bool {
348 (new_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_DEN
349 > (audited_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_NUM
350}
351
352#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354enum LimiterVerdict {
355 Admit,
358 RateDeferred,
361 WindowDeduped,
366}
367
368struct FirstAuditLimiter {
378 tokens: u32,
380 last_refill: Instant,
384 recent: LruCache<PeerId, RecentFirstAudit>,
387}
388
389impl FirstAuditLimiter {
390 fn new(now: Instant) -> Self {
391 Self {
392 tokens: config::FIRST_AUDIT_BUDGET_BURST,
393 last_refill: now,
394 recent: LruCache::new(
395 NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
396 ),
397 }
398 }
399
400 fn window_allows(&self, peer: &PeerId, key_count: u32, now: Instant) -> bool {
405 self.recent.peek(peer).map_or(true, |prev| {
406 now.saturating_duration_since(prev.launched_at)
407 >= config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL
408 || first_audit_count_jump(prev.key_count, key_count)
409 })
410 }
411
412 fn refill(&mut self, now: Instant) {
414 if self.tokens >= config::FIRST_AUDIT_BUDGET_BURST {
415 self.last_refill = now;
418 return;
419 }
420 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
421 let elapsed = now.saturating_duration_since(self.last_refill);
422 let earned = elapsed.as_nanos() / interval.as_nanos().max(1);
423 if earned == 0 {
424 return;
425 }
426 let capacity_gap = u128::from(config::FIRST_AUDIT_BUDGET_BURST - self.tokens);
427 if earned >= capacity_gap {
428 self.tokens = config::FIRST_AUDIT_BUDGET_BURST;
429 self.last_refill = now;
430 } else {
431 self.tokens = self
433 .tokens
434 .saturating_add(u32::try_from(earned).unwrap_or(u32::MAX));
435 let advance = interval.saturating_mul(u32::try_from(earned).unwrap_or(u32::MAX));
436 self.last_refill = self.last_refill.checked_add(advance).unwrap_or(now);
437 }
438 }
439
440 fn assess(
445 &mut self,
446 peer: &PeerId,
447 key_count: u32,
448 now: Instant,
449 inflight: u64,
450 ) -> LimiterVerdict {
451 if !self.window_allows(peer, key_count, now) {
452 return LimiterVerdict::WindowDeduped;
453 }
454 self.refill(now);
455 if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.tokens == 0 {
456 return LimiterVerdict::RateDeferred;
457 }
458 LimiterVerdict::Admit
459 }
460
461 fn reserve_token(&mut self) {
467 self.tokens = self.tokens.saturating_sub(1);
468 }
469
470 fn refund_token(&mut self) {
475 self.tokens = (self.tokens + 1).min(config::FIRST_AUDIT_BUDGET_BURST);
476 }
477
478 fn promote(&mut self, peer: PeerId, key_count: u32, now: Instant) {
482 self.recent.put(
483 peer,
484 RecentFirstAudit {
485 launched_at: now,
486 key_count,
487 },
488 );
489 }
490
491 #[cfg(test)]
496 fn commit_launch(&mut self, peer: PeerId, key_count: u32, now: Instant) {
497 self.reserve_token();
498 self.promote(peer, key_count, now);
499 }
500}
501
502fn quote_answerable_through_nominal_jitter(quote_ts: SystemTime, now: SystemTime) -> bool {
514 let Some(latest_send) = now
515 .checked_add(config::FIRST_AUDIT_LAUNCH_JITTER_MAX)
516 .and_then(|t| t.checked_add(FIRST_AUDIT_SEND_LATENCY_SLACK))
517 else {
518 return false;
519 };
520 quote_within_audit_window(quote_ts, now) && quote_within_audit_window(quote_ts, latest_send)
521}
522
523async fn open_first_audit_reservation(
530 scheduler: &mut FirstAuditScheduler,
531 cooldown: &RwLock<HashMap<PeerId, Instant>>,
532 observability: &Arc<FirstAuditObservability>,
533) {
534 if scheduler.has_reservation() {
535 return;
536 }
537 let jitter = Duration::from_millis(rand::thread_rng().gen_range(
538 0..=u64::try_from(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_millis()).unwrap_or(u64::MAX),
539 ));
540 let inflight = observability.inflight.load(Ordering::Relaxed);
541 let reserved = {
542 let cooldown = cooldown.read().await;
543 scheduler.try_reserve(Instant::now(), inflight, jitter, &cooldown, observability)
544 };
545 if reserved {
546 if let Some(peer) = scheduler.reserved_peer() {
547 debug!(
548 "First-audit scheduler: audit_trigger=first_monetized outcome=reserved peer={peer} pending={}",
549 scheduler.pending_len()
550 );
551 }
552 }
553}
554
555fn first_audit_far_future() -> Instant {
560 Instant::now()
561 .checked_add(Duration::from_secs(3600))
562 .unwrap_or_else(Instant::now)
563}
564
565struct FirstAuditReservation {
571 event: MonetizedPinEvent,
572 ready_at: Instant,
573 inflight: FirstAuditInflightSlot,
574}
575
576struct FirstAuditScheduler {
583 first_audited: LruCache<[u8; 32], ()>,
587 pending: LruCache<PeerId, MonetizedPinEvent>,
596 limiter: FirstAuditLimiter,
598 reserved: Option<FirstAuditReservation>,
602 oldest_first_lane: bool,
604 self_peer: PeerId,
614 rng: StdRng,
618}
619
620impl FirstAuditScheduler {
621 fn new(now: Instant, self_peer: PeerId) -> Self {
622 let dedup_cap = NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN);
623 let pending_cap = NonZeroUsize::new(FIRST_AUDIT_PENDING_CAP).unwrap_or(NonZeroUsize::MIN);
624 Self {
625 first_audited: LruCache::new(dedup_cap),
626 pending: LruCache::new(pending_cap),
627 limiter: FirstAuditLimiter::new(now),
628 reserved: None,
629 oldest_first_lane: false,
630 self_peer,
631 rng: StdRng::from_entropy(),
632 }
633 }
634
635 #[cfg_attr(not(feature = "logging"), allow(dead_code))]
639 fn pending_len(&self) -> usize {
640 self.pending.len()
641 }
642
643 #[cfg_attr(not(feature = "logging"), allow(dead_code))]
645 fn tokens(&self) -> u32 {
646 self.limiter.tokens
647 }
648
649 #[cfg_attr(not(feature = "logging"), allow(dead_code))]
657 fn oldest_pending_quote_age_ms(&self, now: SystemTime) -> u64 {
658 self.pending
659 .iter()
660 .map(|(_, e)| e.quote_ts)
661 .min()
662 .and_then(|oldest| now.duration_since(oldest).ok())
663 .map_or(0, |age| u64::try_from(age.as_millis()).unwrap_or(u64::MAX))
664 }
665
666 fn sweep_expired(&mut self, wall_now: SystemTime, obs: &Arc<FirstAuditObservability>) -> usize {
675 let expired: Vec<PeerId> = self
676 .pending
677 .iter()
678 .filter(|(_, event)| !quote_answerable_through_nominal_jitter(event.quote_ts, wall_now))
679 .map(|(peer, _)| *peer)
680 .collect();
681 for peer in &expired {
682 self.pending.pop(peer);
683 }
684 if !expired.is_empty() {
685 obs.outside_answerability_window.fetch_add(
686 u64::try_from(expired.len()).unwrap_or(u64::MAX),
687 Ordering::Relaxed,
688 );
689 }
690 expired.len()
691 }
692
693 fn has_reservation(&self) -> bool {
694 self.reserved.is_some()
695 }
696
697 fn would_displace(&self, event: &MonetizedPinEvent) -> bool {
704 self.pending.len() >= self.pending.cap().get() && self.pending.peek(&event.peer).is_none()
705 }
706
707 fn reserved_ready_at(&self) -> Option<Instant> {
709 self.reserved.as_ref().map(|r| r.ready_at)
710 }
711
712 fn reserved_peer(&self) -> Option<PeerId> {
714 self.reserved.as_ref().map(|r| r.event.peer)
715 }
716
717 fn enqueue(&mut self, event: MonetizedPinEvent, obs: &Arc<FirstAuditObservability>) {
734 if event.peer == self.self_peer {
735 obs.self_target_skipped.fetch_add(1, Ordering::Relaxed);
736 return;
737 }
738 if self.first_audited.contains(&event.pin) {
739 obs.duplicates.fetch_add(1, Ordering::Relaxed);
740 return;
741 }
742 let reserved_peer = self.reserved_peer();
743 let is_reserved_peer = reserved_peer == Some(event.peer);
744 if !is_reserved_peer
745 && !self
746 .limiter
747 .window_allows(&event.peer, event.key_count, Instant::now())
748 {
749 obs.window_deduped.fetch_add(1, Ordering::Relaxed);
750 return;
751 }
752 let stale_incumbent = self.pending.peek(&event.peer).is_some_and(|existing| {
758 !quote_answerable_through_nominal_jitter(existing.quote_ts, SystemTime::now())
759 });
760 if stale_incumbent {
761 self.pending.pop(&event.peer);
762 obs.outside_answerability_window
763 .fetch_add(1, Ordering::Relaxed);
764 }
765 match coalesce_first_audit_event(&mut self.pending, event, true, &mut self.rng) {
768 FirstAuditQueueOutcome::Queued => {
769 obs.queued.fetch_add(1, Ordering::Relaxed);
770 }
771 FirstAuditQueueOutcome::Coalesced | FirstAuditQueueOutcome::RetainedOnTie => {
772 obs.coalesced.fetch_add(1, Ordering::Relaxed);
773 }
774 FirstAuditQueueOutcome::SuppressedLower => {
775 obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
776 }
777 FirstAuditQueueOutcome::CapacityEvicted { .. } => {
778 obs.queued.fetch_add(1, Ordering::Relaxed);
779 obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
780 }
781 }
782 }
783
784 fn try_reserve(
792 &mut self,
793 mono_now: Instant,
794 inflight: u64,
795 jitter: Duration,
796 cooldown: &HashMap<PeerId, Instant>,
797 obs: &Arc<FirstAuditObservability>,
798 ) -> bool {
799 if self.reserved.is_some() || self.pending.is_empty() {
800 return false;
801 }
802 self.limiter.refill(mono_now);
803 if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.limiter.tokens == 0 {
804 obs.rate_deferred_attempts.fetch_add(1, Ordering::Relaxed);
805 return false;
806 }
807 let mut ordered: Vec<(usize, PeerId, MonetizedPinEvent)> = self
810 .pending
811 .iter()
812 .enumerate()
813 .map(|(i, (p, e))| (i, *p, *e))
814 .collect();
815 self.pending.clear();
816 if self.oldest_first_lane {
817 ordered.reverse();
818 }
819 let mut chosen: Option<MonetizedPinEvent> = None;
820 let mut kept: Vec<(usize, PeerId, MonetizedPinEvent)> = Vec::new();
821 for (idx, peer, event) in ordered {
822 if chosen.is_some() {
823 kept.push((idx, peer, event));
824 continue;
825 }
826 if self.first_audited.contains(&event.pin) {
827 obs.duplicates.fetch_add(1, Ordering::Relaxed);
828 continue; }
830 if !quote_answerable_through_nominal_jitter(event.quote_ts, SystemTime::now()) {
831 obs.outside_answerability_window
832 .fetch_add(1, Ordering::Relaxed);
833 continue; }
835 match self
840 .limiter
841 .assess(&peer, event.key_count, mono_now, inflight)
842 {
843 LimiterVerdict::WindowDeduped => {
844 obs.window_deduped.fetch_add(1, Ordering::Relaxed);
845 continue; }
847 LimiterVerdict::RateDeferred => {
848 kept.push((idx, peer, event));
849 continue; }
851 LimiterVerdict::Admit => {}
852 }
853 if !cooldown_would_allow(cooldown, &peer, mono_now) {
854 obs.cooldown_deferred_attempts
855 .fetch_add(1, Ordering::Relaxed);
856 kept.push((idx, peer, event));
857 continue; }
859 chosen = Some(event);
860 }
861 kept.sort_unstable_by_key(|(idx, _, _)| std::cmp::Reverse(*idx));
863 for (_, peer, event) in kept {
864 self.pending.put(peer, event);
865 }
866 let Some(event) = chosen else {
867 return false;
868 };
869 self.limiter.reserve_token();
870 let inflight_slot = FirstAuditInflightSlot::acquire(obs);
871 let ready_at = mono_now.checked_add(jitter).unwrap_or(mono_now);
872 self.reserved = Some(FirstAuditReservation {
873 event,
874 ready_at,
875 inflight: inflight_slot,
876 });
877 true
878 }
879
880 fn take_due_reservation(&mut self, mono_now: Instant) -> Option<FirstAuditReservation> {
882 if self
883 .reserved
884 .as_ref()
885 .is_some_and(|r| mono_now >= r.ready_at)
886 {
887 self.reserved.take()
888 } else {
889 None
890 }
891 }
892
893 fn resolve(
910 &mut self,
911 reservation: FirstAuditReservation,
912 wall_now: SystemTime,
913 mono_now: Instant,
914 cooldown: &mut HashMap<PeerId, Instant>,
915 obs: &Arc<FirstAuditObservability>,
916 ) -> Option<(MonetizedPinEvent, FirstAuditInflightSlot)> {
917 let FirstAuditReservation {
918 event, inflight, ..
919 } = reservation;
920 if !quote_within_audit_window(event.quote_ts, wall_now) {
922 self.limiter.refund_token();
923 obs.outside_answerability_window
924 .fetch_add(1, Ordering::Relaxed);
925 drop(inflight);
926 return None; }
928 if !cooldown_allows_audit(cooldown, &event.peer, mono_now) {
935 self.limiter.refund_token();
936 obs.cooldown_deferred_attempts
937 .fetch_add(1, Ordering::Relaxed);
938 drop(inflight);
939 match coalesce_first_audit_event(&mut self.pending, event, false, &mut self.rng) {
944 FirstAuditQueueOutcome::CapacityEvicted { .. } => {
945 obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
946 }
947 FirstAuditQueueOutcome::SuppressedLower => {
948 obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
949 }
950 FirstAuditQueueOutcome::Queued
951 | FirstAuditQueueOutcome::Coalesced
952 | FirstAuditQueueOutcome::RetainedOnTie => {}
953 }
954 return None;
955 }
956 self.limiter.promote(event.peer, event.key_count, mono_now);
958 self.first_audited.put(event.pin, ());
959 self.oldest_first_lane = !self.oldest_first_lane;
960 obs.launched.fetch_add(1, Ordering::Relaxed);
961 Some((event, inflight))
962 }
963}
964
965const RR_PREFIX: &str = "/rr/";
971
972const INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY: usize = 64;
991
992const FRESH_OFFER_WORKER_LIMIT: usize = 4;
999
1000const FRESH_OFFER_MAX_OUTSTANDING: usize = 16;
1013
1014const MAX_FRESH_OFFER_ATTEMPTS_PER_KEY: usize = crate::ant_protocol::CLOSE_GROUP_MAJORITY;
1036
1037const FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES: usize = 4;
1043
1044#[allow(clippy::cast_possible_truncation)]
1070const FRESH_OFFER_MAX_OUTSTANDING_PER_PEER: u32 =
1071 (FRESH_OFFER_MAX_OUTSTANDING - FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES) as u32;
1072
1073const PAID_NOTIFY_WORKER_LIMIT: usize = 2;
1080
1081const PAID_NOTIFY_MAX_OUTSTANDING: usize = 64;
1098
1099const PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER: u32 = 16;
1106
1107const FETCH_RESPONDER_WORKER_LIMIT: usize = 3;
1113
1114const FETCH_RESPONDER_MAX_OUTSTANDING: usize = FETCH_RESPONDER_WORKER_LIMIT * 4;
1120
1121const FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 2;
1126
1127const VERIFICATION_RESPONDER_WORKER_LIMIT: usize = 2;
1133
1134const VERIFICATION_RESPONDER_MAX_OUTSTANDING: usize = VERIFICATION_RESPONDER_WORKER_LIMIT * 4;
1140
1141const VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1147
1148const NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT: usize = 2;
1154
1155const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING: usize = NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT * 4;
1160
1161const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1166
1167fn match_replication_protocol(topic: &str) -> Option<(&'static str, bool)> {
1174 for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
1175 if topic == id {
1176 return Some((id, false));
1177 }
1178 if let Some(rest) = topic.strip_prefix(RR_PREFIX) {
1179 if rest == id {
1180 return Some((id, true));
1181 }
1182 }
1183 }
1184 None
1185}
1186
1187fn body_matches_protocol(body: &ReplicationMessageBody, protocol: &str) -> bool {
1195 protocol == response_protocol_for(body)
1196}
1197
1198fn response_protocol_for(body: &ReplicationMessageBody) -> &'static str {
1204 if body.is_subtree_audit() {
1205 SUBTREE_AUDIT_PROTOCOL_ID
1206 } else {
1207 REPLICATION_PROTOCOL_ID
1208 }
1209}
1210
1211fn fresh_offer_payment_context() -> VerificationContext {
1212 VerificationContext::FreshReplication
1213}
1214
1215fn paid_notify_payment_context() -> VerificationContext {
1216 VerificationContext::PaidListAdmission
1217}
1218
1219type FetchFuture = Pin<Box<dyn Future<Output = (XorName, Option<FetchOutcome>)> + Send>>;
1221
1222type FreshOfferInFlight = Arc<Mutex<HashMap<XorName, FreshOfferEntry>>>;
1251
1252struct FreshOfferAttempt {
1257 source: PeerId,
1258 proof_of_payment: Vec<u8>,
1259 request_id: u64,
1260 rr_message_id: Option<String>,
1261}
1262
1263struct FreshOfferEntry {
1268 pending: VecDeque<FreshOfferAttempt>,
1270 sources: HashSet<PeerId>,
1272 admitted: usize,
1281}
1282
1283enum FreshOfferAdmission {
1285 Opened(Box<FreshOfferEntryGuard>),
1288 Joined,
1291 Full,
1293 DuplicateSource,
1295}
1296
1297#[cfg(feature = "logging")]
1300impl FreshOfferAdmission {
1301 const fn surplus_reason(&self) -> &'static str {
1306 match self {
1307 Self::DuplicateSource => "this source already has a proof queued",
1308 Self::Full => "the key already holds its full complement of proofs",
1309 Self::Opened(_) | Self::Joined => "not surplus",
1310 }
1311 }
1312}
1313
1314struct FreshOfferEntryGuard {
1320 in_flight: FreshOfferInFlight,
1321 key: XorName,
1322 data: Vec<u8>,
1324 received_at: Instant,
1326 holds_entry: bool,
1329}
1330
1331impl FreshOfferEntryGuard {
1332 fn admit(
1339 in_flight: &FreshOfferInFlight,
1340 offer: protocol::FreshReplicationOffer,
1341 source: PeerId,
1342 request_id: u64,
1343 rr_message_id: Option<String>,
1344 received_at: Instant,
1345 ) -> FreshOfferAdmission {
1346 let key = offer.key;
1347 let attempt = FreshOfferAttempt {
1348 source,
1349 proof_of_payment: offer.proof_of_payment,
1350 request_id,
1351 rr_message_id,
1352 };
1353
1354 let mut in_flight_map = in_flight.lock();
1355 if let Some(entry) = in_flight_map.get_mut(&key) {
1356 if entry.sources.contains(&source) {
1357 return FreshOfferAdmission::DuplicateSource;
1358 }
1359 if entry.admitted >= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
1362 return FreshOfferAdmission::Full;
1363 }
1364 entry.admitted = entry.admitted.saturating_add(1);
1365 entry.sources.insert(source);
1366 entry.pending.push_back(attempt);
1367 return FreshOfferAdmission::Joined;
1368 }
1369
1370 let mut sources = HashSet::new();
1371 sources.insert(source);
1372 let mut pending = VecDeque::new();
1373 pending.push_back(attempt);
1374 in_flight_map.insert(
1375 key,
1376 FreshOfferEntry {
1377 pending,
1378 sources,
1379 admitted: 1,
1380 },
1381 );
1382 drop(in_flight_map);
1383 FreshOfferAdmission::Opened(Box::new(Self {
1384 in_flight: Arc::clone(in_flight),
1385 key,
1386 data: offer.data,
1387 received_at,
1388 holds_entry: true,
1389 }))
1390 }
1391
1392 fn data(&self) -> &[u8] {
1394 &self.data
1395 }
1396
1397 fn received_at(&self) -> Instant {
1399 self.received_at
1400 }
1401
1402 fn next_attempt(&mut self) -> Option<FreshOfferAttempt> {
1408 let mut in_flight = self.in_flight.lock();
1409 let Some(entry) = in_flight.get_mut(&self.key) else {
1410 self.holds_entry = false;
1411 return None;
1412 };
1413 if let Some(attempt) = entry.pending.pop_front() {
1414 return Some(attempt);
1415 }
1416 in_flight.remove(&self.key);
1417 self.holds_entry = false;
1418 None
1419 }
1420
1421 fn release(&mut self) -> Vec<FreshOfferAttempt> {
1424 let mut in_flight = self.in_flight.lock();
1425 self.holds_entry = false;
1426 in_flight
1427 .remove(&self.key)
1428 .map(|entry| entry.pending.into_iter().collect())
1429 .unwrap_or_default()
1430 }
1431}
1432
1433impl Drop for FreshOfferEntryGuard {
1434 fn drop(&mut self) {
1435 if self.holds_entry {
1436 self.in_flight.lock().remove(&self.key);
1437 }
1438 }
1439}
1440
1441struct VerificationCycleContext<'a> {
1443 p2p_node: &'a Arc<P2PNode>,
1444 paid_list: &'a Arc<PaidList>,
1445 storage: &'a Arc<LmdbStorage>,
1446 queues: &'a Arc<RwLock<ReplicationQueues>>,
1447 config: &'a ReplicationConfig,
1448 bootstrap_state: &'a Arc<RwLock<BootstrapState>>,
1449 is_bootstrapping: &'a Arc<RwLock<bool>>,
1450 bootstrap_complete_notify: &'a Arc<Notify>,
1451 last_commitment_by_peer: &'a Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1456 ever_capable_peers: &'a Arc<RwLock<HashSet<PeerId>>>,
1457 recent_provers: &'a Arc<RwLock<RecentProvers>>,
1458}
1459
1460const FETCH_WORKER_POLL_MS: u64 = 100;
1462
1463const VERIFICATION_WORKER_POLL_MS: u64 = 250;
1465
1466const VERIFICATION_CYCLE_SLOW_LOG_MS: u128 = 500;
1468
1469const REPLICATION_TRUST_WEIGHT: f64 = 1.0;
1475const MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE: usize = 3;
1479
1480const BOOTSTRAP_DRAIN_CHECK_SECS: u64 = 5;
1482
1483const SHUTDOWN_TASK_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
1490
1491const COMMITMENT_ROTATION_INTERVAL_SECS: u64 = 3600;
1515
1516const RETENTION_PERSIST_INTERVAL_SECS: u64 = 30;
1521
1522const TRAFFIC_SUMMARY_INTERVAL_SECS: u64 = 300;
1526
1527#[cfg(feature = "logging")]
1530const BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS: u64 = 60;
1531
1532const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_secs(30 * 60);
1545
1546fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
1553 let too_future = quote_ts
1554 .duration_since(now)
1555 .is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
1556 let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
1557 let too_old = now
1558 .duration_since(quote_ts)
1559 .is_ok_and(|age| age >= audit_cutoff);
1560 !(too_future || too_old)
1561}
1562
1563const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_secs(60);
1572
1573const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
1587
1588#[allow(clippy::cast_possible_truncation)] const FIRST_AUDIT_PENDING_CAP: usize = {
1616 let strict_horizon_secs = GOSSIP_ANSWERABILITY_TTL
1617 .as_secs()
1618 .saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN.as_secs())
1619 .saturating_sub(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_secs())
1620 .saturating_sub(FIRST_AUDIT_SEND_LATENCY_SLACK.as_secs());
1621 let refills =
1626 strict_horizon_secs.saturating_sub(1) / config::FIRST_AUDIT_LAUNCH_INTERVAL.as_secs();
1627 (refills + config::FIRST_AUDIT_BUDGET_BURST as u64) as usize
1628};
1629
1630const _: () = {
1633 assert!(FIRST_AUDIT_PENDING_CAP >= 1);
1634 assert!(FIRST_AUDIT_PENDING_CAP < MAX_LAST_COMMITMENT_BY_PEER);
1635};
1636
1637const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
1646
1647pub struct ReplicationEngine {
1653 config: Arc<ReplicationConfig>,
1655 p2p_node: Arc<P2PNode>,
1657 storage: Arc<LmdbStorage>,
1659 paid_list: Arc<PaidList>,
1661 payment_verifier: Arc<PaymentVerifier>,
1663 queues: Arc<RwLock<ReplicationQueues>>,
1665 sync_state: Arc<RwLock<NeighborSyncState>>,
1667 sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
1673 audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
1679 gossip_lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1684 sync_cycle_epoch: Arc<RwLock<u64>>,
1686 repair_proofs: Arc<RwLock<RepairProofs>>,
1688 bootstrap_state: Arc<RwLock<BootstrapState>>,
1690 is_bootstrapping: Arc<RwLock<bool>>,
1692 sync_trigger: Arc<Notify>,
1694 bootstrap_complete_notify: Arc<Notify>,
1696 identity: Arc<NodeIdentity>,
1701 commitment_state: Arc<ResponderCommitmentState>,
1707 retention_path: PathBuf,
1713 last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1724 ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
1734 recent_provers: Arc<RwLock<RecentProvers>>,
1739 sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1746 send_semaphore: Arc<Semaphore>,
1749 audit_responder_semaphore: Arc<Semaphore>,
1757 audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1765 audit_responder_metrics: Arc<AuditResponderMetrics>,
1768 audit_challenge_coordinator: Arc<AuditChallengeCoordinator>,
1774 fetch_responder_worker_semaphore: Arc<Semaphore>,
1776 fetch_responder_admission_semaphore: Arc<Semaphore>,
1778 fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1780 verification_responder_worker_semaphore: Arc<Semaphore>,
1782 verification_responder_admission_semaphore: Arc<Semaphore>,
1784 verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1786 neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
1788 neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
1790 neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1792 fresh_offer_worker_semaphore: Arc<Semaphore>,
1794 fresh_offer_admission_semaphore: Arc<Semaphore>,
1796 fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1799 fresh_offer_in_flight: FreshOfferInFlight,
1802 paid_notify_worker_semaphore: Arc<Semaphore>,
1804 paid_notify_admission_semaphore: Arc<Semaphore>,
1806 paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1808 subtree_round1: SubtreeRound1Limiter,
1813 fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
1818 possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
1822 possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
1824 monetized_pin_tx: mpsc::Sender<MonetizedPinEvent>,
1832 monetized_pin_rx: Option<mpsc::Receiver<MonetizedPinEvent>>,
1835 first_audit_observability: Arc<FirstAuditObservability>,
1839 shutdown: CancellationToken,
1841 task_handles: Vec<JoinHandle<()>>,
1843 detached_task_tracker: TaskTracker,
1850}
1851
1852impl ReplicationEngine {
1853 #[allow(clippy::too_many_arguments)]
1860 pub async fn new(
1861 config: ReplicationConfig,
1862 p2p_node: Arc<P2PNode>,
1863 storage: Arc<LmdbStorage>,
1864 payment_verifier: Arc<PaymentVerifier>,
1865 identity: Arc<NodeIdentity>,
1866 root_dir: &Path,
1867 fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
1868 shutdown: CancellationToken,
1869 ) -> Result<Self> {
1870 config.validate().map_err(Error::Config)?;
1871
1872 let paid_list = Arc::new(
1873 PaidList::new(root_dir)
1874 .await
1875 .map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
1876 );
1877
1878 let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
1879 let config = Arc::new(config);
1880 let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
1881
1882 let (monetized_pin_tx, monetized_pin_rx) =
1887 mpsc::channel(config::FIRST_AUDIT_INGRESS_CAPACITY);
1888
1889 let engine = Self {
1890 config: Arc::clone(&config),
1891 p2p_node,
1892 storage,
1893 paid_list,
1894 payment_verifier,
1895 queues: Arc::new(RwLock::new(ReplicationQueues::new())),
1896 sync_state: Arc::new(RwLock::new(initial_neighbors)),
1897 sync_history: Arc::new(RwLock::new(HashMap::new())),
1898 audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
1899 gossip_lottery_attempts: Arc::new(RwLock::new(HashMap::new())),
1900 sync_cycle_epoch: Arc::new(RwLock::new(0)),
1901 repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
1902 bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
1903 is_bootstrapping: Arc::new(RwLock::new(true)),
1904 sync_trigger: Arc::new(Notify::new()),
1905 bootstrap_complete_notify: Arc::new(Notify::new()),
1906 identity,
1907 commitment_state: Arc::new(ResponderCommitmentState::new()),
1908 retention_path: root_dir.join("commitment_retention.bin"),
1909 last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
1910 ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
1911 recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
1912 sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
1913 send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
1914 audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
1915 audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1916 audit_responder_metrics: Arc::new(AuditResponderMetrics::default()),
1917 audit_challenge_coordinator: Arc::new(AuditChallengeCoordinator::new()),
1918 fetch_responder_worker_semaphore: Arc::new(Semaphore::new(
1919 FETCH_RESPONDER_WORKER_LIMIT,
1920 )),
1921 fetch_responder_admission_semaphore: Arc::new(Semaphore::new(
1922 FETCH_RESPONDER_MAX_OUTSTANDING,
1923 )),
1924 fetch_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1925 verification_responder_worker_semaphore: Arc::new(Semaphore::new(
1926 VERIFICATION_RESPONDER_WORKER_LIMIT,
1927 )),
1928 verification_responder_admission_semaphore: Arc::new(Semaphore::new(
1929 VERIFICATION_RESPONDER_MAX_OUTSTANDING,
1930 )),
1931 verification_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1932 neighbor_sync_responder_worker_semaphore: Arc::new(Semaphore::new(
1933 NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT,
1934 )),
1935 neighbor_sync_responder_admission_semaphore: Arc::new(Semaphore::new(
1936 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
1937 )),
1938 neighbor_sync_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1939 fresh_offer_worker_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_WORKER_LIMIT)),
1940 fresh_offer_admission_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING)),
1941 fresh_offer_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1942 fresh_offer_in_flight: Arc::new(Mutex::new(HashMap::new())),
1943 paid_notify_worker_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_WORKER_LIMIT)),
1944 paid_notify_admission_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING)),
1945 paid_notify_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1946 subtree_round1: SubtreeRound1Limiter::new(
1947 config.subtree_round1_responder_cooldown,
1948 config.subtree_round1_max_concurrent,
1949 ),
1950 fresh_write_rx: Some(fresh_write_rx),
1951 possession_check_tx,
1952 possession_check_rx: Some(possession_check_rx),
1953 monetized_pin_tx,
1954 monetized_pin_rx: Some(monetized_pin_rx),
1955 first_audit_observability: Arc::new(FirstAuditObservability::default()),
1956 shutdown,
1957 task_handles: Vec::new(),
1958 detached_task_tracker: TaskTracker::new(),
1959 };
1960 load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
1965 Ok(engine)
1966 }
1967
1968 #[must_use]
1973 pub fn monetized_pin_sender(&self) -> mpsc::Sender<MonetizedPinEvent> {
1974 self.monetized_pin_tx.clone()
1975 }
1976
1977 #[must_use]
1979 pub fn paid_list(&self) -> &Arc<PaidList> {
1980 &self.paid_list
1981 }
1982
1983 #[must_use]
1987 pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
1988 &self.commitment_state
1989 }
1990
1991 #[must_use]
1993 pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
1994 &self.last_commitment_by_peer
1995 }
1996
1997 #[must_use]
2000 pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
2001 &self.recent_provers
2002 }
2003
2004 #[cfg(any(test, feature = "test-utils"))]
2013 pub async fn rebuild_commitment_now(&self) -> Result<()> {
2014 rebuild_and_rotate_commitment(
2015 &self.storage,
2016 &self.identity,
2017 &self.commitment_state,
2018 &self.p2p_node,
2019 &self.config,
2020 )
2021 .await
2022 }
2023
2024 #[cfg(any(feature = "test-utils", test))]
2029 pub async fn inject_peer_commitment_for_test(
2030 &self,
2031 peer: &PeerId,
2032 commitment: StorageCommitment,
2033 ) {
2034 let now = Instant::now();
2035 self.last_commitment_by_peer
2036 .write()
2037 .await
2038 .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
2039 self.ever_capable_peers.write().await.insert(*peer);
2040 }
2041
2042 #[cfg(any(test, feature = "test-utils"))]
2047 pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
2048 let now = Instant::now();
2049 let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
2050 let mut launched = self.audit_on_gossip_cooldown.write().await;
2051 lottery_attempts.insert(*peer, now);
2052 launched.remove(peer);
2053 }
2054
2055 #[cfg(any(test, feature = "test-utils"))]
2063 pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
2064 let target = {
2065 let map = self.last_commitment_by_peer.read().await;
2066 map.get(peer)
2067 .and_then(PeerCommitmentRecord::last_commitment)
2068 .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
2069 };
2070 let Some((pin, key_count)) = target else {
2071 return audit::AuditTickResult::Idle;
2072 };
2073 let credit = storage_commitment_audit::AuditCredit {
2074 recent_provers: &self.recent_provers,
2075 };
2076 storage_commitment_audit::run_subtree_audit(
2077 &self.p2p_node,
2078 &self.config,
2079 peer,
2080 pin,
2081 key_count,
2082 Some(&credit),
2083 )
2084 .await
2085 }
2086
2087 #[cfg(any(test, feature = "test-utils"))]
2091 #[must_use]
2092 pub fn first_audit_stats(&self) -> FirstAuditStats {
2093 let o = &self.first_audit_observability;
2094 FirstAuditStats {
2095 received: o.received.load(Ordering::Relaxed),
2096 queued: o.queued.load(Ordering::Relaxed),
2097 self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
2098 launched: o.launched.load(Ordering::Relaxed),
2099 passed: o.passed.load(Ordering::Relaxed),
2100 timed_out: o.timed_out.load(Ordering::Relaxed),
2101 failed: o.failed.load(Ordering::Relaxed),
2102 }
2103 }
2104
2105 #[cfg(any(test, feature = "test-utils"))]
2112 pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
2113 possession::run_possession_check(
2114 key,
2115 peers,
2116 &self.p2p_node,
2117 &self.storage,
2118 &self.config,
2119 &self.sync_state,
2120 &self.audit_challenge_coordinator,
2121 &self.shutdown,
2122 )
2123 .await;
2124 }
2125
2126 #[cfg(any(test, feature = "test-utils"))]
2137 pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
2138 let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
2139 self.queues
2140 .write()
2141 .await
2142 .enqueue_fetch(key, distance, sources)
2143 }
2144
2145 #[cfg(any(test, feature = "test-utils"))]
2148 pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
2149 self.queues.read().await.contains_key(key)
2150 }
2151
2152 pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
2158 if !self.task_handles.is_empty() {
2159 error!("ReplicationEngine::start() called while already running — ignoring");
2160 return;
2161 }
2162 info!("Starting replication engine");
2163
2164 self.start_message_handler();
2165 self.start_neighbor_sync_loop();
2166 self.start_self_lookup_loop();
2167 self.start_audit_loop();
2170 self.start_commitment_rotation_loop();
2173 self.start_retention_persist_loop();
2174 self.start_fetch_worker();
2175 self.start_verification_worker();
2176 self.start_bootstrap_sync(dht_events);
2177 self.start_fresh_write_drainer();
2178 self.start_possession_check_scheduler();
2179 self.start_first_audit_drainer();
2182 self.start_traffic_summary_loop();
2184 #[cfg(feature = "logging")]
2186 self.start_bootstrap_state_snapshot_loop();
2187 #[cfg(feature = "logging")]
2188 self.start_audit_responder_summary_loop();
2189
2190 info!(
2191 "Replication engine started with {} background tasks",
2192 self.task_handles.len()
2193 );
2194 }
2195
2196 pub async fn is_bootstrapping(&self) -> bool {
2201 *self.is_bootstrapping.read().await
2202 }
2203
2204 pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
2213 let notified = self.bootstrap_complete_notify.notified();
2216 tokio::pin!(notified);
2217 notified.as_mut().enable();
2218
2219 if !*self.is_bootstrapping.read().await {
2220 return true;
2221 }
2222
2223 tokio::time::timeout(timeout, notified).await.is_ok()
2224 }
2225
2226 pub async fn shutdown(&mut self) {
2240 self.shutdown.cancel();
2241 for (i, mut handle) in self.task_handles.drain(..).enumerate() {
2242 match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
2243 Ok(Ok(())) => {}
2244 Ok(Err(e)) if e.is_cancelled() => {}
2245 Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
2246 Err(_) => {
2247 warn!(
2248 "Replication task {i} did not stop within {}s, aborting",
2249 SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
2250 );
2251 handle.abort();
2252 match handle.await {
2256 Ok(()) => {}
2257 Err(e) if e.is_cancelled() => {}
2258 Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
2259 }
2260 }
2261 }
2262 }
2263
2264 self.fresh_offer_worker_semaphore.close();
2270 self.paid_notify_worker_semaphore.close();
2271 self.fetch_responder_worker_semaphore.close();
2272 self.verification_responder_worker_semaphore.close();
2273 self.neighbor_sync_responder_worker_semaphore.close();
2274
2275 self.detached_task_tracker.close();
2288 self.detached_task_tracker.wait().await;
2289
2290 self.storage.wait_idle().await;
2298 self.paid_list.wait_idle().await;
2299 }
2300
2301 pub fn trigger_neighbor_sync(&self) {
2307 self.sync_trigger.notify_one();
2308 }
2309
2310 pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
2316 let peers = fresh::replicate_fresh(
2317 key,
2318 data,
2319 proof_of_payment,
2320 &self.p2p_node,
2321 &self.paid_list,
2322 &self.config,
2323 &self.send_semaphore,
2324 )
2325 .await;
2326 if !peers.is_empty() {
2327 let _ = self
2328 .possession_check_tx
2329 .send(possession::PossessionCheckEvent { key: *key, peers });
2330 }
2331 }
2332
2333 fn start_fresh_write_drainer(&mut self) {
2340 let Some(mut rx) = self.fresh_write_rx.take() else {
2341 return;
2342 };
2343 let p2p = Arc::clone(&self.p2p_node);
2344 let paid_list = Arc::clone(&self.paid_list);
2345 let config = Arc::clone(&self.config);
2346 let send_semaphore = Arc::clone(&self.send_semaphore);
2347 let possession_tx = self.possession_check_tx.clone();
2348 let shutdown = self.shutdown.clone();
2349
2350 let handle = tokio::spawn(async move {
2351 loop {
2352 tokio::select! {
2353 () = shutdown.cancelled() => break,
2354 event = rx.recv() => {
2355 let Some(event) = event else { break };
2356 let peers = fresh::replicate_fresh(
2357 &event.key,
2358 &event.data,
2359 &event.payment_proof,
2360 &p2p,
2361 &paid_list,
2362 &config,
2363 &send_semaphore,
2364 )
2365 .await;
2366 if !peers.is_empty() {
2370 let _ = possession_tx.send(possession::PossessionCheckEvent {
2371 key: event.key,
2372 peers,
2373 });
2374 }
2375 }
2376 }
2377 }
2378 debug!("Fresh-write drainer shut down");
2379 });
2380 self.task_handles.push(handle);
2381 }
2382
2383 fn start_possession_check_scheduler(&mut self) {
2390 let Some(mut rx) = self.possession_check_rx.take() else {
2391 return;
2392 };
2393 let p2p = Arc::clone(&self.p2p_node);
2394 let storage = Arc::clone(&self.storage);
2395 let config = Arc::clone(&self.config);
2396 let sync_state = Arc::clone(&self.sync_state);
2397 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
2398 let shutdown = self.shutdown.clone();
2399 let detached_task_tracker = self.detached_task_tracker.clone();
2400
2401 let handle = tokio::spawn(async move {
2402 loop {
2403 tokio::select! {
2404 () = shutdown.cancelled() => break,
2405 event = rx.recv() => {
2406 let Some(event) = event else { break };
2407 let p2p = Arc::clone(&p2p);
2411 let storage = Arc::clone(&storage);
2412 let config = Arc::clone(&config);
2413 let sync_state = Arc::clone(&sync_state);
2414 let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
2415 let shutdown = shutdown.clone();
2416 let delay_min = config.possession_check_delay_min;
2417 let delay_max = config.possession_check_delay_max;
2418 detached_task_tracker.spawn(async move {
2419 let delay = possession::random_delay(delay_min, delay_max);
2420 tokio::select! {
2436 () = shutdown.cancelled() => {}
2437 () = async {
2438 tokio::time::sleep(delay).await;
2439 possession::run_possession_check(
2440 event.key,
2441 event.peers,
2442 &p2p,
2443 &storage,
2444 &config,
2445 &sync_state,
2446 &audit_challenge_coordinator,
2447 &shutdown,
2448 )
2449 .await;
2450 } => {}
2451 }
2452 });
2453 }
2454 }
2455 }
2456 debug!("Possession-check scheduler shut down");
2457 });
2458 self.task_handles.push(handle);
2459 }
2460
2461 #[allow(clippy::too_many_lines)]
2470 fn start_first_audit_drainer(&mut self) {
2471 let Some(mut rx) = self.monetized_pin_rx.take() else {
2472 return;
2473 };
2474 let gossip_audit = GossipAuditTrigger {
2475 p2p_node: Arc::clone(&self.p2p_node),
2476 config: Arc::clone(&self.config),
2477 recent_provers: Arc::clone(&self.recent_provers),
2478 sync_state: Arc::clone(&self.sync_state),
2479 cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2480 detached_task_tracker: self.detached_task_tracker.clone(),
2481 lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2482 };
2483 let shutdown = self.shutdown.clone();
2484 let observability = Arc::clone(&self.first_audit_observability);
2485 let self_peer = *self.p2p_node.peer_id();
2486
2487 let handle = tokio::spawn(async move {
2488 let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
2494 let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
2497 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2498 let mut last_summary = Instant::now();
2499 loop {
2500 let promotion_due = scheduler
2506 .reserved_ready_at()
2507 .unwrap_or_else(first_audit_far_future);
2508 tokio::select! {
2509 () = shutdown.cancelled() => break,
2510 event = rx.recv() => match event {
2511 Some(e) => {
2512 observability.received.fetch_add(1, Ordering::Relaxed);
2513 if scheduler.would_displace(&e) {
2522 open_first_audit_reservation(
2523 &mut scheduler,
2524 &gossip_audit.cooldown,
2525 &observability,
2526 )
2527 .await;
2528 }
2529 scheduler.enqueue(e, &observability);
2530 let mut drained = 1usize;
2533 while drained < config::FIRST_AUDIT_DRAIN_BATCH {
2534 match rx.try_recv() {
2535 Ok(e) => {
2536 observability.received.fetch_add(1, Ordering::Relaxed);
2537 if scheduler.would_displace(&e) {
2538 open_first_audit_reservation(
2539 &mut scheduler,
2540 &gossip_audit.cooldown,
2541 &observability,
2542 )
2543 .await;
2544 }
2545 scheduler.enqueue(e, &observability);
2546 drained += 1;
2547 }
2548 Err(_) => break,
2549 }
2550 }
2551 }
2552 None => break,
2553 },
2554 _ = tick.tick() => {}
2555 () = tokio::time::sleep_until(promotion_due.into()) => {}
2556 }
2557
2558 if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
2564 let promoted = {
2565 let mut cooldown = gossip_audit.cooldown.write().await;
2566 scheduler.resolve(
2567 reservation,
2568 SystemTime::now(),
2569 Instant::now(),
2570 &mut cooldown,
2571 &observability,
2572 )
2573 };
2574 if let Some((event, inflight_slot)) = promoted {
2575 debug!(
2576 "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
2577 event.peer, hex::encode(event.pin), event.key_count,
2578 observability.inflight.load(Ordering::Relaxed)
2579 );
2580 let trigger = gossip_audit.clone();
2581 let audit_observability = Arc::clone(&observability);
2582 let tracker = trigger.detached_task_tracker.clone();
2590 tracker.spawn(async move {
2591 let inflight_slot = inflight_slot;
2595 let started = Instant::now();
2596 let credit = storage_commitment_audit::AuditCredit {
2597 recent_provers: &trigger.recent_provers,
2598 };
2599 let result = storage_commitment_audit::run_subtree_audit(
2600 &trigger.p2p_node,
2601 &trigger.config,
2602 &event.peer,
2603 event.pin,
2604 event.key_count,
2605 Some(&credit),
2606 )
2607 .await;
2608 let outcome = first_audit_terminal_outcome(&result);
2609 match outcome {
2610 FirstAuditTerminalOutcome::Passed => {
2611 audit_observability.passed.fetch_add(1, Ordering::Relaxed);
2612 }
2613 FirstAuditTerminalOutcome::Timeout => {
2614 audit_observability
2615 .timed_out
2616 .fetch_add(1, Ordering::Relaxed);
2617 }
2618 FirstAuditTerminalOutcome::Failed => {
2619 audit_observability.failed.fetch_add(1, Ordering::Relaxed);
2620 }
2621 FirstAuditTerminalOutcome::BootstrapClaim => {
2622 audit_observability
2623 .bootstrap_claims
2624 .fetch_add(1, Ordering::Relaxed);
2625 }
2626 FirstAuditTerminalOutcome::Idle => {
2627 audit_observability.idle.fetch_add(1, Ordering::Relaxed);
2628 }
2629 FirstAuditTerminalOutcome::InsufficientKeys => {
2630 audit_observability
2631 .insufficient_keys
2632 .fetch_add(1, Ordering::Relaxed);
2633 }
2634 }
2635 drop(inflight_slot);
2636 debug!(
2637 "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
2638 outcome.as_str(),
2639 event.peer, hex::encode(event.pin), event.key_count,
2640 started.elapsed().as_millis(),
2641 audit_observability.inflight.load(Ordering::Relaxed)
2642 );
2643 handle_subtree_audit_result(
2644 &result,
2645 &trigger.p2p_node,
2646 &trigger.sync_state,
2647 &trigger.recent_provers,
2648 &trigger.config,
2649 )
2650 .await;
2651 });
2652 }
2653 }
2654
2655 open_first_audit_reservation(
2661 &mut scheduler,
2662 &gossip_audit.cooldown,
2663 &observability,
2664 )
2665 .await;
2666
2667 if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
2668 let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
2673 if swept > 0 {
2674 debug!(
2675 "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
2676 scheduler.pending_len()
2677 );
2678 }
2679 info!(
2680 "First-audit scheduler summary: audit_trigger=first_monetized ingress_dropped={} received={} queued={} coalesced={} suppressed_lower={} duplicates={} capacity_evicted={} self_target_skipped={} cooldown_deferred_attempts={} rate_deferred_attempts={} window_deduped={} launched={} passed={} timeout={} failed={} bootstrap_claims={} idle={} insufficient_keys={} outside_answerability_window={} pending={} pending_cap={} reserved={} oldest_pending_quote_age_ms={} inflight={} tokens={}",
2681 FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
2682 observability.received.load(Ordering::Relaxed),
2683 observability.queued.load(Ordering::Relaxed),
2684 observability.coalesced.load(Ordering::Relaxed),
2685 observability.suppressed_lower.load(Ordering::Relaxed),
2686 observability.duplicates.load(Ordering::Relaxed),
2687 observability.capacity_evicted.load(Ordering::Relaxed),
2688 observability.self_target_skipped.load(Ordering::Relaxed),
2689 observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
2690 observability.rate_deferred_attempts.load(Ordering::Relaxed),
2691 observability.window_deduped.load(Ordering::Relaxed),
2692 observability.launched.load(Ordering::Relaxed),
2693 observability.passed.load(Ordering::Relaxed),
2694 observability.timed_out.load(Ordering::Relaxed),
2695 observability.failed.load(Ordering::Relaxed),
2696 observability.bootstrap_claims.load(Ordering::Relaxed),
2697 observability.idle.load(Ordering::Relaxed),
2698 observability.insufficient_keys.load(Ordering::Relaxed),
2699 observability.outside_answerability_window.load(Ordering::Relaxed),
2700 scheduler.pending_len(),
2701 FIRST_AUDIT_PENDING_CAP,
2702 u8::from(scheduler.has_reservation()),
2703 scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
2704 observability.inflight.load(Ordering::Relaxed),
2705 scheduler.tokens(),
2706 );
2707 last_summary = Instant::now();
2708 }
2709 }
2710 debug!("First-audit drainer shut down");
2711 });
2712 self.task_handles.push(handle);
2713 }
2714
2715 #[allow(clippy::too_many_lines)]
2716 fn start_message_handler(&mut self) {
2717 let mut p2p_events = self.p2p_node.subscribe_events();
2718 let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
2719 let p2p = Arc::clone(&self.p2p_node);
2720 let storage = Arc::clone(&self.storage);
2721 let paid_list = Arc::clone(&self.paid_list);
2722 let payment_verifier = Arc::clone(&self.payment_verifier);
2723 let queues = Arc::clone(&self.queues);
2724 let config = Arc::clone(&self.config);
2725 let shutdown = self.shutdown.clone();
2726 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2727 let bootstrap_state = Arc::clone(&self.bootstrap_state);
2728 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
2729 let sync_history = Arc::clone(&self.sync_history);
2730 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2731 let repair_proofs = Arc::clone(&self.repair_proofs);
2732 let sync_trigger = Arc::clone(&self.sync_trigger);
2733 let my_commitment_state = Arc::clone(&self.commitment_state);
2734 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2735 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2736 let recent_provers = Arc::clone(&self.recent_provers);
2737 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
2738 let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
2739 let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
2740 let sync_state = Arc::clone(&self.sync_state);
2741 let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
2742 let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
2743 let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
2744 let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
2745 let fetch_responder_admission_semaphore =
2746 Arc::clone(&self.fetch_responder_admission_semaphore);
2747 let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
2748 let verification_responder_worker_semaphore =
2749 Arc::clone(&self.verification_responder_worker_semaphore);
2750 let verification_responder_admission_semaphore =
2751 Arc::clone(&self.verification_responder_admission_semaphore);
2752 let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
2753 let neighbor_sync_responder_worker_semaphore =
2754 Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
2755 let neighbor_sync_responder_admission_semaphore =
2756 Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
2757 let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
2758 let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
2759 let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
2760 let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
2761 let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
2762 let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
2763 let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
2764 let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
2765 let detached_task_tracker = self.detached_task_tracker.clone();
2766 let subtree_round1 = self.subtree_round1.clone();
2767
2768 let gossip_audit = GossipAuditTrigger {
2771 p2p_node: Arc::clone(&p2p),
2772 config: Arc::clone(&config),
2773 recent_provers: Arc::clone(&recent_provers),
2774 sync_state: Arc::clone(&sync_state),
2775 cooldown: Arc::clone(&audit_on_gossip_cooldown),
2776 detached_task_tracker: detached_task_tracker.clone(),
2777 lottery_attempts: Arc::clone(&gossip_lottery_attempts),
2778 };
2779
2780 let handler_context = ReplicationMessageHandlerContext {
2781 p2p_node: Arc::clone(&p2p),
2782 storage,
2783 paid_list,
2784 payment_verifier,
2785 queues,
2786 config: Arc::clone(&config),
2787 is_bootstrapping,
2788 bootstrap_state,
2789 sync_history,
2790 sync_cycle_epoch,
2791 repair_proofs: Arc::clone(&repair_proofs),
2792 last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
2793 ever_capable_peers,
2794 sig_verify_attempts: Arc::clone(&sig_verify_attempts),
2795 my_commitment_state,
2796 gossip_audit,
2797 audit_responder_semaphore,
2798 audit_responder_inflight,
2799 audit_responder_metrics,
2800 subtree_round1,
2801 fetch_responder_worker_semaphore,
2802 fetch_responder_admission_semaphore,
2803 fetch_responder_inflight,
2804 verification_responder_worker_semaphore,
2805 verification_responder_admission_semaphore,
2806 verification_responder_inflight,
2807 neighbor_sync_responder_worker_semaphore,
2808 neighbor_sync_responder_admission_semaphore,
2809 neighbor_sync_responder_inflight,
2810 fresh_offer_worker_semaphore,
2811 fresh_offer_admission_semaphore,
2812 fresh_offer_responder_inflight,
2813 fresh_offer_in_flight,
2814 paid_notify_worker_semaphore,
2815 paid_notify_admission_semaphore,
2816 paid_notify_responder_inflight,
2817 shutdown: shutdown.clone(),
2818 detached_task_tracker,
2819 };
2820
2821 let (replication_tx, mut replication_rx) =
2822 mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
2823 let serial_context = handler_context.clone();
2824 let serial_shutdown = shutdown.clone();
2825 let serial_handle = tokio::spawn(async move {
2826 loop {
2827 tokio::select! {
2828 () = serial_shutdown.cancelled() => break,
2829 inbound = replication_rx.recv() => {
2830 let Some(inbound) = inbound else { break };
2831 let source = inbound.source;
2832 match handle_replication_message(
2833 &source,
2834 inbound.msg,
2835 &serial_context,
2836 inbound.received_at,
2837 inbound.rr_message_id.as_deref(),
2838 )
2839 .await
2840 {
2841 Ok(()) => {}
2842 Err(e) => {
2843 debug!("Replication message from {source} error: {e}");
2844 }
2845 }
2846 }
2847 }
2848 }
2849 debug!("Replication non-audit serial handler shut down");
2850 });
2851 self.task_handles.push(serial_handle);
2852
2853 let handle = tokio::spawn(async move {
2854 loop {
2855 tokio::select! {
2856 () = shutdown.cancelled() => break,
2857 event = p2p_events.recv() => {
2858 let event = match event {
2859 Ok(event) => event,
2860 Err(error) => match handle_replication_event_recv_error(&error) {
2861 ControlFlow::Continue(()) => continue,
2862 ControlFlow::Break(()) => break,
2863 },
2864 };
2865 let Some((source, payload, inbound_protocol, rr_message_id)) =
2866 replication_payload_from_event(event)
2867 else {
2868 continue;
2869 };
2870 let received_at = Instant::now();
2871 let msg = match ReplicationMessage::decode(&payload) {
2872 Ok(msg) => msg,
2873 Err(e) => {
2874 debug!("Replication message from {source} decode error: {e}");
2875 continue;
2876 }
2877 };
2878 if !body_matches_protocol(&msg.body, inbound_protocol) {
2879 debug!(
2880 "Dropping replication body (variant {}) on protocol \
2881 {inbound_protocol}: wrong id for its family \
2882 (cross-version or misrouted)",
2883 msg.body.variant_index()
2884 );
2885 continue;
2886 }
2887 if let Some(class) = audit_responder_class(&msg.body) {
2888 handler_context
2889 .audit_responder_metrics
2890 .record_received(source, class);
2891 }
2892 let inbound = InboundReplicationMessage {
2893 source,
2894 msg,
2895 rr_message_id,
2896 received_at,
2897 };
2898 if matches!(
2899 inbound.msg.body,
2900 ReplicationMessageBody::AuditChallenge(_)
2901 | ReplicationMessageBody::SubtreeAuditChallenge(_)
2902 | ReplicationMessageBody::SubtreeSliceChallenge(_)
2903 ) {
2904 let source = inbound.source;
2905 match handle_replication_message(
2906 &source,
2907 inbound.msg,
2908 &handler_context,
2909 inbound.received_at,
2910 inbound.rr_message_id.as_deref(),
2911 )
2912 .await
2913 {
2914 Ok(()) => {}
2915 Err(e) => {
2916 debug!("Replication message from {source} error: {e}");
2917 }
2918 }
2919 continue;
2920 }
2921 if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
2922 if dropped.audit_responder_class.is_some() {
2923 handler_context
2924 .audit_responder_metrics
2925 .record_serial_queue_drop(dropped.source);
2926 }
2927 warn!(
2934 message_class = dropped.message_class,
2935 source = %dropped.source,
2936 queue_depth = dropped.queue_depth,
2937 reason = dropped.reason.as_str(),
2938 "Replication serial-queue message dropped"
2939 );
2940 }
2941 }
2942 dht_event = dht_events.recv() => {
2950 let dht_event = match dht_event {
2951 Ok(event) => event,
2952 Err(RecvError::Lagged(missed)) => {
2953 warn!(
2968 "Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
2969 );
2970 let self_id = *p2p.peer_id();
2971 let neighbors = neighbor_sync::snapshot_close_neighbors(
2972 &p2p,
2973 &self_id,
2974 config.neighbor_sync_scope,
2975 )
2976 .await;
2977 let neighbor_set =
2978 neighbors.iter().copied().collect::<HashSet<_>>();
2979 let (requeued, sync_removals) = {
2980 let mut state = sync_state.write().await;
2981 let sync_removals =
2982 state.retain_sync_peers(&neighbor_set);
2983 let requeued = state.queue_priority_peers(neighbors);
2984 (requeued, sync_removals)
2985 };
2986 if sync_removals > 0 {
2987 debug!(
2988 "Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
2989 );
2990 }
2991 if requeued > 0 {
2992 debug!(
2993 "Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
2994 );
2995 sync_trigger.notify_one();
2996 }
2997 continue;
2998 }
2999 Err(RecvError::Closed) => {
3000 warn!(
3003 "DHT event stream closed on replication branch; stopping message handler"
3004 );
3005 break;
3006 }
3007 };
3008 match dht_event {
3009 DhtNetworkEvent::KClosestPeersChanged { old, new, .. } => {
3010 let old_peers = old
3011 .iter()
3012 .take(config.neighbor_sync_scope)
3013 .copied()
3014 .collect::<HashSet<_>>();
3015 let new_scoped = new
3016 .iter()
3017 .take(config.neighbor_sync_scope)
3018 .copied()
3019 .collect::<Vec<_>>();
3020 let new_peers =
3021 new_scoped.iter().copied().collect::<HashSet<_>>();
3022 let entrants = new_scoped
3023 .iter()
3024 .copied()
3025 .filter(|peer| !old_peers.contains(peer))
3026 .collect::<Vec<_>>();
3027 let entrant_count = entrants.len();
3028 let (priority_insertions, sync_removals) = {
3029 let mut state = sync_state.write().await;
3030 let sync_removals = state.retain_sync_peers(&new_peers);
3031 let priority_insertions = state.queue_priority_peers(entrants);
3032 (priority_insertions, sync_removals)
3033 };
3034 if priority_insertions > 0 {
3035 debug!(
3036 "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
3037 );
3038 } else {
3039 debug!(
3040 "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
3041 );
3042 }
3043 sync_trigger.notify_one();
3044 }
3045 DhtNetworkEvent::PeerRemoved { peer_id } => {
3046 sync_state.write().await.remove_peer(&peer_id);
3047 repair_proofs.write().await.remove_peer(&peer_id);
3048 update_bootstrap_after_peer_removed(
3049 &peer_id,
3050 &handler_context.bootstrap_state,
3051 &handler_context.queues,
3052 &handler_context.is_bootstrapping,
3053 &bootstrap_complete_notify,
3054 )
3055 .await;
3056 last_commitment_by_peer.write().await.remove(&peer_id);
3063 recent_provers.write().await.forget_peer(&peer_id);
3064 sig_verify_attempts.write().await.remove(&peer_id);
3065 audit_on_gossip_cooldown.write().await.remove(&peer_id);
3068 gossip_lottery_attempts.write().await.remove(&peer_id);
3069 }
3076 _ => {}
3077 }
3078 }
3079 }
3080 }
3081 debug!("Replication message handler shut down");
3082 });
3083 self.task_handles.push(handle);
3084 }
3085
3086 fn start_neighbor_sync_loop(&mut self) {
3087 let p2p = Arc::clone(&self.p2p_node);
3088 let storage = Arc::clone(&self.storage);
3089 let paid_list = Arc::clone(&self.paid_list);
3090 let queues = Arc::clone(&self.queues);
3091 let config = Arc::clone(&self.config);
3092 let shutdown = self.shutdown.clone();
3093 let sync_state = Arc::clone(&self.sync_state);
3094 let sync_history = Arc::clone(&self.sync_history);
3095 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3096 let repair_proofs = Arc::clone(&self.repair_proofs);
3097 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3098 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3099 let sync_trigger = Arc::clone(&self.sync_trigger);
3100 let commitment_state = Arc::clone(&self.commitment_state);
3101 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3102 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3103 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3104 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3105 let detached_task_tracker = self.detached_task_tracker.clone();
3106 let gossip_audit = GossipAuditTrigger {
3111 p2p_node: Arc::clone(&p2p),
3112 config: Arc::clone(&config),
3113 recent_provers: Arc::clone(&self.recent_provers),
3114 sync_state: Arc::clone(&sync_state),
3115 cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
3116 detached_task_tracker,
3117 lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
3118 };
3119
3120 let handle = tokio::spawn(async move {
3121 loop {
3122 if !sync_state.read().await.has_priority_peers() {
3131 let interval = config.random_neighbor_sync_interval();
3132 tokio::select! {
3133 () = shutdown.cancelled() => break,
3134 () = tokio::time::sleep(interval) => {}
3135 () = sync_trigger.notified() => {
3136 debug!("Neighbor sync triggered by topology change");
3137 }
3138 }
3139 }
3140 tokio::select! {
3144 () = shutdown.cancelled() => break,
3145 () = run_neighbor_sync_round(
3146 &p2p,
3147 &storage,
3148 &paid_list,
3149 &queues,
3150 &config,
3151 &sync_state,
3152 &sync_history,
3153 &sync_cycle_epoch,
3154 &repair_proofs,
3155 &is_bootstrapping,
3156 &bootstrap_state,
3157 &commitment_state,
3158 &last_commitment_by_peer,
3159 &ever_capable_peers,
3160 &sig_verify_attempts,
3161 &audit_challenge_coordinator,
3162 &gossip_audit,
3163 ) => {}
3164 }
3165 }
3166 debug!("Neighbor sync loop shut down");
3167 });
3168 self.task_handles.push(handle);
3169 }
3170
3171 fn start_self_lookup_loop(&mut self) {
3172 let p2p = Arc::clone(&self.p2p_node);
3173 let config = Arc::clone(&self.config);
3174 let shutdown = self.shutdown.clone();
3175
3176 let handle = tokio::spawn(async move {
3177 loop {
3178 let interval = config.random_self_lookup_interval();
3179 tokio::select! {
3180 () = shutdown.cancelled() => break,
3181 () = tokio::time::sleep(interval) => {
3182 if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
3183 debug!("Self-lookup failed: {e}");
3184 }
3185 }
3186 }
3187 }
3188 debug!("Self-lookup loop shut down");
3189 });
3190 self.task_handles.push(handle);
3191 }
3192
3193 fn start_audit_loop(&mut self) {
3200 let p2p = Arc::clone(&self.p2p_node);
3201 let storage = Arc::clone(&self.storage);
3202 let config = Arc::clone(&self.config);
3203 let shutdown = self.shutdown.clone();
3204 let sync_history = Arc::clone(&self.sync_history);
3205 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3206 let repair_proofs = Arc::clone(&self.repair_proofs);
3207 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3208 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3209 let sync_state = Arc::clone(&self.sync_state);
3210 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3211
3212 let handle = tokio::spawn(async move {
3213 loop {
3215 tokio::select! {
3216 () = shutdown.cancelled() => return,
3217 () = tokio::time::sleep(
3218 std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
3219 ) => {
3220 if bootstrap_state.read().await.is_drained() {
3221 break;
3222 }
3223 }
3224 }
3225 }
3226
3227 {
3229 let bootstrapping = *is_bootstrapping.read().await;
3230 let result = {
3231 let history = sync_history.read().await;
3232 let current_sync_epoch = *sync_cycle_epoch.read().await;
3233 audit::audit_tick_with_repair_proofs(
3234 &p2p,
3235 &storage,
3236 &config,
3237 &history,
3238 &repair_proofs,
3239 &audit_challenge_coordinator,
3240 current_sync_epoch,
3241 bootstrapping,
3242 )
3243 .await
3244 };
3245 handle_audit_result(&result, &p2p, &sync_state, &config).await;
3246 }
3247
3248 loop {
3250 let interval = config.random_audit_tick_interval();
3251 tokio::select! {
3252 () = shutdown.cancelled() => break,
3253 () = tokio::time::sleep(interval) => {
3254 let bootstrapping = *is_bootstrapping.read().await;
3255 let result = {
3256 let history = sync_history.read().await;
3257 let current_sync_epoch = *sync_cycle_epoch.read().await;
3258 audit::audit_tick_with_repair_proofs(
3259 &p2p,
3260 &storage,
3261 &config,
3262 &history,
3263 &repair_proofs,
3264 &audit_challenge_coordinator,
3265 current_sync_epoch,
3266 bootstrapping,
3267 )
3268 .await
3269 };
3270 handle_audit_result(&result, &p2p, &sync_state, &config).await;
3271 }
3272 }
3273 }
3274 debug!("Audit loop shut down");
3275 });
3276 self.task_handles.push(handle);
3277 }
3278
3279 fn start_commitment_rotation_loop(&mut self) {
3294 let storage = Arc::clone(&self.storage);
3295 let identity = Arc::clone(&self.identity);
3296 let commitment_state = Arc::clone(&self.commitment_state);
3297 let shutdown = self.shutdown.clone();
3298 let p2p = Arc::clone(&self.p2p_node);
3299 let config = Arc::clone(&self.config);
3300 let sync_trigger = Arc::clone(&self.sync_trigger);
3301 let recent_provers = Arc::clone(&self.recent_provers);
3302
3303 let handle = tokio::spawn(async move {
3304 if let Err(e) =
3325 rebuild_and_rotate_commitment(&storage, &identity, &commitment_state, &p2p, &config)
3326 .await
3327 {
3328 warn!("Initial commitment build failed: {e}");
3329 } else {
3330 sync_trigger.notify_one();
3331 }
3332 loop {
3333 tokio::select! {
3334 () = shutdown.cancelled() => break,
3335 () = tokio::time::sleep(
3336 std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
3337 ) => {
3338 if let Err(e) = rebuild_and_rotate_commitment(
3339 &storage,
3340 &identity,
3341 &commitment_state,
3342 &p2p,
3343 &config,
3344 ).await {
3345 warn!("Commitment rotation failed: {e}");
3346 }
3347 let dropped = recent_provers.write().await.sweep_expired(
3353 std::time::Instant::now()
3354 );
3355 if dropped > 0 {
3356 debug!("recent_provers: swept {dropped} expired entries");
3357 }
3358 }
3359 }
3360 }
3361 debug!("Commitment rotation loop shut down");
3362 });
3363 self.task_handles.push(handle);
3364 }
3365
3366 fn start_retention_persist_loop(&mut self) {
3371 let commitment_state = Arc::clone(&self.commitment_state);
3372 let retention_path = self.retention_path.clone();
3373 let shutdown = self.shutdown.clone();
3374 let handle = tokio::spawn(async move {
3375 let mut last: Option<Vec<u8>> = None;
3376 persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
3377 loop {
3378 tokio::select! {
3379 () = shutdown.cancelled() => {
3380 persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3381 .await;
3382 break;
3383 }
3384 () = tokio::time::sleep(std::time::Duration::from_secs(
3385 RETENTION_PERSIST_INTERVAL_SECS,
3386 )) => {
3387 persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3388 .await;
3389 }
3390 }
3391 }
3392 debug!("Commitment retention persist loop shut down");
3393 });
3394 self.task_handles.push(handle);
3395 }
3396
3397 fn start_traffic_summary_loop(&mut self) {
3403 let shutdown = self.shutdown.clone();
3404 let handle = tokio::spawn(async move {
3405 loop {
3406 tokio::select! {
3407 () = shutdown.cancelled() => break,
3408 () = tokio::time::sleep(std::time::Duration::from_secs(
3409 TRAFFIC_SUMMARY_INTERVAL_SECS,
3410 )) => {
3411 protocol::log_traffic_summary();
3412 protocol::log_served_peers_summary();
3413 protocol::log_audit_outcome_summary();
3414 audit_metrics::log_responder_admission_summary();
3415 }
3416 }
3417 }
3418 debug!("Replication traffic summary loop shut down");
3419 });
3420 self.task_handles.push(handle);
3421 }
3422
3423 #[cfg(feature = "logging")]
3427 fn start_bootstrap_state_snapshot_loop(&mut self) {
3428 let shutdown = self.shutdown.clone();
3429 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3430 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3431 let started_at = Instant::now();
3432 let handle = tokio::spawn(async move {
3433 loop {
3434 tokio::select! {
3435 () = shutdown.cancelled() => break,
3436 () = tokio::time::sleep(Duration::from_secs(
3437 BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS,
3438 )) => {
3439 let (
3440 drained,
3441 pending_peer_requests,
3442 pending_keys,
3443 capacity_rejected_sources,
3444 ) = {
3445 let state = bootstrap_state.read().await;
3446 (
3447 state.drained,
3448 state.pending_peer_requests,
3449 state.pending_keys.len(),
3450 state.capacity_rejected_sources.len(),
3451 )
3452 };
3453 let bootstrapping = *is_bootstrapping.read().await;
3454 let snapshot_state = if drained && !bootstrapping {
3455 "healthy"
3456 } else if drained {
3457 "drained_waiting_for_bootstrap_flag"
3458 } else {
3459 "pending"
3460 };
3461 info!(
3462 drained,
3463 pending_peer_requests,
3464 pending_keys,
3465 capacity_rejected_sources,
3466 is_bootstrapping = bootstrapping,
3467 snapshot_state,
3468 uptime_secs = started_at.elapsed().as_secs(),
3469 "Replication bootstrap state snapshot"
3470 );
3471 if drained && !bootstrapping {
3472 info!(
3473 "Replication bootstrap diagnostics reached healthy state; stopping periodic snapshots"
3474 );
3475 break;
3476 }
3477 }
3478 }
3479 }
3480 debug!("Bootstrap state snapshot loop shut down");
3481 });
3482 self.task_handles.push(handle);
3483 }
3484
3485 #[cfg(feature = "logging")]
3489 fn start_audit_responder_summary_loop(&mut self) {
3490 let shutdown = self.shutdown.clone();
3491 let metrics = Arc::clone(&self.audit_responder_metrics);
3492 let semaphore = Arc::clone(&self.audit_responder_semaphore);
3493 let handle = tokio::spawn(async move {
3494 let mut window_started = Instant::now();
3495 loop {
3496 tokio::select! {
3497 () = shutdown.cancelled() => {
3498 log_audit_responder_summary(
3499 &metrics,
3500 &semaphore,
3501 window_started.elapsed(),
3502 );
3503 break;
3504 }
3505 () = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
3506 log_audit_responder_summary(
3507 &metrics,
3508 &semaphore,
3509 window_started.elapsed(),
3510 );
3511 window_started = Instant::now();
3512 }
3513 }
3514 }
3515 debug!("Audit responder summary loop shut down");
3516 });
3517 self.task_handles.push(handle);
3518 }
3519
3520 #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
3521 fn start_fetch_worker(&mut self) {
3522 let p2p = Arc::clone(&self.p2p_node);
3523 let storage = Arc::clone(&self.storage);
3524 let queues = Arc::clone(&self.queues);
3525 let config = Arc::clone(&self.config);
3526 let shutdown = self.shutdown.clone();
3527 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3528 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3529 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3530 let detached_task_tracker = self.detached_task_tracker.clone();
3531 let concurrency = max_parallel_fetch();
3532
3533 info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
3534
3535 let handle = tokio::spawn(async move {
3536 let mut in_flight = FuturesUnordered::<FetchFuture>::new();
3539
3540 loop {
3541 {
3543 let mut q = queues.write().await;
3544 while in_flight.len() < concurrency {
3545 let Some(candidate) = q.dequeue_fetch() else {
3546 break;
3547 };
3548 let fetch_key = candidate.key;
3549 let Some(&source) = candidate.sources.first() else {
3550 warn!(
3551 "Fetch candidate {} has no sources; requeueing for verification",
3552 hex::encode(fetch_key)
3553 );
3554 let _ = q.requeue_candidate_for_verification(
3555 candidate,
3556 config.verification_request_timeout,
3557 );
3558 continue;
3559 };
3560 q.start_dequeued_fetch(candidate, source);
3561
3562 let p2p = Arc::clone(&p2p);
3563 let storage = Arc::clone(&storage);
3564 let config = Arc::clone(&config);
3565 let token = shutdown.clone();
3566 let tracker = detached_task_tracker.clone();
3567 in_flight.push(Box::pin(async move {
3568 let handle = tracker.spawn(async move {
3573 tokio::select! {
3575 () = token.cancelled() => FetchOutcome {
3576 key: fetch_key,
3577 result: FetchResult::SourceFailed,
3578 },
3579 outcome = execute_single_fetch(
3580 p2p, storage, config, fetch_key, source,
3581 ) => outcome,
3582 }
3583 });
3584 match handle.await {
3585 Ok(outcome) => (outcome.key, Some(outcome)),
3586 Err(e) => {
3587 error!(
3588 "Fetch task for {} panicked: {e}",
3589 hex::encode(fetch_key)
3590 );
3591 (fetch_key, None)
3592 }
3593 }
3594 }));
3595 }
3596 } if in_flight.is_empty() {
3599 tokio::select! {
3601 () = shutdown.cancelled() => break,
3602 () = tokio::time::sleep(
3603 std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
3604 ) => continue,
3605 }
3606 }
3607
3608 tokio::select! {
3610 () = shutdown.cancelled() => break,
3611 Some((key, maybe_outcome)) = in_flight.next() => {
3612 let mut q = queues.write().await;
3613 let terminal = if let Some(outcome) = maybe_outcome {
3614 match apply_fetch_result(
3615 &mut q,
3616 &key,
3617 &outcome.result,
3618 config.verification_request_timeout,
3619 ) {
3620 FetchFollowUp::Terminal => true,
3621 FetchFollowUp::RequeuedForVerification => false,
3622 FetchFollowUp::RetryFrom(next_peer) => {
3623 let p2p = Arc::clone(&p2p);
3625 let storage = Arc::clone(&storage);
3626 let config = Arc::clone(&config);
3627 let token = shutdown.clone();
3628 let tracker = detached_task_tracker.clone();
3629 let fetch_key = key;
3630 in_flight.push(Box::pin(async move {
3631 let handle = tracker.spawn(async move {
3634 tokio::select! {
3635 () = token.cancelled() => FetchOutcome {
3636 key: fetch_key,
3637 result: FetchResult::SourceFailed,
3638 },
3639 outcome = execute_single_fetch(
3640 p2p, storage, config, fetch_key, next_peer,
3641 ) => outcome,
3642 }
3643 });
3644 match handle.await {
3645 Ok(outcome) => (outcome.key, Some(outcome)),
3646 Err(e) => {
3647 error!(
3648 "Fetch task for {} panicked: {e}",
3649 hex::encode(fetch_key)
3650 );
3651 (fetch_key, None)
3652 }
3653 }
3654 }));
3655 false
3656 }
3657 }
3658 } else {
3659 !q.requeue_fetch_for_verification(
3662 &key,
3663 config.verification_request_timeout,
3664 )
3665 };
3666
3667 if terminal {
3669 drop(q); if !bootstrap_state.read().await.is_drained() {
3671 bootstrap_state.write().await.remove_key(&key);
3672 let q = queues.read().await;
3673 if bootstrap::check_bootstrap_drained(
3674 &bootstrap_state,
3675 &q,
3676 )
3677 .await
3678 {
3679 complete_bootstrap(
3680 &is_bootstrapping,
3681 &bootstrap_complete_notify,
3682 ).await;
3683 }
3684 }
3685 }
3686 }
3687 }
3688 }
3689
3690 while in_flight.next().await.is_some() {}
3694 debug!("Fetch worker shut down");
3695 });
3696 self.task_handles.push(handle);
3697 }
3698
3699 fn start_verification_worker(&mut self) {
3700 let p2p = Arc::clone(&self.p2p_node);
3701 let storage = Arc::clone(&self.storage);
3702 let queues = Arc::clone(&self.queues);
3703 let paid_list = Arc::clone(&self.paid_list);
3704 let config = Arc::clone(&self.config);
3705 let shutdown = self.shutdown.clone();
3706 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3707 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3708 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3709 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3710 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3711 let recent_provers = Arc::clone(&self.recent_provers);
3712
3713 let handle = tokio::spawn(async move {
3714 loop {
3715 tokio::select! {
3716 () = shutdown.cancelled() => break,
3717 () = tokio::time::sleep(
3718 std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
3719 ) => {
3720 let ctx = VerificationCycleContext {
3721 p2p_node: &p2p,
3722 paid_list: &paid_list,
3723 storage: &storage,
3724 queues: &queues,
3725 config: &config,
3726 bootstrap_state: &bootstrap_state,
3727 is_bootstrapping: &is_bootstrapping,
3728 bootstrap_complete_notify: &bootstrap_complete_notify,
3729 last_commitment_by_peer: &last_commitment_by_peer,
3730 ever_capable_peers: &ever_capable_peers,
3731 recent_provers: &recent_provers,
3732 };
3733 run_verification_cycle(ctx).await;
3734 }
3735 }
3736 }
3737 debug!("Verification worker shut down");
3738 });
3739 self.task_handles.push(handle);
3740 }
3741
3742 #[allow(clippy::too_many_lines)]
3754 fn start_bootstrap_sync(
3755 &mut self,
3756 dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
3757 ) {
3758 let p2p = Arc::clone(&self.p2p_node);
3759 let storage = Arc::clone(&self.storage);
3760 let paid_list = Arc::clone(&self.paid_list);
3761 let queues = Arc::clone(&self.queues);
3762 let config = Arc::clone(&self.config);
3763 let shutdown = self.shutdown.clone();
3764 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3765 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3766 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3767 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3768 let repair_proofs = Arc::clone(&self.repair_proofs);
3769 let my_commitment_state = Arc::clone(&self.commitment_state);
3770 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3771 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3772 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3773
3774 let handle = tokio::spawn(async move {
3775 let gate = bootstrap::wait_for_bootstrap_complete(
3779 dht_events,
3780 config.bootstrap_complete_timeout_secs,
3781 &shutdown,
3782 )
3783 .await;
3784
3785 if gate == bootstrap::BootstrapGateResult::Shutdown {
3786 return;
3787 }
3788
3789 let self_id = *p2p.peer_id();
3790 let neighbors =
3791 neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
3792 .await;
3793
3794 if neighbors.is_empty() {
3795 info!("Bootstrap sync: no close neighbors found, marking drained");
3796 bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
3797 complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3798 return;
3799 }
3800
3801 let neighbor_count = neighbors.len();
3802 info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
3803
3804 for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
3806 if shutdown.is_cancelled() {
3807 break;
3808 }
3809
3810 let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
3811 batch,
3812 &storage,
3813 &paid_list,
3814 &p2p,
3815 config.close_group_size,
3816 config.paid_list_close_group_size,
3817 )
3818 .await;
3819
3820 bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
3825 let bootstrapping = *is_bootstrapping.read().await;
3826
3827 let sync_futures = batch.iter().map(|peer| {
3828 let peer = *peer;
3829 let hints = hints_by_peer.remove(&peer).unwrap_or_default();
3830 let commitment = my_commitment_state
3833 .current_for_gossip()
3834 .map(|binding| binding.commitment().clone());
3835 let p2p = &p2p;
3836 let config = &config;
3837 async move {
3838 let outcome = neighbor_sync::sync_with_peer_with_hints(
3839 &peer,
3840 p2p,
3841 config,
3842 bootstrapping,
3843 hints,
3844 commitment,
3845 )
3846 .await;
3847 (peer, outcome)
3848 }
3849 });
3850 let completed = join_all(sync_futures).await;
3851
3852 for (peer, outcome) in &completed {
3855 if let Some(outcome) = outcome {
3856 ingest_peer_commitment(
3871 peer,
3872 outcome.response.commitment.as_ref(),
3873 &p2p,
3874 &last_commitment_by_peer,
3875 &ever_capable_peers,
3876 &sig_verify_attempts,
3877 )
3878 .await; if !outcome.response.bootstrapping {
3881 record_sent_replica_hints(
3882 peer,
3883 &outcome.sent_replica_hints,
3884 &repair_proofs,
3885 &sync_cycle_epoch,
3886 )
3887 .await;
3888 }
3889 }
3890 }
3891
3892 let pending_keys: HashSet<XorName> = {
3893 let q = queues.read().await;
3894 q.pending_keys().into_iter().collect()
3895 };
3896 let admission_futures = completed.iter().map(|(_, outcome)| async {
3897 match outcome {
3898 Some(outcome) if !outcome.response.bootstrapping => Some(
3899 admission::admit_hints(
3900 &self_id,
3901 &outcome.response.replica_hints,
3902 &outcome.response.paid_hints,
3903 &p2p,
3904 &config,
3905 &storage,
3906 &paid_list,
3907 &pending_keys,
3908 )
3909 .await,
3910 ),
3911 _ => None,
3912 }
3913 });
3914 let admitted = join_all(admission_futures).await;
3915
3916 let (batch_outcomes, batch_discovered) = {
3919 let mut q = queues.write().await;
3920 let outcomes = completed
3921 .iter()
3922 .zip(admitted)
3923 .filter_map(|((peer, _), admitted)| {
3924 admitted.map(|admitted| {
3925 (
3926 *peer,
3927 queue_admitted_hints(peer, admitted, &storage, &mut q),
3928 )
3929 })
3930 })
3931 .collect::<Vec<_>>();
3932 let live_discovered = outcomes
3933 .iter()
3934 .flat_map(|(_, outcome)| outcome.discovered.iter().copied())
3935 .filter(|key| q.contains_key(key))
3936 .collect::<HashSet<_>>();
3937 (outcomes, live_discovered)
3938 };
3939
3940 publish_bootstrap_admission_outcomes(
3941 &bootstrap_state,
3942 &batch_outcomes,
3943 &batch_discovered,
3944 )
3945 .await;
3946
3947 bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
3948 }
3949
3950 {
3952 let q = queues.read().await;
3953 if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
3954 complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3955 }
3956 }
3957
3958 info!("Bootstrap sync completed");
3959 });
3960 self.task_handles.push(handle);
3961 }
3962}
3963
3964#[cfg(feature = "logging")]
3969fn log_audit_responder_summary(
3970 metrics: &AuditResponderMetrics,
3971 semaphore: &Semaphore,
3972 window: Duration,
3973) {
3974 let snapshot = metrics.take_snapshot();
3975 if snapshot.origins.is_empty() {
3976 return;
3977 }
3978
3979 let total = snapshot.total;
3980 let [digest_received, subtree_received, byte_received, commitment_pin_received] =
3981 total.received_by_class;
3982 let global_inflight =
3983 MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
3984 info!(
3985 target: "ant_node::replication::audit_responder",
3986 window_ms = window.as_millis(),
3987 source_count = snapshot.origins.len(),
3988 received = total.received(),
3989 digest_received,
3990 subtree_received,
3991 byte_received,
3992 commitment_pin_received,
3993 admitted = total.admitted,
3994 global_pool_drops = total.global_pool_drops,
3995 per_peer_cap_drops = total.per_peer_cap_drops,
3996 serial_queue_drops = total.serial_queue_drops,
3997 completed = total.completed,
3998 send_failures = total.send_failures,
3999 processing_avg_ms = total.processing_avg_ms(),
4000 processing_max_ms = total.processing_max_ms,
4001 total_avg_ms = total.total_avg_ms(),
4002 total_max_ms = total.total_max_ms,
4003 global_inflight,
4004 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4005 peak_global_inflight = total.peak_global_inflight,
4006 "Audit responder summary"
4007 );
4008
4009 for (index, origin) in snapshot
4010 .origins
4011 .iter()
4012 .take(config::AUDIT_RESPONDER_TOP_ORIGINS)
4013 .enumerate()
4014 {
4015 let Some(source) = origin.source else {
4016 continue;
4017 };
4018 let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4019 origin.received_by_class;
4020 info!(
4021 target: "ant_node::replication::audit_responder",
4022 rank = index + 1,
4023 source = %source,
4024 received = origin.received(),
4025 digest_received,
4026 subtree_received,
4027 byte_received,
4028 commitment_pin_received,
4029 admitted = origin.admitted,
4030 global_pool_drops = origin.global_pool_drops,
4031 per_peer_cap_drops = origin.per_peer_cap_drops,
4032 serial_queue_drops = origin.serial_queue_drops,
4033 completed = origin.completed,
4034 send_failures = origin.send_failures,
4035 processing_avg_ms = origin.processing_avg_ms(),
4036 processing_max_ms = origin.processing_max_ms,
4037 total_avg_ms = origin.total_avg_ms(),
4038 total_max_ms = origin.total_max_ms,
4039 peak_global_inflight = origin.peak_global_inflight,
4040 peak_peer_inflight = origin.peak_peer_inflight,
4041 "Audit responder top origin"
4042 );
4043 }
4044}
4045
4046#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4061enum ResponderRejectReason {
4062 GlobalPoolFull,
4065 PerPeerCapFull,
4068}
4069
4070impl ResponderRejectReason {
4071 fn as_str(self) -> &'static str {
4074 match self {
4075 Self::GlobalPoolFull => "global_pool_full",
4076 Self::PerPeerCapFull => "per_peer_cap_full",
4077 }
4078 }
4079}
4080
4081impl From<ResponderRejectReason> for AuditResponderDropReason {
4082 fn from(reason: ResponderRejectReason) -> Self {
4083 match reason {
4084 ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
4085 ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
4086 }
4087 }
4088}
4089
4090impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
4091 fn from(reason: ResponderRejectReason) -> Self {
4092 match reason {
4093 ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
4094 ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
4095 }
4096 }
4097}
4098
4099#[must_use]
4114pub fn fresh_offer_admission_refusals() -> u64 {
4115 audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
4116}
4117
4118#[must_use]
4124pub fn paid_notify_admission_refusals() -> u64 {
4125 audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
4126}
4127
4128#[must_use]
4134pub fn fresh_offer_refusals_global_pool() -> u64 {
4135 audit_metrics::responder_admission_drops_by_ceiling(
4136 ReplicationResponderClass::FreshOffer,
4137 ResponderAdmissionCeiling::GlobalPool,
4138 )
4139}
4140
4141#[must_use]
4148pub fn fresh_offer_refusals_per_peer_share() -> u64 {
4149 audit_metrics::responder_admission_drops_by_ceiling(
4150 ReplicationResponderClass::FreshOffer,
4151 ResponderAdmissionCeiling::PerPeerShare,
4152 )
4153}
4154
4155#[derive(Debug, Clone, Copy)]
4163struct ResponderAdmissionFailure {
4164 reason: ResponderRejectReason,
4165 global_inflight: usize,
4167 global_limit: usize,
4169 peer_inflight: u32,
4171 peer_limit: u32,
4173}
4174
4175impl fmt::Display for ResponderAdmissionFailure {
4176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4179 write!(
4180 f,
4181 "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
4182 self.reason.as_str(),
4183 self.global_inflight,
4184 self.global_limit,
4185 self.peer_inflight,
4186 self.peer_limit,
4187 )
4188 }
4189}
4190
4191struct ResponderGuard {
4196 _permit: tokio::sync::OwnedSemaphorePermit,
4197 _peer_slot: PeerResponderSlot,
4198 global_inflight: usize,
4199 peer_inflight: u32,
4200}
4201
4202type AuditResponderGuard = ResponderGuard;
4203type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
4204
4205struct PeerResponderSlot {
4212 inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4213 peer: PeerId,
4214}
4215
4216#[derive(Clone)]
4217struct ReplicationMessageHandlerContext {
4218 p2p_node: Arc<P2PNode>,
4219 storage: Arc<LmdbStorage>,
4220 paid_list: Arc<PaidList>,
4221 payment_verifier: Arc<PaymentVerifier>,
4222 queues: Arc<RwLock<ReplicationQueues>>,
4223 config: Arc<ReplicationConfig>,
4224 is_bootstrapping: Arc<RwLock<bool>>,
4225 bootstrap_state: Arc<RwLock<BootstrapState>>,
4226 sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4227 sync_cycle_epoch: Arc<RwLock<u64>>,
4228 repair_proofs: Arc<RwLock<RepairProofs>>,
4229 last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4230 ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
4231 sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
4232 my_commitment_state: Arc<ResponderCommitmentState>,
4233 gossip_audit: GossipAuditTrigger,
4234 audit_responder_semaphore: Arc<Semaphore>,
4235 audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4236 audit_responder_metrics: Arc<AuditResponderMetrics>,
4237 subtree_round1: SubtreeRound1Limiter,
4238 fetch_responder_worker_semaphore: Arc<Semaphore>,
4239 fetch_responder_admission_semaphore: Arc<Semaphore>,
4240 fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4241 verification_responder_worker_semaphore: Arc<Semaphore>,
4242 verification_responder_admission_semaphore: Arc<Semaphore>,
4243 verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4244 neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
4245 neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
4246 neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4247 fresh_offer_worker_semaphore: Arc<Semaphore>,
4248 fresh_offer_admission_semaphore: Arc<Semaphore>,
4249 fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4250 fresh_offer_in_flight: FreshOfferInFlight,
4251 paid_notify_worker_semaphore: Arc<Semaphore>,
4252 paid_notify_admission_semaphore: Arc<Semaphore>,
4253 paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4254 shutdown: CancellationToken,
4262 detached_task_tracker: TaskTracker,
4265}
4266
4267struct InboundReplicationMessage {
4268 source: PeerId,
4269 msg: ReplicationMessage,
4270 rr_message_id: Option<String>,
4271 received_at: Instant,
4272}
4273
4274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4275enum SerialQueueDropReason {
4276 Full,
4277 Closed,
4278}
4279
4280#[cfg(feature = "logging")]
4281impl SerialQueueDropReason {
4282 const fn as_str(self) -> &'static str {
4283 match self {
4284 Self::Full => "full",
4285 Self::Closed => "closed",
4286 }
4287 }
4288}
4289
4290#[derive(Debug, Clone, Copy)]
4291#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
4292struct SerialQueueDrop {
4293 source: PeerId,
4294 message_class: &'static str,
4295 audit_responder_class: Option<AuditResponderClass>,
4296 queue_depth: usize,
4297 reason: SerialQueueDropReason,
4298}
4299
4300fn try_enqueue_serial_message(
4301 sender: &mpsc::Sender<InboundReplicationMessage>,
4302 inbound: InboundReplicationMessage,
4303) -> std::result::Result<(), SerialQueueDrop> {
4304 let source = inbound.source;
4305 let message_class = replication_message_class(&inbound.msg.body);
4306 let audit_responder_class = audit_responder_class(&inbound.msg.body);
4307 let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
4308 sender.try_send(inbound).map_err(|error| {
4309 let (reason, dropped) = match error {
4310 mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
4311 mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
4312 };
4313 audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
4314 SerialQueueDrop {
4315 source,
4316 message_class,
4317 audit_responder_class,
4318 queue_depth,
4319 reason,
4320 }
4321 })
4322}
4323
4324const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
4325 match body {
4326 ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
4327 ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
4328 ReplicationMessageBody::PaidNotify(_) => "paid_notify",
4329 ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
4330 ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
4331 ReplicationMessageBody::VerificationRequest(_) => "verification_request",
4332 ReplicationMessageBody::VerificationResponse(_) => "verification_response",
4333 ReplicationMessageBody::FetchRequest(_) => "fetch_request",
4334 ReplicationMessageBody::FetchResponse(_) => "fetch_response",
4335 ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
4336 ReplicationMessageBody::AuditResponse(_) => "audit_response",
4337 ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
4338 ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
4339 ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
4340 ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
4341 ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
4342 ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
4343 }
4344}
4345
4346const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
4347 match body {
4348 ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
4349 ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
4350 ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
4351 ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
4352 _ => None,
4353 }
4354}
4355
4356impl AuditResponderClass {
4357 const fn per_peer_limit(self) -> u32 {
4358 match self {
4359 Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
4360 Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
4361 }
4362 }
4363}
4364
4365fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
4366 match error {
4367 RecvError::Lagged(missed) => {
4368 audit_metrics::record_replication_event_lagged(*missed);
4369 warn!(
4370 "Missed {missed} P2P events on replication branch (broadcast lag); \
4371 replication messages may have been dropped before dispatch"
4372 );
4373 ControlFlow::Continue(())
4374 }
4375 RecvError::Closed => {
4376 warn!("P2P event stream closed on replication branch; stopping message handler");
4379 ControlFlow::Break(())
4380 }
4381 }
4382}
4383
4384fn replication_payload_from_event(
4385 event: P2PEvent,
4386) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
4387 let P2PEvent::Message {
4388 topic,
4389 source: Some(source),
4390 data,
4391 ..
4392 } = event
4393 else {
4394 return None;
4395 };
4396
4397 let (matched_id, is_rr) = match_replication_protocol(&topic)?;
4398 if !is_rr {
4399 return Some((source, data, matched_id, None));
4400 }
4401 if is_rr {
4402 return P2PNode::parse_request_envelope(&data)
4403 .filter(|(_, is_resp, _)| !is_resp)
4404 .map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
4405 }
4406 None
4407}
4408
4409impl Drop for PeerResponderSlot {
4410 fn drop(&mut self) {
4411 let peer = self.peer;
4420 if let Ok(mut map) = self.inflight.try_write() {
4421 if let Some(n) = map.get_mut(&peer) {
4422 *n = n.saturating_sub(1);
4423 if *n == 0 {
4424 map.remove(&peer);
4425 }
4426 }
4427 return;
4428 }
4429 if let Ok(handle) = tokio::runtime::Handle::try_current() {
4430 let inflight = Arc::clone(&self.inflight);
4431 handle.spawn(async move {
4432 let mut map = inflight.write().await;
4433 if let Some(n) = map.get_mut(&peer) {
4434 *n = n.saturating_sub(1);
4435 if *n == 0 {
4436 map.remove(&peer);
4437 }
4438 }
4439 });
4440 }
4441 }
4442}
4443
4444async fn admit_bounded_responder(
4448 semaphore: &Arc<Semaphore>,
4449 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4450 source: &PeerId,
4451 global_limit: usize,
4452 peer_limit: u32,
4453) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
4454 let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
4455
4456 let admitted_peer_inflight = {
4457 let mut map = inflight.write().await;
4458 let entry = map.entry(*source).or_insert(0);
4459 if *entry >= peer_limit {
4460 let peer_inflight = *entry;
4461 drop(map);
4462 return Err(ResponderAdmissionFailure {
4463 reason: ResponderRejectReason::PerPeerCapFull,
4464 global_inflight: global_inflight(semaphore),
4465 global_limit,
4466 peer_inflight,
4467 peer_limit,
4468 });
4469 }
4470 *entry += 1;
4471 *entry
4472 };
4473
4474 let peer_slot = PeerResponderSlot {
4475 inflight: Arc::clone(inflight),
4476 peer: *source,
4477 };
4478 let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
4479 return Err(ResponderAdmissionFailure {
4480 reason: ResponderRejectReason::GlobalPoolFull,
4481 global_inflight: global_inflight(semaphore),
4482 global_limit,
4483 peer_inflight: admitted_peer_inflight.saturating_sub(1),
4484 peer_limit,
4485 });
4486 };
4487
4488 Ok(ResponderGuard {
4489 _permit: permit,
4490 _peer_slot: peer_slot,
4491 global_inflight: global_inflight(semaphore),
4492 peer_inflight: admitted_peer_inflight,
4493 })
4494}
4495
4496struct SubtreeSession {
4498 commitment_hash: [u8; 32],
4499 nonce: [u8; 32],
4500 inserted: Instant,
4501}
4502
4503struct Round1WorkBudget {
4523 balance: i64,
4525 last_refill: Instant,
4526}
4527
4528impl Round1WorkBudget {
4529 const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
4532 const NANOS_PER_SEC: i64 = 1_000_000_000;
4534
4535 fn new() -> Self {
4536 Self {
4537 balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
4538 last_refill: Instant::now(),
4539 }
4540 }
4541
4542 fn refill(&mut self, now: Instant) {
4544 let elapsed = now.saturating_duration_since(self.last_refill);
4545 self.last_refill = now;
4546 let whole_secs = i64::try_from(elapsed.as_secs())
4547 .unwrap_or(i64::MAX)
4548 .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
4549 let sub_sec = i64::from(elapsed.subsec_nanos())
4550 .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
4551 / Self::NANOS_PER_SEC;
4552 self.balance = self
4553 .balance
4554 .saturating_add(whole_secs.saturating_add(sub_sec))
4555 .min(SUBTREE_ROUND1_WORK_BURST_BYTES);
4556 }
4557
4558 fn has_budget(&mut self, now: Instant) -> bool {
4560 self.refill(now);
4561 self.balance > 0
4562 }
4563
4564 fn charge(&mut self, bytes: i64, now: Instant) {
4567 self.refill(now);
4568 self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
4569 }
4570}
4571
4572#[derive(Clone)]
4581struct SubtreeRound1Limiter {
4582 semaphore: Arc<Semaphore>,
4583 max_concurrent: usize,
4587 inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4588 cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4589 cooldown_interval: Duration,
4592 sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
4593 work: Arc<RwLock<Round1WorkBudget>>,
4595}
4596
4597impl SubtreeRound1Limiter {
4598 fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
4603 let max_concurrent = max_concurrent.max(1);
4604 Self {
4605 semaphore: Arc::new(Semaphore::new(max_concurrent)),
4606 max_concurrent,
4607 inflight: Arc::new(RwLock::new(HashMap::new())),
4608 cooldown: Arc::new(RwLock::new(HashMap::new())),
4609 cooldown_interval,
4610 sessions: Arc::new(RwLock::new(HashMap::new())),
4611 work: Arc::new(RwLock::new(Round1WorkBudget::new())),
4612 }
4613 }
4614
4615 async fn charge_work(&self, content_bytes: i64) {
4617 self.work
4618 .write()
4619 .await
4620 .charge(content_bytes, Instant::now());
4621 }
4622
4623 async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
4629 let guard = admit_bounded_responder(
4630 &self.semaphore,
4631 &self.inflight,
4632 source,
4633 self.max_concurrent,
4634 MAX_SUBTREE_ROUND1_PER_PEER,
4635 )
4636 .await
4637 .ok()?;
4638 if !self.work.write().await.has_budget(Instant::now()) {
4641 return None; }
4643 let now = Instant::now();
4644 let mut cooldown = self.cooldown.write().await;
4645 if let Some(&last) = cooldown.get(source) {
4646 if now.duration_since(last) < self.cooldown_interval {
4647 return None; }
4649 }
4650 cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
4653 if cooldown.len() >= MAX_SUBTREE_SESSIONS {
4654 if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
4655 cooldown.remove(&oldest);
4656 }
4657 }
4658 cooldown.insert(*source, now);
4659 Some(guard)
4660 }
4661
4662 async fn open_session(
4665 &self,
4666 source: PeerId,
4667 challenge_id: u64,
4668 commitment_hash: [u8; 32],
4669 nonce: [u8; 32],
4670 ) {
4671 let now = Instant::now();
4672 let mut sessions = self.sessions.write().await;
4673 sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
4674 if sessions.len() >= MAX_SUBTREE_SESSIONS {
4675 if let Some(oldest) = sessions
4676 .iter()
4677 .min_by_key(|(_, e)| e.inserted)
4678 .map(|(k, _)| *k)
4679 {
4680 sessions.remove(&oldest);
4681 }
4682 }
4683 sessions.insert(
4684 (source, challenge_id),
4685 SubtreeSession {
4686 commitment_hash,
4687 nonce,
4688 inserted: now,
4689 },
4690 );
4691 }
4692
4693 async fn consume_session(
4698 &self,
4699 source: &PeerId,
4700 challenge_id: u64,
4701 commitment_hash: &[u8; 32],
4702 nonce: &[u8; 32],
4703 ) -> bool {
4704 let mut sessions = self.sessions.write().await;
4705 let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
4706 Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
4707 && &e.commitment_hash == commitment_hash
4708 && &e.nonce == nonce
4709 });
4710 if matches {
4711 sessions.remove(&(*source, challenge_id));
4712 }
4713 matches
4714 }
4715}
4716
4717enum SliceAdmission {
4719 Admitted(AuditResponderGuard),
4722 Capacity(AuditResponderAdmissionFailure),
4724 NoSession,
4726}
4727
4728async fn admit_slice_challenge(
4751 semaphore: &Arc<Semaphore>,
4752 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4753 round1: &SubtreeRound1Limiter,
4754 source: &PeerId,
4755 challenge: &protocol::SubtreeSliceChallenge,
4756) -> SliceAdmission {
4757 let guard =
4758 match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
4759 Ok(guard) => guard,
4760 Err(failure) => return SliceAdmission::Capacity(failure),
4761 };
4762 if !round1
4763 .consume_session(
4764 source,
4765 challenge.challenge_id,
4766 &challenge.expected_commitment_hash,
4767 &challenge.nonce,
4768 )
4769 .await
4770 {
4771 drop(guard);
4774 return SliceAdmission::NoSession;
4775 }
4776 SliceAdmission::Admitted(guard)
4777}
4778
4779async fn admit_audit_responder(
4788 semaphore: &Arc<Semaphore>,
4789 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4790 source: &PeerId,
4791 class: AuditResponderClass,
4792) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
4793 let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
4794 let peer_limit = class.per_peer_limit();
4795 admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
4796}
4797
4798#[allow(clippy::too_many_lines)]
4804async fn handle_replication_message(
4805 source: &PeerId,
4806 msg: ReplicationMessage,
4807 ctx: &ReplicationMessageHandlerContext,
4808 received_at: Instant,
4809 rr_message_id: Option<&str>,
4810) -> Result<()> {
4811 match msg.body {
4812 ReplicationMessageBody::FreshReplicationOffer(offer) => {
4813 dispatch_fresh_offer(
4814 *source,
4815 offer,
4816 ctx,
4817 msg.request_id,
4818 received_at,
4819 rr_message_id,
4820 )
4821 .await
4822 }
4823 ReplicationMessageBody::PaidNotify(notify) => {
4824 dispatch_paid_notify(*source, notify, ctx, received_at).await
4825 }
4826 ReplicationMessageBody::NeighborSyncRequest(request) => {
4827 let bootstrapping = *ctx.is_bootstrapping.read().await;
4828 if let Some(target) = ingest_peer_commitment(
4833 source,
4834 request.commitment.as_ref(),
4835 &ctx.p2p_node,
4836 &ctx.last_commitment_by_peer,
4837 &ctx.ever_capable_peers,
4838 &ctx.sig_verify_attempts,
4839 )
4840 .await
4841 {
4842 maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
4843 }
4844 dispatch_neighbor_sync_request(
4845 *source,
4846 request,
4847 ctx,
4848 bootstrapping,
4849 ctx.my_commitment_state
4852 .current_for_gossip()
4853 .map(|b| b.commitment().clone()),
4854 msg.request_id,
4855 received_at,
4856 rr_message_id,
4857 )
4858 .await
4859 }
4860 ReplicationMessageBody::VerificationRequest(request) => {
4861 dispatch_verification_request(
4862 *source,
4863 request,
4864 ctx,
4865 msg.request_id,
4866 received_at,
4867 rr_message_id,
4868 )
4869 .await
4870 }
4871 ReplicationMessageBody::FetchRequest(request) => {
4872 dispatch_fetch_request(
4873 *source,
4874 request,
4875 ctx,
4876 msg.request_id,
4877 received_at,
4878 rr_message_id,
4879 )
4880 .await
4881 }
4882 ReplicationMessageBody::AuditChallenge(challenge) => {
4883 let class = AuditResponderClass::Digest;
4898 let guard = match admit_audit_responder(
4899 &ctx.audit_responder_semaphore,
4900 &ctx.audit_responder_inflight,
4901 source,
4902 class,
4903 )
4904 .await
4905 {
4906 Ok(guard) => guard,
4907 Err(failure) => {
4908 protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
4909 audit_metrics::record_admission_drop(class);
4910 ctx.audit_responder_metrics
4911 .record_drop(*source, failure.reason.into());
4912 warn!(
4913 target: "ant_node::replication::audit_responder",
4914 event = "admission_dropped",
4915 kind = "responsible",
4916 responder_class = class.as_str(),
4917 source = %source,
4918 challenge_id = challenge.challenge_id,
4919 key_count = challenge.keys.len(),
4920 request_response = rr_message_id.is_some(),
4921 dispatch_ms = received_at.elapsed().as_millis(),
4922 reason = failure.reason.as_str(),
4923 global_inflight = failure.global_inflight,
4924 global_limit = failure.global_limit,
4925 peer_inflight = failure.peer_inflight,
4926 peer_limit = failure.peer_limit,
4927 "Audit responder admission dropped"
4928 );
4929 return Ok(());
4930 }
4931 };
4932 let admission_global_inflight = guard.global_inflight;
4933 let admission_peer_inflight = guard.peer_inflight;
4934 ctx.audit_responder_metrics.record_admitted(
4935 *source,
4936 admission_global_inflight,
4937 admission_peer_inflight,
4938 );
4939 info!(
4940 target: "ant_node::replication::audit_responder",
4941 event = "admitted",
4942 kind = "responsible",
4943 responder_class = class.as_str(),
4944 source = %source,
4945 challenge_id = challenge.challenge_id,
4946 key_count = challenge.keys.len(),
4947 request_response = rr_message_id.is_some(),
4948 dispatch_ms = received_at.elapsed().as_millis(),
4949 global_inflight = admission_global_inflight,
4950 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4951 peer_inflight = admission_peer_inflight,
4952 peer_limit = class.per_peer_limit(),
4953 "Audit responder request admitted"
4954 );
4955 let bootstrapping = *ctx.is_bootstrapping.read().await;
4956 let dispatch_latency = received_at.elapsed();
4957 audit_metrics::record_digest_dispatch_latency(dispatch_latency);
4958 debug!(
4959 audit_type = "digest_responder",
4960 dispatch_latency_ms = dispatch_latency.as_millis(),
4961 source = %source,
4962 "Audit challenge dispatch latency measured"
4963 );
4964 let storage = Arc::clone(&ctx.storage);
4965 let p2p_node = Arc::clone(&ctx.p2p_node);
4966 let source = *source;
4967 let request_id = msg.request_id;
4968 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
4969 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
4970 ctx.detached_task_tracker.spawn(async move {
4971 let _guard = guard; let worker_started = Instant::now();
4973 match handle_audit_challenge_msg(
4974 &source,
4975 &challenge,
4976 &storage,
4977 &p2p_node,
4978 bootstrapping,
4979 ReplyRoute {
4980 request_id,
4981 rr_message_id: rr_message_id.as_deref(),
4982 protocol: REPLICATION_PROTOCOL_ID,
4983 },
4984 )
4985 .await
4986 {
4987 Ok(completion) => log_audit_responder_completion(
4988 &responder_metrics,
4989 source,
4990 class,
4991 "responsible",
4992 challenge.challenge_id,
4993 challenge.keys.len(),
4994 completion.response_kind,
4995 completion.sent,
4996 received_at,
4997 worker_started,
4998 completion.processing,
4999 completion.response_send,
5000 ),
5001 Err(e) => debug!("Audit challenge from {source} error: {e}"),
5002 }
5003 });
5004 Ok(())
5005 }
5006 ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
5007 let class = AuditResponderClass::Subtree;
5020 info!(
5021 "Audit challenge received: kind=subtree source={source} request_response={}",
5022 rr_message_id.is_some(),
5023 );
5024 let Some(guard) = ctx.subtree_round1.admit(source).await else {
5029 protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5030 warn!(
5031 target: "ant_node::replication::audit_responder",
5032 event = "admission_dropped",
5033 kind = "subtree",
5034 responder_class = class.as_str(),
5035 source = %source,
5036 challenge_id = challenge.challenge_id,
5037 request_response = rr_message_id.is_some(),
5038 dispatch_ms = received_at.elapsed().as_millis(),
5039 reason = "heavy_pool_cooldown_or_work_budget",
5040 "Audit responder admission dropped"
5041 );
5042 return Ok(());
5043 };
5044 let admission_global_inflight = guard.global_inflight;
5045 let admission_peer_inflight = guard.peer_inflight;
5046 ctx.audit_responder_metrics.record_admitted(
5047 *source,
5048 admission_global_inflight,
5049 admission_peer_inflight,
5050 );
5051 info!(
5052 target: "ant_node::replication::audit_responder",
5053 event = "admitted",
5054 kind = "subtree",
5055 responder_class = class.as_str(),
5056 source = %source,
5057 challenge_id = challenge.challenge_id,
5058 request_response = rr_message_id.is_some(),
5059 dispatch_ms = received_at.elapsed().as_millis(),
5060 global_inflight = admission_global_inflight,
5061 global_limit = ctx.subtree_round1.max_concurrent,
5062 peer_inflight = admission_peer_inflight,
5063 peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
5064 "Audit responder request admitted"
5065 );
5066 let bootstrapping = *ctx.is_bootstrapping.read().await;
5067 let storage = Arc::clone(&ctx.storage);
5068 let p2p_node = Arc::clone(&ctx.p2p_node);
5069 let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5070 let source = *source;
5071 let request_id = msg.request_id;
5072 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5073 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5074 let subtree_round1 = ctx.subtree_round1.clone();
5075 ctx.detached_task_tracker.spawn(async move {
5076 let _guard = guard; let worker_started = Instant::now();
5078 let processing_started = Instant::now();
5079 let storage_commitment_audit::Round1Work {
5080 response,
5081 content_bytes,
5082 } = storage_commitment_audit::handle_subtree_challenge_measured(
5083 &challenge,
5084 &storage,
5085 p2p_node.peer_id(),
5086 bootstrapping,
5087 Some(&my_commitment_state),
5088 )
5089 .await;
5090 let processing = processing_started.elapsed();
5091 subtree_round1.charge_work(content_bytes).await;
5106 if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
5110 {
5111 subtree_round1
5112 .open_session(
5113 source,
5114 challenge.challenge_id,
5115 challenge.expected_commitment_hash,
5116 challenge.nonce,
5117 )
5118 .await;
5119 }
5120 let response_kind = subtree_audit_response_kind(&response);
5121 let work_items = subtree_audit_response_work_items(&response);
5122 let response_send_started = Instant::now();
5123 let sent = send_replication_response_checked(
5124 &source,
5125 &p2p_node,
5126 request_id,
5127 ReplicationMessageBody::SubtreeAuditResponse(response),
5128 rr_message_id.as_deref(),
5129 None,
5130 )
5131 .await;
5132 let response_send = response_send_started.elapsed();
5133 log_audit_responder_completion(
5134 &responder_metrics,
5135 source,
5136 class,
5137 "subtree",
5138 challenge.challenge_id,
5139 work_items,
5140 response_kind,
5141 sent,
5142 received_at,
5143 worker_started,
5144 processing,
5145 response_send,
5146 );
5147 });
5148 Ok(())
5149 }
5150 ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
5151 let class = AuditResponderClass::Byte;
5157 info!(
5158 "Audit challenge received: kind=slice source={source} request_response={}",
5159 rr_message_id.is_some(),
5160 );
5161 let guard = match admit_slice_challenge(
5162 &ctx.audit_responder_semaphore,
5163 &ctx.audit_responder_inflight,
5164 &ctx.subtree_round1,
5165 source,
5166 &challenge,
5167 )
5168 .await
5169 {
5170 SliceAdmission::Admitted(guard) => guard,
5171 SliceAdmission::Capacity(failure) => {
5172 protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5173 audit_metrics::record_admission_drop(class);
5174 ctx.audit_responder_metrics
5175 .record_drop(*source, failure.reason.into());
5176 warn!(
5177 target: "ant_node::replication::audit_responder",
5178 event = "admission_dropped",
5179 kind = "byte",
5180 responder_class = class.as_str(),
5181 source = %source,
5182 challenge_id = challenge.challenge_id,
5183 key_count = challenge.openings.len(),
5184 request_response = rr_message_id.is_some(),
5185 dispatch_ms = received_at.elapsed().as_millis(),
5186 reason = failure.reason.as_str(),
5187 global_inflight = failure.global_inflight,
5188 global_limit = failure.global_limit,
5189 peer_inflight = failure.peer_inflight,
5190 peer_limit = failure.peer_limit,
5191 "Audit responder admission dropped"
5192 );
5193 return Ok(());
5194 }
5195 SliceAdmission::NoSession => {
5205 protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5206 debug!(
5207 "Slice challenge without a live round-1 session source={source} \
5208 challenge_id={} → Transient reject",
5209 challenge.challenge_id
5210 );
5211 send_replication_response_checked(
5212 source,
5213 &ctx.p2p_node,
5214 msg.request_id,
5215 ReplicationMessageBody::SubtreeSliceResponse(
5216 protocol::SubtreeSliceResponse::Rejected {
5217 challenge_id: challenge.challenge_id,
5218 kind: protocol::RejectKind::Transient,
5219 reason: "no live round-1 session".to_string(),
5220 },
5221 ),
5222 rr_message_id,
5223 None,
5224 )
5225 .await;
5226 return Ok(());
5227 }
5228 };
5229 let admission_global_inflight = guard.global_inflight;
5230 let admission_peer_inflight = guard.peer_inflight;
5231 ctx.audit_responder_metrics.record_admitted(
5232 *source,
5233 admission_global_inflight,
5234 admission_peer_inflight,
5235 );
5236 info!(
5237 target: "ant_node::replication::audit_responder",
5238 event = "admitted",
5239 kind = "byte",
5240 responder_class = class.as_str(),
5241 source = %source,
5242 challenge_id = challenge.challenge_id,
5243 key_count = challenge.openings.len(),
5244 request_response = rr_message_id.is_some(),
5245 dispatch_ms = received_at.elapsed().as_millis(),
5246 global_inflight = admission_global_inflight,
5247 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5248 peer_inflight = admission_peer_inflight,
5249 peer_limit = class.per_peer_limit(),
5250 "Audit responder request admitted"
5251 );
5252 let bootstrapping = *ctx.is_bootstrapping.read().await;
5253 let storage = Arc::clone(&ctx.storage);
5254 let p2p_node = Arc::clone(&ctx.p2p_node);
5255 let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5256 let source = *source;
5257 let request_id = msg.request_id;
5258 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5259 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5260 ctx.detached_task_tracker.spawn(async move {
5261 let _guard = guard; let worker_started = Instant::now();
5263 let processing_started = Instant::now();
5264 let response = storage_commitment_audit::handle_subtree_slice_challenge(
5265 &challenge,
5266 &storage,
5267 p2p_node.peer_id(),
5268 bootstrapping,
5269 Some(&my_commitment_state),
5270 )
5271 .await;
5272 let processing = processing_started.elapsed();
5273 let response_kind = subtree_slice_response_kind(&response);
5274 let response_send_started = Instant::now();
5275 let sent = send_replication_response_checked(
5276 &source,
5277 &p2p_node,
5278 request_id,
5279 ReplicationMessageBody::SubtreeSliceResponse(response),
5280 rr_message_id.as_deref(),
5281 None,
5282 )
5283 .await;
5284 let response_send = response_send_started.elapsed();
5285 log_audit_responder_completion(
5286 &responder_metrics,
5287 source,
5288 class,
5289 "byte",
5290 challenge.challenge_id,
5291 challenge.openings.len(),
5292 response_kind,
5293 sent,
5294 received_at,
5295 worker_started,
5296 processing,
5297 response_send,
5298 );
5299 });
5300 Ok(())
5301 }
5302 ReplicationMessageBody::GetCommitmentByPin(ref request) => {
5303 let class = AuditResponderClass::CommitmentPin;
5315 let guard = match admit_audit_responder(
5316 &ctx.audit_responder_semaphore,
5317 &ctx.audit_responder_inflight,
5318 source,
5319 class,
5320 )
5321 .await
5322 {
5323 Ok(guard) => guard,
5324 Err(failure) => {
5325 audit_metrics::record_admission_drop(class);
5326 ctx.audit_responder_metrics
5327 .record_drop(*source, failure.reason.into());
5328 warn!(
5329 target: "ant_node::replication::audit_responder",
5330 event = "admission_dropped",
5331 kind = "commitment_pin",
5332 responder_class = class.as_str(),
5333 source = %source,
5334 challenge_id = msg.request_id,
5335 request_response = rr_message_id.is_some(),
5336 dispatch_ms = received_at.elapsed().as_millis(),
5337 reason = failure.reason.as_str(),
5338 global_inflight = failure.global_inflight,
5339 global_limit = failure.global_limit,
5340 peer_inflight = failure.peer_inflight,
5341 peer_limit = failure.peer_limit,
5342 "Audit responder admission dropped"
5343 );
5344 return Ok(());
5345 }
5346 };
5347 ctx.audit_responder_metrics.record_admitted(
5348 *source,
5349 guard.global_inflight,
5350 guard.peer_inflight,
5351 );
5352 info!(
5353 target: "ant_node::replication::audit_responder",
5354 event = "admitted",
5355 kind = "commitment_pin",
5356 responder_class = class.as_str(),
5357 source = %source,
5358 challenge_id = msg.request_id,
5359 request_response = rr_message_id.is_some(),
5360 dispatch_ms = received_at.elapsed().as_millis(),
5361 global_inflight = guard.global_inflight,
5362 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5363 peer_inflight = guard.peer_inflight,
5364 peer_limit = class.per_peer_limit(),
5365 "Audit responder request admitted"
5366 );
5367 let worker_started = Instant::now();
5368 let processing_started = Instant::now();
5369 let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
5370 protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
5371 |built| protocol::GetCommitmentByPinResponse::Found {
5372 commitment: built.commitment().clone(),
5373 },
5374 );
5375 let processing = processing_started.elapsed();
5376 let response_kind = commitment_pin_response_kind(&response);
5377 let response_send_started = Instant::now();
5378 let sent = send_replication_response_checked(
5379 source,
5380 &ctx.p2p_node,
5381 msg.request_id,
5382 ReplicationMessageBody::GetCommitmentByPinResponse(response),
5383 rr_message_id,
5384 None,
5385 )
5386 .await;
5387 let response_send = response_send_started.elapsed();
5388 log_audit_responder_completion(
5389 &ctx.audit_responder_metrics,
5390 *source,
5391 class,
5392 "commitment_pin",
5393 msg.request_id,
5394 1,
5395 response_kind,
5396 sent,
5397 received_at,
5398 worker_started,
5399 processing,
5400 response_send,
5401 );
5402 drop(guard);
5403 Ok(())
5404 }
5405 ReplicationMessageBody::FreshReplicationResponse(_)
5407 | ReplicationMessageBody::NeighborSyncResponse(_)
5408 | ReplicationMessageBody::VerificationResponse(_)
5409 | ReplicationMessageBody::FetchResponse(_)
5410 | ReplicationMessageBody::AuditResponse(_)
5411 | ReplicationMessageBody::SubtreeAuditResponse(_)
5412 | ReplicationMessageBody::SubtreeSliceResponse(_)
5413 | ReplicationMessageBody::GetCommitmentByPinResponse(_) => Ok(()),
5414 }
5415}
5416
5417async fn verify_payment_until_shutdown(
5437 payment_verifier: &Arc<PaymentVerifier>,
5438 key: &XorName,
5439 proof_of_payment: &[u8],
5440 context: VerificationContext,
5441 shutdown: &CancellationToken,
5442) -> Option<Result<crate::payment::PaymentStatus>> {
5443 tokio::select! {
5444 () = shutdown.cancelled() => None,
5445 result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
5446 Some(result)
5447 }
5448 }
5449}
5450
5451struct FreshOfferRejection {
5453 reason: String,
5455 penalise: bool,
5458}
5459
5460fn fresh_offer_structural_rejection(
5485 key: &XorName,
5486 data: &[u8],
5487 proof_of_payment: &[u8],
5488) -> Option<FreshOfferRejection> {
5489 if proof_of_payment.is_empty() {
5493 return Some(FreshOfferRejection {
5494 reason: "Missing proof of payment".to_string(),
5495 penalise: true,
5496 });
5497 }
5498
5499 if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
5508 return Some(FreshOfferRejection {
5509 reason: format!(
5510 "Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
5511 proof_of_payment.len(),
5512 ),
5513 penalise: true,
5514 });
5515 }
5516 if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
5517 return Some(FreshOfferRejection {
5518 reason: format!(
5519 "Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
5520 proof_of_payment.len(),
5521 ),
5522 penalise: true,
5523 });
5524 }
5525
5526 if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
5530 return Some(FreshOfferRejection {
5531 reason: format!(
5532 "Data size {} exceeds maximum chunk size {}",
5533 data.len(),
5534 crate::ant_protocol::MAX_CHUNK_SIZE,
5535 ),
5536 penalise: true,
5537 });
5538 }
5539
5540 let computed_key = crate::client::compute_address(data);
5553 if computed_key != *key {
5554 return Some(FreshOfferRejection {
5555 reason: format!(
5556 "Content address mismatch: expected {}, computed {}",
5557 hex::encode(key),
5558 hex::encode(computed_key),
5559 ),
5560 penalise: true,
5561 });
5562 }
5563
5564 None
5565}
5566
5567async fn refuse_fresh_offer(
5573 source: &PeerId,
5574 key: XorName,
5575 reason: String,
5576 ctx: &ReplicationMessageHandlerContext,
5577 request_id: u64,
5578 rr_message_id: Option<&str>,
5579) {
5580 send_replication_response(
5581 source,
5582 &ctx.p2p_node,
5583 request_id,
5584 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5585 key,
5586 reason,
5587 }),
5588 rr_message_id,
5589 )
5590 .await;
5591}
5592
5593async fn refuse_malformed_fresh_offer(
5599 source: &PeerId,
5600 key: XorName,
5601 rejection: FreshOfferRejection,
5602 ctx: &ReplicationMessageHandlerContext,
5603 request_id: u64,
5604 rr_message_id: Option<&str>,
5605) {
5606 if rejection.penalise {
5607 warn!(
5608 "Rejecting fresh offer for key {} from {source}: {}",
5609 hex::encode(key),
5610 rejection.reason
5611 );
5612 ctx.p2p_node
5613 .report_trust_event(
5614 source,
5615 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5616 )
5617 .await;
5618 } else {
5619 debug!(
5620 "Fresh offer for {} from {source} refused before admission: {}",
5621 hex::encode(key),
5622 rejection.reason
5623 );
5624 }
5625 refuse_fresh_offer(
5626 source,
5627 key,
5628 rejection.reason,
5629 ctx,
5630 request_id,
5631 rr_message_id,
5632 )
5633 .await;
5634}
5635
5636async fn refuse_stranded_fresh_offers(
5643 key: XorName,
5644 stranded: Vec<FreshOfferAttempt>,
5645 ctx: &ReplicationMessageHandlerContext,
5646) {
5647 for attempt in stranded {
5648 refuse_fresh_offer(
5649 &attempt.source,
5650 key,
5651 "Receiver at fresh-offer capacity".to_string(),
5652 ctx,
5653 attempt.request_id,
5654 attempt.rr_message_id.as_deref(),
5655 )
5656 .await;
5657 }
5658}
5659
5660async fn dispatch_fresh_offer(
5684 source: PeerId,
5685 offer: protocol::FreshReplicationOffer,
5686 ctx: &ReplicationMessageHandlerContext,
5687 request_id: u64,
5688 received_at: Instant,
5689 rr_message_id: Option<&str>,
5690) -> Result<()> {
5691 if let Some(rejection) =
5692 fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
5693 {
5694 refuse_malformed_fresh_offer(
5695 &source,
5696 offer.key,
5697 rejection,
5698 ctx,
5699 request_id,
5700 rr_message_id,
5701 )
5702 .await;
5703 return Ok(());
5704 }
5705
5706 let key = offer.key;
5716 let admission_outcome = FreshOfferEntryGuard::admit(
5717 &ctx.fresh_offer_in_flight,
5718 offer,
5719 source,
5720 request_id,
5721 rr_message_id.map(ToOwned::to_owned),
5722 received_at,
5723 );
5724 let mut entry = match admission_outcome {
5725 FreshOfferAdmission::Opened(entry) => entry,
5726 FreshOfferAdmission::Joined => {
5727 debug!(
5730 "Fresh offer for {} from {source} queued behind the handler already \
5731 holding the key",
5732 hex::encode(key)
5733 );
5734 return Ok(());
5735 }
5736 surplus => {
5739 debug!(
5740 "Fresh offer for {} from {source} refused: {}",
5741 hex::encode(key),
5742 surplus.surplus_reason()
5743 );
5744 refuse_fresh_offer(
5745 &source,
5746 key,
5747 "Duplicate offer already in flight".to_string(),
5748 ctx,
5749 request_id,
5750 rr_message_id,
5751 )
5752 .await;
5753 return Ok(());
5754 }
5755 };
5756
5757 let admission = match admit_bounded_responder(
5758 &ctx.fresh_offer_admission_semaphore,
5759 &ctx.fresh_offer_responder_inflight,
5760 &source,
5761 FRESH_OFFER_MAX_OUTSTANDING,
5762 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
5763 )
5764 .await
5765 {
5766 Ok(guard) => guard,
5767 Err(failure) => {
5768 audit_metrics::record_responder_admission_drop(
5769 ReplicationResponderClass::FreshOffer,
5770 failure.reason.into(),
5771 );
5772 warn!(
5779 responder_class = "fresh_offer",
5780 source = %source,
5781 key = %hex::encode(key),
5782 "Fresh offer refused at admission — this node will be penalised for the resulting absence: {failure}"
5783 );
5784 let stranded = entry.release();
5790 refuse_fresh_offer(
5791 &source,
5792 key,
5793 "Receiver at fresh-offer capacity".to_string(),
5794 ctx,
5795 request_id,
5796 rr_message_id,
5797 )
5798 .await;
5799 refuse_stranded_fresh_offers(key, stranded, ctx).await;
5800 return Ok(());
5801 }
5802 };
5803
5804 let ctx = ctx.clone();
5805 ctx.detached_task_tracker
5809 .clone()
5810 .spawn(run_fresh_offer_worker(key, entry, ctx, admission));
5811 Ok(())
5812}
5813
5814async fn run_fresh_offer_worker(
5830 key: XorName,
5831 mut entry: Box<FreshOfferEntryGuard>,
5832 ctx: ReplicationMessageHandlerContext,
5833 admission: ResponderGuard,
5834) {
5835 let _admission = admission;
5839 let received_at = entry.received_at();
5840 let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
5848 .acquire_owned()
5849 .await
5850 else {
5851 debug!(
5852 "Fresh offer for {} dropped: worker pool shut down",
5853 hex::encode(key)
5854 );
5855 return;
5856 };
5857 if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
5870 debug!(
5871 responder_class = "fresh_offer",
5872 key = %hex::encode(key),
5873 request_age_ms = received_at.elapsed().as_millis(),
5874 "Superseded fresh offer shed at dequeue"
5875 );
5876 return;
5877 }
5878
5879 let mut verdict = FreshOfferOutcome::Abandoned;
5880 while let Some(attempt) = entry.next_attempt() {
5881 match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
5882 Ok(outcome) => {
5883 verdict = outcome;
5884 match outcome {
5885 FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
5890 FreshOfferOutcome::ProofRejected => {}
5893 }
5894 }
5895 Err(e) => {
5896 debug!(
5897 "Fresh replication offer for {} from {} error: {e}",
5898 hex::encode(key),
5899 attempt.source
5900 );
5901 verdict = FreshOfferOutcome::Abandoned;
5902 break;
5903 }
5904 }
5905 }
5906
5907 let unreached = entry.release();
5911 if unreached.is_empty() {
5912 return;
5913 }
5914 let response = match verdict {
5915 FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
5916 FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
5917 FreshReplicationResponse::Rejected {
5918 key,
5919 reason: "Record could not be stored from any offered proof".to_string(),
5920 }
5921 }
5922 };
5923 for attempt in unreached {
5924 send_replication_response(
5925 &attempt.source,
5926 &ctx.p2p_node,
5927 attempt.request_id,
5928 ReplicationMessageBody::FreshReplicationResponse(response.clone()),
5929 attempt.rr_message_id.as_deref(),
5930 )
5931 .await;
5932 }
5933}
5934
5935#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5942enum FreshOfferOutcome {
5943 Settled,
5945 ProofRejected,
5948 Abandoned,
5951}
5952
5953#[allow(clippy::too_many_lines)]
5957async fn handle_fresh_offer(
5958 key: &XorName,
5959 data: &[u8],
5960 attempt: &FreshOfferAttempt,
5961 ctx: &ReplicationMessageHandlerContext,
5962) -> Result<FreshOfferOutcome> {
5963 let source = &attempt.source;
5964 let request_id = attempt.request_id;
5965 let rr_message_id = attempt.rr_message_id.as_deref();
5966 let p2p_node = &ctx.p2p_node;
5967 let config = &ctx.config;
5968 let self_id = *p2p_node.peer_id();
5969
5970 if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
5977 {
5978 if rejection.penalise {
5979 warn!(
5980 "Rejecting fresh offer for key {}: {}",
5981 hex::encode(key),
5982 rejection.reason
5983 );
5984 p2p_node
5985 .report_trust_event(
5986 source,
5987 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5988 )
5989 .await;
5990 }
5991 send_replication_response(
5992 source,
5993 p2p_node,
5994 request_id,
5995 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5996 key: *key,
5997 reason: rejection.reason,
5998 }),
5999 rr_message_id,
6000 )
6001 .await;
6002 return Ok(FreshOfferOutcome::ProofRejected);
6004 }
6005
6006 if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
6015 {
6016 send_replication_response(
6017 source,
6018 p2p_node,
6019 request_id,
6020 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6021 key: *key,
6022 reason: "Not in storage-admission range for this key".to_string(),
6023 }),
6024 rr_message_id,
6025 )
6026 .await;
6027 return Ok(FreshOfferOutcome::Abandoned);
6030 }
6031
6032 if let Err(e) = ctx.storage.check_capacity() {
6039 info!(
6040 target: "ant_node::storage::disk_precheck",
6041 key = %hex::encode(key),
6042 "Rejecting fresh replication offer before payment verification: {e}"
6043 );
6044 send_replication_response(
6045 source,
6046 p2p_node,
6047 request_id,
6048 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6049 key: *key,
6050 reason: e.to_string(),
6051 }),
6052 rr_message_id,
6053 )
6054 .await;
6055 return Ok(FreshOfferOutcome::Abandoned);
6057 }
6058
6059 let Some(verification) = verify_payment_until_shutdown(
6068 &ctx.payment_verifier,
6069 key,
6070 &attempt.proof_of_payment,
6071 fresh_offer_payment_context(),
6072 &ctx.shutdown,
6073 )
6074 .await
6075 else {
6076 debug!(
6077 "Fresh offer for {} from {source} abandoned: engine shutting down \
6078 during payment verification",
6079 hex::encode(key)
6080 );
6081 return Ok(FreshOfferOutcome::Abandoned);
6082 };
6083 match verification {
6084 Ok(status) if status.can_store() => {
6085 debug!("PoP validated for fresh offer key {}", hex::encode(key));
6086 }
6087 Ok(_) => {
6098 debug!(
6099 "Fresh offer for {} from {source}: no payment found for this proof",
6100 hex::encode(key)
6101 );
6102 send_replication_response(
6103 source,
6104 p2p_node,
6105 request_id,
6106 ReplicationMessageBody::FreshReplicationResponse(
6107 FreshReplicationResponse::Rejected {
6108 key: *key,
6109 reason: "Payment verification failed: payment required".to_string(),
6110 },
6111 ),
6112 rr_message_id,
6113 )
6114 .await;
6115 return Ok(FreshOfferOutcome::ProofRejected);
6116 }
6117 Err(e) => {
6122 warn!("PoP verification error for key {}: {e}", hex::encode(key));
6123 send_replication_response(
6124 source,
6125 p2p_node,
6126 request_id,
6127 ReplicationMessageBody::FreshReplicationResponse(
6128 FreshReplicationResponse::Rejected {
6129 key: *key,
6130 reason: format!("Payment verification error: {e}"),
6131 },
6132 ),
6133 rr_message_id,
6134 )
6135 .await;
6136 return Ok(FreshOfferOutcome::ProofRejected);
6137 }
6138 }
6139
6140 if let Err(e) = ctx.paid_list.insert(key).await {
6142 warn!("Failed to add key to PaidForList: {e}");
6143 }
6144
6145 match ctx.storage.put(key, data).await {
6147 Ok(_) => {
6148 send_replication_response(
6149 source,
6150 p2p_node,
6151 request_id,
6152 ReplicationMessageBody::FreshReplicationResponse(
6153 FreshReplicationResponse::Accepted { key: *key },
6154 ),
6155 rr_message_id,
6156 )
6157 .await;
6158 Ok(FreshOfferOutcome::Settled)
6159 }
6160 Err(e) => {
6161 send_replication_response(
6162 source,
6163 p2p_node,
6164 request_id,
6165 ReplicationMessageBody::FreshReplicationResponse(
6166 FreshReplicationResponse::Rejected {
6167 key: *key,
6168 reason: e.to_string(),
6169 },
6170 ),
6171 rr_message_id,
6172 )
6173 .await;
6174 Ok(FreshOfferOutcome::Abandoned)
6177 }
6178 }
6179}
6180
6181async fn dispatch_paid_notify(
6200 source: PeerId,
6201 notify: protocol::PaidNotify,
6202 ctx: &ReplicationMessageHandlerContext,
6203 received_at: Instant,
6204) -> Result<()> {
6205 let admission = match admit_bounded_responder(
6206 &ctx.paid_notify_admission_semaphore,
6207 &ctx.paid_notify_responder_inflight,
6208 &source,
6209 PAID_NOTIFY_MAX_OUTSTANDING,
6210 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
6211 )
6212 .await
6213 {
6214 Ok(guard) => guard,
6215 Err(failure) => {
6216 audit_metrics::record_responder_admission_drop(
6217 ReplicationResponderClass::PaidNotify,
6218 failure.reason.into(),
6219 );
6220 warn!(
6224 responder_class = "paid_notify",
6225 source = %source,
6226 key = %hex::encode(notify.key),
6227 "Paid notify dropped at admission — paid-list evidence lost until a verification cycle re-derives it: {failure}"
6228 );
6229 return Ok(());
6230 }
6231 };
6232
6233 let ctx = ctx.clone();
6234 let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
6235 let queue_max_age = ctx.config.neighbor_sync_interval_max;
6243 ctx.detached_task_tracker.clone().spawn(async move {
6244 let _admission = admission;
6245 let Ok(_worker) = worker_semaphore.acquire_owned().await else {
6248 debug!("Paid notify from {source} dropped: worker pool shut down");
6249 return;
6250 };
6251 if request_is_stale(received_at, queue_max_age) {
6252 debug!(
6253 responder_class = "paid_notify",
6254 source = %source,
6255 request_age_ms = received_at.elapsed().as_millis(),
6256 "Redundant paid notify shed at dequeue"
6257 );
6258 return;
6259 }
6260 if let Err(e) = handle_paid_notify(
6261 &source,
6262 ¬ify,
6263 &ctx.paid_list,
6264 &ctx.payment_verifier,
6265 &ctx.p2p_node,
6266 &ctx.config,
6267 &ctx.shutdown,
6268 )
6269 .await
6270 {
6271 debug!("Paid notify from {source} error: {e}");
6272 }
6273 });
6274
6275 Ok(())
6276}
6277
6278async fn handle_paid_notify(
6279 _source: &PeerId,
6280 notify: &protocol::PaidNotify,
6281 paid_list: &Arc<PaidList>,
6282 payment_verifier: &Arc<PaymentVerifier>,
6283 p2p_node: &Arc<P2PNode>,
6284 config: &ReplicationConfig,
6285 shutdown: &CancellationToken,
6286) -> Result<()> {
6287 let self_id = *p2p_node.peer_id();
6288
6289 if notify.proof_of_payment.is_empty() {
6291 return Ok(());
6292 }
6293
6294 if !admission::is_in_paid_close_group(
6296 &self_id,
6297 ¬ify.key,
6298 p2p_node,
6299 config.paid_list_close_group_size,
6300 )
6301 .await
6302 {
6303 return Ok(());
6304 }
6305
6306 let Some(verification) = verify_payment_until_shutdown(
6311 payment_verifier,
6312 ¬ify.key,
6313 ¬ify.proof_of_payment,
6314 paid_notify_payment_context(),
6315 shutdown,
6316 )
6317 .await
6318 else {
6319 debug!(
6320 "Paid notify for {} abandoned: engine shutting down during payment \
6321 verification",
6322 hex::encode(notify.key)
6323 );
6324 return Ok(());
6325 };
6326 match verification {
6327 Ok(status) if status.can_store() => {
6328 debug!(
6329 "PoP validated for paid notify key {}",
6330 hex::encode(notify.key)
6331 );
6332 }
6333 Ok(_) => {
6334 warn!(
6335 "Paid notify rejected: payment required for key {}",
6336 hex::encode(notify.key)
6337 );
6338 return Ok(());
6339 }
6340 Err(e) => {
6341 warn!(
6342 "PoP verification error for paid notify key {}: {e}",
6343 hex::encode(notify.key)
6344 );
6345 return Ok(());
6346 }
6347 }
6348
6349 if let Err(e) = paid_list.insert(¬ify.key).await {
6350 warn!("Failed to add paid notify key to PaidForList: {e}");
6351 }
6352
6353 Ok(())
6354}
6355
6356#[allow(clippy::too_many_arguments)]
6357async fn dispatch_neighbor_sync_request(
6358 source: PeerId,
6359 request: protocol::NeighborSyncRequest,
6360 ctx: &ReplicationMessageHandlerContext,
6361 is_bootstrapping: bool,
6362 my_commitment: Option<StorageCommitment>,
6363 request_id: u64,
6364 received_at: Instant,
6365 rr_message_id: Option<&str>,
6366) -> Result<()> {
6367 let guard = match admit_bounded_responder(
6368 &ctx.neighbor_sync_responder_admission_semaphore,
6369 &ctx.neighbor_sync_responder_inflight,
6370 &source,
6371 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
6372 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6373 )
6374 .await
6375 {
6376 Ok(guard) => guard,
6377 Err(failure) => {
6378 audit_metrics::record_responder_admission_drop(
6379 ReplicationResponderClass::NeighborSync,
6380 failure.reason.into(),
6381 );
6382 warn!(
6383 responder_class = "neighbor_sync",
6384 source = %source,
6385 "Neighbor-sync response dropped at admission: {failure}"
6386 );
6387 return Ok(());
6388 }
6389 };
6390
6391 let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
6392 let p2p_node = Arc::clone(&ctx.p2p_node);
6393 let storage = Arc::clone(&ctx.storage);
6394 let paid_list = Arc::clone(&ctx.paid_list);
6395 let queues = Arc::clone(&ctx.queues);
6396 let config = Arc::clone(&ctx.config);
6397 let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
6398 let sync_history = Arc::clone(&ctx.sync_history);
6399 let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
6400 let repair_proofs = Arc::clone(&ctx.repair_proofs);
6401 let request_timeout = ctx.config.verification_request_timeout;
6402 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6403 ctx.detached_task_tracker.spawn(async move {
6404 let _guard = guard;
6405 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6406 debug!(
6407 responder_class = "neighbor_sync",
6408 source = %source,
6409 "Neighbor-sync responder worker pool closed before dequeue"
6410 );
6411 return;
6412 };
6413 if request_is_stale(received_at, request_timeout) {
6414 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
6415 debug!(
6416 responder_class = "neighbor_sync",
6417 source = %source,
6418 request_age_ms = received_at.elapsed().as_millis(),
6419 "Stale neighbor-sync request shed at dequeue"
6420 );
6421 return;
6422 }
6423 if let Err(e) = handle_neighbor_sync_request(
6424 &source,
6425 &request,
6426 &p2p_node,
6427 &storage,
6428 &paid_list,
6429 &queues,
6430 &config,
6431 is_bootstrapping,
6432 &bootstrap_state,
6433 &sync_history,
6434 &sync_cycle_epoch,
6435 &repair_proofs,
6436 my_commitment,
6437 request_id,
6438 rr_message_id.as_deref(),
6439 )
6440 .await
6441 {
6442 debug!(source = %source, "Neighbor-sync request handling failed: {e}");
6443 }
6444 });
6445
6446 Ok(())
6447}
6448
6449#[allow(clippy::too_many_arguments)]
6450async fn handle_neighbor_sync_request(
6451 source: &PeerId,
6452 request: &protocol::NeighborSyncRequest,
6453 p2p_node: &Arc<P2PNode>,
6454 storage: &Arc<LmdbStorage>,
6455 paid_list: &Arc<PaidList>,
6456 queues: &Arc<RwLock<ReplicationQueues>>,
6457 config: &ReplicationConfig,
6458 is_bootstrapping: bool,
6459 bootstrap_state: &Arc<RwLock<BootstrapState>>,
6460 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
6461 sync_cycle_epoch: &Arc<RwLock<u64>>,
6462 repair_proofs: &Arc<RwLock<RepairProofs>>,
6463 my_commitment: Option<StorageCommitment>,
6464 request_id: u64,
6465 rr_message_id: Option<&str>,
6466) -> Result<()> {
6467 let self_id = *p2p_node.peer_id();
6468
6469 let (response, sent_replica_hints, sender_in_rt) =
6477 neighbor_sync::handle_sync_request_with_proofs(
6478 source,
6479 request,
6480 p2p_node,
6481 storage,
6482 paid_list,
6483 config,
6484 is_bootstrapping,
6485 my_commitment.clone(),
6486 )
6487 .await;
6488
6489 let response_sent = send_replication_response_checked(
6491 source,
6492 p2p_node,
6493 request_id,
6494 ReplicationMessageBody::NeighborSyncResponse(response),
6495 rr_message_id,
6496 None,
6497 )
6498 .await;
6499
6500 if !sender_in_rt {
6502 return Ok(());
6503 }
6504
6505 {
6508 let mut history = sync_history.write().await;
6509 let record = history.entry(*source).or_insert(PeerSyncRecord {
6510 last_sync: None,
6511 cycles_since_sync: 0,
6512 });
6513 record.last_sync = Some(Instant::now());
6514 record.cycles_since_sync = 0;
6515 }
6516
6517 if response_sent && !request.bootstrapping {
6518 record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
6519 .await;
6520 }
6521
6522 let outcome = admit_and_queue_hints(
6524 &self_id,
6525 source,
6526 &request.replica_hints,
6527 &request.paid_hints,
6528 p2p_node,
6529 config,
6530 storage,
6531 paid_list,
6532 queues,
6533 )
6534 .await;
6535
6536 if is_bootstrapping {
6541 let live_discovered = outcome.discovered.clone();
6542 let outcomes = [(*source, outcome)];
6543 publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
6544 }
6545
6546 Ok(())
6547}
6548
6549async fn handle_verification_request(
6550 source: &PeerId,
6551 request: &protocol::VerificationRequest,
6552 storage: &Arc<LmdbStorage>,
6553 paid_list: &Arc<PaidList>,
6554 p2p_node: &Arc<P2PNode>,
6555 request_id: u64,
6556 rr_message_id: Option<&str>,
6557) -> Result<()> {
6558 #[derive(Clone, Copy)]
6559 enum CachedPaidLookup {
6560 NotChecked,
6561 Checked(Option<bool>),
6562 }
6563
6564 #[derive(Clone, Copy)]
6565 struct CachedVerificationLookup {
6566 present: Option<bool>,
6567 paid: CachedPaidLookup,
6568 }
6569
6570 if verification_request_exceeds_limit(request.keys.len()) {
6571 warn!(
6572 "Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
6573 request.keys.len(),
6574 );
6575 send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6576 return Ok(());
6577 }
6578
6579 let requested_keys = request.keys.as_slice();
6580
6581 if request.paid_list_check_indices.len() > request.keys.len() {
6582 warn!(
6583 "Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
6584 request.paid_list_check_indices.len(),
6585 request.keys.len(),
6586 );
6587 send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6588 return Ok(());
6589 }
6590
6591 let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
6592 let paid_check_set: HashSet<u32> = request
6593 .paid_list_check_indices
6594 .iter()
6595 .copied()
6596 .filter(|&idx| {
6597 if idx >= keys_len {
6598 warn!(
6599 "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
6600 requested_keys.len(),
6601 );
6602 false
6603 } else {
6604 true
6605 }
6606 })
6607 .collect();
6608
6609 let mut results = Vec::with_capacity(requested_keys.len());
6610 let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
6611 for (i, key) in requested_keys.iter().enumerate() {
6612 let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
6613 let cached = lookup_cache.entry(*key).or_insert_with(|| {
6614 let present = match storage.exists(key) {
6615 Ok(present) => Some(present),
6616 Err(e) => {
6617 warn!(
6618 "Verification request from {source}: failed to check storage for {}: {e}",
6619 hex::encode(key)
6620 );
6621 None
6622 }
6623 };
6624 CachedVerificationLookup {
6625 present,
6626 paid: CachedPaidLookup::NotChecked,
6627 }
6628 });
6629
6630 if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
6631 cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
6632 Ok(paid) => Some(paid),
6633 Err(e) => {
6634 warn!(
6635 "Verification request from {source}: failed to check paid-list for {}: {e}",
6636 hex::encode(key)
6637 );
6638 None
6639 }
6640 });
6641 }
6642
6643 let paid = if needs_paid {
6644 match cached.paid {
6645 CachedPaidLookup::Checked(paid) => paid,
6646 CachedPaidLookup::NotChecked => None,
6647 }
6648 } else {
6649 None
6650 };
6651
6652 if cached.present.is_none() && paid.is_none() {
6653 continue;
6654 }
6655
6656 results.push(protocol::KeyVerificationResult {
6657 key: *key,
6658 present: cached.present.unwrap_or(false),
6659 paid,
6660 });
6661 }
6662
6663 send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
6664
6665 Ok(())
6666}
6667
6668async fn dispatch_verification_request(
6669 source: PeerId,
6670 request: protocol::VerificationRequest,
6671 ctx: &ReplicationMessageHandlerContext,
6672 request_id: u64,
6673 received_at: Instant,
6674 rr_message_id: Option<&str>,
6675) -> Result<()> {
6676 let guard = match admit_bounded_responder(
6677 &ctx.verification_responder_admission_semaphore,
6678 &ctx.verification_responder_inflight,
6679 &source,
6680 VERIFICATION_RESPONDER_MAX_OUTSTANDING,
6681 VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6682 )
6683 .await
6684 {
6685 Ok(guard) => guard,
6686 Err(failure) => {
6687 audit_metrics::record_responder_admission_drop(
6688 ReplicationResponderClass::Verification,
6689 failure.reason.into(),
6690 );
6691 warn!(
6692 responder_class = "verification",
6693 source = %source,
6694 "Verification response dropped at admission: {failure}"
6695 );
6696 return Ok(());
6697 }
6698 };
6699
6700 let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
6701 let storage = Arc::clone(&ctx.storage);
6702 let paid_list = Arc::clone(&ctx.paid_list);
6703 let p2p_node = Arc::clone(&ctx.p2p_node);
6704 let request_timeout = ctx.config.verification_request_timeout;
6705 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6706 ctx.detached_task_tracker.spawn(async move {
6707 let _guard = guard;
6708 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6709 debug!(
6710 responder_class = "verification",
6711 source = %source,
6712 "Verification responder worker pool closed before dequeue"
6713 );
6714 return;
6715 };
6716 if request_is_stale(received_at, request_timeout) {
6717 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
6718 debug!(
6719 responder_class = "verification",
6720 source = %source,
6721 request_age_ms = received_at.elapsed().as_millis(),
6722 "Stale verification request shed at dequeue"
6723 );
6724 return;
6725 }
6726 if let Err(e) = handle_verification_request(
6727 &source,
6728 &request,
6729 &storage,
6730 &paid_list,
6731 &p2p_node,
6732 request_id,
6733 rr_message_id.as_deref(),
6734 )
6735 .await
6736 {
6737 debug!(source = %source, "Verification request handling failed: {e}");
6738 }
6739 });
6740
6741 Ok(())
6742}
6743
6744const fn verification_request_exceeds_limit(key_count: usize) -> bool {
6745 key_count > MAX_INCOMING_VERIFICATION_KEYS
6746}
6747
6748async fn send_verification_results(
6749 source: &PeerId,
6750 p2p_node: &Arc<P2PNode>,
6751 request_id: u64,
6752 results: Vec<protocol::KeyVerificationResult>,
6753 rr_message_id: Option<&str>,
6754) {
6755 send_replication_response(
6756 source,
6757 p2p_node,
6758 request_id,
6759 ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
6760 rr_message_id,
6761 )
6762 .await;
6763}
6764
6765async fn dispatch_fetch_request(
6766 source: PeerId,
6767 request: protocol::FetchRequest,
6768 ctx: &ReplicationMessageHandlerContext,
6769 request_id: u64,
6770 received_at: Instant,
6771 rr_message_id: Option<&str>,
6772) -> Result<()> {
6773 let guard = match admit_bounded_responder(
6774 &ctx.fetch_responder_admission_semaphore,
6775 &ctx.fetch_responder_inflight,
6776 &source,
6777 FETCH_RESPONDER_MAX_OUTSTANDING,
6778 FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6779 )
6780 .await
6781 {
6782 Ok(guard) => guard,
6783 Err(failure) => {
6784 audit_metrics::record_responder_admission_drop(
6785 ReplicationResponderClass::Fetch,
6786 failure.reason.into(),
6787 );
6788 warn!(
6789 responder_class = "fetch",
6790 source = %source,
6791 "Fetch response dropped at admission: {failure}"
6792 );
6793 return Ok(());
6794 }
6795 };
6796
6797 let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
6798 let storage = Arc::clone(&ctx.storage);
6799 let p2p_node = Arc::clone(&ctx.p2p_node);
6800 let request_timeout = ctx.config.fetch_request_timeout;
6801 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6802 ctx.detached_task_tracker.spawn(async move {
6803 let _guard = guard;
6804 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6805 debug!(
6806 responder_class = "fetch",
6807 source = %source,
6808 "Fetch responder worker pool closed before dequeue"
6809 );
6810 return;
6811 };
6812 if request_is_stale(received_at, request_timeout) {
6813 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
6814 debug!(
6815 responder_class = "fetch",
6816 source = %source,
6817 request_age_ms = received_at.elapsed().as_millis(),
6818 "Stale fetch request shed at dequeue"
6819 );
6820 return;
6821 }
6822 if let Err(e) = handle_fetch_request(
6823 &source,
6824 &request,
6825 &storage,
6826 &p2p_node,
6827 request_id,
6828 rr_message_id.as_deref(),
6829 )
6830 .await
6831 {
6832 debug!(source = %source, "Fetch request handling failed: {e}");
6833 }
6834 });
6835
6836 Ok(())
6837}
6838
6839fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
6840 received_at.elapsed() >= timeout
6841}
6842
6843async fn handle_fetch_request(
6844 source: &PeerId,
6845 request: &protocol::FetchRequest,
6846 storage: &Arc<LmdbStorage>,
6847 p2p_node: &Arc<P2PNode>,
6848 request_id: u64,
6849 rr_message_id: Option<&str>,
6850) -> Result<()> {
6851 let response = match storage.get(&request.key).await {
6852 Ok(Some(data)) => protocol::FetchResponse::Success {
6853 key: request.key,
6854 data,
6855 },
6856 Ok(None) => protocol::FetchResponse::NotFound { key: request.key },
6857 Err(e) => protocol::FetchResponse::Error {
6858 key: request.key,
6859 reason: format!("{e}"),
6860 },
6861 };
6862
6863 send_replication_response(
6864 source,
6865 p2p_node,
6866 request_id,
6867 ReplicationMessageBody::FetchResponse(response),
6868 rr_message_id,
6869 )
6870 .await;
6871
6872 Ok(())
6873}
6874
6875struct AuditResponderCompletion {
6879 response_kind: &'static str,
6880 sent: bool,
6881 processing: Duration,
6882 response_send: Duration,
6883}
6884
6885async fn handle_audit_challenge_msg(
6886 source: &PeerId,
6887 challenge: &protocol::AuditChallenge,
6888 storage: &Arc<LmdbStorage>,
6889 p2p_node: &Arc<P2PNode>,
6890 is_bootstrapping: bool,
6891 reply: ReplyRoute<'_>,
6892) -> Result<AuditResponderCompletion> {
6893 #[allow(clippy::cast_possible_truncation)]
6894 let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
6895 info!(
6896 "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
6897 challenge.keys.len(),
6898 is_bootstrapping,
6899 reply.rr_message_id.is_some(),
6900 );
6901
6902 let processing_started = Instant::now();
6903 let response = audit::handle_audit_challenge(
6904 challenge,
6905 storage,
6906 p2p_node.peer_id(),
6907 is_bootstrapping,
6908 stored_chunks,
6909 )
6910 .await;
6911 let processing = processing_started.elapsed();
6912 let response_kind = audit_response_kind(&response);
6913
6914 let response_send_started = Instant::now();
6915 let sent = send_replication_response_checked(
6916 source,
6917 p2p_node,
6918 reply.request_id,
6919 ReplicationMessageBody::AuditResponse(response),
6920 reply.rr_message_id,
6921 Some(reply.protocol),
6922 )
6923 .await;
6924 let response_send = response_send_started.elapsed();
6925
6926 Ok(AuditResponderCompletion {
6927 response_kind,
6928 sent,
6929 processing,
6930 response_send,
6931 })
6932}
6933
6934#[allow(clippy::too_many_arguments)]
6935fn log_audit_responder_completion(
6936 metrics: &AuditResponderMetrics,
6937 source: PeerId,
6938 class: AuditResponderClass,
6939 kind: &'static str,
6940 challenge_id: u64,
6941 work_items: usize,
6942 response_kind: &'static str,
6943 sent: bool,
6944 received_at: Instant,
6945 worker_started: Instant,
6946 processing: Duration,
6947 response_send: Duration,
6948) {
6949 let dispatch = worker_started.saturating_duration_since(received_at);
6950 let total = received_at.elapsed();
6951 metrics.record_completed(source, processing, total, sent);
6952 if sent {
6953 info!(
6954 target: "ant_node::replication::audit_responder",
6955 event = "completed",
6956 kind,
6957 responder_class = class.as_str(),
6958 source = %source,
6959 challenge_id,
6960 work_items,
6961 response = response_kind,
6962 sent,
6963 dispatch_ms = dispatch.as_millis(),
6964 processing_ms = processing.as_millis(),
6965 response_send_ms = response_send.as_millis(),
6966 total_ms = total.as_millis(),
6967 "Audit responder request completed"
6968 );
6969 } else {
6970 warn!(
6971 target: "ant_node::replication::audit_responder",
6972 event = "completed",
6973 kind,
6974 responder_class = class.as_str(),
6975 source = %source,
6976 challenge_id,
6977 work_items,
6978 response = response_kind,
6979 sent,
6980 dispatch_ms = dispatch.as_millis(),
6981 processing_ms = processing.as_millis(),
6982 response_send_ms = response_send.as_millis(),
6983 total_ms = total.as_millis(),
6984 "Audit responder request completed without sending a reply"
6985 );
6986 }
6987}
6988
6989struct ReplyRoute<'a> {
6996 request_id: u64,
6998 rr_message_id: Option<&'a str>,
7001 protocol: &'static str,
7003}
7004
7005fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
7006 match response {
7007 protocol::AuditResponse::Digests { .. } => "digests",
7008 protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
7009 protocol::AuditResponse::Rejected { .. } => "rejected",
7010 }
7011}
7012
7013fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
7014 match response {
7015 protocol::SubtreeAuditResponse::Proof { .. } => "proof",
7016 protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
7017 protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
7018 }
7019}
7020
7021fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
7022 match response {
7023 protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
7024 protocol::SubtreeAuditResponse::Bootstrapping { .. }
7025 | protocol::SubtreeAuditResponse::Rejected { .. } => 0,
7026 }
7027}
7028
7029fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
7030 match response {
7031 protocol::SubtreeSliceResponse::Items { .. } => "items",
7032 protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
7033 protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
7034 }
7035}
7036
7037fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
7038 match response {
7039 protocol::GetCommitmentByPinResponse::Found { .. } => "found",
7040 protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
7041 }
7042}
7043
7044async fn send_replication_response(
7054 peer: &PeerId,
7055 p2p_node: &Arc<P2PNode>,
7056 request_id: u64,
7057 body: ReplicationMessageBody,
7058 rr_message_id: Option<&str>,
7059) {
7060 let _ =
7061 send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
7062 .await;
7063}
7064
7065async fn send_replication_response_checked(
7081 peer: &PeerId,
7082 p2p_node: &Arc<P2PNode>,
7083 request_id: u64,
7084 body: ReplicationMessageBody,
7085 rr_message_id: Option<&str>,
7086 protocol: Option<&'static str>,
7087) -> bool {
7088 let msg = ReplicationMessage { request_id, body };
7089 let encoded = match msg.encode() {
7090 Ok(data) => data,
7091 Err(e) => {
7092 warn!("Failed to encode replication response: {e}");
7093 return false;
7094 }
7095 };
7096 if matches!(
7102 msg.body,
7103 ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
7104 ) {
7105 protocol::record_served(peer, encoded.len());
7106 }
7107 let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
7108 let result = if let Some(msg_id) = rr_message_id {
7109 p2p_node
7110 .send_response(peer, protocol, msg_id, encoded)
7111 .await
7112 } else {
7113 p2p_node.send_message(peer, protocol, encoded, &[]).await
7114 };
7115 if let Err(e) = result {
7116 debug!("Failed to send replication response to {peer}: {e}");
7117 return false;
7118 }
7119 true
7120}
7121
7122async fn record_sent_replica_hints(
7123 peer: &PeerId,
7124 hints: &[neighbor_sync::SentReplicaHint],
7125 repair_proofs: &Arc<RwLock<RepairProofs>>,
7126 sync_cycle_epoch: &Arc<RwLock<u64>>,
7127) {
7128 if hints.is_empty() {
7129 return;
7130 }
7131
7132 let hinted_at_epoch = *sync_cycle_epoch.read().await;
7133 let mut proofs = repair_proofs.write().await;
7134 for hint in hints {
7135 if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
7136 debug!(
7137 "Recorded repair hint proof for peer {peer} and key {}",
7138 hex::encode(hint.key)
7139 );
7140 }
7141 }
7142}
7143
7144#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
7150async fn run_neighbor_sync_round(
7151 p2p_node: &Arc<P2PNode>,
7152 storage: &Arc<LmdbStorage>,
7153 paid_list: &Arc<PaidList>,
7154 queues: &Arc<RwLock<ReplicationQueues>>,
7155 config: &ReplicationConfig,
7156 sync_state: &Arc<RwLock<NeighborSyncState>>,
7157 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7158 sync_cycle_epoch: &Arc<RwLock<u64>>,
7159 repair_proofs: &Arc<RwLock<RepairProofs>>,
7160 is_bootstrapping: &Arc<RwLock<bool>>,
7161 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7162 commitment_state: &Arc<ResponderCommitmentState>,
7163 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7164 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7165 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7166 audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
7167 gossip_audit: &GossipAuditTrigger,
7168) {
7169 let self_id = *p2p_node.peer_id();
7170 let bootstrapping = *is_bootstrapping.read().await;
7171
7172 let cycle_complete = sync_state.read().await.is_cycle_complete();
7176 if cycle_complete {
7177 {
7181 let mut history = sync_history.write().await;
7182 for record in history.values_mut() {
7183 record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
7184 }
7185 }
7186 {
7187 let mut epoch = sync_cycle_epoch.write().await;
7188 *epoch = epoch.saturating_add(1);
7189 }
7190
7191 let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
7196 pruning::run_prune_pass_with_context(pruning::PrunePassContext {
7197 self_id: &self_id,
7198 storage,
7199 paid_list,
7200 p2p_node,
7201 config,
7202 sync_state,
7203 repair_proofs,
7204 allow_remote_prune_audits,
7205 commitment_state: Some(commitment_state),
7206 audit_challenge_coordinator,
7207 })
7208 .await;
7209
7210 let neighbors =
7212 neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
7213 .await;
7214
7215 let mut state = sync_state.write().await;
7217 if state.is_cycle_complete() {
7218 let old_sync_times = std::mem::take(&mut state.last_sync_times);
7222 let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
7223 let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
7224 let old_prune_cursor = state.prune_cursor;
7225 *state = NeighborSyncState::new_cycle(neighbors);
7226 state.last_sync_times = old_sync_times;
7227 state.bootstrap_claims = old_bootstrap_claims;
7228 state.bootstrap_claim_history = old_bootstrap_claim_history;
7229 state.prune_cursor = old_prune_cursor;
7230 }
7231 }
7232
7233 let batch = {
7235 let mut state = sync_state.write().await;
7236 neighbor_sync::select_sync_batch(
7237 &mut state,
7238 config.neighbor_sync_peer_count,
7239 config.neighbor_sync_cooldown,
7240 )
7241 };
7242
7243 if batch.is_empty() {
7244 return;
7245 }
7246
7247 debug!("Neighbor sync: syncing with {} peers", batch.len());
7248
7249 let my_commitment = commitment_state
7255 .current_for_gossip()
7256 .map(|b| b.commitment().clone());
7257
7258 let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
7259 &batch,
7260 storage,
7261 paid_list,
7262 p2p_node,
7263 config.close_group_size,
7264 config.paid_list_close_group_size,
7265 )
7266 .await;
7267
7268 for peer in &batch {
7270 let hints = hints_by_peer.remove(peer).unwrap_or_default();
7271 let outcome = neighbor_sync::sync_with_peer_with_hints(
7272 peer,
7273 p2p_node,
7274 config,
7275 bootstrapping,
7276 hints,
7277 my_commitment.clone(),
7278 )
7279 .await;
7280
7281 if let Some(outcome) = outcome {
7282 handle_sync_response(
7283 &self_id,
7284 peer,
7285 &outcome.response,
7286 &outcome.sent_replica_hints,
7287 p2p_node,
7288 config,
7289 bootstrapping,
7290 bootstrap_state,
7291 storage,
7292 paid_list,
7293 queues,
7294 sync_state,
7295 sync_history,
7296 sync_cycle_epoch,
7297 repair_proofs,
7298 last_commitment_by_peer,
7299 ever_capable_peers,
7300 sig_verify_attempts,
7301 gossip_audit,
7302 )
7303 .await;
7304 } else {
7305 let replacement = {
7307 let mut state = sync_state.write().await;
7308 neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
7309 };
7310
7311 if let Some(replacement_peer) = replacement {
7313 let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
7314 std::slice::from_ref(&replacement_peer),
7315 storage,
7316 paid_list,
7317 p2p_node,
7318 config.close_group_size,
7319 config.paid_list_close_group_size,
7320 )
7321 .await;
7322 let hints = replacement_hints
7323 .remove(&replacement_peer)
7324 .unwrap_or_default();
7325 let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
7326 &replacement_peer,
7327 p2p_node,
7328 config,
7329 bootstrapping,
7330 hints,
7331 my_commitment.clone(),
7332 )
7333 .await;
7334
7335 if let Some(outcome) = replacement_outcome {
7336 handle_sync_response(
7337 &self_id,
7338 &replacement_peer,
7339 &outcome.response,
7340 &outcome.sent_replica_hints,
7341 p2p_node,
7342 config,
7343 bootstrapping,
7344 bootstrap_state,
7345 storage,
7346 paid_list,
7347 queues,
7348 sync_state,
7349 sync_history,
7350 sync_cycle_epoch,
7351 repair_proofs,
7352 last_commitment_by_peer,
7353 ever_capable_peers,
7354 sig_verify_attempts,
7355 gossip_audit,
7356 )
7357 .await;
7358 }
7359 }
7360 }
7361 }
7362}
7363
7364#[allow(clippy::too_many_arguments)]
7367async fn handle_sync_response(
7368 self_id: &PeerId,
7369 peer: &PeerId,
7370 resp: &NeighborSyncResponse,
7371 sent_replica_hints: &[neighbor_sync::SentReplicaHint],
7372 p2p_node: &Arc<P2PNode>,
7373 config: &ReplicationConfig,
7374 bootstrapping: bool,
7375 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7376 storage: &Arc<LmdbStorage>,
7377 paid_list: &Arc<PaidList>,
7378 queues: &Arc<RwLock<ReplicationQueues>>,
7379 sync_state: &Arc<RwLock<NeighborSyncState>>,
7380 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7381 sync_cycle_epoch: &Arc<RwLock<u64>>,
7382 repair_proofs: &Arc<RwLock<RepairProofs>>,
7383 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7384 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7385 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7386 gossip_audit: &GossipAuditTrigger,
7387) {
7388 if let Some(target) = ingest_peer_commitment(
7394 peer,
7395 resp.commitment.as_ref(),
7396 p2p_node,
7397 last_commitment_by_peer,
7398 ever_capable_peers,
7399 sig_verify_attempts,
7400 )
7401 .await
7402 {
7403 maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
7404 }
7405
7406 {
7408 let mut state = sync_state.write().await;
7409 neighbor_sync::record_successful_sync(&mut state, peer);
7410 }
7411 {
7412 let mut history = sync_history.write().await;
7413 let record = history.entry(*peer).or_insert(PeerSyncRecord {
7414 last_sync: None,
7415 cycles_since_sync: 0,
7416 });
7417 record.last_sync = Some(Instant::now());
7418 record.cycles_since_sync = 0;
7419 }
7420
7421 if resp.bootstrapping {
7423 let should_report = {
7427 let now = Instant::now();
7428 let mut state = sync_state.write().await;
7429 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
7430 BootstrapClaimObservation::WithinGrace { .. } => false,
7431 BootstrapClaimObservation::PastGrace { first_seen } => {
7432 warn!(
7433 "Peer {peer} has been claiming bootstrap for {:?}, \
7434 exceeding grace period of {:?} — reporting abuse",
7435 now.duration_since(first_seen),
7436 config.bootstrap_claim_grace_period,
7437 );
7438 true
7439 }
7440 BootstrapClaimObservation::Repeated { first_seen } => {
7441 warn!(
7442 "Peer {peer} repeated bootstrap claim after previously stopping; \
7443 first claim was {:?} ago — reporting abuse",
7444 now.duration_since(first_seen),
7445 );
7446 true
7447 }
7448 }
7449 };
7450 if should_report {
7451 p2p_node
7452 .report_trust_event(
7453 peer,
7454 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7455 )
7456 .await;
7457 }
7458 } else {
7459 {
7462 let mut state = sync_state.write().await;
7463 state.clear_active_bootstrap_claim(peer);
7464 }
7465 record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
7466 let outcome = admit_and_queue_hints(
7467 self_id,
7468 peer,
7469 &resp.replica_hints,
7470 &resp.paid_hints,
7471 p2p_node,
7472 config,
7473 storage,
7474 paid_list,
7475 queues,
7476 )
7477 .await;
7478
7479 if bootstrapping {
7484 let live_discovered = outcome.discovered.clone();
7485 let outcomes = [(*peer, outcome)];
7486 publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
7487 .await;
7488 }
7489 }
7490}
7491
7492#[allow(clippy::too_many_arguments)]
7497struct AdmissionOutcome {
7505 discovered: HashSet<XorName>,
7506 capacity_rejected_count: usize,
7507 displaced: Vec<CapacityDisplacement>,
7508}
7509
7510async fn publish_bootstrap_admission_outcomes(
7521 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7522 outcomes: &[(PeerId, AdmissionOutcome)],
7523 live_discovered: &HashSet<XorName>,
7524) {
7525 let mut rejected_sources = HashSet::new();
7526 let mut clean_sources = HashSet::new();
7527 let mut displaced_keys = HashSet::new();
7528
7529 for (source, outcome) in outcomes {
7530 if outcome.capacity_rejected_count > 0 {
7531 rejected_sources.insert(*source);
7532 } else {
7533 clean_sources.insert(*source);
7534 }
7535 for displacement in &outcome.displaced {
7543 displaced_keys.insert(displacement.key);
7544 }
7545 }
7546 clean_sources.retain(|source| !rejected_sources.contains(source));
7547
7548 let now = Instant::now();
7549 let mut state = bootstrap_state.write().await;
7550 for key in displaced_keys {
7551 state.remove_key(&key);
7552 }
7553 state.pending_keys.extend(live_discovered);
7554 for source in clean_sources {
7555 state.capacity_rejected_sources.remove(&source);
7556 }
7557 for source in rejected_sources {
7558 state.note_capacity_rejected(source, now);
7561 }
7562}
7563
7564#[allow(clippy::too_many_arguments)]
7565async fn admit_and_queue_hints(
7566 self_id: &PeerId,
7567 source_peer: &PeerId,
7568 replica_hints: &[XorName],
7569 paid_hints: &[XorName],
7570 p2p_node: &Arc<P2PNode>,
7571 config: &ReplicationConfig,
7572 storage: &Arc<LmdbStorage>,
7573 paid_list: &Arc<PaidList>,
7574 queues: &Arc<RwLock<ReplicationQueues>>,
7575) -> AdmissionOutcome {
7576 let pending_keys: HashSet<XorName> = {
7577 let q = queues.read().await;
7578 q.pending_keys().into_iter().collect()
7579 };
7580
7581 let admitted = admission::admit_hints(
7582 self_id,
7583 replica_hints,
7584 paid_hints,
7585 p2p_node,
7586 config,
7587 storage,
7588 paid_list,
7589 &pending_keys,
7590 )
7591 .await;
7592
7593 let mut q = queues.write().await;
7594 queue_admitted_hints(source_peer, admitted, storage, &mut q)
7595}
7596
7597fn queue_admitted_hints(
7598 source_peer: &PeerId,
7599 admitted: admission::AdmissionResult,
7600 storage: &LmdbStorage,
7601 q: &mut ReplicationQueues,
7602) -> AdmissionOutcome {
7603 let mut discovered = HashSet::new();
7604 let mut capacity_rejected_count: usize = 0;
7605 let mut displaced = Vec::new();
7606 let now = Instant::now();
7607
7608 for key in admitted.replica_keys {
7609 if !storage.exists(&key).unwrap_or(false) {
7610 let result = q.add_pending_verify(
7611 key,
7612 VerificationEntry {
7613 state: VerificationState::PendingVerify,
7614 verified_sources: Vec::new(),
7615 tried_sources: HashSet::new(),
7616 created_at: now,
7617 next_verify_at: now,
7618 hint_sources: HashSet::from([*source_peer]),
7619 replica_hint_sources: HashSet::from([*source_peer]),
7622 },
7623 );
7624 match result {
7625 crate::replication::scheduling::AdmissionResult::Admitted => {
7626 discovered.insert(key);
7627 }
7628 crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7629 crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7630 capacity_rejected_count += 1;
7631 }
7632 }
7633 }
7634 }
7635
7636 for key in admitted.paid_only_keys {
7637 let result = q.add_pending_verify(
7638 key,
7639 VerificationEntry {
7640 state: VerificationState::PendingVerify,
7641 verified_sources: Vec::new(),
7642 tried_sources: HashSet::new(),
7643 created_at: now,
7644 next_verify_at: now,
7645 hint_sources: HashSet::from([*source_peer]),
7646 replica_hint_sources: HashSet::new(),
7649 },
7650 );
7651 match result {
7652 crate::replication::scheduling::AdmissionResult::Admitted => {
7653 discovered.insert(key);
7654 }
7655 crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7656 crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7657 capacity_rejected_count += 1;
7658 }
7659 }
7660 }
7661
7662 if capacity_rejected_count > 0 {
7663 debug!(
7664 "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
7665 rejected at queue capacity; source will need to re-hint after pending_verify drains"
7666 );
7667 }
7668
7669 displaced.extend(q.take_capacity_displacements());
7670
7671 AdmissionOutcome {
7672 discovered,
7673 capacity_rejected_count,
7674 displaced,
7675 }
7676}
7677
7678#[allow(clippy::too_many_lines)]
7684async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
7685 let cycle_started = Instant::now();
7686 let VerificationCycleContext {
7687 p2p_node,
7688 paid_list,
7689 storage,
7690 queues,
7691 config,
7692 bootstrap_state,
7693 is_bootstrapping,
7694 bootstrap_complete_notify,
7695 last_commitment_by_peer,
7696 ever_capable_peers,
7697 recent_provers,
7698 } = ctx;
7699
7700 expire_and_recheck_bootstrap_drain(
7705 bootstrap_state,
7706 queues,
7707 is_bootstrapping,
7708 bootstrap_complete_notify,
7709 config.capacity_rejected_max_age(),
7710 )
7711 .await;
7712
7713 if bootstrap_state.read().await.pending_peer_requests > 0 {
7717 return;
7718 }
7719
7720 let stale_pending_keys = {
7723 let mut q = queues.write().await;
7724 q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
7725 };
7726 if !stale_pending_keys.is_empty() {
7727 update_bootstrap_after_verification(
7728 &stale_pending_keys,
7729 bootstrap_state,
7730 queues,
7731 is_bootstrapping,
7732 bootstrap_complete_notify,
7733 )
7734 .await;
7735 }
7736
7737 let pending_keys = {
7738 let mut q = queues.write().await;
7739 if bootstrap_state.read().await.pending_peer_requests > 0 {
7745 return;
7746 }
7747 q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
7748 };
7749
7750 if pending_keys.is_empty() {
7751 return;
7752 }
7753 let initial_pending_count = pending_keys.len();
7754
7755 let self_id = *p2p_node.peer_id();
7756
7757 let mut local_paid_keys = Vec::new();
7762 let mut keys_needing_network = Vec::new();
7763 let mut terminal_keys: Vec<XorName> = Vec::new();
7764 {
7765 let mut q = queues.write().await;
7766 for key in &pending_keys {
7767 if paid_list.contains(key).unwrap_or(false) {
7768 if q.set_pending_state(key, VerificationState::PaidListVerified) {
7769 local_paid_keys.push(*key);
7770 }
7771 } else {
7772 keys_needing_network.push(*key);
7773 }
7774 }
7775 }
7776
7777 let mut local_paid_presence_probe_keys = Vec::new();
7783 if !local_paid_keys.is_empty() {
7784 let mut terminal_paid = Vec::new();
7785 for key in local_paid_keys {
7786 if storage.exists(&key).unwrap_or(false) {
7787 terminal_paid.push(key);
7788 } else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
7789 local_paid_presence_probe_keys.push(key);
7793 } else {
7794 terminal_paid.push(key);
7795 }
7796 }
7797
7798 if !terminal_paid.is_empty() {
7799 let mut q = queues.write().await;
7800 for key in terminal_paid {
7801 q.remove_pending(&key);
7802 terminal_keys.push(key);
7803 }
7804 }
7805 }
7806
7807 let local_paid_probe_count = local_paid_presence_probe_keys.len();
7808 let keys_needing_network_count = keys_needing_network.len();
7809
7810 if !local_paid_presence_probe_keys.is_empty() {
7814 let targets = quorum::compute_presence_targets(
7815 &local_paid_presence_probe_keys,
7816 p2p_node,
7817 config,
7818 &self_id,
7819 )
7820 .await;
7821 let evidence = quorum::run_verification_round(
7822 &local_paid_presence_probe_keys,
7823 &targets,
7824 p2p_node,
7825 config,
7826 )
7827 .await;
7828
7829 let mut q = queues.write().await;
7830 for key in local_paid_presence_probe_keys {
7831 if storage.exists(&key).unwrap_or(false) {
7832 q.remove_pending(&key);
7833 terminal_keys.push(key);
7834 continue;
7835 }
7836 let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
7837 quorum::present_sources_for_key(&key, ev, &targets)
7838 });
7839 if let Some(entry) = q.get_pending(&key) {
7840 add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
7841 }
7842 if sources.is_empty() {
7843 warn!(
7844 "Locally paid key {} has no responding holders yet; deferring retry",
7845 hex::encode(key)
7846 );
7847 q.defer_pending(&key, config.verification_request_timeout);
7848 } else {
7849 let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
7850 let _ = q.promote_pending_to_fetch(key, distance, sources);
7854 }
7855 }
7856 }
7857
7858 if !keys_needing_network.is_empty() {
7860 let targets =
7862 quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
7863 .await;
7864
7865 let evidence =
7866 quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
7867
7868 let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
7889 let map = last_commitment_by_peer.read().await;
7890 map.iter()
7891 .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
7894 .collect()
7895 };
7896 let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
7897 let provers_snapshot = recent_provers.read().await.clone();
7901 let mut locally_held: HashSet<XorName> = HashSet::new();
7911 for key in &keys_needing_network {
7912 if storage.exists(key).unwrap_or(false) {
7913 locally_held.insert(*key);
7914 }
7915 }
7916 let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
7917 if !locally_held.contains(key) {
7918 return true;
7924 }
7925 if !capable_peer_snapshot.contains(peer) {
7926 return true;
7933 }
7934 let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
7935 return false;
7941 };
7942 provers_snapshot.is_credited_holder(key, peer, hash)
7943 };
7944
7945 let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
7946 {
7947 let q = queues.read().await;
7948 for key in &keys_needing_network {
7949 let Some(ev) = evidence.get(key) else {
7950 continue;
7951 };
7952 if q.get_pending(key).is_none() {
7953 continue;
7954 }
7955 let outcome = quorum::evaluate_key_evidence_with_holder_check(
7956 key,
7957 ev,
7958 &targets,
7959 config,
7960 holder_credit,
7961 );
7962 evaluated.push((*key, outcome));
7963 }
7964 } let mut paid_insert_keys: Vec<XorName> = Vec::new();
7968 for (key, outcome) in &evaluated {
7969 if matches!(
7970 outcome,
7971 KeyVerificationOutcome::QuorumVerified { .. }
7972 | KeyVerificationOutcome::PaidListVerified { .. }
7973 ) {
7974 paid_insert_keys.push(*key);
7975 }
7976 }
7977 for key in &paid_insert_keys {
7978 if let Err(e) = paid_list.insert(key).await {
7979 warn!("Failed to add verified key to PaidForList: {e}");
7980 }
7981 }
7982
7983 let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
7993 for (key, outcome) in &evaluated {
7994 if matches!(
7995 outcome,
7996 KeyVerificationOutcome::QuorumVerified { .. }
7997 | KeyVerificationOutcome::PaidListVerified { .. }
7998 ) && !storage.exists(key).unwrap_or(false)
7999 && is_storage_admitted(&self_id, key, p2p_node, config).await
8000 {
8001 fetch_allowed_keys.insert(*key);
8002 }
8003 }
8004
8005 let mut bad_singleton_hints: HashMap<PeerId, usize> = HashMap::new();
8007 let mut q = queues.write().await;
8008 for (key, outcome) in evaluated {
8009 let replica_hint_sources = q
8010 .get_pending(&key)
8011 .map(|entry| entry.replica_hint_sources.clone())
8012 .unwrap_or_default();
8013 if let Some(ev) = evidence.get(&key) {
8014 if let Some(source) =
8015 punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
8016 {
8017 *bad_singleton_hints.entry(source).or_insert(0) += 1;
8018 }
8019 }
8020 match outcome {
8021 KeyVerificationOutcome::QuorumVerified { sources }
8022 | KeyVerificationOutcome::PaidListVerified { sources } => {
8023 let mut fetch_sources = sources;
8024 add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
8025 let fetch_eligible = fetch_allowed_keys.contains(&key);
8026 if fetch_eligible && !fetch_sources.is_empty() {
8027 let distance =
8028 crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8029 let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
8033 } else if fetch_eligible && fetch_sources.is_empty() {
8036 warn!(
8037 "Verified storage-admitted key {} has no holders yet; deferring retry",
8038 hex::encode(key)
8039 );
8040 q.defer_pending(&key, config.verification_request_timeout);
8041 } else {
8042 q.remove_pending(&key);
8043 terminal_keys.push(key);
8044 }
8045 }
8046 KeyVerificationOutcome::QuorumFailed => {
8047 q.remove_pending(&key);
8048 terminal_keys.push(key);
8049 }
8050 KeyVerificationOutcome::QuorumInconclusive => {
8051 q.set_pending_state(&key, VerificationState::QuorumInconclusive);
8052 q.defer_pending(&key, config.verification_request_timeout);
8053 }
8054 }
8055 }
8056 drop(q);
8057
8058 for (peer, bad_hint_count) in bad_singleton_hints {
8059 let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
8060 warn!(
8061 "Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
8062 sole-source replica hints; \
8063 reporting {reports} bounded trust failure(s)"
8064 );
8065 for _ in 0..reports {
8066 p2p_node
8067 .report_trust_event(
8068 &peer,
8069 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8070 )
8071 .await;
8072 }
8073 }
8074 }
8075
8076 update_bootstrap_after_verification(
8079 &terminal_keys,
8080 bootstrap_state,
8081 queues,
8082 is_bootstrapping,
8083 bootstrap_complete_notify,
8084 )
8085 .await;
8086
8087 let (pending_after, fetch_after, in_flight_after) = {
8088 let q = queues.read().await;
8089 (
8090 q.pending_count(),
8091 q.fetch_queue_count(),
8092 q.in_flight_count(),
8093 )
8094 };
8095 let terminal_key_count = terminal_keys.len();
8096 let elapsed_ms = cycle_started.elapsed().as_millis();
8097
8098 if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
8099 info!(
8100 target: "ant_node::replication::verification",
8101 "Slow replication verification cycle: pending_start={initial_pending_count}, local_paid_probe={local_paid_probe_count}, network_verify={keys_needing_network_count}, terminal={terminal_key_count}, pending_after={pending_after}, fetch_after={fetch_after}, in_flight_after={in_flight_after}, elapsed_ms={elapsed_ms}",
8102 );
8103 } else {
8104 debug!(
8105 target: "ant_node::replication::verification",
8106 "Replication verification cycle: pending_start={initial_pending_count}, local_paid_probe={local_paid_probe_count}, network_verify={keys_needing_network_count}, terminal={terminal_key_count}, pending_after={pending_after}, fetch_after={fetch_after}, in_flight_after={in_flight_after}, elapsed_ms={elapsed_ms}",
8107 );
8108 }
8109}
8110
8111fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
8116 for source in replica_hint_sources {
8117 if !sources.contains(source) {
8118 sources.push(*source);
8119 }
8120 }
8121}
8122
8123fn punishable_singleton_replica_hint_source(
8128 replica_hint_sources: &HashSet<PeerId>,
8129 outcome: &KeyVerificationOutcome,
8130 evidence: &crate::replication::types::KeyVerificationEvidence,
8131) -> Option<PeerId> {
8132 if replica_hint_sources.len() != 1 {
8135 return None;
8136 }
8137 let source = *replica_hint_sources.iter().next()?;
8138 let rejected_by_close_group = matches!(outcome, KeyVerificationOutcome::QuorumFailed);
8139 let denied_possession = evidence.presence.get(&source) == Some(&PresenceEvidence::Absent);
8140
8141 (rejected_by_close_group || denied_possession).then_some(source)
8142}
8143
8144async fn update_bootstrap_after_verification(
8147 terminal_keys: &[XorName],
8148 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8149 queues: &Arc<RwLock<ReplicationQueues>>,
8150 is_bootstrapping: &Arc<RwLock<bool>>,
8151 bootstrap_complete_notify: &Arc<Notify>,
8152) {
8153 if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
8154 return;
8155 }
8156 {
8157 let mut bs = bootstrap_state.write().await;
8158 for key in terminal_keys {
8159 bs.remove_key(key);
8160 }
8161 }
8162 let q = queues.read().await;
8163 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8164 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8165 }
8166}
8167
8168async fn update_bootstrap_after_peer_removed(
8172 peer: &PeerId,
8173 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8174 queues: &Arc<RwLock<ReplicationQueues>>,
8175 is_bootstrapping: &Arc<RwLock<bool>>,
8176 bootstrap_complete_notify: &Arc<Notify>,
8177) {
8178 let orphaned_keys = queues.write().await.remove_hint_source(peer);
8179 let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
8180
8181 if !orphaned_keys.is_empty() {
8182 let mut state = bootstrap_state.write().await;
8183 for key in &orphaned_keys {
8184 state.remove_key(key);
8185 }
8186 }
8187
8188 if orphaned_keys.is_empty() && !cleared_rejection {
8189 return;
8190 }
8191 let q = queues.read().await;
8192 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8193 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8194 }
8195}
8196
8197async fn expire_and_recheck_bootstrap_drain(
8209 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8210 queues: &Arc<RwLock<ReplicationQueues>>,
8211 is_bootstrapping: &Arc<RwLock<bool>>,
8212 bootstrap_complete_notify: &Arc<Notify>,
8213 max_age: Duration,
8214) {
8215 if bootstrap_state.read().await.is_drained() {
8216 return;
8217 }
8218 bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
8219 let q = queues.read().await;
8220 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8221 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8222 }
8223}
8224
8225async fn complete_bootstrap(
8227 is_bootstrapping: &Arc<RwLock<bool>>,
8228 bootstrap_complete_notify: &Arc<Notify>,
8229) {
8230 *is_bootstrapping.write().await = false;
8231 bootstrap_complete_notify.notify_waiters();
8232 info!("Replication bootstrap complete");
8233}
8234
8235enum FetchResult {
8241 Stored,
8243 IntegrityFailed,
8245 SourceFailed,
8247 LocalWriteFailed,
8260 AlreadyHeld,
8279 NoLongerResponsible,
8284}
8285
8286struct FetchOutcome {
8289 key: XorName,
8290 result: FetchResult,
8291}
8292
8293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8295enum FetchFollowUp {
8296 Terminal,
8300 RequeuedForVerification,
8302 RetryFrom(PeerId),
8304}
8305
8306#[allow(clippy::option_if_let_else)]
8319fn apply_fetch_result(
8320 q: &mut ReplicationQueues,
8321 key: &XorName,
8322 result: &FetchResult,
8323 verification_retry_after: Duration,
8324) -> FetchFollowUp {
8325 match result {
8326 FetchResult::Stored | FetchResult::NoLongerResponsible | FetchResult::AlreadyHeld => {
8327 q.complete_fetch(key);
8328 FetchFollowUp::Terminal
8329 }
8330 FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
8331 if let Some(next_peer) = q.retry_fetch(key) {
8332 FetchFollowUp::RetryFrom(next_peer)
8333 } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
8334 FetchFollowUp::RequeuedForVerification
8335 } else {
8336 FetchFollowUp::Terminal
8337 }
8338 }
8339 FetchResult::LocalWriteFailed => {
8346 if q.requeue_fetch_for_verification(key, verification_retry_after) {
8347 FetchFollowUp::RequeuedForVerification
8348 } else {
8349 FetchFollowUp::Terminal
8350 }
8351 }
8352 }
8353}
8354
8355async fn is_storage_admitted(
8363 self_id: &PeerId,
8364 key: &XorName,
8365 p2p_node: &Arc<P2PNode>,
8366 config: &ReplicationConfig,
8367) -> bool {
8368 admission::is_responsible(
8369 self_id,
8370 key,
8371 p2p_node,
8372 storage_admission_width(config.close_group_size),
8373 )
8374 .await
8375}
8376
8377#[allow(clippy::too_many_lines)]
8378async fn execute_single_fetch(
8392 p2p_node: Arc<P2PNode>,
8393 storage: Arc<LmdbStorage>,
8394 config: Arc<ReplicationConfig>,
8395 key: XorName,
8396 source: PeerId,
8397) -> FetchOutcome {
8398 let self_id = *p2p_node.peer_id();
8399 if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8400 debug!(
8401 "Skipping fetch for {}: no longer in the storage-admission group",
8402 hex::encode(key)
8403 );
8404 return FetchOutcome {
8405 key,
8406 result: FetchResult::NoLongerResponsible,
8407 };
8408 }
8409
8410 if storage.exists(&key).unwrap_or(false) {
8417 debug!(
8418 "Skipping fetch for {}: already held locally",
8419 hex::encode(key)
8420 );
8421 return FetchOutcome {
8422 key,
8423 result: FetchResult::AlreadyHeld,
8424 };
8425 }
8426
8427 if let Err(e) = storage.check_capacity() {
8442 debug!(
8443 "Skipping fetch for {}: local storage cannot accept a write: {e}",
8444 hex::encode(key)
8445 );
8446 return FetchOutcome {
8447 key,
8448 result: FetchResult::LocalWriteFailed,
8449 };
8450 }
8451
8452 let request = protocol::FetchRequest { key };
8453 let msg = ReplicationMessage {
8454 request_id: rand::thread_rng().gen::<u64>(),
8455 body: ReplicationMessageBody::FetchRequest(request),
8456 };
8457
8458 let encoded = match msg.encode() {
8459 Ok(data) => data,
8460 Err(e) => {
8461 warn!("Failed to encode fetch request: {e}");
8462 return FetchOutcome {
8463 key,
8464 result: FetchResult::SourceFailed,
8465 };
8466 }
8467 };
8468
8469 let result = p2p_node
8470 .send_request(
8471 &source,
8472 REPLICATION_PROTOCOL_ID,
8473 encoded,
8474 config.fetch_request_timeout,
8475 )
8476 .await;
8477
8478 match result {
8479 Ok(response) => {
8480 let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
8481 p2p_node
8482 .report_trust_event(
8483 &source,
8484 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8485 )
8486 .await;
8487 return FetchOutcome {
8488 key,
8489 result: FetchResult::SourceFailed,
8490 };
8491 };
8492
8493 match resp_msg.body {
8494 ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
8495 key: resp_key,
8496 data,
8497 }) => {
8498 if resp_key != key {
8503 warn!(
8504 "Fetch response key mismatch: requested {}, got {}",
8505 hex::encode(key),
8506 hex::encode(resp_key)
8507 );
8508 p2p_node
8509 .report_trust_event(
8510 &source,
8511 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8512 )
8513 .await;
8514 return FetchOutcome {
8515 key,
8516 result: FetchResult::IntegrityFailed,
8517 };
8518 }
8519
8520 if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
8524 warn!(
8525 "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
8526 hex::encode(resp_key),
8527 data.len(),
8528 crate::ant_protocol::MAX_CHUNK_SIZE,
8529 );
8530 p2p_node
8531 .report_trust_event(
8532 &source,
8533 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8534 )
8535 .await;
8536 return FetchOutcome {
8537 key,
8538 result: FetchResult::IntegrityFailed,
8539 };
8540 }
8541
8542 let computed = crate::client::compute_address(&data);
8544 if computed != resp_key {
8545 warn!(
8546 "Fetched record integrity check failed: expected {}, got {}",
8547 hex::encode(resp_key),
8548 hex::encode(computed)
8549 );
8550 p2p_node
8551 .report_trust_event(
8552 &source,
8553 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8554 )
8555 .await;
8556 return FetchOutcome {
8557 key,
8558 result: FetchResult::IntegrityFailed,
8559 };
8560 }
8561
8562 if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8569 debug!(
8570 "Fetched {} but responsibility lapsed in transit; not storing",
8571 hex::encode(key)
8572 );
8573 return FetchOutcome {
8574 key,
8575 result: FetchResult::NoLongerResponsible,
8576 };
8577 }
8578
8579 if let Err(e) = storage.put(&resp_key, &data).await {
8580 warn!(
8587 "Failed to store fetched record {}: {e}",
8588 hex::encode(resp_key)
8589 );
8590 return FetchOutcome {
8591 key,
8592 result: FetchResult::LocalWriteFailed,
8593 };
8594 }
8595
8596 FetchOutcome {
8597 key,
8598 result: FetchResult::Stored,
8599 }
8600 }
8601 ReplicationMessageBody::FetchResponse(protocol::FetchResponse::NotFound {
8602 ..
8603 }) => {
8604 warn!(
8610 "Fetch: verified source {source} returned NotFound for {}",
8611 hex::encode(key)
8612 );
8613 p2p_node
8614 .report_trust_event(
8615 &source,
8616 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8617 )
8618 .await;
8619 FetchOutcome {
8620 key,
8621 result: FetchResult::SourceFailed,
8622 }
8623 }
8624 ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Error {
8625 reason,
8626 ..
8627 }) => {
8628 warn!(
8629 "Fetch: peer {source} returned error for {}: {reason}",
8630 hex::encode(key)
8631 );
8632 p2p_node
8633 .report_trust_event(
8634 &source,
8635 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8636 )
8637 .await;
8638 FetchOutcome {
8639 key,
8640 result: FetchResult::SourceFailed,
8641 }
8642 }
8643 _ => {
8644 p2p_node
8646 .report_trust_event(
8647 &source,
8648 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8649 )
8650 .await;
8651 FetchOutcome {
8652 key,
8653 result: FetchResult::SourceFailed,
8654 }
8655 }
8656 }
8657 }
8658 Err(e) => {
8659 debug!("Fetch request to {source} failed: {e}");
8660 FetchOutcome {
8663 key,
8664 result: FetchResult::SourceFailed,
8665 }
8666 }
8667 }
8668}
8669
8670fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
8686 confirmed_failed_keys.first().map_or_else(
8687 || "0x".to_string(),
8688 |k| format!("0x{}", hex::encode(&k[..8])),
8689 )
8690}
8691
8692async fn handle_subtree_failed_audit(
8699 challenged_peer: &PeerId,
8700 confirmed_failed_key_count: usize,
8701 reason: &AuditFailureReason,
8702 p2p_node: &Arc<P2PNode>,
8703 sync_state: &Arc<RwLock<NeighborSyncState>>,
8704 recent_provers: &Arc<RwLock<RecentProvers>>,
8705) {
8706 if matches!(reason, AuditFailureReason::Timeout) {
8707 debug!(
8708 "Audit timeout for {challenged_peer} fully graced \
8709 (subtree audit does not evict on timeout)"
8710 );
8711 return;
8712 }
8713
8714 let _ = confirmed_failed_key_count;
8717 {
8718 let mut state = sync_state.write().await;
8719 state.clear_active_bootstrap_claim(challenged_peer);
8720 }
8721 {
8722 let mut provers_guard = recent_provers.write().await;
8723 apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
8724 }
8725 p2p_node
8726 .report_trust_event(
8727 challenged_peer,
8728 TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
8729 )
8730 .await;
8731}
8732
8733async fn handle_subtree_audit_result(
8735 result: &AuditTickResult,
8736 p2p_node: &Arc<P2PNode>,
8737 sync_state: &Arc<RwLock<NeighborSyncState>>,
8738 recent_provers: &Arc<RwLock<RecentProvers>>,
8739 config: &ReplicationConfig,
8740) {
8741 match result {
8742 AuditTickResult::Passed {
8743 challenged_peer,
8744 keys_checked,
8745 } => {
8746 protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
8747 debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
8748 {
8751 let mut state = sync_state.write().await;
8752 state.clear_active_bootstrap_claim(challenged_peer);
8753 }
8754 p2p_node
8755 .report_trust_event(
8756 challenged_peer,
8757 TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
8758 )
8759 .await;
8760 }
8761 AuditTickResult::Failed {
8762 evidence,
8763 no_response_class,
8764 } => {
8765 if let FailureEvidence::AuditFailure {
8766 challenged_peer,
8767 confirmed_failed_keys,
8768 summary,
8769 reason,
8770 ..
8771 } = evidence
8772 {
8773 protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
8774 let first_failed_key = first_failed_key_label(confirmed_failed_keys);
8777 let audit_failure_class = no_response_class.unwrap_or("confirmed");
8778 error!(
8779 "Audit failure for {challenged_peer}: reason={reason:?}, audit_failure_class={}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
8780 audit_failure_class,
8781 confirmed_failed_keys.len(),
8782 summary.challenged_keys,
8783 summary.absent_keys,
8784 summary.digest_mismatch_keys,
8785 );
8786 handle_subtree_failed_audit(
8790 challenged_peer,
8791 confirmed_failed_keys.len(),
8792 reason,
8793 p2p_node,
8794 sync_state,
8795 recent_provers,
8796 )
8797 .await;
8798 }
8799 }
8800 AuditTickResult::BootstrapClaim { peer } => {
8801 let should_report = {
8805 let now = Instant::now();
8806 let mut state = sync_state.write().await;
8807 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
8808 {
8809 BootstrapClaimObservation::WithinGrace { .. } => {
8810 debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
8811 false
8812 }
8813 BootstrapClaimObservation::PastGrace { first_seen } => {
8814 warn!(
8815 "Audit: peer {peer} claiming bootstrap past grace period \
8816 ({:?} > {:?}), reporting abuse",
8817 now.duration_since(first_seen),
8818 config.bootstrap_claim_grace_period,
8819 );
8820 true
8821 }
8822 BootstrapClaimObservation::Repeated { first_seen } => {
8823 warn!(
8824 "Audit: peer {peer} repeated bootstrap claim after previously \
8825 stopping; first claim was {:?} ago, reporting abuse",
8826 now.duration_since(first_seen),
8827 );
8828 true
8829 }
8830 }
8831 };
8832 if should_report {
8833 p2p_node
8834 .report_trust_event(
8835 peer,
8836 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8837 )
8838 .await;
8839 }
8840 }
8841 AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
8842 }
8843}
8844
8845fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
8853 !matches!(reason, AuditFailureReason::Timeout)
8854}
8855
8856#[allow(clippy::too_many_lines)]
8864async fn handle_audit_result(
8865 result: &AuditTickResult,
8866 p2p_node: &Arc<P2PNode>,
8867 sync_state: &Arc<RwLock<NeighborSyncState>>,
8868 config: &ReplicationConfig,
8869) {
8870 match result {
8871 AuditTickResult::Passed {
8872 challenged_peer,
8873 keys_checked,
8874 } => {
8875 protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
8876 debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
8877 {
8878 let mut state = sync_state.write().await;
8879 state.clear_active_bootstrap_claim(challenged_peer);
8880 }
8881 p2p_node
8882 .report_trust_event(
8883 challenged_peer,
8884 TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
8885 )
8886 .await;
8887 }
8888 AuditTickResult::Failed {
8889 evidence,
8890 no_response_class,
8891 } => {
8892 if let FailureEvidence::AuditFailure {
8893 challenged_peer,
8894 confirmed_failed_keys,
8895 summary,
8896 reason,
8897 ..
8898 } = evidence
8899 {
8900 protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
8901 let first_failed_key = first_failed_key_label(confirmed_failed_keys);
8902 let audit_failure_class = no_response_class.unwrap_or("confirmed");
8903 error!(
8904 "Audit failure for {challenged_peer}: reason={reason:?}, audit_failure_class={}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
8905 audit_failure_class,
8906 confirmed_failed_keys.len(),
8907 summary.challenged_keys,
8908 summary.absent_keys,
8909 summary.digest_mismatch_keys,
8910 );
8911 if audit_failure_clears_bootstrap_claim(reason) {
8912 let mut state = sync_state.write().await;
8913 state.clear_active_bootstrap_claim(challenged_peer);
8914 } else {
8915 debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
8916 }
8917 p2p_node
8918 .report_trust_event(
8919 challenged_peer,
8920 TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
8921 )
8922 .await;
8923 }
8924 }
8925 AuditTickResult::BootstrapClaim { peer } => {
8926 let should_report = {
8927 let now = Instant::now();
8928 let mut state = sync_state.write().await;
8929 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
8930 {
8931 BootstrapClaimObservation::WithinGrace { .. } => {
8932 debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
8933 false
8934 }
8935 BootstrapClaimObservation::PastGrace { first_seen } => {
8936 warn!(
8937 "Audit: peer {peer} claiming bootstrap past grace period \
8938 ({:?} > {:?}), reporting abuse",
8939 now.duration_since(first_seen),
8940 config.bootstrap_claim_grace_period,
8941 );
8942 true
8943 }
8944 BootstrapClaimObservation::Repeated { first_seen } => {
8945 warn!(
8946 "Audit: peer {peer} repeated bootstrap claim after previously \
8947 stopping; first claim was {:?} ago, reporting abuse",
8948 now.duration_since(first_seen),
8949 );
8950 true
8951 }
8952 }
8953 };
8954 if should_report {
8955 p2p_node
8956 .report_trust_event(
8957 peer,
8958 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8959 )
8960 .await;
8961 }
8962 }
8963 AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
8964 }
8965}
8966
8967fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
8978 !matches!(reason, AuditFailureReason::Timeout)
8979}
8980
8981fn apply_audit_failure_credit_revocation(
8986 provers: &mut RecentProvers,
8987 challenged_peer: &PeerId,
8988 reason: &AuditFailureReason,
8989) {
8990 if audit_failure_revokes_holder_credit(reason) {
8991 provers.forget_peer(challenged_peer);
8992 }
8993}
8994
8995#[derive(Clone)]
9005struct GossipAuditTrigger {
9006 p2p_node: Arc<P2PNode>,
9007 config: Arc<ReplicationConfig>,
9008 recent_provers: Arc<RwLock<RecentProvers>>,
9009 sync_state: Arc<RwLock<NeighborSyncState>>,
9010 cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
9015 detached_task_tracker: TaskTracker,
9016 lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
9020}
9021
9022#[derive(Debug, Clone, Copy)]
9028struct AuditTarget {
9029 pin_hash: [u8; 32],
9030 key_count: u32,
9031}
9032
9033#[derive(Debug, Clone, Copy)]
9042pub struct MonetizedPinEvent {
9043 pub peer: PeerId,
9045 pub pin: [u8; 32],
9047 pub key_count: u32,
9049 pub quote_ts: SystemTime,
9054}
9055
9056fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9064 let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9065 let known = match map.get(peer) {
9066 Some(&last) => {
9067 if now.saturating_duration_since(last) < cooldown {
9068 return false;
9069 }
9070 true
9071 }
9072 None => false,
9073 };
9074 if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
9077 if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9078 map.remove(&victim);
9079 }
9080 }
9081 map.insert(*peer, now);
9082 true
9083}
9084
9085fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9091 let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9092 map.get(peer).map_or(true, |&last| {
9093 now.saturating_duration_since(last) >= cooldown
9094 })
9095}
9096
9097fn audit_launch_decision(
9114 attempts: &mut HashMap<PeerId, Instant>,
9115 launched: &mut HashMap<PeerId, Instant>,
9116 peer: &PeerId,
9117 now: Instant,
9118 lottery_wins: bool,
9119) -> bool {
9120 if !cooldown_allows_audit(attempts, peer, now) {
9123 return false;
9124 }
9125 if !lottery_wins {
9128 return false;
9129 }
9130 cooldown_allows_audit(launched, peer, now)
9133}
9134
9135async fn maybe_trigger_gossip_audit(
9140 trigger: &GossipAuditTrigger,
9141 peer: &PeerId,
9142 target: AuditTarget,
9143) {
9144 let now = Instant::now();
9148 let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
9149 {
9150 let mut attempts = trigger.lottery_attempts.write().await;
9153 let mut launched = trigger.cooldown.write().await;
9154 if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
9155 return;
9156 }
9157 }
9158
9159 let detached_task_tracker = trigger.detached_task_tracker.clone();
9160 let trigger = trigger.clone();
9161 let peer = *peer;
9162 detached_task_tracker.spawn(async move {
9163 let credit = storage_commitment_audit::AuditCredit {
9164 recent_provers: &trigger.recent_provers,
9165 };
9166 let result = storage_commitment_audit::run_subtree_audit_with_origin(
9167 &trigger.p2p_node,
9168 &trigger.config,
9169 &peer,
9170 target.pin_hash,
9171 target.key_count,
9172 Some(&credit),
9173 storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9174 )
9175 .await;
9176 handle_subtree_audit_result(
9177 &result,
9178 &trigger.p2p_node,
9179 &trigger.sync_state,
9180 &trigger.recent_provers,
9181 &trigger.config,
9182 )
9183 .await;
9184 });
9185}
9186
9187async fn sig_verify_rate_limit_ok(
9196 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9197 source: &PeerId,
9198 now: Instant,
9199) -> bool {
9200 let mut attempts = sig_verify_attempts.write().await;
9201 if let Some(&last) = attempts.get(source) {
9202 if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9203 return false;
9204 }
9205 }
9206 if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9207 if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9208 attempts.remove(&victim);
9209 }
9210 }
9211 attempts.insert(*source, now);
9212 true
9213}
9214
9215async fn handle_commitment_downgrade(
9266 source: &PeerId,
9267 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9268) -> Option<AuditTarget> {
9269 let now = Instant::now();
9270 let cached = {
9271 let map = last_commitment_by_peer.read().await;
9272 map.get(source).and_then(|rec| {
9273 if !rec.commitment_capable {
9274 return None;
9275 }
9276 let last = rec.last_commitment()?;
9277 let pin = rec.commitment_hash()?;
9278 let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
9279 Some((pin, last.key_count, fresh))
9280 })
9281 };
9282 match cached {
9283 Some((pin, key_count, true)) => {
9284 warn!(
9285 "ingest_peer_commitment: commitment-capable peer {source} sent None \
9286 (downgrade attempt); auditing against its last cached commitment"
9287 );
9288 Some(AuditTarget {
9289 pin_hash: pin,
9290 key_count,
9291 })
9292 }
9293 Some((_, _, false)) => {
9294 if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
9301 let still_stale =
9302 now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
9303 if still_stale {
9304 rec.clear_commitment();
9305 debug!(
9306 "ingest_peer_commitment: capable peer {source} sent None and its cached \
9307 commitment aged past the answerability TTL; forgetting it"
9308 );
9309 }
9310 }
9311 None
9312 }
9313 None => None,
9314 }
9315}
9316
9317async fn ingest_peer_commitment(
9318 source: &PeerId,
9319 commitment: Option<&StorageCommitment>,
9320 p2p_node: &Arc<P2PNode>,
9321 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9322 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
9323 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9324) -> Option<AuditTarget> {
9325 let Some(c) = commitment else {
9326 return handle_commitment_downgrade(source, last_commitment_by_peer).await;
9327 };
9328 if !p2p_node.dht_manager().is_in_routing_table(source).await {
9337 debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
9338 return None;
9339 }
9340 if &c.sender_peer_id != source.as_bytes() {
9346 warn!(
9347 "ingest_peer_commitment: sender_peer_id mismatch from {source} \
9348 (dropped, possible relay attempt)"
9349 );
9350 return None;
9351 }
9352 let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
9357 if derived_peer_id != c.sender_peer_id {
9358 warn!(
9359 "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
9360 {source} (dropped, throwaway-key attack)"
9361 );
9362 return None;
9363 }
9364 let now = Instant::now();
9378 if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
9379 debug!(
9380 "ingest_peer_commitment: rate-limited sig verify from {source} \
9381 (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
9382 );
9383 return None;
9384 }
9385 if !crate::replication::commitment::verify_commitment_signature(c) {
9390 warn!(
9391 "ingest_peer_commitment: signature did not verify under embedded key for {source} \
9392 (dropped, forged commitment)"
9393 );
9394 return None;
9395 }
9396 let new_hash = commitment_hash(c);
9398 let mut map = last_commitment_by_peer.write().await;
9399 if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
9403 if let Some(victim) = map.keys().next().copied() {
9408 map.remove(&victim);
9409 warn!(
9410 "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
9411 evicted {victim} to admit {source}"
9412 );
9413 }
9414 }
9415 map.entry(*source)
9419 .and_modify(|r| {
9420 r.set_commitment(c.clone(), now);
9423 r.last_sig_verify_at = now;
9424 r.commitment_capable = true; })
9426 .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
9427 drop(map);
9428 {
9440 let mut set = ever_capable_peers.write().await;
9441 if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
9442 set.insert(*source);
9443 } else {
9444 warn!(
9445 "ingest_peer_commitment: ever_capable_peers at cap \
9446 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
9447 );
9448 }
9449 }
9450 new_hash.map(|pin_hash| AuditTarget {
9455 pin_hash,
9456 key_count: c.key_count,
9457 })
9458}
9459
9460async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
9468 let bytes = match tokio::fs::read(path).await {
9469 Ok(b) => b,
9470 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
9471 debug!(
9472 "Commitment retention: no snapshot at {} (fresh start)",
9473 path.display()
9474 );
9475 return;
9476 }
9477 Err(e) => {
9478 warn!(
9479 "Commitment retention: failed to read {}: {e}",
9480 path.display()
9481 );
9482 return;
9483 }
9484 };
9485 if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
9486 state.restore(&persisted);
9487 info!(
9488 "Commitment retention: reloaded {} slot(s) from {}",
9489 state.retained_slot_count(),
9490 path.display()
9491 );
9492 } else {
9493 warn!(
9494 "Commitment retention: corrupt snapshot at {}; starting with empty retention",
9495 path.display()
9496 );
9497 }
9498}
9499
9500async fn persist_retention_if_changed(
9506 state: &ResponderCommitmentState,
9507 path: &Path,
9508 last: &mut Option<Vec<u8>>,
9509) {
9510 let Some(bytes) = state.snapshot().to_bytes() else {
9511 warn!("Commitment retention: serialization failed; keeping previous snapshot");
9512 return;
9513 };
9514 if last.as_deref() == Some(bytes.as_slice()) {
9515 return;
9516 }
9517 if write_retention_atomic(path, bytes.clone()).await {
9518 *last = Some(bytes);
9519 }
9520}
9521
9522async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
9527 let path = path.to_path_buf();
9528 let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
9529 let tmp = path.with_extension("tmp");
9530 std::fs::write(&tmp, &bytes)?;
9531 std::fs::File::open(&tmp)?.sync_all()?;
9532 std::fs::rename(&tmp, &path)?;
9533 let dir = path
9537 .parent()
9538 .filter(|p| !p.as_os_str().is_empty())
9539 .unwrap_or_else(|| Path::new("."));
9540 std::fs::File::open(dir)?.sync_all()?;
9541 Ok(())
9542 })
9543 .await;
9544 match res {
9545 Ok(Ok(())) => true,
9546 Ok(Err(e)) => {
9547 warn!("Commitment retention: persist failed: {e}");
9548 false
9549 }
9550 Err(e) => {
9551 warn!("Commitment retention: persist task join failed: {e}");
9552 false
9553 }
9554 }
9555}
9556
9557async fn rebuild_and_rotate_commitment(
9570 storage: &Arc<LmdbStorage>,
9571 identity: &Arc<NodeIdentity>,
9572 state: &Arc<ResponderCommitmentState>,
9573 p2p: &Arc<P2PNode>,
9574 config: &Arc<ReplicationConfig>,
9575) -> Result<()> {
9576 let stored_keys = storage
9577 .all_keys()
9578 .await
9579 .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
9580
9581 let storage_empty = stored_keys.is_empty();
9592 let self_id = *p2p.peer_id();
9593 let mut keys = Vec::with_capacity(stored_keys.len());
9594 for k in stored_keys {
9595 if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
9596 keys.push(k);
9597 }
9598 }
9599
9600 if keys.is_empty() {
9601 if storage_empty {
9602 if state.retained_slot_count() > 0 {
9607 debug!("Commitment rotation: storage empty, clearing retained slots");
9608 state.clear_all();
9609 }
9610 return Ok(());
9611 }
9612 debug!(
9625 "Commitment rotation: no responsible keys to commit to; retiring current commitment \
9626 (stays answerable until its gossip TTL lapses, bytes still on disk)"
9627 );
9628 state.retire_current();
9629 return Ok(());
9630 }
9631
9632 let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
9636 if keys.len() > cap {
9637 warn!(
9638 "Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
9639 truncating — investigate as this likely means a misconfiguration",
9640 keys.len(),
9641 cap
9642 );
9643 }
9644
9645 let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
9664
9665 let candidate_tree = commitment::MerkleTree::build(entries)
9680 .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
9681 let candidate_root = candidate_tree.root();
9682 if let Some(current) = state.current() {
9683 if current.commitment().root == candidate_root {
9684 debug!(
9685 "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
9686 hex::encode(candidate_root)
9687 );
9688 state.age_out();
9695 return Ok(());
9696 }
9697 }
9698
9699 let sk_bytes = identity.secret_key_bytes().to_vec();
9700 let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
9701 .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
9702 let pk_bytes = identity.public_key().as_bytes().to_vec();
9703 let peer_id_bytes = *p2p.peer_id().as_bytes();
9704
9705 let built = commitment_state::BuiltCommitment::build_from_tree(
9706 candidate_tree,
9707 &peer_id_bytes,
9708 &sk,
9709 &pk_bytes,
9710 )
9711 .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
9712
9713 let hash = hex::encode(built.hash());
9714 let key_count = built.commitment().key_count;
9715 state.rotate(built);
9716 info!("Storage commitment rotated: hash={hash} key_count={key_count}");
9717 Ok(())
9718}
9719
9720#[cfg(test)]
9721#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
9722mod tests {
9723 use super::*;
9724 use super::{
9725 apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
9726 audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
9727 config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
9728 first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
9729 quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
9730 FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
9731 FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
9732 FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
9733 };
9734 use crate::payment::VerificationContext;
9735 use crate::replication::audit::AuditTickResult;
9736 use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
9737 use crate::replication::recent_provers::RecentProvers;
9738 use crate::replication::types::{AuditFailureReason, FailureEvidence};
9739 use lru::LruCache;
9740 use saorsa_core::identity::PeerId;
9741 use std::collections::HashMap;
9742 use std::num::NonZeroUsize;
9743 use std::sync::atomic::Ordering;
9744 use std::sync::Arc;
9745 use std::time::Duration;
9746 use std::time::Instant;
9747 use std::time::SystemTime;
9748
9749 #[test]
9750 fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
9751 for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
9752 assert_eq!(match_replication_protocol(id), Some((id, false)));
9753 assert_eq!(
9754 match_replication_protocol(&format!("{RR_PREFIX}{id}")),
9755 Some((id, true))
9756 );
9757 }
9758 assert_eq!(
9759 match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
9760 None
9761 );
9762 assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
9763 assert_eq!(match_replication_protocol(RR_PREFIX), None);
9764 }
9765
9766 #[test]
9767 fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
9768 use crate::replication::protocol::{
9769 AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
9770 SubtreeSliceChallenge,
9771 };
9772
9773 let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
9774 challenge_id: 1,
9775 nonce: [0u8; 32],
9776 challenged_peer_id: [0u8; 32],
9777 expected_commitment_hash: [0u8; 32],
9778 openings: vec![],
9779 });
9780 let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
9781 challenge_id: 1,
9782 nonce: [0u8; 32],
9783 challenged_peer_id: [0u8; 32],
9784 keys: vec![[0u8; 32]],
9785 });
9786 let digest_response =
9787 ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
9788 let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
9789 key: [0u8; 32],
9790 data: vec![],
9791 proof_of_payment: vec![],
9792 });
9793
9794 assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
9795 assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
9796
9797 for body in [&digest_challenge, &digest_response, &core] {
9798 assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
9799 assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
9800 }
9801
9802 for body in [&subtree, &digest_challenge, &digest_response, &core] {
9803 assert!(body_matches_protocol(body, response_protocol_for(body)));
9804 }
9805 }
9806
9807 fn test_peer(b: u8) -> PeerId {
9808 let mut bytes = [0u8; 32];
9809 bytes[0] = b;
9810 PeerId::from_bytes(bytes)
9811 }
9812
9813 fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
9817 protocol::FreshReplicationOffer {
9818 key: crate::client::compute_address(&data),
9819 data,
9820 proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
9821 }
9822 }
9823
9824 fn admit_test_offer(
9825 in_flight: &FreshOfferInFlight,
9826 offer: protocol::FreshReplicationOffer,
9827 source: PeerId,
9828 ) -> FreshOfferAdmission {
9829 FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
9830 }
9831
9832 #[test]
9833 fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
9834 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9835 let data = vec![0x11u8; 64];
9836
9837 let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
9838 let FreshOfferAdmission::Opened(entry) = opened else {
9839 panic!("first offer for a key should open the entry")
9840 };
9841
9842 assert!(
9845 matches!(
9846 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
9847 FreshOfferAdmission::Joined
9848 ),
9849 "a duplicate from a new source should queue its proof"
9850 );
9851 assert!(
9853 matches!(
9854 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
9855 FreshOfferAdmission::DuplicateSource
9856 ),
9857 "one source should hold at most one queued proof per key"
9858 );
9859
9860 drop(entry);
9862 assert!(
9863 matches!(
9864 admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
9865 FreshOfferAdmission::Opened(_)
9866 ),
9867 "a released key should be openable again"
9868 );
9869 }
9870
9871 #[test]
9872 fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
9873 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9874
9875 let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
9879 assert!(
9880 matches!(
9881 admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
9882 FreshOfferAdmission::Opened(_)
9883 ),
9884 "distinct keys should never block each other"
9885 );
9886 }
9887
9888 #[test]
9895 fn a_failing_proof_hands_the_key_to_the_next_sender() {
9896 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9897 let data = vec![0x5Au8; 128];
9898 let forger = test_peer(0xF0);
9899 let genuine = test_peer(0x0F);
9900
9901 let FreshOfferAdmission::Opened(mut entry) =
9902 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
9903 else {
9904 panic!("the first offer should open the entry");
9905 };
9906 assert!(
9907 matches!(
9908 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
9909 FreshOfferAdmission::Joined
9910 ),
9911 "the genuine sender must not be turned away by the forger"
9912 );
9913
9914 let first = entry
9915 .next_attempt()
9916 .expect("the opener's proof comes first");
9917 assert_eq!(first.source, forger);
9918
9919 let second = entry
9922 .next_attempt()
9923 .expect("a failed proof must not consume the key");
9924 assert_eq!(second.source, genuine);
9925 assert_eq!(
9926 second.proof_of_payment,
9927 vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
9928 );
9929 assert_eq!(
9930 entry.data(),
9931 data.as_slice(),
9932 "every proof is tried against the one copy of the bytes"
9933 );
9934
9935 assert!(entry.next_attempt().is_none());
9937 assert!(
9938 matches!(
9939 admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
9940 FreshOfferAdmission::Opened(_)
9941 ),
9942 "an exhausted entry should release its key"
9943 );
9944 }
9945
9946 #[test]
9955 fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
9956 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9957 let data = vec![0x3Du8; 32];
9958
9959 let FreshOfferAdmission::Opened(mut entry) =
9960 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
9961 else {
9962 panic!("the first offer should open the entry")
9963 };
9964
9965 let mut admitted = 1;
9969 for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
9970 let _ = entry.next_attempt();
9971 if matches!(
9972 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
9973 FreshOfferAdmission::Joined
9974 ) {
9975 admitted += 1;
9976 }
9977 }
9978
9979 assert!(
9980 admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
9981 "a key accepted {admitted} proofs over its lifetime, but the budget is \
9982 {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
9983 );
9984 }
9985
9986 #[test]
9987 fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
9988 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9989 let data = vec![0x2Cu8; 32];
9990
9991 let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
9994 for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
9995 let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
9996 assert!(
9997 matches!(
9998 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
9999 FreshOfferAdmission::Joined
10000 ),
10001 "sender {i} is within the legitimate close-group fan-out"
10002 );
10003 }
10004
10005 let surplus = test_peer(0xEE);
10006 assert!(
10007 matches!(
10008 admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
10009 FreshOfferAdmission::Full
10010 ),
10011 "past the cap a proof is surplus: enough are already queued to place the record"
10012 );
10013 }
10014
10015 #[test]
10016 fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
10017 assert!(!verification_request_exceeds_limit(
10018 config::MAX_VERIFICATION_KEYS_PER_CYCLE
10019 ));
10020 assert!(verification_request_exceeds_limit(
10021 config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
10022 ));
10023 }
10024
10025 #[tokio::test]
10028 async fn subtree_round1_limiter_cooldown_and_single_use_session() {
10029 let limiter = SubtreeRound1Limiter::new(
10030 Duration::from_secs(3600),
10031 config::MAX_CONCURRENT_SUBTREE_ROUND1,
10032 );
10033 let peer = test_peer(1);
10034
10035 let guard = limiter.admit(&peer).await;
10037 assert!(guard.is_some(), "first round-1 admitted");
10038 drop(guard);
10039 assert!(
10042 limiter.admit(&peer).await.is_none(),
10043 "second round-1 within cooldown is rate-dropped"
10044 );
10045 assert!(limiter.admit(&test_peer(2)).await.is_some());
10047
10048 let hash = [7u8; 32];
10050 let nonce = [9u8; 32];
10051 limiter.open_session(peer, 42, hash, nonce).await;
10052 assert!(!limiter.consume_session(&peer, 42, &hash, &[0u8; 32]).await);
10054 assert!(!limiter.consume_session(&peer, 42, &[0u8; 32], &nonce).await);
10055 assert!(!limiter.consume_session(&peer, 99, &hash, &nonce).await);
10057 assert!(limiter.consume_session(&peer, 42, &hash, &nonce).await);
10059 assert!(!limiter.consume_session(&peer, 42, &hash, &nonce).await);
10060 }
10061
10062 #[tokio::test]
10070 async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
10071 let limiter =
10073 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10074 assert!(
10075 limiter.admit(&test_peer(1)).await.is_some(),
10076 "a node starts with budget in hand so it can serve audits at once"
10077 );
10078
10079 limiter
10083 .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
10084 .await;
10085
10086 for id in 2..8u8 {
10087 assert!(
10088 limiter.admit(&test_peer(id)).await.is_none(),
10089 "a never-seen peer must still be refused while the budget is spent"
10090 );
10091 }
10092 }
10093
10094 #[test]
10100 fn round1_work_budget_carries_debt_and_refills_over_time() {
10101 let now = Instant::now();
10102 let at = |secs: u64| {
10103 now.checked_add(Duration::from_secs(secs))
10104 .unwrap_or_else(Instant::now)
10105 };
10106 let mut budget = Round1WorkBudget {
10107 balance: 0,
10108 last_refill: now,
10109 };
10110 assert!(!budget.has_budget(now), "empty means empty");
10111
10112 budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
10115 assert!(
10116 !budget.has_budget(at(3)),
10117 "still in debt three seconds after an over-large proof"
10118 );
10119 assert!(
10120 budget.has_budget(at(5)),
10121 "the debt is worked off at the refill rate"
10122 );
10123
10124 budget.refill(at(24 * 60 * 60));
10126 assert_eq!(
10127 budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
10128 "refill is capped at the burst size"
10129 );
10130 }
10131
10132 #[tokio::test]
10140 async fn round1_pool_size_comes_from_config() {
10141 let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
10143 let held = limiter.admit(&test_peer(1)).await;
10144 assert!(held.is_some(), "the single configured slot is admitted");
10145 assert!(
10146 limiter.admit(&test_peer(2)).await.is_none(),
10147 "a second concurrent round 1 is refused at a configured pool of 1, \
10148 proving admission follows config rather than the compiled-in default"
10149 );
10150 drop(held);
10151 assert!(
10152 limiter.admit(&test_peer(2)).await.is_some(),
10153 "the slot is reusable once the first proof completes"
10154 );
10155 }
10156
10157 #[tokio::test]
10158 async fn round1_pool_size_of_zero_is_clamped_to_one() {
10159 let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
10160 assert!(
10161 limiter.admit(&test_peer(1)).await.is_some(),
10162 "a mis-set pool of 0 must still serve audits, not silently refuse every one"
10163 );
10164 }
10165
10166 fn test_key(b: u8) -> crate::ant_protocol::XorName {
10167 let mut k = [0u8; 32];
10168 k[0] = b;
10169 k
10170 }
10171
10172 #[test]
10173 fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
10174 let source = test_peer(0x91);
10175 let corroborator = test_peer(0x92);
10176 let mut evidence = types::KeyVerificationEvidence {
10177 presence: HashMap::from([(source, PresenceEvidence::Absent)]),
10178 paid_list: HashMap::new(),
10179 };
10180 let failed = KeyVerificationOutcome::QuorumFailed;
10181
10182 assert_eq!(
10183 punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10184 Some(source)
10185 );
10186 assert_eq!(
10187 punishable_singleton_replica_hint_source(
10188 &HashSet::from([source, corroborator]),
10189 &failed,
10190 &evidence,
10191 ),
10192 None,
10193 "corroborated hints must not use the sole-source penalty lane"
10194 );
10195 assert_eq!(
10196 punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
10197 None,
10198 "paid-list advertisements do not claim possession, so they leave the \
10199 replica-hint source set empty and cannot be penalized"
10200 );
10201
10202 evidence
10203 .presence
10204 .insert(source, PresenceEvidence::Unresolved);
10205 assert_eq!(
10206 punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10207 Some(source),
10208 "definitive close-group rejection is punishable without direct contradiction"
10209 );
10210 assert_eq!(
10211 punishable_singleton_replica_hint_source(
10212 &HashSet::from([source]),
10213 &KeyVerificationOutcome::QuorumInconclusive,
10214 &evidence,
10215 ),
10216 None,
10217 "timeouts and inconclusive evidence are neutral"
10218 );
10219
10220 evidence.presence.insert(source, PresenceEvidence::Absent);
10221 assert_eq!(
10222 punishable_singleton_replica_hint_source(
10223 &HashSet::from([source]),
10224 &KeyVerificationOutcome::QuorumVerified {
10225 sources: vec![corroborator],
10226 },
10227 &evidence,
10228 ),
10229 Some(source),
10230 "an explicit denial is punishable regardless of the overall outcome"
10231 );
10232 }
10233
10234 fn slice_challenge(
10238 challenge_id: u64,
10239 commitment_hash: [u8; 32],
10240 nonce: [u8; 32],
10241 ) -> protocol::SubtreeSliceChallenge {
10242 protocol::SubtreeSliceChallenge {
10243 challenge_id,
10244 nonce,
10245 challenged_peer_id: [0u8; 32],
10246 expected_commitment_hash: commitment_hash,
10247 openings: Vec::new(),
10248 }
10249 }
10250
10251 #[tokio::test]
10260 async fn capacity_refused_slice_challenge_preserves_round1_session() {
10261 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10262 let inflight = Arc::new(RwLock::new(HashMap::new()));
10263 let round1 =
10264 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10265 let peer = test_peer(0xB1);
10266 let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
10267 let challenge = slice_challenge(id, hash, nonce);
10268
10269 round1.open_session(peer, id, hash, nonce).await;
10270
10271 let mut hold = Vec::new();
10273 for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10274 match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
10275 .await
10276 {
10277 Ok(guard) => hold.push(guard),
10278 Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
10279 }
10280 }
10281
10282 let refused =
10283 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10284 assert!(
10285 matches!(refused, SliceAdmission::Capacity(_)),
10286 "a saturated peer share must refuse on capacity, not on session"
10287 );
10288
10289 drop(hold);
10291 let retried =
10292 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10293 assert!(
10294 matches!(retried, SliceAdmission::Admitted(_)),
10295 "the round-1 session must survive a capacity refusal so the retry succeeds"
10296 );
10297
10298 drop(retried);
10300 let replayed =
10301 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10302 assert!(
10303 matches!(replayed, SliceAdmission::NoSession),
10304 "a consumed session must not be replayable"
10305 );
10306 }
10307
10308 #[tokio::test]
10311 async fn unsessioned_slice_challenge_releases_its_admission_slot() {
10312 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10313 let inflight = Arc::new(RwLock::new(HashMap::new()));
10314 let round1 =
10315 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10316 let peer = test_peer(0xB2);
10317 let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
10318
10319 for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
10322 let outcome =
10323 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10324 assert!(
10325 matches!(outcome, SliceAdmission::NoSession),
10326 "no session was ever opened, so every attempt must miss"
10327 );
10328 }
10329
10330 assert_eq!(
10331 semaphore.available_permits(),
10332 MAX_CONCURRENT_AUDIT_RESPONSES,
10333 "every global permit must be returned"
10334 );
10335 assert!(
10336 inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
10337 "no per-peer slot may be left occupied"
10338 );
10339 }
10340
10341 #[test]
10342 fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
10343 assert!(!audit_failure_revokes_holder_credit(
10344 &AuditFailureReason::Timeout
10345 ));
10346 assert!(audit_failure_revokes_holder_credit(
10347 &AuditFailureReason::DigestMismatch
10348 ));
10349 }
10350
10351 #[tokio::test]
10352 async fn audit_responder_admission_reports_per_peer_cap_full() {
10353 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10354 let inflight = Arc::new(RwLock::new(HashMap::new()));
10355 let peer = test_peer(0xA1);
10356
10357 let mut guards = Vec::new();
10358 for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10359 match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
10360 .await
10361 {
10362 Ok(guard) => guards.push(guard),
10363 Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
10364 }
10365 }
10366
10367 let Err(err) =
10368 admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10369 else {
10370 panic!("admission should fail once per-peer cap is full");
10371 };
10372 assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
10373 assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
10374 assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10375 assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10376
10377 drop(guards);
10378 }
10379
10380 #[tokio::test]
10381 async fn audit_responder_admission_reports_global_pool_full() {
10382 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10383 let inflight = Arc::new(RwLock::new(HashMap::new()));
10384 let peer = test_peer(0xA2);
10385
10386 let mut held_global_permits = Vec::new();
10387 for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
10388 held_global_permits.push(
10389 Arc::clone(&semaphore)
10390 .try_acquire_owned()
10391 .expect("test should be able to exhaust the global pool"),
10392 );
10393 }
10394
10395 let Err(err) =
10396 admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10397 else {
10398 panic!("admission should fail once global pool is full");
10399 };
10400 assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
10401 assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
10402 assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10403 assert_eq!(err.peer_inflight, 0);
10404 assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10405
10406 drop(held_global_permits);
10407 }
10408
10409 #[tokio::test]
10410 async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
10411 let semaphore = Arc::new(Semaphore::new(1));
10412 let inflight = Arc::new(RwLock::new(HashMap::new()));
10413 let peer = test_peer(0xA3);
10414
10415 let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
10416 .await
10417 .expect("first responder should be admitted");
10418 assert_eq!(semaphore.available_permits(), 0);
10419 assert_eq!(inflight.read().await.get(&peer), Some(&1));
10420
10421 drop(guard);
10422 assert_eq!(semaphore.available_permits(), 1);
10423 assert!(!inflight.read().await.contains_key(&peer));
10424 }
10425
10426 #[tokio::test]
10427 async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
10428 let semaphore = Arc::new(Semaphore::new(1));
10429 let inflight = Arc::new(RwLock::new(HashMap::new()));
10430 let peer = test_peer(0xA4);
10431 let held_map = inflight.write().await;
10432
10433 let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
10434 assert!(
10435 tokio::time::timeout(Duration::from_millis(10), waiting)
10436 .await
10437 .is_err(),
10438 "admission should still be waiting for the peer map"
10439 );
10440
10441 drop(held_map);
10442 assert_eq!(semaphore.available_permits(), 1);
10443 assert!(!inflight.read().await.contains_key(&peer));
10444 }
10445
10446 #[test]
10447 fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
10448 let timeout = Duration::from_secs(1);
10449 let old_received_at = Instant::now()
10450 .checked_sub(timeout)
10451 .unwrap_or_else(Instant::now);
10452
10453 assert!(request_is_stale(old_received_at, timeout));
10454 assert!(!request_is_stale(Instant::now(), timeout));
10455 }
10456
10457 #[tokio::test]
10458 async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
10459 let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
10460 let inflight = Arc::new(RwLock::new(HashMap::new()));
10461 let first_peer = test_peer(0xB3);
10462 let second_peer = test_peer(0xB4);
10463
10464 let first_guard = admit_bounded_responder(
10465 &semaphore,
10466 &inflight,
10467 &first_peer,
10468 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10469 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10470 )
10471 .await
10472 .expect("first sync from a peer should be admitted");
10473 let duplicate = admit_bounded_responder(
10474 &semaphore,
10475 &inflight,
10476 &first_peer,
10477 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10478 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10479 )
10480 .await;
10481 let other_peer = admit_bounded_responder(
10482 &semaphore,
10483 &inflight,
10484 &second_peer,
10485 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10486 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10487 )
10488 .await;
10489
10490 assert!(matches!(
10491 duplicate,
10492 Err(ResponderAdmissionFailure {
10493 reason: ResponderRejectReason::PerPeerCapFull,
10494 ..
10495 })
10496 ));
10497 assert!(other_peer.is_ok());
10498 drop(first_guard);
10499 drop(other_peer);
10500 }
10501
10502 #[tokio::test]
10510 async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
10511 let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
10512 let inflight = Arc::new(RwLock::new(HashMap::new()));
10513 let flooder = test_peer(0xC1);
10514 let honest = test_peer(0xC2);
10515
10516 let mut held = Vec::new();
10517 for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
10518 held.push(
10519 admit_bounded_responder(
10520 &semaphore,
10521 &inflight,
10522 &flooder,
10523 FRESH_OFFER_MAX_OUTSTANDING,
10524 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10525 )
10526 .await
10527 .expect("offers within the per-peer share are admitted"),
10528 );
10529 }
10530
10531 let flooder_excess = admit_bounded_responder(
10532 &semaphore,
10533 &inflight,
10534 &flooder,
10535 FRESH_OFFER_MAX_OUTSTANDING,
10536 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10537 )
10538 .await;
10539 assert!(
10540 matches!(
10541 flooder_excess,
10542 Err(ResponderAdmissionFailure {
10543 reason: ResponderRejectReason::PerPeerCapFull,
10544 ..
10545 })
10546 ),
10547 "one source must not exceed its fresh-offer share"
10548 );
10549
10550 let honest_offer = admit_bounded_responder(
10551 &semaphore,
10552 &inflight,
10553 &honest,
10554 FRESH_OFFER_MAX_OUTSTANDING,
10555 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10556 )
10557 .await;
10558 assert!(
10559 honest_offer.is_ok(),
10560 "an honest sender must still be admitted while another peer floods"
10561 );
10562
10563 assert!(
10564 usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
10565 < FRESH_OFFER_MAX_OUTSTANDING,
10566 "the per-peer share must leave room for other sources"
10567 );
10568
10569 drop(held);
10570 drop(honest_offer);
10571 }
10572
10573 #[tokio::test]
10575 async fn paid_notify_admission_reserves_capacity_for_other_peers() {
10576 let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
10577 let inflight = Arc::new(RwLock::new(HashMap::new()));
10578 let flooder = test_peer(0xC3);
10579 let honest = test_peer(0xC4);
10580
10581 let mut held = Vec::new();
10582 for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
10583 held.push(
10584 admit_bounded_responder(
10585 &semaphore,
10586 &inflight,
10587 &flooder,
10588 PAID_NOTIFY_MAX_OUTSTANDING,
10589 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10590 )
10591 .await
10592 .expect("notifies within the per-peer share are admitted"),
10593 );
10594 }
10595
10596 assert!(
10597 matches!(
10598 admit_bounded_responder(
10599 &semaphore,
10600 &inflight,
10601 &flooder,
10602 PAID_NOTIFY_MAX_OUTSTANDING,
10603 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10604 )
10605 .await,
10606 Err(ResponderAdmissionFailure {
10607 reason: ResponderRejectReason::PerPeerCapFull,
10608 ..
10609 })
10610 ),
10611 "one source must not exceed its paid-notify share"
10612 );
10613 assert!(
10614 admit_bounded_responder(
10615 &semaphore,
10616 &inflight,
10617 &honest,
10618 PAID_NOTIFY_MAX_OUTSTANDING,
10619 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10620 )
10621 .await
10622 .is_ok(),
10623 "an honest sender must still be admitted while another peer floods"
10624 );
10625
10626 drop(held);
10627 }
10628
10629 #[test]
10637 fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
10638 let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
10639
10640 assert_eq!(
10641 FRESH_OFFER_MAX_OUTSTANDING - share,
10642 FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
10643 "a source holding none must always find a free slot"
10644 );
10645 assert!(
10646 share < FRESH_OFFER_MAX_OUTSTANDING,
10647 "one peer must not be able to take the whole pool"
10648 );
10649 assert!(
10653 share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
10654 "fresh offers are one-way bulk, not request/response — their share \
10655 must not be sized like the request classes'"
10656 );
10657 }
10658
10659 #[test]
10662 fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
10663 let key = test_key(0xC5);
10664
10665 let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
10666
10667 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
10668 .expect("an offer with no proof must be refused");
10669 assert!(
10670 rejection.penalise,
10671 "an honest sender always attaches a proof"
10672 );
10673
10674 let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
10677 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
10678 .expect("an undersized proof must be refused");
10679 assert!(
10680 rejection.penalise,
10681 "no honest sender constructs an undersized proof"
10682 );
10683 let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
10684 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
10685 .expect("an oversized proof must be refused");
10686 assert!(
10687 rejection.penalise,
10688 "no honest sender constructs an oversized proof"
10689 );
10690
10691 let rejection = fresh_offer_structural_rejection(
10692 &key,
10693 &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
10694 &valid_proof,
10695 )
10696 .expect("an oversized offer must be refused");
10697 assert!(
10698 rejection.penalise,
10699 "no honest sender constructs an oversized offer"
10700 );
10701
10702 let data = vec![0u8; 1];
10703 assert!(
10704 fresh_offer_structural_rejection(
10705 &crate::client::compute_address(&data),
10706 &data,
10707 &valid_proof
10708 )
10709 .is_none(),
10710 "a well-formed offer must reach admission"
10711 );
10712 }
10713
10714 #[test]
10723 fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
10724 let genuine_data = vec![0x5Au8; 128];
10725 let key = crate::client::compute_address(&genuine_data);
10726 let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
10727
10728 let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
10729 .expect("bytes that do not hash to the advertised key must be refused");
10730 assert!(
10731 rejection.penalise,
10732 "no honest sender offers bytes that do not hash to the advertised key"
10733 );
10734
10735 assert!(
10738 fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
10739 "the offer that actually carries the key's bytes must reach the entry"
10740 );
10741
10742 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10743 assert!(
10744 matches!(
10745 admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
10746 FreshOfferAdmission::Opened(_)
10747 ),
10748 "an offer refused on payload shape must leave the key openable"
10749 );
10750 }
10751
10752 #[tokio::test]
10753 async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
10754 let peer = test_peer(0xA5);
10755 let key = test_key(0xA5);
10756 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10757 let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
10758 let is_bootstrapping = Arc::new(RwLock::new(true));
10759 let bootstrap_complete_notify = Arc::new(Notify::new());
10760
10761 let now = Instant::now();
10762 queues.write().await.add_pending_verify(
10763 key,
10764 VerificationEntry {
10765 state: VerificationState::PendingVerify,
10766 verified_sources: Vec::new(),
10767 tried_sources: HashSet::new(),
10768 created_at: now,
10769 next_verify_at: now,
10770 hint_sources: HashSet::from([peer]),
10771 replica_hint_sources: HashSet::from([peer]),
10772 },
10773 );
10774 super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
10775 super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
10776 {
10777 let q = queues.read().await;
10778 assert!(
10779 !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
10780 "capacity rejection should initially block bootstrap drain"
10781 );
10782 }
10783
10784 update_bootstrap_after_peer_removed(
10785 &peer,
10786 &bootstrap_state,
10787 &queues,
10788 &is_bootstrapping,
10789 &bootstrap_complete_notify,
10790 )
10791 .await;
10792
10793 let state = bootstrap_state.read().await;
10794 assert!(state.capacity_rejected_sources.is_empty());
10795 assert!(state.pending_keys.is_empty());
10796 assert!(state.is_drained());
10797 drop(state);
10798 assert!(!*is_bootstrapping.read().await);
10799 }
10800
10801 #[tokio::test]
10805 async fn fairness_displacement_does_not_stamp_its_victim() {
10806 let displaced_owner = test_peer(0xB1);
10807 let incoming_source = test_peer(0xB2);
10808 let displaced_key = test_key(0xB1);
10809 let admitted_key = test_key(0xB2);
10810 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10811 {
10812 let mut state = bootstrap_state.write().await;
10813 state.pending_keys.insert(displaced_key);
10814 state
10815 .capacity_rejected_sources
10816 .insert(incoming_source, Instant::now());
10817 }
10818 let outcomes = [(
10819 incoming_source,
10820 AdmissionOutcome {
10821 discovered: HashSet::from([admitted_key]),
10822 capacity_rejected_count: 0,
10823 displaced: vec![CapacityDisplacement {
10824 key: displaced_key,
10825 owner: displaced_owner,
10826 }],
10827 },
10828 )];
10829
10830 publish_bootstrap_admission_outcomes(
10831 &bootstrap_state,
10832 &outcomes,
10833 &HashSet::from([admitted_key]),
10834 )
10835 .await;
10836
10837 let state = bootstrap_state.read().await;
10838 assert!(!state.pending_keys.contains(&displaced_key));
10839 assert!(state.pending_keys.contains(&admitted_key));
10840 assert!(
10841 !state
10842 .capacity_rejected_sources
10843 .contains_key(&displaced_owner),
10844 "the displaced owner must not be charged for our own fairness reclaim"
10845 );
10846 assert!(!state
10847 .capacity_rejected_sources
10848 .contains_key(&incoming_source));
10849 }
10850
10851 #[tokio::test]
10857 async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
10858 const REJECTION_ROUNDS: usize = 5;
10859
10860 let source = test_peer(0xB3);
10861 let key = test_key(0xB3);
10862 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10863
10864 let first_seen = {
10865 let outcomes = [(
10866 source,
10867 AdmissionOutcome {
10868 discovered: HashSet::new(),
10869 capacity_rejected_count: 1,
10870 displaced: Vec::new(),
10871 },
10872 )];
10873 publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
10874 .await;
10875 bootstrap_state
10876 .read()
10877 .await
10878 .capacity_rejected_sources
10879 .get(&source)
10880 .copied()
10881 .expect("first rejection recorded")
10882 };
10883
10884 for _ in 0..REJECTION_ROUNDS {
10885 let outcomes = [(
10886 source,
10887 AdmissionOutcome {
10888 discovered: HashSet::from([key]),
10889 capacity_rejected_count: 1,
10890 displaced: Vec::new(),
10891 },
10892 )];
10893 publish_bootstrap_admission_outcomes(
10894 &bootstrap_state,
10895 &outcomes,
10896 &HashSet::from([key]),
10897 )
10898 .await;
10899 }
10900
10901 let recorded = bootstrap_state
10902 .read()
10903 .await
10904 .capacity_rejected_sources
10905 .get(&source)
10906 .copied()
10907 .expect("debt still outstanding");
10908 assert_eq!(
10909 recorded, first_seen,
10910 "repeat rejections must not restart the expiry clock"
10911 );
10912 }
10913
10914 #[tokio::test]
10919 async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
10920 let peer = test_peer(0xA6);
10921 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10922 let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
10923 let is_bootstrapping = Arc::new(RwLock::new(true));
10924 let bootstrap_complete_notify = Arc::new(Notify::new());
10925
10926 super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
10929
10930 expire_and_recheck_bootstrap_drain(
10932 &bootstrap_state,
10933 &queues,
10934 &is_bootstrapping,
10935 &bootstrap_complete_notify,
10936 ReplicationConfig::default().capacity_rejected_max_age(),
10937 )
10938 .await;
10939 assert!(!bootstrap_state.read().await.is_drained());
10940 assert!(*is_bootstrapping.read().await);
10941
10942 expire_and_recheck_bootstrap_drain(
10944 &bootstrap_state,
10945 &queues,
10946 &is_bootstrapping,
10947 &bootstrap_complete_notify,
10948 Duration::ZERO,
10949 )
10950 .await;
10951 assert!(bootstrap_state.read().await.is_drained());
10952 assert!(!*is_bootstrapping.read().await);
10953 }
10954
10955 #[test]
10956 fn first_audit_terminal_outcomes_are_stable() {
10957 let peer = test_peer(1);
10958 let passed = AuditTickResult::Passed {
10959 challenged_peer: peer,
10960 keys_checked: 1,
10961 };
10962 let timed_out = AuditTickResult::Failed {
10963 evidence: FailureEvidence::AuditFailure {
10964 challenge_id: 1,
10965 challenged_peer: peer,
10966 confirmed_failed_keys: vec![test_key(1)],
10967 summary: crate::replication::types::AuditFailureSummary::default(),
10968 reason: AuditFailureReason::Timeout,
10969 },
10970 no_response_class: Some("timeout"),
10971 };
10972
10973 assert_eq!(
10974 first_audit_terminal_outcome(&passed),
10975 FirstAuditTerminalOutcome::Passed
10976 );
10977 assert_eq!(
10978 first_audit_terminal_outcome(&timed_out),
10979 FirstAuditTerminalOutcome::Timeout
10980 );
10981 assert_eq!(
10982 first_audit_terminal_outcome(&AuditTickResult::Idle),
10983 FirstAuditTerminalOutcome::Idle
10984 );
10985 assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
10986 assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
10987 assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
10988 assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
10989 assert_eq!(
10990 FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
10991 "insufficient_keys"
10992 );
10993 assert_eq!(
10994 FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
10995 "bootstrap_claim"
10996 );
10997 }
10998
10999 #[test]
11000 fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
11001 let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11002 let mut rng = StdRng::seed_from_u64(7);
11003 let peer = test_peer(1);
11004 let base = MonetizedPinEvent {
11005 peer,
11006 pin: [1; 32],
11007 key_count: 100,
11008 quote_ts: SystemTime::now(),
11009 };
11010
11011 assert_eq!(
11013 coalesce_first_audit_event(&mut pending, base, true, &mut rng),
11014 FirstAuditQueueOutcome::Queued
11015 );
11016
11017 let lower = MonetizedPinEvent {
11019 pin: [2; 32],
11020 key_count: 50,
11021 ..base
11022 };
11023 assert_eq!(
11024 coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
11025 FirstAuditQueueOutcome::SuppressedLower
11026 );
11027 assert_eq!(
11028 pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11029 Some(([1; 32], 100)),
11030 "the higher-count pin is retained"
11031 );
11032
11033 let higher = MonetizedPinEvent {
11035 pin: [3; 32],
11036 key_count: 400,
11037 ..base
11038 };
11039 assert_eq!(
11040 coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
11041 FirstAuditQueueOutcome::Coalesced
11042 );
11043 assert_eq!(
11044 pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11045 Some(([3; 32], 400))
11046 );
11047
11048 let equal_newer = MonetizedPinEvent {
11050 pin: [4; 32],
11051 key_count: 400,
11052 ..base
11053 };
11054 assert_eq!(
11055 coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
11056 FirstAuditQueueOutcome::Coalesced
11057 );
11058 assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11059 let equal_older = MonetizedPinEvent {
11061 pin: [5; 32],
11062 key_count: 400,
11063 ..base
11064 };
11065 assert_eq!(
11066 coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
11067 FirstAuditQueueOutcome::RetainedOnTie
11068 );
11069 assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11070
11071 let other_peer = MonetizedPinEvent {
11073 peer: test_peer(2),
11074 pin: [6; 32],
11075 key_count: 100,
11076 ..base
11077 };
11078 assert_eq!(
11079 coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
11080 FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
11081 );
11082 assert_eq!(pending.len(), 1);
11083 assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
11084 }
11085
11086 #[test]
11089 fn first_audit_limiter_enforces_burst_then_refills() {
11090 let base = Instant::now();
11091 let mut limiter = FirstAuditLimiter::new(base);
11092 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11093
11094 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11096 let peer = test_peer(u8::try_from(i).expect("small burst"));
11097 assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11098 limiter.commit_launch(peer, 10, base);
11099 }
11100 let extra = test_peer(0xEE);
11102 assert_eq!(
11103 limiter.assess(&extra, 10, base, 0),
11104 LimiterVerdict::RateDeferred
11105 );
11106
11107 let later = base + interval;
11109 assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
11110 limiter.commit_launch(extra, 10, later);
11111 let extra2 = test_peer(0xEF);
11112 assert_eq!(
11113 limiter.assess(&extra2, 10, later, 0),
11114 LimiterVerdict::RateDeferred
11115 );
11116 }
11117
11118 #[test]
11119 fn first_audit_limiter_refill_keeps_fractional_remainder() {
11120 let base = Instant::now();
11121 let mut limiter = FirstAuditLimiter::new(base);
11122 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11123 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11124 let peer = test_peer(u8::try_from(i).expect("small burst"));
11125 assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
11126 limiter.commit_launch(peer, 1, base);
11127 }
11128 let at_1_5 = base + interval + interval / 2;
11131 let p = test_peer(0xAA);
11132 assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
11133 limiter.commit_launch(p, 1, at_1_5);
11134 let at_2_0 = base + interval * 2;
11136 let q = test_peer(0xAB);
11137 assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
11138 }
11139
11140 #[test]
11141 fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
11142 let base = Instant::now();
11143 let mut limiter = FirstAuditLimiter::new(base);
11144 let peer = test_peer(1);
11145 assert_eq!(
11146 limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
11147 LimiterVerdict::RateDeferred
11148 );
11149 assert_eq!(
11151 limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
11152 LimiterVerdict::Admit
11153 );
11154 }
11155
11156 #[test]
11157 fn first_audit_limiter_assess_consumes_nothing() {
11158 let base = Instant::now();
11159 let mut limiter = FirstAuditLimiter::new(base);
11160 let peer = test_peer(3);
11161 for _ in 0..10 {
11165 assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
11166 }
11167 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11168 let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
11169 assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
11170 limiter.commit_launch(p, 5, base);
11171 }
11172 }
11173
11174 #[test]
11175 fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
11176 let base = Instant::now();
11177 let mut limiter = FirstAuditLimiter::new(base);
11178 let peer = test_peer(7);
11179 assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
11180 limiter.commit_launch(peer, 100, base);
11181
11182 let soon = base + Duration::from_secs(60);
11184 assert_eq!(
11185 limiter.assess(&peer, 100, soon, 0),
11186 LimiterVerdict::WindowDeduped
11187 );
11188 assert_eq!(
11190 limiter.assess(&peer, 150, soon, 0),
11191 LimiterVerdict::WindowDeduped
11192 );
11193 assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
11197
11198 let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
11200 assert_eq!(
11201 limiter.assess(&peer, 100, expired, 0),
11202 LimiterVerdict::Admit
11203 );
11204 }
11205
11206 #[test]
11207 fn first_audit_limiter_window_verdict_outranks_empty_budget() {
11208 let base = Instant::now();
11212 let mut limiter = FirstAuditLimiter::new(base);
11213 let peer = test_peer(9);
11214 assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11215 limiter.commit_launch(peer, 10, base);
11216 let other = test_peer(10);
11217 assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
11218 limiter.commit_launch(other, 10, base);
11219 assert_eq!(
11220 limiter.assess(&peer, 10, base, 0),
11221 LimiterVerdict::WindowDeduped
11222 );
11223 }
11224
11225 #[test]
11230 fn first_audit_horizon_prefilter_boundary() {
11231 let now = SystemTime::now();
11232 let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
11234 let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
11235 let boundary = now
11237 .checked_add(h)
11238 .and_then(|t| t.checked_sub(c))
11239 .expect("boundary time");
11240
11241 assert!(quote_within_audit_window(boundary, now));
11243 assert!(!quote_answerable_through_nominal_jitter(boundary, now));
11245
11246 let newer = boundary
11250 .checked_add(Duration::from_micros(1))
11251 .expect("newer");
11252 let older = boundary
11253 .checked_sub(Duration::from_micros(1))
11254 .expect("older");
11255 assert!(quote_answerable_through_nominal_jitter(newer, now));
11256 assert!(!quote_answerable_through_nominal_jitter(older, now));
11257
11258 let future = now
11261 .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
11262 .and_then(|t| t.checked_add(Duration::from_secs(60)))
11263 .expect("future");
11264 assert!(!quote_answerable_through_nominal_jitter(future, now));
11265 }
11266
11267 #[test]
11281 fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
11282 let obs = Arc::new(FirstAuditObservability::default());
11283 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11284 let peer = test_peer(1);
11285
11286 let dead_quote = SystemTime::now()
11287 .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11288 .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11289 .expect("past wall time");
11290 let stale_high = MonetizedPinEvent {
11291 peer,
11292 pin: [1; 32],
11293 key_count: 400,
11294 quote_ts: dead_quote,
11295 };
11296 scheduler.enqueue(stale_high, &obs);
11297 assert_eq!(scheduler.pending_len(), 1);
11298
11299 let fresh_lower = MonetizedPinEvent {
11301 peer,
11302 pin: [2; 32],
11303 key_count: 100,
11304 quote_ts: SystemTime::now(),
11305 };
11306 scheduler.enqueue(fresh_lower, &obs);
11307
11308 assert_eq!(scheduler.pending_len(), 1);
11309 assert_eq!(
11310 scheduler.pending.peek(&peer).map(|e| e.pin),
11311 Some([2; 32]),
11312 "the live nomination replaced the dead incumbent"
11313 );
11314 assert_eq!(
11315 obs.suppressed_lower.load(Ordering::Relaxed),
11316 0,
11317 "no self-erasure signal for displacing a dead pin"
11318 );
11319 assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
11320 assert_eq!(
11321 obs.outside_answerability_window.load(Ordering::Relaxed),
11322 1,
11323 "the dead incumbent is accounted as an expiry"
11324 );
11325 }
11326
11327 #[test]
11330 fn first_audit_live_incumbent_still_suppresses_lower_count() {
11331 let obs = Arc::new(FirstAuditObservability::default());
11332 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11333 let peer = test_peer(1);
11334
11335 let live_high = MonetizedPinEvent {
11336 peer,
11337 pin: [1; 32],
11338 key_count: 400,
11339 quote_ts: SystemTime::now(),
11340 };
11341 scheduler.enqueue(live_high, &obs);
11342 let cheaper = MonetizedPinEvent {
11343 peer,
11344 pin: [2; 32],
11345 key_count: 100,
11346 quote_ts: SystemTime::now(),
11347 };
11348 scheduler.enqueue(cheaper, &obs);
11349
11350 assert_eq!(scheduler.pending_len(), 1);
11351 assert_eq!(
11352 scheduler.pending.peek(&peer).map(|e| e.pin),
11353 Some([1; 32]),
11354 "the higher-count live pin is retained"
11355 );
11356 assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
11357 assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
11358 }
11359
11360 fn live_nomination(b: u8) -> MonetizedPinEvent {
11362 MonetizedPinEvent {
11363 peer: test_peer(b),
11364 pin: [b; 32],
11365 key_count: 100,
11366 quote_ts: SystemTime::now(),
11367 }
11368 }
11369
11370 #[test]
11378 fn first_audit_pending_cap_matches_strict_launch_horizon() {
11379 let quote_ts = SystemTime::now();
11380 assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
11382 let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
11383 let mut refill = 1u32;
11384 loop {
11385 let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
11386 let at = quote_ts + age;
11387 if !quote_answerable_through_nominal_jitter(quote_ts, at) {
11388 break;
11389 }
11390 usable += 1;
11391 refill += 1;
11392 assert!(refill < 10_000, "runaway horizon simulation");
11393 }
11394 assert_eq!(
11395 FIRST_AUDIT_PENDING_CAP, usable,
11396 "cap must match the simulated strict launch horizon"
11397 );
11398 }
11399
11400 #[test]
11404 fn first_audit_pending_cap_independent_of_dedup_cap() {
11405 let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11406 assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
11407 assert_eq!(
11408 scheduler.first_audited.cap().get(),
11409 MAX_LAST_COMMITMENT_BY_PEER
11410 );
11411 }
11412
11413 #[test]
11417 fn first_audit_admission_beyond_cap_displaces_and_counts() {
11418 let obs = Arc::new(FirstAuditObservability::default());
11419 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11420 let overflow: usize = 5;
11421 let total = FIRST_AUDIT_PENDING_CAP + overflow;
11422
11423 for i in 0..total {
11424 let b = u8::try_from(i + 1).expect("test peer count fits u8");
11425 scheduler.enqueue(live_nomination(b), &obs);
11426 }
11427
11428 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11429 assert_eq!(
11430 obs.capacity_evicted.load(Ordering::Relaxed),
11431 u64::try_from(overflow).expect("overflow fits u64"),
11432 "each admission past the cap displaces exactly one entry"
11433 );
11434 assert_eq!(
11435 obs.queued.load(Ordering::Relaxed),
11436 u64::try_from(total).expect("total fits u64"),
11437 "displacement is not an admission refusal"
11438 );
11439 let last = u8::try_from(total).expect("test peer count fits u8");
11441 assert!(
11442 scheduler.pending.peek(&test_peer(last)).is_some(),
11443 "the newest arrival always enters the sample"
11444 );
11445 }
11446
11447 #[test]
11457 fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
11458 let flood: usize = 60; assert!(FIRST_AUDIT_PENDING_CAP < flood);
11460 assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
11461
11462 let trials = 100u64;
11463 let mut survived = 0u32;
11464 let mut evicted = 0u32;
11465 for trial in 0..trials {
11466 let obs = Arc::new(FirstAuditObservability::default());
11467 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11468 scheduler.rng = StdRng::seed_from_u64(trial);
11472 scheduler.limiter.reserve_token();
11475 scheduler.limiter.reserve_token();
11476
11477 let target = test_peer(200);
11478 scheduler.enqueue(live_nomination(200), &obs);
11479 for i in 0..flood {
11480 let b = u8::try_from(i + 1).expect("flood peer fits u8");
11481 scheduler.enqueue(live_nomination(b), &obs);
11482 }
11483
11484 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11485 let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
11486 .expect("overflow count fits u64");
11487 assert_eq!(
11488 obs.capacity_evicted.load(Ordering::Relaxed),
11489 overflows,
11490 "every overflow past the cap is accounted, none silent"
11491 );
11492 if scheduler.pending.peek(&target).is_some() {
11493 survived += 1;
11494 } else {
11495 evicted += 1;
11496 }
11497 }
11498 assert!(
11503 survived > 0,
11504 "target must survive some ordered floods — deterministic eviction \
11505 would mean keep-newest retention regressed"
11506 );
11507 assert!(
11508 evicted > 0,
11509 "target must also be displaceable — otherwise overflow is refusing \
11510 admissions instead of sampling"
11511 );
11512 }
11513
11514 #[test]
11518 fn first_audit_overflow_reserves_before_destructive_eviction() {
11519 let obs = Arc::new(FirstAuditObservability::default());
11520 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11521 let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11522
11523 for i in 0..FIRST_AUDIT_PENDING_CAP {
11524 let b = u8::try_from(i + 1).expect("test peer count fits u8");
11525 scheduler.enqueue(live_nomination(b), &obs);
11526 }
11527 let overflowing = live_nomination(250);
11528 assert!(scheduler.would_displace(&overflowing));
11529
11530 assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
11532 assert!(
11533 !scheduler.would_displace(&overflowing),
11534 "a successful reservation frees the slot"
11535 );
11536 scheduler.enqueue(overflowing, &obs);
11537
11538 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11539 assert_eq!(
11540 obs.capacity_evicted.load(Ordering::Relaxed),
11541 0,
11542 "no destructive eviction when a launch opportunity existed"
11543 );
11544 }
11545
11546 #[test]
11551 fn first_audit_displaced_peer_may_be_renominated() {
11552 let obs = Arc::new(FirstAuditObservability::default());
11553 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11554 let total = FIRST_AUDIT_PENDING_CAP + 1;
11555
11556 for i in 0..total {
11557 let b = u8::try_from(i + 1).expect("test peer count fits u8");
11558 scheduler.enqueue(live_nomination(b), &obs);
11559 }
11560 assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
11561 let displaced = (1..=total)
11563 .map(|i| u8::try_from(i).expect("test peer count fits u8"))
11564 .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
11565 .expect("exactly one admitted peer was displaced");
11566
11567 scheduler.enqueue(live_nomination(displaced), &obs);
11568
11569 assert!(
11570 scheduler.pending.peek(&test_peer(displaced)).is_some(),
11571 "the displaced peer re-enters the sample"
11572 );
11573 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11574 assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
11575 assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
11576 assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
11577 }
11578
11579 #[test]
11584 fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
11585 let obs = Arc::new(FirstAuditObservability::default());
11586 let mono = Instant::now();
11587 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11588
11589 let dead_quote = SystemTime::now()
11590 .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11591 .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11592 .expect("past wall time");
11593 scheduler.enqueue(
11594 MonetizedPinEvent {
11595 peer: test_peer(1),
11596 pin: [1; 32],
11597 key_count: 100,
11598 quote_ts: dead_quote,
11599 },
11600 &obs,
11601 );
11602 scheduler.enqueue(
11603 MonetizedPinEvent {
11604 peer: test_peer(2),
11605 pin: [2; 32],
11606 key_count: 100,
11607 quote_ts: SystemTime::now(),
11608 },
11609 &obs,
11610 );
11611 assert_eq!(scheduler.pending_len(), 2);
11612
11613 scheduler.limiter.tokens = 0;
11616 let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11617 assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
11618 assert_eq!(
11619 scheduler.pending_len(),
11620 2,
11621 "budget-gated reserve scans nothing"
11622 );
11623
11624 let wall_now = SystemTime::now();
11625 assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
11626 assert_eq!(scheduler.pending_len(), 1);
11627 assert!(
11628 scheduler.pending.peek(&test_peer(2)).is_some(),
11629 "the live entry survives the sweep"
11630 );
11631 assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
11632 let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
11633 assert!(
11634 Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
11635 "the age gauge reflects only live work after the sweep"
11636 );
11637 }
11638
11639 #[test]
11640 #[allow(clippy::too_many_lines)]
11641 fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
11642 let obs = Arc::new(FirstAuditObservability::default());
11643 let mono = Instant::now();
11644 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11645
11646 let sentinel_peer = test_peer(0xAA);
11649 scheduler.limiter.promote(sentinel_peer, 500, mono);
11650 let sentinel_before = scheduler
11651 .limiter
11652 .recent
11653 .peek(&sentinel_peer)
11654 .copied()
11655 .expect("sentinel present");
11656
11657 let peer = test_peer(1);
11658 let a = MonetizedPinEvent {
11659 peer,
11660 pin: [1; 32],
11661 key_count: 100,
11662 quote_ts: SystemTime::now(), };
11664 scheduler.enqueue(a, &obs);
11665
11666 let tokens_before = scheduler.tokens();
11667 let lane_before = scheduler.oldest_first_lane;
11668 let launched_before = obs.launched.load(Ordering::Relaxed);
11669 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11670
11671 let inflight0 = obs.inflight.load(Ordering::Relaxed);
11673 assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
11674 assert_eq!(scheduler.reserved_peer(), Some(peer));
11675 assert_eq!(
11676 scheduler.tokens(),
11677 tokens_before - 1,
11678 "reserve consumes a token"
11679 );
11680 assert_eq!(
11681 obs.inflight.load(Ordering::Relaxed),
11682 1,
11683 "reserve holds a slot"
11684 );
11685
11686 let b = MonetizedPinEvent {
11690 peer,
11691 pin: [2; 32],
11692 key_count: 100,
11693 quote_ts: SystemTime::now(),
11694 };
11695 scheduler.enqueue(b, &obs);
11696 assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
11697 assert!(
11698 !scheduler.try_reserve(
11699 mono,
11700 obs.inflight.load(Ordering::Relaxed),
11701 Duration::ZERO,
11702 &cooldown,
11703 &obs
11704 ),
11705 "no second reservation while one is outstanding"
11706 );
11707
11708 let reservation = scheduler
11710 .take_due_reservation(mono)
11711 .expect("A is due at jitter 0");
11712 let wall_fail = a
11713 .quote_ts
11714 .checked_add(GOSSIP_ANSWERABILITY_TTL)
11715 .and_then(|t| t.checked_add(Duration::from_secs(1)))
11716 .expect("past-cutoff wall time");
11717 let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
11718 assert!(
11719 promoted.is_none(),
11720 "answerability lapsed -> cancelled, not promoted"
11721 );
11722
11723 assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
11725 assert!(
11726 scheduler.limiter.recent.peek(&peer).is_none(),
11727 "cancel stamps no per-peer window"
11728 );
11729 assert_eq!(
11730 scheduler.limiter.recent.peek(&sentinel_peer).copied(),
11731 Some(sentinel_before),
11732 "unrelated window sentinel untouched"
11733 );
11734 assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
11735 assert_eq!(
11736 scheduler.tokens(),
11737 tokens_before,
11738 "token refunded on cancel"
11739 );
11740 assert_eq!(
11741 obs.inflight.load(Ordering::Relaxed),
11742 0,
11743 "in-flight slot released"
11744 );
11745 assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
11746 assert_eq!(
11747 obs.launched.load(Ordering::Relaxed),
11748 launched_before,
11749 "no launch counted"
11750 );
11751 assert_eq!(
11752 obs.outside_answerability_window.load(Ordering::Relaxed),
11753 1,
11754 "the cancel reason is recorded"
11755 );
11756
11757 assert_eq!(
11761 scheduler.pending_len(),
11762 1,
11763 "successor still pending after cancel"
11764 );
11765 assert!(scheduler.reserved.is_none());
11766 assert!(scheduler.try_reserve(
11767 mono,
11768 obs.inflight.load(Ordering::Relaxed),
11769 Duration::ZERO,
11770 &cooldown,
11771 &obs
11772 ));
11773 assert_eq!(
11774 scheduler.reserved_peer(),
11775 Some(peer),
11776 "the retained successor becomes the next reservation"
11777 );
11778 }
11779
11780 #[test]
11786 fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
11787 let obs = Arc::new(FirstAuditObservability::default());
11788 let mono = Instant::now();
11789 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11790 let peer = test_peer(1);
11791
11792 let a = MonetizedPinEvent {
11794 peer,
11795 pin: [1; 32],
11796 key_count: 100,
11797 quote_ts: SystemTime::now(),
11798 };
11799 scheduler.enqueue(a, &obs);
11800 let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
11801 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
11802
11803 let b = MonetizedPinEvent {
11806 peer,
11807 pin: [2; 32],
11808 key_count: 400,
11809 quote_ts: SystemTime::now(),
11810 };
11811 scheduler.enqueue(b, &obs);
11812 assert_eq!(scheduler.pending_len(), 1);
11813
11814 let reservation = scheduler.take_due_reservation(mono).expect("due");
11817 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11818 cooldown.insert(peer, mono); let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
11820 assert!(promoted.is_none(), "cooldown race -> not promoted");
11821
11822 assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
11824 assert_eq!(
11825 scheduler.pending.peek(&peer).map(|e| e.pin),
11826 Some([2; 32]),
11827 "the newer successor B is retained, not the older reserved A"
11828 );
11829 assert!(scheduler.first_audited.is_empty());
11830 assert!(scheduler.limiter.recent.peek(&peer).is_none());
11831 }
11832
11833 #[test]
11838 fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
11839 let now = SystemTime::now();
11840 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11841 assert_eq!(
11842 scheduler.oldest_pending_quote_age_ms(now),
11843 0,
11844 "empty pending -> zero"
11845 );
11846
11847 for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
11849 let _ = coalesce_first_audit_event(
11850 &mut scheduler.pending,
11851 MonetizedPinEvent {
11852 peer: test_peer(peer_id),
11853 pin,
11854 key_count: 100,
11855 quote_ts: now - Duration::from_secs(secs),
11856 },
11857 true,
11858 &mut scheduler.rng,
11859 );
11860 }
11861 assert_eq!(
11862 scheduler.oldest_pending_quote_age_ms(now),
11863 10_000,
11864 "tracks the oldest (10s), not the newest (2s)"
11865 );
11866
11867 let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11869 let _ = coalesce_first_audit_event(
11870 &mut skewed.pending,
11871 MonetizedPinEvent {
11872 peer: test_peer(3),
11873 pin: [3; 32],
11874 key_count: 100,
11875 quote_ts: now + Duration::from_secs(5),
11876 },
11877 true,
11878 &mut skewed.rng,
11879 );
11880 assert_eq!(
11881 skewed.oldest_pending_quote_age_ms(now),
11882 0,
11883 "future quote_ts saturates to zero"
11884 );
11885 }
11886
11887 #[test]
11897 fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
11898 let mut pending: LruCache<PeerId, MonetizedPinEvent> =
11899 LruCache::new(NonZeroUsize::new(2).unwrap());
11900 let mut rng = StdRng::seed_from_u64(11);
11901 let victim = test_peer(1);
11902 let other = test_peer(2);
11903 let _ = coalesce_first_audit_event(
11905 &mut pending,
11906 MonetizedPinEvent {
11907 peer: victim,
11908 pin: [1; 32],
11909 key_count: 400,
11910 quote_ts: SystemTime::now(),
11911 },
11912 true,
11913 &mut rng,
11914 );
11915 let _ = coalesce_first_audit_event(
11916 &mut pending,
11917 MonetizedPinEvent {
11918 peer: other,
11919 pin: [9; 32],
11920 key_count: 100,
11921 quote_ts: SystemTime::now(),
11922 },
11923 true,
11924 &mut rng,
11925 );
11926 let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
11927 assert_eq!(
11928 order_before,
11929 vec![other, victim],
11930 "sanity: `other` is MRU, the victim is LRU"
11931 );
11932
11933 let mut suppressed = 0u64;
11935 for i in 0..8u8 {
11936 let out = coalesce_first_audit_event(
11937 &mut pending,
11938 MonetizedPinEvent {
11939 peer: victim,
11940 pin: [i; 32],
11941 key_count: 50,
11942 quote_ts: SystemTime::now(),
11943 },
11944 true,
11945 &mut rng,
11946 );
11947 assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
11948 suppressed += 1;
11949 }
11950 assert_eq!(suppressed, 8);
11951 assert_eq!(
11953 pending.peek(&victim).map(|e| (e.pin, e.key_count)),
11954 Some(([1; 32], 400))
11955 );
11956 let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
11959 assert_eq!(
11960 order_after, order_before,
11961 "the suppressed-lower flood must not have changed any recency position"
11962 );
11963 }
11964
11965 #[test]
11968 fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
11969 let obs = Arc::new(FirstAuditObservability::default());
11970 let mono = Instant::now();
11971 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11972 scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11974 let reserved_peer = test_peer(1);
11975 let other_peer = test_peer(2);
11976
11977 scheduler.enqueue(
11979 MonetizedPinEvent {
11980 peer: reserved_peer,
11981 pin: [1; 32],
11982 key_count: 100,
11983 quote_ts: SystemTime::now(),
11984 },
11985 &obs,
11986 );
11987 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
11988 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
11989
11990 scheduler.enqueue(
11992 MonetizedPinEvent {
11993 peer: other_peer,
11994 pin: [2; 32],
11995 key_count: 100,
11996 quote_ts: SystemTime::now(),
11997 },
11998 &obs,
11999 );
12000 assert_eq!(scheduler.pending_len(), 1);
12001
12002 let reservation = scheduler.take_due_reservation(mono).expect("due");
12004 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12005 cooldown.insert(reserved_peer, mono);
12006 let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
12007 assert!(scheduler
12008 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12009 .is_none());
12010 assert_eq!(
12011 obs.capacity_evicted.load(Ordering::Relaxed),
12012 cap_before + 1,
12013 "the requeue eviction of a different peer is counted"
12014 );
12015 assert_eq!(
12016 scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
12017 Some([1; 32])
12018 );
12019 }
12020
12021 #[test]
12025 fn first_audit_pending_lower_count_does_not_replace_higher() {
12026 let obs = Arc::new(FirstAuditObservability::default());
12027 let mono = Instant::now();
12028 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12029 let peer = test_peer(1);
12030
12031 scheduler.enqueue(
12033 MonetizedPinEvent {
12034 peer,
12035 pin: [1; 32],
12036 key_count: 400,
12037 quote_ts: SystemTime::now(),
12038 },
12039 &obs,
12040 );
12041 scheduler.enqueue(
12043 MonetizedPinEvent {
12044 peer,
12045 pin: [2; 32],
12046 key_count: 100,
12047 quote_ts: SystemTime::now(),
12048 },
12049 &obs,
12050 );
12051
12052 assert_eq!(scheduler.pending_len(), 1);
12053 assert_eq!(
12054 scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12055 Some(([1; 32], 400)),
12056 "the inflated pin must not be erased by the cheaper successor"
12057 );
12058 assert_eq!(
12060 obs.suppressed_lower.load(Ordering::Relaxed),
12061 1,
12062 "the attempted cheaper-pin self-erasure is observable"
12063 );
12064
12065 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12067 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12068 let reservation = scheduler.take_due_reservation(mono).expect("due");
12069 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12070 let (event, _slot) = scheduler
12071 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12072 .expect("promotes");
12073 assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12074 }
12075
12076 #[test]
12081 fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
12082 let obs = Arc::new(FirstAuditObservability::default());
12083 let mono = Instant::now();
12084 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12085 let peer = test_peer(1);
12086
12087 scheduler.enqueue(
12089 MonetizedPinEvent {
12090 peer,
12091 pin: [1; 32],
12092 key_count: 400,
12093 quote_ts: SystemTime::now(),
12094 },
12095 &obs,
12096 );
12097 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12098 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12099
12100 scheduler.enqueue(
12103 MonetizedPinEvent {
12104 peer,
12105 pin: [2; 32],
12106 key_count: 100,
12107 quote_ts: SystemTime::now(),
12108 },
12109 &obs,
12110 );
12111 assert_eq!(scheduler.pending_len(), 1);
12112
12113 let reservation = scheduler.take_due_reservation(mono).expect("due");
12116 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12117 cooldown.insert(peer, mono);
12118 assert!(scheduler
12119 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12120 .is_none());
12121
12122 assert_eq!(scheduler.pending_len(), 1);
12124 assert_eq!(
12125 scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12126 Some(([1; 32], 400)),
12127 "the inflated reserved pin must survive the requeue over the cheaper successor"
12128 );
12129 assert!(scheduler.first_audited.is_empty());
12130 assert!(scheduler.limiter.recent.peek(&peer).is_none());
12131
12132 let later = mono
12135 .checked_add(Duration::from_secs(
12136 config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
12137 ))
12138 .expect("later");
12139 let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
12140 assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
12141 let reservation = scheduler.take_due_reservation(later).expect("due");
12142 let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
12143 let (event, _slot) = scheduler
12144 .resolve(
12145 reservation,
12146 SystemTime::now(),
12147 later,
12148 &mut cooldown_later,
12149 &obs,
12150 )
12151 .expect("promotes after cooldown");
12152 assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12153 }
12154
12155 #[test]
12160 fn first_audit_lane_alternates_across_promotions() {
12161 let obs = Arc::new(FirstAuditObservability::default());
12162 let mono = Instant::now();
12163 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12164 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12165
12166 let oldest_peer = test_peer(1);
12168 let newest_peer = test_peer(2);
12169 scheduler.enqueue(
12170 MonetizedPinEvent {
12171 peer: oldest_peer,
12172 pin: [1; 32],
12173 key_count: 100,
12174 quote_ts: SystemTime::now(),
12175 },
12176 &obs,
12177 );
12178 scheduler.enqueue(
12179 MonetizedPinEvent {
12180 peer: newest_peer,
12181 pin: [2; 32],
12182 key_count: 100,
12183 quote_ts: SystemTime::now(),
12184 },
12185 &obs,
12186 );
12187
12188 let mut launched_peers = Vec::new();
12189 for _ in 0..2 {
12190 assert!(scheduler.try_reserve(
12191 mono,
12192 obs.inflight.load(Ordering::Relaxed),
12193 Duration::ZERO,
12194 &cooldown,
12195 &obs
12196 ));
12197 let reservation = scheduler.take_due_reservation(mono).expect("due");
12198 let (event, _slot) = scheduler
12200 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12201 .expect("fresh in-window quote promotes");
12202 launched_peers.push(event.peer);
12203 }
12204
12205 assert_eq!(
12208 launched_peers,
12209 vec![newest_peer, oldest_peer],
12210 "consecutive promotions alternate newest-then-oldest lane"
12211 );
12212 }
12213
12214 #[test]
12215 fn first_audit_count_jump_boundaries() {
12216 assert!(!first_audit_count_jump(100, 150));
12218 assert!(first_audit_count_jump(100, 151));
12219 assert!(first_audit_count_jump(0, 1));
12221 assert!(!first_audit_count_jump(0, 0));
12222 assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
12224 }
12225
12226 #[test]
12232 fn first_audit_queue_drops_self_targeting_events() {
12233 let obs = Arc::new(FirstAuditObservability::default());
12234 let self_peer = test_peer(1);
12235 let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
12236 let self_event = MonetizedPinEvent {
12237 peer: self_peer,
12238 pin: [7; 32],
12239 key_count: 1,
12240 quote_ts: SystemTime::now(),
12241 };
12242
12243 scheduler.enqueue(self_event, &obs);
12244 assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
12245 assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
12246 assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
12247
12248 let remote_event = MonetizedPinEvent {
12250 peer: test_peer(2),
12251 pin: [8; 32],
12252 ..self_event
12253 };
12254 scheduler.enqueue(remote_event, &obs);
12255 assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
12256 assert_eq!(scheduler.pending_len(), 1);
12257 assert_eq!(
12258 obs.self_target_skipped.load(Ordering::Relaxed),
12259 1,
12260 "remote event must not count as a self-target skip"
12261 );
12262 }
12263
12264 #[test]
12265 fn fresh_offer_runs_store_admission_payment_checks() {
12266 let context = fresh_offer_payment_context();
12267 assert_eq!(context, VerificationContext::FreshReplication);
12268 assert!(context.is_store_admission());
12272 }
12273
12274 #[test]
12275 fn paid_notify_uses_paid_list_admission_payment_checks() {
12276 assert_eq!(
12277 paid_notify_payment_context(),
12278 VerificationContext::PaidListAdmission
12279 );
12280 }
12281
12282 #[test]
12286 fn monetized_quote_audit_window_fails_closed_both_ends() {
12287 let now = SystemTime::now();
12288 assert!(quote_within_audit_window(now, now));
12290 assert!(quote_within_audit_window(
12291 now + Duration::from_secs(60),
12292 now
12293 ));
12294 assert!(quote_within_audit_window(
12295 now - Duration::from_secs(3600),
12296 now
12297 ));
12298 assert!(!quote_within_audit_window(
12300 now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_secs(60),
12301 now
12302 ));
12303 assert!(!quote_within_audit_window(
12305 now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
12306 now
12307 ));
12308 }
12309
12310 #[tokio::test]
12311 async fn replication_branch_lagged_events_are_counted() {
12312 let before = audit_metrics::replication_event_lagged_total();
12313 let flow = handle_replication_event_recv_error(
12314 &tokio::sync::broadcast::error::RecvError::Lagged(3),
12315 );
12316 assert_eq!(flow, std::ops::ControlFlow::Continue(()));
12317 let after = audit_metrics::replication_event_lagged_total();
12318 assert_eq!(after.saturating_sub(before), 3);
12319 }
12320
12321 #[tokio::test]
12322 async fn replication_branch_closed_events_stop_the_loop() {
12323 let flow =
12324 handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
12325 assert_eq!(flow, std::ops::ControlFlow::Break(()));
12326 }
12327
12328 #[tokio::test]
12329 async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
12330 let (sender, mut receiver) = mpsc::channel(1);
12331 let dropped_body =
12332 ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
12333 keys: Vec::new(),
12334 paid_list_check_indices: Vec::new(),
12335 });
12336 let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12337 let first = InboundReplicationMessage {
12338 source: test_peer(0xC1),
12339 msg: ReplicationMessage {
12340 request_id: 1,
12341 body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
12342 key: test_key(1),
12343 }),
12344 },
12345 rr_message_id: None,
12346 received_at: Instant::now(),
12347 };
12348 let second = InboundReplicationMessage {
12349 source: test_peer(0xC2),
12350 msg: ReplicationMessage {
12351 request_id: 2,
12352 body: dropped_body.clone(),
12353 },
12354 rr_message_id: None,
12355 received_at: Instant::now(),
12356 };
12357
12358 assert!(try_enqueue_serial_message(&sender, first).is_ok());
12359 let dropped = try_enqueue_serial_message(&sender, second)
12360 .expect_err("a full serial queue must refuse the second message");
12361 assert_eq!(dropped.reason, SerialQueueDropReason::Full);
12362 assert_eq!(dropped.message_class, "verification_request");
12363 assert_eq!(dropped.queue_depth, 1);
12364 let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12365 assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
12366
12367 let queued = receiver
12368 .recv()
12369 .await
12370 .expect("first message should remain queued");
12371 assert_eq!(queued.msg.request_id, 1);
12372 assert!(receiver.try_recv().is_err());
12373 }
12374
12375 #[tokio::test]
12376 async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
12377 let peer = test_peer(0x44);
12378 let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
12379
12380 let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
12381 let mut digest_guards = Vec::new();
12382 for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
12383 let guard = admit_audit_responder(
12384 &semaphore,
12385 &digest_inflight,
12386 &peer,
12387 AuditResponderClass::Digest,
12388 )
12389 .await;
12390 assert!(guard.is_ok());
12391 digest_guards.push(guard);
12392 }
12393 assert!(
12394 admit_audit_responder(
12395 &semaphore,
12396 &digest_inflight,
12397 &peer,
12398 AuditResponderClass::Digest,
12399 )
12400 .await
12401 .is_err(),
12402 "digest class must stop at its documented per-source cap"
12403 );
12404 drop(digest_guards);
12405
12406 let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
12407 let mut subtree_guards = Vec::new();
12408 for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
12409 let guard = admit_audit_responder(
12410 &semaphore,
12411 &subtree_inflight,
12412 &peer,
12413 AuditResponderClass::Subtree,
12414 )
12415 .await;
12416 assert!(guard.is_ok());
12417 subtree_guards.push(guard);
12418 }
12419 assert!(
12420 admit_audit_responder(
12421 &semaphore,
12422 &subtree_inflight,
12423 &peer,
12424 AuditResponderClass::Subtree,
12425 )
12426 .await
12427 .is_err(),
12428 "subtree class must retain the deployed cap of two"
12429 );
12430 drop(subtree_guards);
12431 }
12432
12433 #[test]
12434 fn in_scope_audit_deadlines_share_one_formula() {
12435 let config = config::ReplicationConfig::default();
12436 for key_count in [1, 4, 16] {
12437 assert_eq!(
12438 audit::responsible_audit_response_timeout(&config, key_count),
12439 config.audit_response_timeout(key_count)
12440 );
12441 assert_eq!(
12442 pruning::prune_audit_response_timeout(&config, key_count),
12443 config.audit_response_timeout(key_count)
12444 );
12445 }
12446 assert_eq!(
12447 possession::possession_probe_response_timeout(&config),
12448 config.audit_response_timeout(1)
12449 );
12450 }
12451
12452 #[test]
12453 fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
12454 const EXISTING_SOURCE_ID: u8 = 1;
12455 const HINT_SENDER_ID: u8 = 2;
12456
12457 let existing_source = test_peer(EXISTING_SOURCE_ID);
12458 let hint_sender = test_peer(HINT_SENDER_ID);
12459 let mut sources = vec![existing_source];
12460
12461 let hint_sources = HashSet::from([hint_sender]);
12462 add_replica_hint_sources(&mut sources, &hint_sources);
12463 add_replica_hint_sources(&mut sources, &hint_sources);
12464
12465 add_replica_hint_sources(&mut sources, &HashSet::new());
12468
12469 assert_eq!(sources, vec![existing_source, hint_sender]);
12470 }
12471
12472 #[test]
12473 fn audit_timeout_preserves_active_bootstrap_claim() {
12474 assert!(!audit_failure_clears_bootstrap_claim(
12475 &AuditFailureReason::Timeout
12476 ));
12477 }
12478
12479 fn strike_peer(b: u8) -> PeerId {
12480 let mut bytes = [0u8; 32];
12481 bytes[0] = b;
12482 PeerId::from_bytes(bytes)
12483 }
12484
12485 #[test]
12489 fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
12490 let peer = strike_peer(1);
12491 let mut map: HashMap<PeerId, Instant> = HashMap::new();
12492 let t0 = Instant::now();
12493 assert!(cooldown_allows_audit(&mut map, &peer, t0));
12496 let mut passed = 1;
12497 for _ in 0..100 {
12498 if cooldown_allows_audit(&mut map, &peer, t0) {
12499 passed += 1;
12500 }
12501 }
12502 assert_eq!(
12503 passed, 1,
12504 "a flood at one instant must trigger exactly one audit"
12505 );
12506 }
12507
12508 #[test]
12529 fn losing_lottery_still_consumes_attempt_window() {
12530 let peer = strike_peer(3);
12534 let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12535 let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12536 let t0 = Instant::now();
12537
12538 assert!(
12541 !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
12542 "a losing ticket launches no audit"
12543 );
12544
12545 let mut audits = 0;
12550 for _ in 0..99 {
12551 if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
12552 audits += 1;
12553 }
12554 }
12555 assert_eq!(
12556 audits, 0,
12557 "a losing first ticket must consume the attempt window so no later \
12558 flooded message in the same window can audit"
12559 );
12560
12561 let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12564 assert!(
12565 audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
12566 "after the window a winning ticket audits again"
12567 );
12568 assert!(
12569 launched.contains_key(&peer),
12570 "a real launch stamps the shared cooldown"
12571 );
12572 }
12573
12574 #[test]
12582 fn losing_lottery_does_not_suppress_monetized_first_audit() {
12583 let peer = strike_peer(4);
12584 let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12585 let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12586 let t0 = Instant::now();
12587
12588 assert!(!audit_launch_decision(
12590 &mut attempts,
12591 &mut launched,
12592 &peer,
12593 t0,
12594 false
12595 ));
12596 assert!(
12600 cooldown_would_allow(&launched, &peer, t0),
12601 "reserve gate must not see a losing ticket as audit coverage"
12602 );
12603 assert!(
12604 cooldown_allows_audit(&mut launched, &peer, t0),
12605 "promotion must not be deferred by a losing ticket"
12606 );
12607
12608 let peer_won = strike_peer(5);
12611 assert!(audit_launch_decision(
12612 &mut attempts,
12613 &mut launched,
12614 &peer_won,
12615 t0,
12616 true
12617 ));
12618 assert!(
12619 !cooldown_would_allow(&launched, &peer_won, t0),
12620 "a real gossip audit still covers the peer for the window"
12621 );
12622 }
12623
12624 #[test]
12625 fn cooldown_lets_audit_through_after_the_window() {
12626 let peer = strike_peer(2);
12627 let mut map: HashMap<PeerId, Instant> = HashMap::new();
12628 let t0 = Instant::now();
12629 assert!(cooldown_allows_audit(&mut map, &peer, t0));
12630 let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
12632 assert!(!cooldown_allows_audit(&mut map, &peer, within));
12633 let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12635 assert!(cooldown_allows_audit(&mut map, &peer, after));
12636 }
12637
12638 #[test]
12639 fn cooldown_is_per_peer_independent() {
12640 let mut map: HashMap<PeerId, Instant> = HashMap::new();
12641 let t0 = Instant::now();
12642 for i in 0..20u8 {
12644 assert!(
12645 cooldown_allows_audit(&mut map, &strike_peer(i), t0),
12646 "peer {i} should be auditable independently"
12647 );
12648 }
12649 }
12650
12651 #[test]
12652 fn audit_on_gossip_constants_match_adr() {
12653 assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
12657 assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
12658 assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
12659 }
12660
12661 #[test]
12664 fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
12665 assert!(audit_failure_clears_bootstrap_claim(
12666 &AuditFailureReason::DigestMismatch
12667 ));
12668 assert!(audit_failure_revokes_holder_credit(
12669 &AuditFailureReason::DigestMismatch
12670 ));
12671 }
12672
12673 #[test]
12676 fn confirmed_failures_revoke_credit_timeout_does_not() {
12677 for reason in [
12678 AuditFailureReason::MalformedResponse,
12679 AuditFailureReason::DigestMismatch,
12680 AuditFailureReason::KeyAbsent,
12681 AuditFailureReason::Rejected,
12682 ] {
12683 assert!(
12684 audit_failure_revokes_holder_credit(&reason),
12685 "confirmed failure {reason:?} must revoke holder credit"
12686 );
12687 }
12688 assert!(
12689 !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
12690 "Timeout must NOT revoke credit (single dropped packet != storage loss)"
12691 );
12692 }
12693
12694 #[test]
12701 fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
12702 let peer = test_peer(0xAB);
12703 let key = test_key(1);
12704 let hash = [0xCD; 32];
12705
12706 let mut provers = RecentProvers::new();
12708 provers.record_proof(key, peer, hash, Instant::now());
12709 assert!(
12710 provers.is_credited_holder(&key, &peer, &hash),
12711 "precondition: peer credited before failure"
12712 );
12713 apply_audit_failure_credit_revocation(
12714 &mut provers,
12715 &peer,
12716 &AuditFailureReason::DigestMismatch,
12717 );
12718 assert!(
12719 !provers.is_credited_holder(&key, &peer, &hash),
12720 "DigestMismatch must strip the peer's holder credit"
12721 );
12722
12723 let mut provers_timeout = RecentProvers::new();
12725 provers_timeout.record_proof(key, peer, hash, Instant::now());
12726 apply_audit_failure_credit_revocation(
12727 &mut provers_timeout,
12728 &peer,
12729 &AuditFailureReason::Timeout,
12730 );
12731 assert!(
12732 provers_timeout.is_credited_holder(&key, &peer, &hash),
12733 "Timeout must retain holder credit (deliberate liveness cushion)"
12734 );
12735 }
12736
12737 #[test]
12738 fn decoded_audit_failures_clear_active_bootstrap_claim() {
12739 for reason in [
12740 AuditFailureReason::MalformedResponse,
12741 AuditFailureReason::DigestMismatch,
12742 AuditFailureReason::KeyAbsent,
12743 AuditFailureReason::Rejected,
12744 ] {
12745 assert!(
12746 audit_failure_clears_bootstrap_claim(&reason),
12747 "decoded non-bootstrap failure {reason:?} should clear active claim"
12748 );
12749 }
12750 }
12751
12752 #[test]
12753 fn first_failed_key_label_truncates_to_16_hex_chars() {
12754 let mut key = [0u8; 32];
12757 key[0] = 0x18;
12758 key[7] = 0xff;
12759 for byte in &mut key[8..] {
12762 *byte = 0xAA;
12763 }
12764 let label = first_failed_key_label(&[key]);
12765 assert_eq!(label, "0x18000000000000ff");
12767 assert_eq!(label.len(), "0x".len() + 16);
12768 }
12769
12770 #[test]
12771 fn first_failed_key_label_falls_back_when_empty() {
12772 assert_eq!(first_failed_key_label(&[]), "0x");
12776 }
12777
12778 #[test]
12779 fn first_failed_key_label_uses_first_key_only() {
12780 let first = [0x11u8; 32];
12781 let second = [0x22u8; 32];
12782 assert_eq!(
12783 first_failed_key_label(&[first, second]),
12784 format!("0x{}", hex::encode(&first[..8]))
12785 );
12786 }
12787
12788 fn drive_key_in_flight(
12801 q: &mut ReplicationQueues,
12802 key: XorName,
12803 sources: Vec<PeerId>,
12804 ) -> PeerId {
12805 let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
12806 let now = Instant::now();
12807 let entry = VerificationEntry {
12808 state: VerificationState::PendingVerify,
12809 verified_sources: Vec::new(),
12810 tried_sources: HashSet::new(),
12811 created_at: now,
12812 next_verify_at: now,
12813 hint_sources: HashSet::from([hinter]),
12814 replica_hint_sources: HashSet::from([hinter]),
12815 };
12816 assert!(q.add_pending_verify(key, entry).admitted());
12817 assert!(q.promote_pending_to_fetch(key, key, sources));
12818 let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
12819 let source = *candidate.sources.first().expect("candidate has a source");
12820 q.start_dequeued_fetch(candidate, source);
12821 source
12822 }
12823
12824 #[test]
12825 fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
12826 const RETRY_AFTER: Duration = Duration::from_secs(60);
12827
12828 let mut q = ReplicationQueues::new();
12829 let key = test_key(0xAB);
12830 drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
12831 assert_eq!(q.retry_reserved_slot_count(), 1);
12832
12833 let follow_up =
12834 apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
12835
12836 assert_eq!(
12837 follow_up,
12838 FetchFollowUp::Terminal,
12839 "lapsed responsibility must run the caller's terminal bootstrap accounting"
12840 );
12841 assert!(
12842 !q.contains_key(&key),
12843 "the key must leave every pipeline stage — alternate sources included"
12844 );
12845 assert_eq!(
12846 q.pending_count(),
12847 0,
12848 "a lapsed-responsibility key must not be requeued for verification"
12849 );
12850 assert_eq!(
12851 q.retry_reserved_slot_count(),
12852 0,
12853 "terminal exit must release the verification retry-slot reservation"
12854 );
12855 }
12856
12857 #[test]
12858 fn no_longer_responsible_shares_the_stored_terminal_path() {
12859 const RETRY_AFTER: Duration = Duration::from_secs(60);
12860
12861 for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
12865 let mut q = ReplicationQueues::new();
12866 let key = test_key(0xCD);
12867 drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
12868
12869 let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
12870
12871 assert_eq!(follow_up, FetchFollowUp::Terminal);
12872 assert!(!q.contains_key(&key));
12873 assert_eq!(q.retry_reserved_slot_count(), 0);
12874 }
12875 }
12876
12877 #[test]
12878 fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
12879 const RETRY_AFTER: Duration = Duration::from_secs(60);
12880
12881 let mut q = ReplicationQueues::new();
12882 let key = test_key(0xEF);
12883 let first = test_peer(0x04);
12884 let second = test_peer(0x05);
12885 drive_key_in_flight(&mut q, key, vec![first, second]);
12886
12887 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12888 assert_eq!(
12889 follow_up,
12890 FetchFollowUp::RetryFrom(second),
12891 "a failed source must not abandon the remaining verified sources"
12892 );
12893 assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
12894
12895 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12896 assert_eq!(
12897 follow_up,
12898 FetchFollowUp::RequeuedForVerification,
12899 "exhausted sources must restore the reserved verification entry"
12900 );
12901 assert_eq!(q.pending_count(), 1);
12902 assert_eq!(
12903 q.retry_reserved_slot_count(),
12904 0,
12905 "the reservation converts back into the pending entry itself"
12906 );
12907 }
12908
12909 #[test]
12910 fn source_failure_without_retry_metadata_is_terminal() {
12911 const RETRY_AFTER: Duration = Duration::from_secs(60);
12912
12913 let mut q = ReplicationQueues::new();
12916 let key = test_key(0x1F);
12917 let source = test_peer(0x06);
12918 assert!(q.enqueue_fetch(key, key, vec![source]));
12919 let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
12920 q.start_dequeued_fetch(candidate, source);
12921
12922 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12923
12924 assert_eq!(follow_up, FetchFollowUp::Terminal);
12925 assert!(!q.contains_key(&key));
12926 }
12927
12928 #[test]
12929 fn already_held_key_leaves_the_pipeline_terminally() {
12930 const RETRY_AFTER: Duration = Duration::from_secs(60);
12931
12932 let mut q = ReplicationQueues::new();
12933 let key = test_key(0x4C);
12934 let source = test_peer(0x0B);
12935 drive_key_in_flight(&mut q, key, vec![source, test_peer(0x0C)]);
12936
12937 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::AlreadyHeld, RETRY_AFTER);
12938
12939 assert_eq!(
12940 follow_up,
12941 FetchFollowUp::Terminal,
12942 "holding the key already discharges the duty, so the key must leave \
12943 the pipeline exactly as a completed fetch does — requeueing it \
12944 would re-verify a key that needs nothing"
12945 );
12946 assert!(!q.contains_key(&key));
12947 assert_eq!(
12948 q.retry_reserved_slot_count(),
12949 0,
12950 "the terminal path must release the retry-slot reservation, or the \
12951 owner's verification budget leaks"
12952 );
12953 }
12954
12955 #[test]
12956 fn local_write_failure_does_not_conscript_the_remaining_sources() {
12957 const RETRY_AFTER: Duration = Duration::from_secs(60);
12958
12959 let mut q = ReplicationQueues::new();
12960 let key = test_key(0x2A);
12961 let first = test_peer(0x07);
12962 let second = test_peer(0x08);
12963 let third = test_peer(0x09);
12964 drive_key_in_flight(&mut q, key, vec![first, second, third]);
12965
12966 let follow_up =
12967 apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
12968
12969 assert_eq!(
12970 follow_up,
12971 FetchFollowUp::RequeuedForVerification,
12972 "a local write failure must go straight back to verification: the two \
12973 untried sources would each re-upload the same chunk into the same \
12974 full disk, and neither of them did anything wrong"
12975 );
12976 assert_eq!(q.in_flight_count(), 0);
12977 assert_eq!(
12978 q.pending_count(),
12979 1,
12980 "the key must come back — capacity frees up, and a stranded key is \
12981 a replica this node silently stops owing"
12982 );
12983 assert_eq!(q.retry_reserved_slot_count(), 0);
12984 }
12985
12986 #[test]
12987 fn local_write_failure_without_retry_metadata_is_terminal() {
12988 const RETRY_AFTER: Duration = Duration::from_secs(60);
12989
12990 let mut q = ReplicationQueues::new();
12994 let key = test_key(0x3B);
12995 let source = test_peer(0x0A);
12996 assert!(q.enqueue_fetch(key, key, vec![source]));
12997 let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
12998 q.start_dequeued_fetch(candidate, source);
12999
13000 let follow_up =
13001 apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13002
13003 assert_eq!(follow_up, FetchFollowUp::Terminal);
13004 assert!(!q.contains_key(&key));
13005 assert_eq!(q.retry_reserved_slot_count(), 0);
13006 }
13007}