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
1527const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_secs(30 * 60);
1540
1541fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
1548 let too_future = quote_ts
1549 .duration_since(now)
1550 .is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
1551 let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
1552 let too_old = now
1553 .duration_since(quote_ts)
1554 .is_ok_and(|age| age >= audit_cutoff);
1555 !(too_future || too_old)
1556}
1557
1558const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_secs(60);
1567
1568const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
1582
1583#[allow(clippy::cast_possible_truncation)] const FIRST_AUDIT_PENDING_CAP: usize = {
1611 let strict_horizon_secs = GOSSIP_ANSWERABILITY_TTL
1612 .as_secs()
1613 .saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN.as_secs())
1614 .saturating_sub(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_secs())
1615 .saturating_sub(FIRST_AUDIT_SEND_LATENCY_SLACK.as_secs());
1616 let refills =
1621 strict_horizon_secs.saturating_sub(1) / config::FIRST_AUDIT_LAUNCH_INTERVAL.as_secs();
1622 (refills + config::FIRST_AUDIT_BUDGET_BURST as u64) as usize
1623};
1624
1625const _: () = {
1628 assert!(FIRST_AUDIT_PENDING_CAP >= 1);
1629 assert!(FIRST_AUDIT_PENDING_CAP < MAX_LAST_COMMITMENT_BY_PEER);
1630};
1631
1632const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
1641
1642pub struct ReplicationEngine {
1648 config: Arc<ReplicationConfig>,
1650 p2p_node: Arc<P2PNode>,
1652 storage: Arc<LmdbStorage>,
1654 paid_list: Arc<PaidList>,
1656 payment_verifier: Arc<PaymentVerifier>,
1658 queues: Arc<RwLock<ReplicationQueues>>,
1660 sync_state: Arc<RwLock<NeighborSyncState>>,
1662 sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
1668 audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
1674 gossip_lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1679 sync_cycle_epoch: Arc<RwLock<u64>>,
1681 repair_proofs: Arc<RwLock<RepairProofs>>,
1683 bootstrap_state: Arc<RwLock<BootstrapState>>,
1685 is_bootstrapping: Arc<RwLock<bool>>,
1687 sync_trigger: Arc<Notify>,
1689 bootstrap_complete_notify: Arc<Notify>,
1691 identity: Arc<NodeIdentity>,
1696 commitment_state: Arc<ResponderCommitmentState>,
1702 retention_path: PathBuf,
1708 last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1719 ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
1729 recent_provers: Arc<RwLock<RecentProvers>>,
1734 sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1741 send_semaphore: Arc<Semaphore>,
1744 audit_responder_semaphore: Arc<Semaphore>,
1752 audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1760 audit_responder_metrics: Arc<AuditResponderMetrics>,
1763 audit_challenge_coordinator: Arc<AuditChallengeCoordinator>,
1769 fetch_responder_worker_semaphore: Arc<Semaphore>,
1771 fetch_responder_admission_semaphore: Arc<Semaphore>,
1773 fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1775 verification_responder_worker_semaphore: Arc<Semaphore>,
1777 verification_responder_admission_semaphore: Arc<Semaphore>,
1779 verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1781 neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
1783 neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
1785 neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1787 fresh_offer_worker_semaphore: Arc<Semaphore>,
1789 fresh_offer_admission_semaphore: Arc<Semaphore>,
1791 fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1794 fresh_offer_in_flight: FreshOfferInFlight,
1797 paid_notify_worker_semaphore: Arc<Semaphore>,
1799 paid_notify_admission_semaphore: Arc<Semaphore>,
1801 paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1803 subtree_round1: SubtreeRound1Limiter,
1808 fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
1813 possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
1817 possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
1819 monetized_pin_tx: mpsc::Sender<MonetizedPinEvent>,
1827 monetized_pin_rx: Option<mpsc::Receiver<MonetizedPinEvent>>,
1830 first_audit_observability: Arc<FirstAuditObservability>,
1834 shutdown: CancellationToken,
1836 task_handles: Vec<JoinHandle<()>>,
1838 detached_task_tracker: TaskTracker,
1845}
1846
1847impl ReplicationEngine {
1848 #[allow(clippy::too_many_arguments)]
1855 pub async fn new(
1856 config: ReplicationConfig,
1857 p2p_node: Arc<P2PNode>,
1858 storage: Arc<LmdbStorage>,
1859 payment_verifier: Arc<PaymentVerifier>,
1860 identity: Arc<NodeIdentity>,
1861 root_dir: &Path,
1862 fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
1863 shutdown: CancellationToken,
1864 ) -> Result<Self> {
1865 config.validate().map_err(Error::Config)?;
1866
1867 let paid_list = Arc::new(
1868 PaidList::new(root_dir)
1869 .await
1870 .map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
1871 );
1872
1873 let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
1874 let config = Arc::new(config);
1875 let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
1876
1877 let (monetized_pin_tx, monetized_pin_rx) =
1882 mpsc::channel(config::FIRST_AUDIT_INGRESS_CAPACITY);
1883
1884 let engine = Self {
1885 config: Arc::clone(&config),
1886 p2p_node,
1887 storage,
1888 paid_list,
1889 payment_verifier,
1890 queues: Arc::new(RwLock::new(ReplicationQueues::new())),
1891 sync_state: Arc::new(RwLock::new(initial_neighbors)),
1892 sync_history: Arc::new(RwLock::new(HashMap::new())),
1893 audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
1894 gossip_lottery_attempts: Arc::new(RwLock::new(HashMap::new())),
1895 sync_cycle_epoch: Arc::new(RwLock::new(0)),
1896 repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
1897 bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
1898 is_bootstrapping: Arc::new(RwLock::new(true)),
1899 sync_trigger: Arc::new(Notify::new()),
1900 bootstrap_complete_notify: Arc::new(Notify::new()),
1901 identity,
1902 commitment_state: Arc::new(ResponderCommitmentState::new()),
1903 retention_path: root_dir.join("commitment_retention.bin"),
1904 last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
1905 ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
1906 recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
1907 sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
1908 send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
1909 audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
1910 audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1911 audit_responder_metrics: Arc::new(AuditResponderMetrics::default()),
1912 audit_challenge_coordinator: Arc::new(AuditChallengeCoordinator::new()),
1913 fetch_responder_worker_semaphore: Arc::new(Semaphore::new(
1914 FETCH_RESPONDER_WORKER_LIMIT,
1915 )),
1916 fetch_responder_admission_semaphore: Arc::new(Semaphore::new(
1917 FETCH_RESPONDER_MAX_OUTSTANDING,
1918 )),
1919 fetch_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1920 verification_responder_worker_semaphore: Arc::new(Semaphore::new(
1921 VERIFICATION_RESPONDER_WORKER_LIMIT,
1922 )),
1923 verification_responder_admission_semaphore: Arc::new(Semaphore::new(
1924 VERIFICATION_RESPONDER_MAX_OUTSTANDING,
1925 )),
1926 verification_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1927 neighbor_sync_responder_worker_semaphore: Arc::new(Semaphore::new(
1928 NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT,
1929 )),
1930 neighbor_sync_responder_admission_semaphore: Arc::new(Semaphore::new(
1931 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
1932 )),
1933 neighbor_sync_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1934 fresh_offer_worker_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_WORKER_LIMIT)),
1935 fresh_offer_admission_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING)),
1936 fresh_offer_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1937 fresh_offer_in_flight: Arc::new(Mutex::new(HashMap::new())),
1938 paid_notify_worker_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_WORKER_LIMIT)),
1939 paid_notify_admission_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING)),
1940 paid_notify_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1941 subtree_round1: SubtreeRound1Limiter::new(
1942 config.subtree_round1_responder_cooldown,
1943 config.subtree_round1_max_concurrent,
1944 ),
1945 fresh_write_rx: Some(fresh_write_rx),
1946 possession_check_tx,
1947 possession_check_rx: Some(possession_check_rx),
1948 monetized_pin_tx,
1949 monetized_pin_rx: Some(monetized_pin_rx),
1950 first_audit_observability: Arc::new(FirstAuditObservability::default()),
1951 shutdown,
1952 task_handles: Vec::new(),
1953 detached_task_tracker: TaskTracker::new(),
1954 };
1955 load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
1960 Ok(engine)
1961 }
1962
1963 #[must_use]
1968 pub fn monetized_pin_sender(&self) -> mpsc::Sender<MonetizedPinEvent> {
1969 self.monetized_pin_tx.clone()
1970 }
1971
1972 #[must_use]
1974 pub fn paid_list(&self) -> &Arc<PaidList> {
1975 &self.paid_list
1976 }
1977
1978 #[must_use]
1982 pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
1983 &self.commitment_state
1984 }
1985
1986 #[must_use]
1988 pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
1989 &self.last_commitment_by_peer
1990 }
1991
1992 #[must_use]
1995 pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
1996 &self.recent_provers
1997 }
1998
1999 #[cfg(any(test, feature = "test-utils"))]
2008 pub async fn rebuild_commitment_now(&self) -> Result<()> {
2009 rebuild_and_rotate_commitment(
2010 &self.storage,
2011 &self.identity,
2012 &self.commitment_state,
2013 &self.p2p_node,
2014 &self.config,
2015 )
2016 .await
2017 }
2018
2019 #[cfg(any(feature = "test-utils", test))]
2024 pub async fn inject_peer_commitment_for_test(
2025 &self,
2026 peer: &PeerId,
2027 commitment: StorageCommitment,
2028 ) {
2029 let now = Instant::now();
2030 self.last_commitment_by_peer
2031 .write()
2032 .await
2033 .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
2034 self.ever_capable_peers.write().await.insert(*peer);
2035 }
2036
2037 #[cfg(any(test, feature = "test-utils"))]
2042 pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
2043 let now = Instant::now();
2044 let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
2045 let mut launched = self.audit_on_gossip_cooldown.write().await;
2046 lottery_attempts.insert(*peer, now);
2047 launched.remove(peer);
2048 }
2049
2050 #[cfg(any(test, feature = "test-utils"))]
2058 pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
2059 let target = {
2060 let map = self.last_commitment_by_peer.read().await;
2061 map.get(peer)
2062 .and_then(PeerCommitmentRecord::last_commitment)
2063 .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
2064 };
2065 let Some((pin, key_count)) = target else {
2066 return audit::AuditTickResult::Idle;
2067 };
2068 let credit = storage_commitment_audit::AuditCredit {
2069 recent_provers: &self.recent_provers,
2070 };
2071 storage_commitment_audit::run_subtree_audit(
2072 &self.p2p_node,
2073 &self.config,
2074 peer,
2075 pin,
2076 key_count,
2077 Some(&credit),
2078 )
2079 .await
2080 }
2081
2082 #[cfg(any(test, feature = "test-utils"))]
2086 #[must_use]
2087 pub fn first_audit_stats(&self) -> FirstAuditStats {
2088 let o = &self.first_audit_observability;
2089 FirstAuditStats {
2090 received: o.received.load(Ordering::Relaxed),
2091 queued: o.queued.load(Ordering::Relaxed),
2092 self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
2093 launched: o.launched.load(Ordering::Relaxed),
2094 passed: o.passed.load(Ordering::Relaxed),
2095 timed_out: o.timed_out.load(Ordering::Relaxed),
2096 failed: o.failed.load(Ordering::Relaxed),
2097 }
2098 }
2099
2100 #[cfg(any(test, feature = "test-utils"))]
2107 pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
2108 possession::run_possession_check(
2109 key,
2110 peers,
2111 &self.p2p_node,
2112 &self.storage,
2113 &self.config,
2114 &self.sync_state,
2115 &self.audit_challenge_coordinator,
2116 &self.shutdown,
2117 )
2118 .await;
2119 }
2120
2121 #[cfg(any(test, feature = "test-utils"))]
2132 pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
2133 let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
2134 self.queues
2135 .write()
2136 .await
2137 .enqueue_fetch(key, distance, sources)
2138 }
2139
2140 #[cfg(any(test, feature = "test-utils"))]
2143 pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
2144 self.queues.read().await.contains_key(key)
2145 }
2146
2147 pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
2153 if !self.task_handles.is_empty() {
2154 error!("ReplicationEngine::start() called while already running — ignoring");
2155 return;
2156 }
2157 info!("Starting replication engine");
2158
2159 self.start_message_handler();
2160 self.start_neighbor_sync_loop();
2161 self.start_self_lookup_loop();
2162 self.start_audit_loop();
2165 self.start_commitment_rotation_loop();
2168 self.start_retention_persist_loop();
2169 self.start_fetch_worker();
2170 self.start_verification_worker();
2171 self.start_bootstrap_sync(dht_events);
2172 self.start_fresh_write_drainer();
2173 self.start_possession_check_scheduler();
2174 self.start_first_audit_drainer();
2177 self.start_traffic_summary_loop();
2179 #[cfg(feature = "logging")]
2180 self.start_audit_responder_summary_loop();
2181
2182 info!(
2183 "Replication engine started with {} background tasks",
2184 self.task_handles.len()
2185 );
2186 }
2187
2188 pub async fn is_bootstrapping(&self) -> bool {
2193 *self.is_bootstrapping.read().await
2194 }
2195
2196 pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
2205 let notified = self.bootstrap_complete_notify.notified();
2208 tokio::pin!(notified);
2209 notified.as_mut().enable();
2210
2211 if !*self.is_bootstrapping.read().await {
2212 return true;
2213 }
2214
2215 tokio::time::timeout(timeout, notified).await.is_ok()
2216 }
2217
2218 pub async fn shutdown(&mut self) {
2232 self.shutdown.cancel();
2233 for (i, mut handle) in self.task_handles.drain(..).enumerate() {
2234 match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
2235 Ok(Ok(())) => {}
2236 Ok(Err(e)) if e.is_cancelled() => {}
2237 Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
2238 Err(_) => {
2239 warn!(
2240 "Replication task {i} did not stop within {}s, aborting",
2241 SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
2242 );
2243 handle.abort();
2244 match handle.await {
2248 Ok(()) => {}
2249 Err(e) if e.is_cancelled() => {}
2250 Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
2251 }
2252 }
2253 }
2254 }
2255
2256 self.fresh_offer_worker_semaphore.close();
2262 self.paid_notify_worker_semaphore.close();
2263 self.fetch_responder_worker_semaphore.close();
2264 self.verification_responder_worker_semaphore.close();
2265 self.neighbor_sync_responder_worker_semaphore.close();
2266
2267 self.detached_task_tracker.close();
2280 self.detached_task_tracker.wait().await;
2281
2282 self.storage.wait_idle().await;
2290 self.paid_list.wait_idle().await;
2291 }
2292
2293 pub fn trigger_neighbor_sync(&self) {
2299 self.sync_trigger.notify_one();
2300 }
2301
2302 pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
2308 let peers = fresh::replicate_fresh(
2309 key,
2310 data,
2311 proof_of_payment,
2312 &self.p2p_node,
2313 &self.paid_list,
2314 &self.config,
2315 &self.send_semaphore,
2316 )
2317 .await;
2318 if !peers.is_empty() {
2319 let _ = self
2320 .possession_check_tx
2321 .send(possession::PossessionCheckEvent { key: *key, peers });
2322 }
2323 }
2324
2325 fn start_fresh_write_drainer(&mut self) {
2332 let Some(mut rx) = self.fresh_write_rx.take() else {
2333 return;
2334 };
2335 let p2p = Arc::clone(&self.p2p_node);
2336 let paid_list = Arc::clone(&self.paid_list);
2337 let config = Arc::clone(&self.config);
2338 let send_semaphore = Arc::clone(&self.send_semaphore);
2339 let possession_tx = self.possession_check_tx.clone();
2340 let shutdown = self.shutdown.clone();
2341
2342 let handle = tokio::spawn(async move {
2343 loop {
2344 tokio::select! {
2345 () = shutdown.cancelled() => break,
2346 event = rx.recv() => {
2347 let Some(event) = event else { break };
2348 let peers = fresh::replicate_fresh(
2349 &event.key,
2350 &event.data,
2351 &event.payment_proof,
2352 &p2p,
2353 &paid_list,
2354 &config,
2355 &send_semaphore,
2356 )
2357 .await;
2358 if !peers.is_empty() {
2362 let _ = possession_tx.send(possession::PossessionCheckEvent {
2363 key: event.key,
2364 peers,
2365 });
2366 }
2367 }
2368 }
2369 }
2370 debug!("Fresh-write drainer shut down");
2371 });
2372 self.task_handles.push(handle);
2373 }
2374
2375 fn start_possession_check_scheduler(&mut self) {
2382 let Some(mut rx) = self.possession_check_rx.take() else {
2383 return;
2384 };
2385 let p2p = Arc::clone(&self.p2p_node);
2386 let storage = Arc::clone(&self.storage);
2387 let config = Arc::clone(&self.config);
2388 let sync_state = Arc::clone(&self.sync_state);
2389 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
2390 let shutdown = self.shutdown.clone();
2391 let detached_task_tracker = self.detached_task_tracker.clone();
2392
2393 let handle = tokio::spawn(async move {
2394 loop {
2395 tokio::select! {
2396 () = shutdown.cancelled() => break,
2397 event = rx.recv() => {
2398 let Some(event) = event else { break };
2399 let p2p = Arc::clone(&p2p);
2403 let storage = Arc::clone(&storage);
2404 let config = Arc::clone(&config);
2405 let sync_state = Arc::clone(&sync_state);
2406 let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
2407 let shutdown = shutdown.clone();
2408 let delay_min = config.possession_check_delay_min;
2409 let delay_max = config.possession_check_delay_max;
2410 detached_task_tracker.spawn(async move {
2411 let delay = possession::random_delay(delay_min, delay_max);
2412 tokio::select! {
2428 () = shutdown.cancelled() => {}
2429 () = async {
2430 tokio::time::sleep(delay).await;
2431 possession::run_possession_check(
2432 event.key,
2433 event.peers,
2434 &p2p,
2435 &storage,
2436 &config,
2437 &sync_state,
2438 &audit_challenge_coordinator,
2439 &shutdown,
2440 )
2441 .await;
2442 } => {}
2443 }
2444 });
2445 }
2446 }
2447 }
2448 debug!("Possession-check scheduler shut down");
2449 });
2450 self.task_handles.push(handle);
2451 }
2452
2453 #[allow(clippy::too_many_lines)]
2462 fn start_first_audit_drainer(&mut self) {
2463 let Some(mut rx) = self.monetized_pin_rx.take() else {
2464 return;
2465 };
2466 let gossip_audit = GossipAuditTrigger {
2467 p2p_node: Arc::clone(&self.p2p_node),
2468 config: Arc::clone(&self.config),
2469 recent_provers: Arc::clone(&self.recent_provers),
2470 sync_state: Arc::clone(&self.sync_state),
2471 cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2472 detached_task_tracker: self.detached_task_tracker.clone(),
2473 lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2474 };
2475 let shutdown = self.shutdown.clone();
2476 let observability = Arc::clone(&self.first_audit_observability);
2477 let self_peer = *self.p2p_node.peer_id();
2478
2479 let handle = tokio::spawn(async move {
2480 let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
2486 let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
2489 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2490 let mut last_summary = Instant::now();
2491 loop {
2492 let promotion_due = scheduler
2498 .reserved_ready_at()
2499 .unwrap_or_else(first_audit_far_future);
2500 tokio::select! {
2501 () = shutdown.cancelled() => break,
2502 event = rx.recv() => match event {
2503 Some(e) => {
2504 observability.received.fetch_add(1, Ordering::Relaxed);
2505 if scheduler.would_displace(&e) {
2514 open_first_audit_reservation(
2515 &mut scheduler,
2516 &gossip_audit.cooldown,
2517 &observability,
2518 )
2519 .await;
2520 }
2521 scheduler.enqueue(e, &observability);
2522 let mut drained = 1usize;
2525 while drained < config::FIRST_AUDIT_DRAIN_BATCH {
2526 match rx.try_recv() {
2527 Ok(e) => {
2528 observability.received.fetch_add(1, Ordering::Relaxed);
2529 if scheduler.would_displace(&e) {
2530 open_first_audit_reservation(
2531 &mut scheduler,
2532 &gossip_audit.cooldown,
2533 &observability,
2534 )
2535 .await;
2536 }
2537 scheduler.enqueue(e, &observability);
2538 drained += 1;
2539 }
2540 Err(_) => break,
2541 }
2542 }
2543 }
2544 None => break,
2545 },
2546 _ = tick.tick() => {}
2547 () = tokio::time::sleep_until(promotion_due.into()) => {}
2548 }
2549
2550 if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
2556 let promoted = {
2557 let mut cooldown = gossip_audit.cooldown.write().await;
2558 scheduler.resolve(
2559 reservation,
2560 SystemTime::now(),
2561 Instant::now(),
2562 &mut cooldown,
2563 &observability,
2564 )
2565 };
2566 if let Some((event, inflight_slot)) = promoted {
2567 debug!(
2568 "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
2569 event.peer, hex::encode(event.pin), event.key_count,
2570 observability.inflight.load(Ordering::Relaxed)
2571 );
2572 let trigger = gossip_audit.clone();
2573 let audit_observability = Arc::clone(&observability);
2574 let tracker = trigger.detached_task_tracker.clone();
2582 tracker.spawn(async move {
2583 let inflight_slot = inflight_slot;
2587 let started = Instant::now();
2588 let credit = storage_commitment_audit::AuditCredit {
2589 recent_provers: &trigger.recent_provers,
2590 };
2591 let result = storage_commitment_audit::run_subtree_audit(
2592 &trigger.p2p_node,
2593 &trigger.config,
2594 &event.peer,
2595 event.pin,
2596 event.key_count,
2597 Some(&credit),
2598 )
2599 .await;
2600 let outcome = first_audit_terminal_outcome(&result);
2601 match outcome {
2602 FirstAuditTerminalOutcome::Passed => {
2603 audit_observability.passed.fetch_add(1, Ordering::Relaxed);
2604 }
2605 FirstAuditTerminalOutcome::Timeout => {
2606 audit_observability
2607 .timed_out
2608 .fetch_add(1, Ordering::Relaxed);
2609 }
2610 FirstAuditTerminalOutcome::Failed => {
2611 audit_observability.failed.fetch_add(1, Ordering::Relaxed);
2612 }
2613 FirstAuditTerminalOutcome::BootstrapClaim => {
2614 audit_observability
2615 .bootstrap_claims
2616 .fetch_add(1, Ordering::Relaxed);
2617 }
2618 FirstAuditTerminalOutcome::Idle => {
2619 audit_observability.idle.fetch_add(1, Ordering::Relaxed);
2620 }
2621 FirstAuditTerminalOutcome::InsufficientKeys => {
2622 audit_observability
2623 .insufficient_keys
2624 .fetch_add(1, Ordering::Relaxed);
2625 }
2626 }
2627 drop(inflight_slot);
2628 debug!(
2629 "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
2630 outcome.as_str(),
2631 event.peer, hex::encode(event.pin), event.key_count,
2632 started.elapsed().as_millis(),
2633 audit_observability.inflight.load(Ordering::Relaxed)
2634 );
2635 handle_subtree_audit_result(
2636 &result,
2637 &trigger.p2p_node,
2638 &trigger.sync_state,
2639 &trigger.recent_provers,
2640 &trigger.config,
2641 )
2642 .await;
2643 });
2644 }
2645 }
2646
2647 open_first_audit_reservation(
2653 &mut scheduler,
2654 &gossip_audit.cooldown,
2655 &observability,
2656 )
2657 .await;
2658
2659 if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
2660 let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
2665 if swept > 0 {
2666 debug!(
2667 "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
2668 scheduler.pending_len()
2669 );
2670 }
2671 info!(
2672 "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={}",
2673 FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
2674 observability.received.load(Ordering::Relaxed),
2675 observability.queued.load(Ordering::Relaxed),
2676 observability.coalesced.load(Ordering::Relaxed),
2677 observability.suppressed_lower.load(Ordering::Relaxed),
2678 observability.duplicates.load(Ordering::Relaxed),
2679 observability.capacity_evicted.load(Ordering::Relaxed),
2680 observability.self_target_skipped.load(Ordering::Relaxed),
2681 observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
2682 observability.rate_deferred_attempts.load(Ordering::Relaxed),
2683 observability.window_deduped.load(Ordering::Relaxed),
2684 observability.launched.load(Ordering::Relaxed),
2685 observability.passed.load(Ordering::Relaxed),
2686 observability.timed_out.load(Ordering::Relaxed),
2687 observability.failed.load(Ordering::Relaxed),
2688 observability.bootstrap_claims.load(Ordering::Relaxed),
2689 observability.idle.load(Ordering::Relaxed),
2690 observability.insufficient_keys.load(Ordering::Relaxed),
2691 observability.outside_answerability_window.load(Ordering::Relaxed),
2692 scheduler.pending_len(),
2693 FIRST_AUDIT_PENDING_CAP,
2694 u8::from(scheduler.has_reservation()),
2695 scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
2696 observability.inflight.load(Ordering::Relaxed),
2697 scheduler.tokens(),
2698 );
2699 last_summary = Instant::now();
2700 }
2701 }
2702 debug!("First-audit drainer shut down");
2703 });
2704 self.task_handles.push(handle);
2705 }
2706
2707 #[allow(clippy::too_many_lines)]
2708 fn start_message_handler(&mut self) {
2709 let mut p2p_events = self.p2p_node.subscribe_events();
2710 let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
2711 let p2p = Arc::clone(&self.p2p_node);
2712 let storage = Arc::clone(&self.storage);
2713 let paid_list = Arc::clone(&self.paid_list);
2714 let payment_verifier = Arc::clone(&self.payment_verifier);
2715 let queues = Arc::clone(&self.queues);
2716 let config = Arc::clone(&self.config);
2717 let shutdown = self.shutdown.clone();
2718 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2719 let bootstrap_state = Arc::clone(&self.bootstrap_state);
2720 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
2721 let sync_history = Arc::clone(&self.sync_history);
2722 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2723 let repair_proofs = Arc::clone(&self.repair_proofs);
2724 let sync_trigger = Arc::clone(&self.sync_trigger);
2725 let my_commitment_state = Arc::clone(&self.commitment_state);
2726 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2727 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2728 let recent_provers = Arc::clone(&self.recent_provers);
2729 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
2730 let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
2731 let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
2732 let sync_state = Arc::clone(&self.sync_state);
2733 let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
2734 let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
2735 let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
2736 let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
2737 let fetch_responder_admission_semaphore =
2738 Arc::clone(&self.fetch_responder_admission_semaphore);
2739 let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
2740 let verification_responder_worker_semaphore =
2741 Arc::clone(&self.verification_responder_worker_semaphore);
2742 let verification_responder_admission_semaphore =
2743 Arc::clone(&self.verification_responder_admission_semaphore);
2744 let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
2745 let neighbor_sync_responder_worker_semaphore =
2746 Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
2747 let neighbor_sync_responder_admission_semaphore =
2748 Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
2749 let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
2750 let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
2751 let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
2752 let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
2753 let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
2754 let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
2755 let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
2756 let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
2757 let detached_task_tracker = self.detached_task_tracker.clone();
2758 let subtree_round1 = self.subtree_round1.clone();
2759
2760 let gossip_audit = GossipAuditTrigger {
2763 p2p_node: Arc::clone(&p2p),
2764 config: Arc::clone(&config),
2765 recent_provers: Arc::clone(&recent_provers),
2766 sync_state: Arc::clone(&sync_state),
2767 cooldown: Arc::clone(&audit_on_gossip_cooldown),
2768 detached_task_tracker: detached_task_tracker.clone(),
2769 lottery_attempts: Arc::clone(&gossip_lottery_attempts),
2770 };
2771
2772 let handler_context = ReplicationMessageHandlerContext {
2773 p2p_node: Arc::clone(&p2p),
2774 storage,
2775 paid_list,
2776 payment_verifier,
2777 queues,
2778 config: Arc::clone(&config),
2779 is_bootstrapping,
2780 bootstrap_state,
2781 sync_history,
2782 sync_cycle_epoch,
2783 repair_proofs: Arc::clone(&repair_proofs),
2784 last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
2785 ever_capable_peers,
2786 sig_verify_attempts: Arc::clone(&sig_verify_attempts),
2787 my_commitment_state,
2788 gossip_audit,
2789 audit_responder_semaphore,
2790 audit_responder_inflight,
2791 audit_responder_metrics,
2792 subtree_round1,
2793 fetch_responder_worker_semaphore,
2794 fetch_responder_admission_semaphore,
2795 fetch_responder_inflight,
2796 verification_responder_worker_semaphore,
2797 verification_responder_admission_semaphore,
2798 verification_responder_inflight,
2799 neighbor_sync_responder_worker_semaphore,
2800 neighbor_sync_responder_admission_semaphore,
2801 neighbor_sync_responder_inflight,
2802 fresh_offer_worker_semaphore,
2803 fresh_offer_admission_semaphore,
2804 fresh_offer_responder_inflight,
2805 fresh_offer_in_flight,
2806 paid_notify_worker_semaphore,
2807 paid_notify_admission_semaphore,
2808 paid_notify_responder_inflight,
2809 shutdown: shutdown.clone(),
2810 detached_task_tracker,
2811 };
2812
2813 let (replication_tx, mut replication_rx) =
2814 mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
2815 let serial_context = handler_context.clone();
2816 let serial_shutdown = shutdown.clone();
2817 let serial_handle = tokio::spawn(async move {
2818 loop {
2819 tokio::select! {
2820 () = serial_shutdown.cancelled() => break,
2821 inbound = replication_rx.recv() => {
2822 let Some(inbound) = inbound else { break };
2823 let source = inbound.source;
2824 match handle_replication_message(
2825 &source,
2826 inbound.msg,
2827 &serial_context,
2828 inbound.received_at,
2829 inbound.rr_message_id.as_deref(),
2830 )
2831 .await
2832 {
2833 Ok(()) => {}
2834 Err(e) => {
2835 debug!("Replication message from {source} error: {e}");
2836 }
2837 }
2838 }
2839 }
2840 }
2841 debug!("Replication non-audit serial handler shut down");
2842 });
2843 self.task_handles.push(serial_handle);
2844
2845 let handle = tokio::spawn(async move {
2846 loop {
2847 tokio::select! {
2848 () = shutdown.cancelled() => break,
2849 event = p2p_events.recv() => {
2850 let event = match event {
2851 Ok(event) => event,
2852 Err(error) => match handle_replication_event_recv_error(&error) {
2853 ControlFlow::Continue(()) => continue,
2854 ControlFlow::Break(()) => break,
2855 },
2856 };
2857 let Some((source, payload, inbound_protocol, rr_message_id)) =
2858 replication_payload_from_event(event)
2859 else {
2860 continue;
2861 };
2862 let received_at = Instant::now();
2863 let msg = match ReplicationMessage::decode(&payload) {
2864 Ok(msg) => msg,
2865 Err(e) => {
2866 debug!("Replication message from {source} decode error: {e}");
2867 continue;
2868 }
2869 };
2870 if !body_matches_protocol(&msg.body, inbound_protocol) {
2871 debug!(
2872 "Dropping replication body (variant {}) on protocol \
2873 {inbound_protocol}: wrong id for its family \
2874 (cross-version or misrouted)",
2875 msg.body.variant_index()
2876 );
2877 continue;
2878 }
2879 if let Some(class) = audit_responder_class(&msg.body) {
2880 handler_context
2881 .audit_responder_metrics
2882 .record_received(source, class);
2883 }
2884 let inbound = InboundReplicationMessage {
2885 source,
2886 msg,
2887 rr_message_id,
2888 received_at,
2889 };
2890 if matches!(
2891 inbound.msg.body,
2892 ReplicationMessageBody::AuditChallenge(_)
2893 | ReplicationMessageBody::SubtreeAuditChallenge(_)
2894 | ReplicationMessageBody::SubtreeSliceChallenge(_)
2895 ) {
2896 let source = inbound.source;
2897 match handle_replication_message(
2898 &source,
2899 inbound.msg,
2900 &handler_context,
2901 inbound.received_at,
2902 inbound.rr_message_id.as_deref(),
2903 )
2904 .await
2905 {
2906 Ok(()) => {}
2907 Err(e) => {
2908 debug!("Replication message from {source} error: {e}");
2909 }
2910 }
2911 continue;
2912 }
2913 if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
2914 if dropped.audit_responder_class.is_some() {
2915 handler_context
2916 .audit_responder_metrics
2917 .record_serial_queue_drop(dropped.source);
2918 }
2919 warn!(
2926 message_class = dropped.message_class,
2927 source = %dropped.source,
2928 queue_depth = dropped.queue_depth,
2929 reason = dropped.reason.as_str(),
2930 "Replication serial-queue message dropped"
2931 );
2932 }
2933 }
2934 dht_event = dht_events.recv() => {
2942 let dht_event = match dht_event {
2943 Ok(event) => event,
2944 Err(RecvError::Lagged(missed)) => {
2945 warn!(
2960 "Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
2961 );
2962 let self_id = *p2p.peer_id();
2963 let neighbors = neighbor_sync::snapshot_close_neighbors(
2964 &p2p,
2965 &self_id,
2966 config.neighbor_sync_scope,
2967 )
2968 .await;
2969 let neighbor_set =
2970 neighbors.iter().copied().collect::<HashSet<_>>();
2971 let (requeued, sync_removals) = {
2972 let mut state = sync_state.write().await;
2973 let sync_removals =
2974 state.retain_sync_peers(&neighbor_set);
2975 let requeued = state.queue_priority_peers(neighbors);
2976 (requeued, sync_removals)
2977 };
2978 if sync_removals > 0 {
2979 debug!(
2980 "Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
2981 );
2982 }
2983 if requeued > 0 {
2984 debug!(
2985 "Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
2986 );
2987 sync_trigger.notify_one();
2988 }
2989 continue;
2990 }
2991 Err(RecvError::Closed) => {
2992 warn!(
2995 "DHT event stream closed on replication branch; stopping message handler"
2996 );
2997 break;
2998 }
2999 };
3000 match dht_event {
3001 DhtNetworkEvent::KClosestPeersChanged { old, new } => {
3002 let old_peers = old
3003 .iter()
3004 .take(config.neighbor_sync_scope)
3005 .copied()
3006 .collect::<HashSet<_>>();
3007 let new_scoped = new
3008 .iter()
3009 .take(config.neighbor_sync_scope)
3010 .copied()
3011 .collect::<Vec<_>>();
3012 let new_peers =
3013 new_scoped.iter().copied().collect::<HashSet<_>>();
3014 let entrants = new_scoped
3015 .iter()
3016 .copied()
3017 .filter(|peer| !old_peers.contains(peer))
3018 .collect::<Vec<_>>();
3019 let entrant_count = entrants.len();
3020 let (priority_insertions, sync_removals) = {
3021 let mut state = sync_state.write().await;
3022 let sync_removals = state.retain_sync_peers(&new_peers);
3023 let priority_insertions = state.queue_priority_peers(entrants);
3024 (priority_insertions, sync_removals)
3025 };
3026 if priority_insertions > 0 {
3027 debug!(
3028 "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
3029 );
3030 } else {
3031 debug!(
3032 "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
3033 );
3034 }
3035 sync_trigger.notify_one();
3036 }
3037 DhtNetworkEvent::PeerRemoved { peer_id } => {
3038 sync_state.write().await.remove_peer(&peer_id);
3039 repair_proofs.write().await.remove_peer(&peer_id);
3040 update_bootstrap_after_peer_removed(
3041 &peer_id,
3042 &handler_context.bootstrap_state,
3043 &handler_context.queues,
3044 &handler_context.is_bootstrapping,
3045 &bootstrap_complete_notify,
3046 )
3047 .await;
3048 last_commitment_by_peer.write().await.remove(&peer_id);
3055 recent_provers.write().await.forget_peer(&peer_id);
3056 sig_verify_attempts.write().await.remove(&peer_id);
3057 audit_on_gossip_cooldown.write().await.remove(&peer_id);
3060 gossip_lottery_attempts.write().await.remove(&peer_id);
3061 }
3068 _ => {}
3069 }
3070 }
3071 }
3072 }
3073 debug!("Replication message handler shut down");
3074 });
3075 self.task_handles.push(handle);
3076 }
3077
3078 fn start_neighbor_sync_loop(&mut self) {
3079 let p2p = Arc::clone(&self.p2p_node);
3080 let storage = Arc::clone(&self.storage);
3081 let paid_list = Arc::clone(&self.paid_list);
3082 let queues = Arc::clone(&self.queues);
3083 let config = Arc::clone(&self.config);
3084 let shutdown = self.shutdown.clone();
3085 let sync_state = Arc::clone(&self.sync_state);
3086 let sync_history = Arc::clone(&self.sync_history);
3087 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3088 let repair_proofs = Arc::clone(&self.repair_proofs);
3089 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3090 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3091 let sync_trigger = Arc::clone(&self.sync_trigger);
3092 let commitment_state = Arc::clone(&self.commitment_state);
3093 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3094 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3095 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3096 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3097 let detached_task_tracker = self.detached_task_tracker.clone();
3098 let gossip_audit = GossipAuditTrigger {
3103 p2p_node: Arc::clone(&p2p),
3104 config: Arc::clone(&config),
3105 recent_provers: Arc::clone(&self.recent_provers),
3106 sync_state: Arc::clone(&sync_state),
3107 cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
3108 detached_task_tracker,
3109 lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
3110 };
3111
3112 let handle = tokio::spawn(async move {
3113 loop {
3114 if !sync_state.read().await.has_priority_peers() {
3123 let interval = config.random_neighbor_sync_interval();
3124 tokio::select! {
3125 () = shutdown.cancelled() => break,
3126 () = tokio::time::sleep(interval) => {}
3127 () = sync_trigger.notified() => {
3128 debug!("Neighbor sync triggered by topology change");
3129 }
3130 }
3131 }
3132 tokio::select! {
3136 () = shutdown.cancelled() => break,
3137 () = run_neighbor_sync_round(
3138 &p2p,
3139 &storage,
3140 &paid_list,
3141 &queues,
3142 &config,
3143 &sync_state,
3144 &sync_history,
3145 &sync_cycle_epoch,
3146 &repair_proofs,
3147 &is_bootstrapping,
3148 &bootstrap_state,
3149 &commitment_state,
3150 &last_commitment_by_peer,
3151 &ever_capable_peers,
3152 &sig_verify_attempts,
3153 &audit_challenge_coordinator,
3154 &gossip_audit,
3155 ) => {}
3156 }
3157 }
3158 debug!("Neighbor sync loop shut down");
3159 });
3160 self.task_handles.push(handle);
3161 }
3162
3163 fn start_self_lookup_loop(&mut self) {
3164 let p2p = Arc::clone(&self.p2p_node);
3165 let config = Arc::clone(&self.config);
3166 let shutdown = self.shutdown.clone();
3167
3168 let handle = tokio::spawn(async move {
3169 loop {
3170 let interval = config.random_self_lookup_interval();
3171 tokio::select! {
3172 () = shutdown.cancelled() => break,
3173 () = tokio::time::sleep(interval) => {
3174 if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
3175 debug!("Self-lookup failed: {e}");
3176 }
3177 }
3178 }
3179 }
3180 debug!("Self-lookup loop shut down");
3181 });
3182 self.task_handles.push(handle);
3183 }
3184
3185 fn start_audit_loop(&mut self) {
3192 let p2p = Arc::clone(&self.p2p_node);
3193 let storage = Arc::clone(&self.storage);
3194 let config = Arc::clone(&self.config);
3195 let shutdown = self.shutdown.clone();
3196 let sync_history = Arc::clone(&self.sync_history);
3197 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3198 let repair_proofs = Arc::clone(&self.repair_proofs);
3199 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3200 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3201 let sync_state = Arc::clone(&self.sync_state);
3202 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3203
3204 let handle = tokio::spawn(async move {
3205 loop {
3207 tokio::select! {
3208 () = shutdown.cancelled() => return,
3209 () = tokio::time::sleep(
3210 std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
3211 ) => {
3212 if bootstrap_state.read().await.is_drained() {
3213 break;
3214 }
3215 }
3216 }
3217 }
3218
3219 {
3221 let bootstrapping = *is_bootstrapping.read().await;
3222 let result = {
3223 let history = sync_history.read().await;
3224 let current_sync_epoch = *sync_cycle_epoch.read().await;
3225 audit::audit_tick_with_repair_proofs(
3226 &p2p,
3227 &storage,
3228 &config,
3229 &history,
3230 &repair_proofs,
3231 &audit_challenge_coordinator,
3232 current_sync_epoch,
3233 bootstrapping,
3234 )
3235 .await
3236 };
3237 handle_audit_result(&result, &p2p, &sync_state, &config).await;
3238 }
3239
3240 loop {
3242 let interval = config.random_audit_tick_interval();
3243 tokio::select! {
3244 () = shutdown.cancelled() => break,
3245 () = tokio::time::sleep(interval) => {
3246 let bootstrapping = *is_bootstrapping.read().await;
3247 let result = {
3248 let history = sync_history.read().await;
3249 let current_sync_epoch = *sync_cycle_epoch.read().await;
3250 audit::audit_tick_with_repair_proofs(
3251 &p2p,
3252 &storage,
3253 &config,
3254 &history,
3255 &repair_proofs,
3256 &audit_challenge_coordinator,
3257 current_sync_epoch,
3258 bootstrapping,
3259 )
3260 .await
3261 };
3262 handle_audit_result(&result, &p2p, &sync_state, &config).await;
3263 }
3264 }
3265 }
3266 debug!("Audit loop shut down");
3267 });
3268 self.task_handles.push(handle);
3269 }
3270
3271 fn start_commitment_rotation_loop(&mut self) {
3286 let storage = Arc::clone(&self.storage);
3287 let identity = Arc::clone(&self.identity);
3288 let commitment_state = Arc::clone(&self.commitment_state);
3289 let shutdown = self.shutdown.clone();
3290 let p2p = Arc::clone(&self.p2p_node);
3291 let config = Arc::clone(&self.config);
3292 let sync_trigger = Arc::clone(&self.sync_trigger);
3293 let recent_provers = Arc::clone(&self.recent_provers);
3294
3295 let handle = tokio::spawn(async move {
3296 if let Err(e) =
3317 rebuild_and_rotate_commitment(&storage, &identity, &commitment_state, &p2p, &config)
3318 .await
3319 {
3320 warn!("Initial commitment build failed: {e}");
3321 } else {
3322 sync_trigger.notify_one();
3323 }
3324 loop {
3325 tokio::select! {
3326 () = shutdown.cancelled() => break,
3327 () = tokio::time::sleep(
3328 std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
3329 ) => {
3330 if let Err(e) = rebuild_and_rotate_commitment(
3331 &storage,
3332 &identity,
3333 &commitment_state,
3334 &p2p,
3335 &config,
3336 ).await {
3337 warn!("Commitment rotation failed: {e}");
3338 }
3339 let dropped = recent_provers.write().await.sweep_expired(
3345 std::time::Instant::now()
3346 );
3347 if dropped > 0 {
3348 debug!("recent_provers: swept {dropped} expired entries");
3349 }
3350 }
3351 }
3352 }
3353 debug!("Commitment rotation loop shut down");
3354 });
3355 self.task_handles.push(handle);
3356 }
3357
3358 fn start_retention_persist_loop(&mut self) {
3363 let commitment_state = Arc::clone(&self.commitment_state);
3364 let retention_path = self.retention_path.clone();
3365 let shutdown = self.shutdown.clone();
3366 let handle = tokio::spawn(async move {
3367 let mut last: Option<Vec<u8>> = None;
3368 persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
3369 loop {
3370 tokio::select! {
3371 () = shutdown.cancelled() => {
3372 persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3373 .await;
3374 break;
3375 }
3376 () = tokio::time::sleep(std::time::Duration::from_secs(
3377 RETENTION_PERSIST_INTERVAL_SECS,
3378 )) => {
3379 persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3380 .await;
3381 }
3382 }
3383 }
3384 debug!("Commitment retention persist loop shut down");
3385 });
3386 self.task_handles.push(handle);
3387 }
3388
3389 fn start_traffic_summary_loop(&mut self) {
3395 let shutdown = self.shutdown.clone();
3396 let handle = tokio::spawn(async move {
3397 loop {
3398 tokio::select! {
3399 () = shutdown.cancelled() => break,
3400 () = tokio::time::sleep(std::time::Duration::from_secs(
3401 TRAFFIC_SUMMARY_INTERVAL_SECS,
3402 )) => {
3403 protocol::log_traffic_summary();
3404 protocol::log_served_peers_summary();
3405 protocol::log_audit_outcome_summary();
3406 audit_metrics::log_responder_admission_summary();
3407 }
3408 }
3409 }
3410 debug!("Replication traffic summary loop shut down");
3411 });
3412 self.task_handles.push(handle);
3413 }
3414
3415 #[cfg(feature = "logging")]
3419 fn start_audit_responder_summary_loop(&mut self) {
3420 let shutdown = self.shutdown.clone();
3421 let metrics = Arc::clone(&self.audit_responder_metrics);
3422 let semaphore = Arc::clone(&self.audit_responder_semaphore);
3423 let handle = tokio::spawn(async move {
3424 let mut window_started = Instant::now();
3425 loop {
3426 tokio::select! {
3427 () = shutdown.cancelled() => {
3428 log_audit_responder_summary(
3429 &metrics,
3430 &semaphore,
3431 window_started.elapsed(),
3432 );
3433 break;
3434 }
3435 () = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
3436 log_audit_responder_summary(
3437 &metrics,
3438 &semaphore,
3439 window_started.elapsed(),
3440 );
3441 window_started = Instant::now();
3442 }
3443 }
3444 }
3445 debug!("Audit responder summary loop shut down");
3446 });
3447 self.task_handles.push(handle);
3448 }
3449
3450 #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
3451 fn start_fetch_worker(&mut self) {
3452 let p2p = Arc::clone(&self.p2p_node);
3453 let storage = Arc::clone(&self.storage);
3454 let queues = Arc::clone(&self.queues);
3455 let config = Arc::clone(&self.config);
3456 let shutdown = self.shutdown.clone();
3457 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3458 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3459 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3460 let detached_task_tracker = self.detached_task_tracker.clone();
3461 let concurrency = max_parallel_fetch();
3462
3463 info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
3464
3465 let handle = tokio::spawn(async move {
3466 let mut in_flight = FuturesUnordered::<FetchFuture>::new();
3469
3470 loop {
3471 {
3473 let mut q = queues.write().await;
3474 while in_flight.len() < concurrency {
3475 let Some(candidate) = q.dequeue_fetch() else {
3476 break;
3477 };
3478 let fetch_key = candidate.key;
3479 let Some(&source) = candidate.sources.first() else {
3480 warn!(
3481 "Fetch candidate {} has no sources; requeueing for verification",
3482 hex::encode(fetch_key)
3483 );
3484 let _ = q.requeue_candidate_for_verification(
3485 candidate,
3486 config.verification_request_timeout,
3487 );
3488 continue;
3489 };
3490 q.start_dequeued_fetch(candidate, source);
3491
3492 let p2p = Arc::clone(&p2p);
3493 let storage = Arc::clone(&storage);
3494 let config = Arc::clone(&config);
3495 let token = shutdown.clone();
3496 let tracker = detached_task_tracker.clone();
3497 in_flight.push(Box::pin(async move {
3498 let handle = tracker.spawn(async move {
3503 tokio::select! {
3505 () = token.cancelled() => FetchOutcome {
3506 key: fetch_key,
3507 result: FetchResult::SourceFailed,
3508 },
3509 outcome = execute_single_fetch(
3510 p2p, storage, config, fetch_key, source,
3511 ) => outcome,
3512 }
3513 });
3514 match handle.await {
3515 Ok(outcome) => (outcome.key, Some(outcome)),
3516 Err(e) => {
3517 error!(
3518 "Fetch task for {} panicked: {e}",
3519 hex::encode(fetch_key)
3520 );
3521 (fetch_key, None)
3522 }
3523 }
3524 }));
3525 }
3526 } if in_flight.is_empty() {
3529 tokio::select! {
3531 () = shutdown.cancelled() => break,
3532 () = tokio::time::sleep(
3533 std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
3534 ) => continue,
3535 }
3536 }
3537
3538 tokio::select! {
3540 () = shutdown.cancelled() => break,
3541 Some((key, maybe_outcome)) = in_flight.next() => {
3542 let mut q = queues.write().await;
3543 let terminal = if let Some(outcome) = maybe_outcome {
3544 match apply_fetch_result(
3545 &mut q,
3546 &key,
3547 &outcome.result,
3548 config.verification_request_timeout,
3549 ) {
3550 FetchFollowUp::Terminal => true,
3551 FetchFollowUp::RequeuedForVerification => false,
3552 FetchFollowUp::RetryFrom(next_peer) => {
3553 let p2p = Arc::clone(&p2p);
3555 let storage = Arc::clone(&storage);
3556 let config = Arc::clone(&config);
3557 let token = shutdown.clone();
3558 let tracker = detached_task_tracker.clone();
3559 let fetch_key = key;
3560 in_flight.push(Box::pin(async move {
3561 let handle = tracker.spawn(async move {
3564 tokio::select! {
3565 () = token.cancelled() => FetchOutcome {
3566 key: fetch_key,
3567 result: FetchResult::SourceFailed,
3568 },
3569 outcome = execute_single_fetch(
3570 p2p, storage, config, fetch_key, next_peer,
3571 ) => outcome,
3572 }
3573 });
3574 match handle.await {
3575 Ok(outcome) => (outcome.key, Some(outcome)),
3576 Err(e) => {
3577 error!(
3578 "Fetch task for {} panicked: {e}",
3579 hex::encode(fetch_key)
3580 );
3581 (fetch_key, None)
3582 }
3583 }
3584 }));
3585 false
3586 }
3587 }
3588 } else {
3589 !q.requeue_fetch_for_verification(
3592 &key,
3593 config.verification_request_timeout,
3594 )
3595 };
3596
3597 if terminal {
3599 drop(q); if !bootstrap_state.read().await.is_drained() {
3601 bootstrap_state.write().await.remove_key(&key);
3602 let q = queues.read().await;
3603 if bootstrap::check_bootstrap_drained(
3604 &bootstrap_state,
3605 &q,
3606 )
3607 .await
3608 {
3609 complete_bootstrap(
3610 &is_bootstrapping,
3611 &bootstrap_complete_notify,
3612 ).await;
3613 }
3614 }
3615 }
3616 }
3617 }
3618 }
3619
3620 while in_flight.next().await.is_some() {}
3624 debug!("Fetch worker shut down");
3625 });
3626 self.task_handles.push(handle);
3627 }
3628
3629 fn start_verification_worker(&mut self) {
3630 let p2p = Arc::clone(&self.p2p_node);
3631 let storage = Arc::clone(&self.storage);
3632 let queues = Arc::clone(&self.queues);
3633 let paid_list = Arc::clone(&self.paid_list);
3634 let config = Arc::clone(&self.config);
3635 let shutdown = self.shutdown.clone();
3636 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3637 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3638 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3639 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3640 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3641 let recent_provers = Arc::clone(&self.recent_provers);
3642
3643 let handle = tokio::spawn(async move {
3644 loop {
3645 tokio::select! {
3646 () = shutdown.cancelled() => break,
3647 () = tokio::time::sleep(
3648 std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
3649 ) => {
3650 let ctx = VerificationCycleContext {
3651 p2p_node: &p2p,
3652 paid_list: &paid_list,
3653 storage: &storage,
3654 queues: &queues,
3655 config: &config,
3656 bootstrap_state: &bootstrap_state,
3657 is_bootstrapping: &is_bootstrapping,
3658 bootstrap_complete_notify: &bootstrap_complete_notify,
3659 last_commitment_by_peer: &last_commitment_by_peer,
3660 ever_capable_peers: &ever_capable_peers,
3661 recent_provers: &recent_provers,
3662 };
3663 run_verification_cycle(ctx).await;
3664 }
3665 }
3666 }
3667 debug!("Verification worker shut down");
3668 });
3669 self.task_handles.push(handle);
3670 }
3671
3672 #[allow(clippy::too_many_lines)]
3684 fn start_bootstrap_sync(
3685 &mut self,
3686 dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
3687 ) {
3688 let p2p = Arc::clone(&self.p2p_node);
3689 let storage = Arc::clone(&self.storage);
3690 let paid_list = Arc::clone(&self.paid_list);
3691 let queues = Arc::clone(&self.queues);
3692 let config = Arc::clone(&self.config);
3693 let shutdown = self.shutdown.clone();
3694 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3695 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3696 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3697 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3698 let repair_proofs = Arc::clone(&self.repair_proofs);
3699 let my_commitment_state = Arc::clone(&self.commitment_state);
3700 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3701 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3702 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3703
3704 let handle = tokio::spawn(async move {
3705 let gate = bootstrap::wait_for_bootstrap_complete(
3709 dht_events,
3710 config.bootstrap_complete_timeout_secs,
3711 &shutdown,
3712 )
3713 .await;
3714
3715 if gate == bootstrap::BootstrapGateResult::Shutdown {
3716 return;
3717 }
3718
3719 let self_id = *p2p.peer_id();
3720 let neighbors =
3721 neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
3722 .await;
3723
3724 if neighbors.is_empty() {
3725 info!("Bootstrap sync: no close neighbors found, marking drained");
3726 bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
3727 complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3728 return;
3729 }
3730
3731 let neighbor_count = neighbors.len();
3732 info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
3733
3734 for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
3736 if shutdown.is_cancelled() {
3737 break;
3738 }
3739
3740 let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
3741 batch,
3742 &storage,
3743 &paid_list,
3744 &p2p,
3745 config.close_group_size,
3746 config.paid_list_close_group_size,
3747 )
3748 .await;
3749
3750 bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
3755 let bootstrapping = *is_bootstrapping.read().await;
3756
3757 let sync_futures = batch.iter().map(|peer| {
3758 let peer = *peer;
3759 let hints = hints_by_peer.remove(&peer).unwrap_or_default();
3760 let commitment = my_commitment_state
3763 .current_for_gossip()
3764 .map(|binding| binding.commitment().clone());
3765 let p2p = &p2p;
3766 let config = &config;
3767 async move {
3768 let outcome = neighbor_sync::sync_with_peer_with_hints(
3769 &peer,
3770 p2p,
3771 config,
3772 bootstrapping,
3773 hints,
3774 commitment,
3775 )
3776 .await;
3777 (peer, outcome)
3778 }
3779 });
3780 let completed = join_all(sync_futures).await;
3781
3782 for (peer, outcome) in &completed {
3785 if let Some(outcome) = outcome {
3786 ingest_peer_commitment(
3801 peer,
3802 outcome.response.commitment.as_ref(),
3803 &p2p,
3804 &last_commitment_by_peer,
3805 &ever_capable_peers,
3806 &sig_verify_attempts,
3807 )
3808 .await; if !outcome.response.bootstrapping {
3811 record_sent_replica_hints(
3812 peer,
3813 &outcome.sent_replica_hints,
3814 &repair_proofs,
3815 &sync_cycle_epoch,
3816 )
3817 .await;
3818 }
3819 }
3820 }
3821
3822 let pending_keys: HashSet<XorName> = {
3823 let q = queues.read().await;
3824 q.pending_keys().into_iter().collect()
3825 };
3826 let admission_futures = completed.iter().map(|(_, outcome)| async {
3827 match outcome {
3828 Some(outcome) if !outcome.response.bootstrapping => Some(
3829 admission::admit_hints(
3830 &self_id,
3831 &outcome.response.replica_hints,
3832 &outcome.response.paid_hints,
3833 &p2p,
3834 &config,
3835 &storage,
3836 &paid_list,
3837 &pending_keys,
3838 )
3839 .await,
3840 ),
3841 _ => None,
3842 }
3843 });
3844 let admitted = join_all(admission_futures).await;
3845
3846 let (batch_outcomes, batch_discovered) = {
3849 let mut q = queues.write().await;
3850 let outcomes = completed
3851 .iter()
3852 .zip(admitted)
3853 .filter_map(|((peer, _), admitted)| {
3854 admitted.map(|admitted| {
3855 (
3856 *peer,
3857 queue_admitted_hints(peer, admitted, &storage, &mut q),
3858 )
3859 })
3860 })
3861 .collect::<Vec<_>>();
3862 let live_discovered = outcomes
3863 .iter()
3864 .flat_map(|(_, outcome)| outcome.discovered.iter().copied())
3865 .filter(|key| q.contains_key(key))
3866 .collect::<HashSet<_>>();
3867 (outcomes, live_discovered)
3868 };
3869
3870 publish_bootstrap_admission_outcomes(
3871 &bootstrap_state,
3872 &batch_outcomes,
3873 &batch_discovered,
3874 )
3875 .await;
3876
3877 bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
3878 }
3879
3880 {
3882 let q = queues.read().await;
3883 if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
3884 complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3885 }
3886 }
3887
3888 info!("Bootstrap sync completed");
3889 });
3890 self.task_handles.push(handle);
3891 }
3892}
3893
3894#[cfg(feature = "logging")]
3899fn log_audit_responder_summary(
3900 metrics: &AuditResponderMetrics,
3901 semaphore: &Semaphore,
3902 window: Duration,
3903) {
3904 let snapshot = metrics.take_snapshot();
3905 if snapshot.origins.is_empty() {
3906 return;
3907 }
3908
3909 let total = snapshot.total;
3910 let [digest_received, subtree_received, byte_received, commitment_pin_received] =
3911 total.received_by_class;
3912 let global_inflight =
3913 MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
3914 info!(
3915 target: "ant_node::replication::audit_responder",
3916 window_ms = window.as_millis(),
3917 source_count = snapshot.origins.len(),
3918 received = total.received(),
3919 digest_received,
3920 subtree_received,
3921 byte_received,
3922 commitment_pin_received,
3923 admitted = total.admitted,
3924 global_pool_drops = total.global_pool_drops,
3925 per_peer_cap_drops = total.per_peer_cap_drops,
3926 serial_queue_drops = total.serial_queue_drops,
3927 completed = total.completed,
3928 send_failures = total.send_failures,
3929 processing_avg_ms = total.processing_avg_ms(),
3930 processing_max_ms = total.processing_max_ms,
3931 total_avg_ms = total.total_avg_ms(),
3932 total_max_ms = total.total_max_ms,
3933 global_inflight,
3934 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
3935 peak_global_inflight = total.peak_global_inflight,
3936 "Audit responder summary"
3937 );
3938
3939 for (index, origin) in snapshot
3940 .origins
3941 .iter()
3942 .take(config::AUDIT_RESPONDER_TOP_ORIGINS)
3943 .enumerate()
3944 {
3945 let Some(source) = origin.source else {
3946 continue;
3947 };
3948 let [digest_received, subtree_received, byte_received, commitment_pin_received] =
3949 origin.received_by_class;
3950 info!(
3951 target: "ant_node::replication::audit_responder",
3952 rank = index + 1,
3953 source = %source,
3954 received = origin.received(),
3955 digest_received,
3956 subtree_received,
3957 byte_received,
3958 commitment_pin_received,
3959 admitted = origin.admitted,
3960 global_pool_drops = origin.global_pool_drops,
3961 per_peer_cap_drops = origin.per_peer_cap_drops,
3962 serial_queue_drops = origin.serial_queue_drops,
3963 completed = origin.completed,
3964 send_failures = origin.send_failures,
3965 processing_avg_ms = origin.processing_avg_ms(),
3966 processing_max_ms = origin.processing_max_ms,
3967 total_avg_ms = origin.total_avg_ms(),
3968 total_max_ms = origin.total_max_ms,
3969 peak_global_inflight = origin.peak_global_inflight,
3970 peak_peer_inflight = origin.peak_peer_inflight,
3971 "Audit responder top origin"
3972 );
3973 }
3974}
3975
3976#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3991enum ResponderRejectReason {
3992 GlobalPoolFull,
3995 PerPeerCapFull,
3998}
3999
4000impl ResponderRejectReason {
4001 fn as_str(self) -> &'static str {
4004 match self {
4005 Self::GlobalPoolFull => "global_pool_full",
4006 Self::PerPeerCapFull => "per_peer_cap_full",
4007 }
4008 }
4009}
4010
4011impl From<ResponderRejectReason> for AuditResponderDropReason {
4012 fn from(reason: ResponderRejectReason) -> Self {
4013 match reason {
4014 ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
4015 ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
4016 }
4017 }
4018}
4019
4020impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
4021 fn from(reason: ResponderRejectReason) -> Self {
4022 match reason {
4023 ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
4024 ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
4025 }
4026 }
4027}
4028
4029#[must_use]
4044pub fn fresh_offer_admission_refusals() -> u64 {
4045 audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
4046}
4047
4048#[must_use]
4054pub fn paid_notify_admission_refusals() -> u64 {
4055 audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
4056}
4057
4058#[must_use]
4064pub fn fresh_offer_refusals_global_pool() -> u64 {
4065 audit_metrics::responder_admission_drops_by_ceiling(
4066 ReplicationResponderClass::FreshOffer,
4067 ResponderAdmissionCeiling::GlobalPool,
4068 )
4069}
4070
4071#[must_use]
4078pub fn fresh_offer_refusals_per_peer_share() -> u64 {
4079 audit_metrics::responder_admission_drops_by_ceiling(
4080 ReplicationResponderClass::FreshOffer,
4081 ResponderAdmissionCeiling::PerPeerShare,
4082 )
4083}
4084
4085#[derive(Debug, Clone, Copy)]
4093struct ResponderAdmissionFailure {
4094 reason: ResponderRejectReason,
4095 global_inflight: usize,
4097 global_limit: usize,
4099 peer_inflight: u32,
4101 peer_limit: u32,
4103}
4104
4105impl fmt::Display for ResponderAdmissionFailure {
4106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4109 write!(
4110 f,
4111 "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
4112 self.reason.as_str(),
4113 self.global_inflight,
4114 self.global_limit,
4115 self.peer_inflight,
4116 self.peer_limit,
4117 )
4118 }
4119}
4120
4121struct ResponderGuard {
4126 _permit: tokio::sync::OwnedSemaphorePermit,
4127 _peer_slot: PeerResponderSlot,
4128 global_inflight: usize,
4129 peer_inflight: u32,
4130}
4131
4132type AuditResponderGuard = ResponderGuard;
4133type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
4134
4135struct PeerResponderSlot {
4142 inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4143 peer: PeerId,
4144}
4145
4146#[derive(Clone)]
4147struct ReplicationMessageHandlerContext {
4148 p2p_node: Arc<P2PNode>,
4149 storage: Arc<LmdbStorage>,
4150 paid_list: Arc<PaidList>,
4151 payment_verifier: Arc<PaymentVerifier>,
4152 queues: Arc<RwLock<ReplicationQueues>>,
4153 config: Arc<ReplicationConfig>,
4154 is_bootstrapping: Arc<RwLock<bool>>,
4155 bootstrap_state: Arc<RwLock<BootstrapState>>,
4156 sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4157 sync_cycle_epoch: Arc<RwLock<u64>>,
4158 repair_proofs: Arc<RwLock<RepairProofs>>,
4159 last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4160 ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
4161 sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
4162 my_commitment_state: Arc<ResponderCommitmentState>,
4163 gossip_audit: GossipAuditTrigger,
4164 audit_responder_semaphore: Arc<Semaphore>,
4165 audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4166 audit_responder_metrics: Arc<AuditResponderMetrics>,
4167 subtree_round1: SubtreeRound1Limiter,
4168 fetch_responder_worker_semaphore: Arc<Semaphore>,
4169 fetch_responder_admission_semaphore: Arc<Semaphore>,
4170 fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4171 verification_responder_worker_semaphore: Arc<Semaphore>,
4172 verification_responder_admission_semaphore: Arc<Semaphore>,
4173 verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4174 neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
4175 neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
4176 neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4177 fresh_offer_worker_semaphore: Arc<Semaphore>,
4178 fresh_offer_admission_semaphore: Arc<Semaphore>,
4179 fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4180 fresh_offer_in_flight: FreshOfferInFlight,
4181 paid_notify_worker_semaphore: Arc<Semaphore>,
4182 paid_notify_admission_semaphore: Arc<Semaphore>,
4183 paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4184 shutdown: CancellationToken,
4192 detached_task_tracker: TaskTracker,
4195}
4196
4197struct InboundReplicationMessage {
4198 source: PeerId,
4199 msg: ReplicationMessage,
4200 rr_message_id: Option<String>,
4201 received_at: Instant,
4202}
4203
4204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4205enum SerialQueueDropReason {
4206 Full,
4207 Closed,
4208}
4209
4210#[cfg(feature = "logging")]
4211impl SerialQueueDropReason {
4212 const fn as_str(self) -> &'static str {
4213 match self {
4214 Self::Full => "full",
4215 Self::Closed => "closed",
4216 }
4217 }
4218}
4219
4220#[derive(Debug, Clone, Copy)]
4221#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
4222struct SerialQueueDrop {
4223 source: PeerId,
4224 message_class: &'static str,
4225 audit_responder_class: Option<AuditResponderClass>,
4226 queue_depth: usize,
4227 reason: SerialQueueDropReason,
4228}
4229
4230fn try_enqueue_serial_message(
4231 sender: &mpsc::Sender<InboundReplicationMessage>,
4232 inbound: InboundReplicationMessage,
4233) -> std::result::Result<(), SerialQueueDrop> {
4234 let source = inbound.source;
4235 let message_class = replication_message_class(&inbound.msg.body);
4236 let audit_responder_class = audit_responder_class(&inbound.msg.body);
4237 let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
4238 sender.try_send(inbound).map_err(|error| {
4239 let (reason, dropped) = match error {
4240 mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
4241 mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
4242 };
4243 audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
4244 SerialQueueDrop {
4245 source,
4246 message_class,
4247 audit_responder_class,
4248 queue_depth,
4249 reason,
4250 }
4251 })
4252}
4253
4254const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
4255 match body {
4256 ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
4257 ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
4258 ReplicationMessageBody::PaidNotify(_) => "paid_notify",
4259 ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
4260 ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
4261 ReplicationMessageBody::VerificationRequest(_) => "verification_request",
4262 ReplicationMessageBody::VerificationResponse(_) => "verification_response",
4263 ReplicationMessageBody::FetchRequest(_) => "fetch_request",
4264 ReplicationMessageBody::FetchResponse(_) => "fetch_response",
4265 ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
4266 ReplicationMessageBody::AuditResponse(_) => "audit_response",
4267 ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
4268 ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
4269 ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
4270 ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
4271 ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
4272 ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
4273 }
4274}
4275
4276const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
4277 match body {
4278 ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
4279 ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
4280 ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
4281 ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
4282 _ => None,
4283 }
4284}
4285
4286impl AuditResponderClass {
4287 const fn per_peer_limit(self) -> u32 {
4288 match self {
4289 Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
4290 Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
4291 }
4292 }
4293}
4294
4295fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
4296 match error {
4297 RecvError::Lagged(missed) => {
4298 audit_metrics::record_replication_event_lagged(*missed);
4299 warn!(
4300 "Missed {missed} P2P events on replication branch (broadcast lag); \
4301 replication messages may have been dropped before dispatch"
4302 );
4303 ControlFlow::Continue(())
4304 }
4305 RecvError::Closed => {
4306 warn!("P2P event stream closed on replication branch; stopping message handler");
4309 ControlFlow::Break(())
4310 }
4311 }
4312}
4313
4314fn replication_payload_from_event(
4315 event: P2PEvent,
4316) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
4317 let P2PEvent::Message {
4318 topic,
4319 source: Some(source),
4320 data,
4321 ..
4322 } = event
4323 else {
4324 return None;
4325 };
4326
4327 let (matched_id, is_rr) = match_replication_protocol(&topic)?;
4328 if !is_rr {
4329 return Some((source, data, matched_id, None));
4330 }
4331 if is_rr {
4332 return P2PNode::parse_request_envelope(&data)
4333 .filter(|(_, is_resp, _)| !is_resp)
4334 .map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
4335 }
4336 None
4337}
4338
4339impl Drop for PeerResponderSlot {
4340 fn drop(&mut self) {
4341 let peer = self.peer;
4350 if let Ok(mut map) = self.inflight.try_write() {
4351 if let Some(n) = map.get_mut(&peer) {
4352 *n = n.saturating_sub(1);
4353 if *n == 0 {
4354 map.remove(&peer);
4355 }
4356 }
4357 return;
4358 }
4359 if let Ok(handle) = tokio::runtime::Handle::try_current() {
4360 let inflight = Arc::clone(&self.inflight);
4361 handle.spawn(async move {
4362 let mut map = inflight.write().await;
4363 if let Some(n) = map.get_mut(&peer) {
4364 *n = n.saturating_sub(1);
4365 if *n == 0 {
4366 map.remove(&peer);
4367 }
4368 }
4369 });
4370 }
4371 }
4372}
4373
4374async fn admit_bounded_responder(
4378 semaphore: &Arc<Semaphore>,
4379 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4380 source: &PeerId,
4381 global_limit: usize,
4382 peer_limit: u32,
4383) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
4384 let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
4385
4386 let admitted_peer_inflight = {
4387 let mut map = inflight.write().await;
4388 let entry = map.entry(*source).or_insert(0);
4389 if *entry >= peer_limit {
4390 let peer_inflight = *entry;
4391 drop(map);
4392 return Err(ResponderAdmissionFailure {
4393 reason: ResponderRejectReason::PerPeerCapFull,
4394 global_inflight: global_inflight(semaphore),
4395 global_limit,
4396 peer_inflight,
4397 peer_limit,
4398 });
4399 }
4400 *entry += 1;
4401 *entry
4402 };
4403
4404 let peer_slot = PeerResponderSlot {
4405 inflight: Arc::clone(inflight),
4406 peer: *source,
4407 };
4408 let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
4409 return Err(ResponderAdmissionFailure {
4410 reason: ResponderRejectReason::GlobalPoolFull,
4411 global_inflight: global_inflight(semaphore),
4412 global_limit,
4413 peer_inflight: admitted_peer_inflight.saturating_sub(1),
4414 peer_limit,
4415 });
4416 };
4417
4418 Ok(ResponderGuard {
4419 _permit: permit,
4420 _peer_slot: peer_slot,
4421 global_inflight: global_inflight(semaphore),
4422 peer_inflight: admitted_peer_inflight,
4423 })
4424}
4425
4426struct SubtreeSession {
4428 commitment_hash: [u8; 32],
4429 nonce: [u8; 32],
4430 inserted: Instant,
4431}
4432
4433struct Round1WorkBudget {
4453 balance: i64,
4455 last_refill: Instant,
4456}
4457
4458impl Round1WorkBudget {
4459 const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
4462 const NANOS_PER_SEC: i64 = 1_000_000_000;
4464
4465 fn new() -> Self {
4466 Self {
4467 balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
4468 last_refill: Instant::now(),
4469 }
4470 }
4471
4472 fn refill(&mut self, now: Instant) {
4474 let elapsed = now.saturating_duration_since(self.last_refill);
4475 self.last_refill = now;
4476 let whole_secs = i64::try_from(elapsed.as_secs())
4477 .unwrap_or(i64::MAX)
4478 .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
4479 let sub_sec = i64::from(elapsed.subsec_nanos())
4480 .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
4481 / Self::NANOS_PER_SEC;
4482 self.balance = self
4483 .balance
4484 .saturating_add(whole_secs.saturating_add(sub_sec))
4485 .min(SUBTREE_ROUND1_WORK_BURST_BYTES);
4486 }
4487
4488 fn has_budget(&mut self, now: Instant) -> bool {
4490 self.refill(now);
4491 self.balance > 0
4492 }
4493
4494 fn charge(&mut self, bytes: i64, now: Instant) {
4497 self.refill(now);
4498 self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
4499 }
4500}
4501
4502#[derive(Clone)]
4511struct SubtreeRound1Limiter {
4512 semaphore: Arc<Semaphore>,
4513 max_concurrent: usize,
4517 inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4518 cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4519 cooldown_interval: Duration,
4522 sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
4523 work: Arc<RwLock<Round1WorkBudget>>,
4525}
4526
4527impl SubtreeRound1Limiter {
4528 fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
4533 let max_concurrent = max_concurrent.max(1);
4534 Self {
4535 semaphore: Arc::new(Semaphore::new(max_concurrent)),
4536 max_concurrent,
4537 inflight: Arc::new(RwLock::new(HashMap::new())),
4538 cooldown: Arc::new(RwLock::new(HashMap::new())),
4539 cooldown_interval,
4540 sessions: Arc::new(RwLock::new(HashMap::new())),
4541 work: Arc::new(RwLock::new(Round1WorkBudget::new())),
4542 }
4543 }
4544
4545 async fn charge_work(&self, content_bytes: i64) {
4547 self.work
4548 .write()
4549 .await
4550 .charge(content_bytes, Instant::now());
4551 }
4552
4553 async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
4559 let guard = admit_bounded_responder(
4560 &self.semaphore,
4561 &self.inflight,
4562 source,
4563 self.max_concurrent,
4564 MAX_SUBTREE_ROUND1_PER_PEER,
4565 )
4566 .await
4567 .ok()?;
4568 if !self.work.write().await.has_budget(Instant::now()) {
4571 return None; }
4573 let now = Instant::now();
4574 let mut cooldown = self.cooldown.write().await;
4575 if let Some(&last) = cooldown.get(source) {
4576 if now.duration_since(last) < self.cooldown_interval {
4577 return None; }
4579 }
4580 cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
4583 if cooldown.len() >= MAX_SUBTREE_SESSIONS {
4584 if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
4585 cooldown.remove(&oldest);
4586 }
4587 }
4588 cooldown.insert(*source, now);
4589 Some(guard)
4590 }
4591
4592 async fn open_session(
4595 &self,
4596 source: PeerId,
4597 challenge_id: u64,
4598 commitment_hash: [u8; 32],
4599 nonce: [u8; 32],
4600 ) {
4601 let now = Instant::now();
4602 let mut sessions = self.sessions.write().await;
4603 sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
4604 if sessions.len() >= MAX_SUBTREE_SESSIONS {
4605 if let Some(oldest) = sessions
4606 .iter()
4607 .min_by_key(|(_, e)| e.inserted)
4608 .map(|(k, _)| *k)
4609 {
4610 sessions.remove(&oldest);
4611 }
4612 }
4613 sessions.insert(
4614 (source, challenge_id),
4615 SubtreeSession {
4616 commitment_hash,
4617 nonce,
4618 inserted: now,
4619 },
4620 );
4621 }
4622
4623 async fn consume_session(
4628 &self,
4629 source: &PeerId,
4630 challenge_id: u64,
4631 commitment_hash: &[u8; 32],
4632 nonce: &[u8; 32],
4633 ) -> bool {
4634 let mut sessions = self.sessions.write().await;
4635 let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
4636 Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
4637 && &e.commitment_hash == commitment_hash
4638 && &e.nonce == nonce
4639 });
4640 if matches {
4641 sessions.remove(&(*source, challenge_id));
4642 }
4643 matches
4644 }
4645}
4646
4647enum SliceAdmission {
4649 Admitted(AuditResponderGuard),
4652 Capacity(AuditResponderAdmissionFailure),
4654 NoSession,
4656}
4657
4658async fn admit_slice_challenge(
4681 semaphore: &Arc<Semaphore>,
4682 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4683 round1: &SubtreeRound1Limiter,
4684 source: &PeerId,
4685 challenge: &protocol::SubtreeSliceChallenge,
4686) -> SliceAdmission {
4687 let guard =
4688 match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
4689 Ok(guard) => guard,
4690 Err(failure) => return SliceAdmission::Capacity(failure),
4691 };
4692 if !round1
4693 .consume_session(
4694 source,
4695 challenge.challenge_id,
4696 &challenge.expected_commitment_hash,
4697 &challenge.nonce,
4698 )
4699 .await
4700 {
4701 drop(guard);
4704 return SliceAdmission::NoSession;
4705 }
4706 SliceAdmission::Admitted(guard)
4707}
4708
4709async fn admit_audit_responder(
4718 semaphore: &Arc<Semaphore>,
4719 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4720 source: &PeerId,
4721 class: AuditResponderClass,
4722) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
4723 let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
4724 let peer_limit = class.per_peer_limit();
4725 admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
4726}
4727
4728#[allow(clippy::too_many_lines)]
4734async fn handle_replication_message(
4735 source: &PeerId,
4736 msg: ReplicationMessage,
4737 ctx: &ReplicationMessageHandlerContext,
4738 received_at: Instant,
4739 rr_message_id: Option<&str>,
4740) -> Result<()> {
4741 match msg.body {
4742 ReplicationMessageBody::FreshReplicationOffer(offer) => {
4743 dispatch_fresh_offer(
4744 *source,
4745 offer,
4746 ctx,
4747 msg.request_id,
4748 received_at,
4749 rr_message_id,
4750 )
4751 .await
4752 }
4753 ReplicationMessageBody::PaidNotify(notify) => {
4754 dispatch_paid_notify(*source, notify, ctx, received_at).await
4755 }
4756 ReplicationMessageBody::NeighborSyncRequest(request) => {
4757 let bootstrapping = *ctx.is_bootstrapping.read().await;
4758 if let Some(target) = ingest_peer_commitment(
4763 source,
4764 request.commitment.as_ref(),
4765 &ctx.p2p_node,
4766 &ctx.last_commitment_by_peer,
4767 &ctx.ever_capable_peers,
4768 &ctx.sig_verify_attempts,
4769 )
4770 .await
4771 {
4772 maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
4773 }
4774 dispatch_neighbor_sync_request(
4775 *source,
4776 request,
4777 ctx,
4778 bootstrapping,
4779 ctx.my_commitment_state
4782 .current_for_gossip()
4783 .map(|b| b.commitment().clone()),
4784 msg.request_id,
4785 received_at,
4786 rr_message_id,
4787 )
4788 .await
4789 }
4790 ReplicationMessageBody::VerificationRequest(request) => {
4791 dispatch_verification_request(
4792 *source,
4793 request,
4794 ctx,
4795 msg.request_id,
4796 received_at,
4797 rr_message_id,
4798 )
4799 .await
4800 }
4801 ReplicationMessageBody::FetchRequest(request) => {
4802 dispatch_fetch_request(
4803 *source,
4804 request,
4805 ctx,
4806 msg.request_id,
4807 received_at,
4808 rr_message_id,
4809 )
4810 .await
4811 }
4812 ReplicationMessageBody::AuditChallenge(challenge) => {
4813 let class = AuditResponderClass::Digest;
4828 let guard = match admit_audit_responder(
4829 &ctx.audit_responder_semaphore,
4830 &ctx.audit_responder_inflight,
4831 source,
4832 class,
4833 )
4834 .await
4835 {
4836 Ok(guard) => guard,
4837 Err(failure) => {
4838 protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
4839 audit_metrics::record_admission_drop(class);
4840 ctx.audit_responder_metrics
4841 .record_drop(*source, failure.reason.into());
4842 warn!(
4843 target: "ant_node::replication::audit_responder",
4844 event = "admission_dropped",
4845 kind = "responsible",
4846 responder_class = class.as_str(),
4847 source = %source,
4848 challenge_id = challenge.challenge_id,
4849 key_count = challenge.keys.len(),
4850 request_response = rr_message_id.is_some(),
4851 dispatch_ms = received_at.elapsed().as_millis(),
4852 reason = failure.reason.as_str(),
4853 global_inflight = failure.global_inflight,
4854 global_limit = failure.global_limit,
4855 peer_inflight = failure.peer_inflight,
4856 peer_limit = failure.peer_limit,
4857 "Audit responder admission dropped"
4858 );
4859 return Ok(());
4860 }
4861 };
4862 let admission_global_inflight = guard.global_inflight;
4863 let admission_peer_inflight = guard.peer_inflight;
4864 ctx.audit_responder_metrics.record_admitted(
4865 *source,
4866 admission_global_inflight,
4867 admission_peer_inflight,
4868 );
4869 info!(
4870 target: "ant_node::replication::audit_responder",
4871 event = "admitted",
4872 kind = "responsible",
4873 responder_class = class.as_str(),
4874 source = %source,
4875 challenge_id = challenge.challenge_id,
4876 key_count = challenge.keys.len(),
4877 request_response = rr_message_id.is_some(),
4878 dispatch_ms = received_at.elapsed().as_millis(),
4879 global_inflight = admission_global_inflight,
4880 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4881 peer_inflight = admission_peer_inflight,
4882 peer_limit = class.per_peer_limit(),
4883 "Audit responder request admitted"
4884 );
4885 let bootstrapping = *ctx.is_bootstrapping.read().await;
4886 let dispatch_latency = received_at.elapsed();
4887 audit_metrics::record_digest_dispatch_latency(dispatch_latency);
4888 debug!(
4889 audit_type = "digest_responder",
4890 dispatch_latency_ms = dispatch_latency.as_millis(),
4891 source = %source,
4892 "Audit challenge dispatch latency measured"
4893 );
4894 let storage = Arc::clone(&ctx.storage);
4895 let p2p_node = Arc::clone(&ctx.p2p_node);
4896 let source = *source;
4897 let request_id = msg.request_id;
4898 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
4899 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
4900 ctx.detached_task_tracker.spawn(async move {
4901 let _guard = guard; let worker_started = Instant::now();
4903 match handle_audit_challenge_msg(
4904 &source,
4905 &challenge,
4906 &storage,
4907 &p2p_node,
4908 bootstrapping,
4909 ReplyRoute {
4910 request_id,
4911 rr_message_id: rr_message_id.as_deref(),
4912 protocol: REPLICATION_PROTOCOL_ID,
4913 },
4914 )
4915 .await
4916 {
4917 Ok(completion) => log_audit_responder_completion(
4918 &responder_metrics,
4919 source,
4920 class,
4921 "responsible",
4922 challenge.challenge_id,
4923 challenge.keys.len(),
4924 completion.response_kind,
4925 completion.sent,
4926 received_at,
4927 worker_started,
4928 completion.processing,
4929 completion.response_send,
4930 ),
4931 Err(e) => debug!("Audit challenge from {source} error: {e}"),
4932 }
4933 });
4934 Ok(())
4935 }
4936 ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
4937 let class = AuditResponderClass::Subtree;
4950 info!(
4951 "Audit challenge received: kind=subtree source={source} request_response={}",
4952 rr_message_id.is_some(),
4953 );
4954 let Some(guard) = ctx.subtree_round1.admit(source).await else {
4959 protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
4960 warn!(
4961 target: "ant_node::replication::audit_responder",
4962 event = "admission_dropped",
4963 kind = "subtree",
4964 responder_class = class.as_str(),
4965 source = %source,
4966 challenge_id = challenge.challenge_id,
4967 request_response = rr_message_id.is_some(),
4968 dispatch_ms = received_at.elapsed().as_millis(),
4969 reason = "heavy_pool_cooldown_or_work_budget",
4970 "Audit responder admission dropped"
4971 );
4972 return Ok(());
4973 };
4974 let admission_global_inflight = guard.global_inflight;
4975 let admission_peer_inflight = guard.peer_inflight;
4976 ctx.audit_responder_metrics.record_admitted(
4977 *source,
4978 admission_global_inflight,
4979 admission_peer_inflight,
4980 );
4981 info!(
4982 target: "ant_node::replication::audit_responder",
4983 event = "admitted",
4984 kind = "subtree",
4985 responder_class = class.as_str(),
4986 source = %source,
4987 challenge_id = challenge.challenge_id,
4988 request_response = rr_message_id.is_some(),
4989 dispatch_ms = received_at.elapsed().as_millis(),
4990 global_inflight = admission_global_inflight,
4991 global_limit = ctx.subtree_round1.max_concurrent,
4992 peer_inflight = admission_peer_inflight,
4993 peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
4994 "Audit responder request admitted"
4995 );
4996 let bootstrapping = *ctx.is_bootstrapping.read().await;
4997 let storage = Arc::clone(&ctx.storage);
4998 let p2p_node = Arc::clone(&ctx.p2p_node);
4999 let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5000 let source = *source;
5001 let request_id = msg.request_id;
5002 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5003 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5004 let subtree_round1 = ctx.subtree_round1.clone();
5005 ctx.detached_task_tracker.spawn(async move {
5006 let _guard = guard; let worker_started = Instant::now();
5008 let processing_started = Instant::now();
5009 let storage_commitment_audit::Round1Work {
5010 response,
5011 content_bytes,
5012 } = storage_commitment_audit::handle_subtree_challenge_measured(
5013 &challenge,
5014 &storage,
5015 p2p_node.peer_id(),
5016 bootstrapping,
5017 Some(&my_commitment_state),
5018 )
5019 .await;
5020 let processing = processing_started.elapsed();
5021 subtree_round1.charge_work(content_bytes).await;
5036 if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
5040 {
5041 subtree_round1
5042 .open_session(
5043 source,
5044 challenge.challenge_id,
5045 challenge.expected_commitment_hash,
5046 challenge.nonce,
5047 )
5048 .await;
5049 }
5050 let response_kind = subtree_audit_response_kind(&response);
5051 let work_items = subtree_audit_response_work_items(&response);
5052 let response_send_started = Instant::now();
5053 let sent = send_replication_response_checked(
5054 &source,
5055 &p2p_node,
5056 request_id,
5057 ReplicationMessageBody::SubtreeAuditResponse(response),
5058 rr_message_id.as_deref(),
5059 None,
5060 )
5061 .await;
5062 let response_send = response_send_started.elapsed();
5063 log_audit_responder_completion(
5064 &responder_metrics,
5065 source,
5066 class,
5067 "subtree",
5068 challenge.challenge_id,
5069 work_items,
5070 response_kind,
5071 sent,
5072 received_at,
5073 worker_started,
5074 processing,
5075 response_send,
5076 );
5077 });
5078 Ok(())
5079 }
5080 ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
5081 let class = AuditResponderClass::Byte;
5087 info!(
5088 "Audit challenge received: kind=slice source={source} request_response={}",
5089 rr_message_id.is_some(),
5090 );
5091 let guard = match admit_slice_challenge(
5092 &ctx.audit_responder_semaphore,
5093 &ctx.audit_responder_inflight,
5094 &ctx.subtree_round1,
5095 source,
5096 &challenge,
5097 )
5098 .await
5099 {
5100 SliceAdmission::Admitted(guard) => guard,
5101 SliceAdmission::Capacity(failure) => {
5102 protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5103 audit_metrics::record_admission_drop(class);
5104 ctx.audit_responder_metrics
5105 .record_drop(*source, failure.reason.into());
5106 warn!(
5107 target: "ant_node::replication::audit_responder",
5108 event = "admission_dropped",
5109 kind = "byte",
5110 responder_class = class.as_str(),
5111 source = %source,
5112 challenge_id = challenge.challenge_id,
5113 key_count = challenge.openings.len(),
5114 request_response = rr_message_id.is_some(),
5115 dispatch_ms = received_at.elapsed().as_millis(),
5116 reason = failure.reason.as_str(),
5117 global_inflight = failure.global_inflight,
5118 global_limit = failure.global_limit,
5119 peer_inflight = failure.peer_inflight,
5120 peer_limit = failure.peer_limit,
5121 "Audit responder admission dropped"
5122 );
5123 return Ok(());
5124 }
5125 SliceAdmission::NoSession => {
5135 protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5136 debug!(
5137 "Slice challenge without a live round-1 session source={source} \
5138 challenge_id={} → Transient reject",
5139 challenge.challenge_id
5140 );
5141 send_replication_response_checked(
5142 source,
5143 &ctx.p2p_node,
5144 msg.request_id,
5145 ReplicationMessageBody::SubtreeSliceResponse(
5146 protocol::SubtreeSliceResponse::Rejected {
5147 challenge_id: challenge.challenge_id,
5148 kind: protocol::RejectKind::Transient,
5149 reason: "no live round-1 session".to_string(),
5150 },
5151 ),
5152 rr_message_id,
5153 None,
5154 )
5155 .await;
5156 return Ok(());
5157 }
5158 };
5159 let admission_global_inflight = guard.global_inflight;
5160 let admission_peer_inflight = guard.peer_inflight;
5161 ctx.audit_responder_metrics.record_admitted(
5162 *source,
5163 admission_global_inflight,
5164 admission_peer_inflight,
5165 );
5166 info!(
5167 target: "ant_node::replication::audit_responder",
5168 event = "admitted",
5169 kind = "byte",
5170 responder_class = class.as_str(),
5171 source = %source,
5172 challenge_id = challenge.challenge_id,
5173 key_count = challenge.openings.len(),
5174 request_response = rr_message_id.is_some(),
5175 dispatch_ms = received_at.elapsed().as_millis(),
5176 global_inflight = admission_global_inflight,
5177 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5178 peer_inflight = admission_peer_inflight,
5179 peer_limit = class.per_peer_limit(),
5180 "Audit responder request admitted"
5181 );
5182 let bootstrapping = *ctx.is_bootstrapping.read().await;
5183 let storage = Arc::clone(&ctx.storage);
5184 let p2p_node = Arc::clone(&ctx.p2p_node);
5185 let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5186 let source = *source;
5187 let request_id = msg.request_id;
5188 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5189 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5190 ctx.detached_task_tracker.spawn(async move {
5191 let _guard = guard; let worker_started = Instant::now();
5193 let processing_started = Instant::now();
5194 let response = storage_commitment_audit::handle_subtree_slice_challenge(
5195 &challenge,
5196 &storage,
5197 p2p_node.peer_id(),
5198 bootstrapping,
5199 Some(&my_commitment_state),
5200 )
5201 .await;
5202 let processing = processing_started.elapsed();
5203 let response_kind = subtree_slice_response_kind(&response);
5204 let response_send_started = Instant::now();
5205 let sent = send_replication_response_checked(
5206 &source,
5207 &p2p_node,
5208 request_id,
5209 ReplicationMessageBody::SubtreeSliceResponse(response),
5210 rr_message_id.as_deref(),
5211 None,
5212 )
5213 .await;
5214 let response_send = response_send_started.elapsed();
5215 log_audit_responder_completion(
5216 &responder_metrics,
5217 source,
5218 class,
5219 "byte",
5220 challenge.challenge_id,
5221 challenge.openings.len(),
5222 response_kind,
5223 sent,
5224 received_at,
5225 worker_started,
5226 processing,
5227 response_send,
5228 );
5229 });
5230 Ok(())
5231 }
5232 ReplicationMessageBody::GetCommitmentByPin(ref request) => {
5233 let class = AuditResponderClass::CommitmentPin;
5245 let guard = match admit_audit_responder(
5246 &ctx.audit_responder_semaphore,
5247 &ctx.audit_responder_inflight,
5248 source,
5249 class,
5250 )
5251 .await
5252 {
5253 Ok(guard) => guard,
5254 Err(failure) => {
5255 audit_metrics::record_admission_drop(class);
5256 ctx.audit_responder_metrics
5257 .record_drop(*source, failure.reason.into());
5258 warn!(
5259 target: "ant_node::replication::audit_responder",
5260 event = "admission_dropped",
5261 kind = "commitment_pin",
5262 responder_class = class.as_str(),
5263 source = %source,
5264 challenge_id = msg.request_id,
5265 request_response = rr_message_id.is_some(),
5266 dispatch_ms = received_at.elapsed().as_millis(),
5267 reason = failure.reason.as_str(),
5268 global_inflight = failure.global_inflight,
5269 global_limit = failure.global_limit,
5270 peer_inflight = failure.peer_inflight,
5271 peer_limit = failure.peer_limit,
5272 "Audit responder admission dropped"
5273 );
5274 return Ok(());
5275 }
5276 };
5277 ctx.audit_responder_metrics.record_admitted(
5278 *source,
5279 guard.global_inflight,
5280 guard.peer_inflight,
5281 );
5282 info!(
5283 target: "ant_node::replication::audit_responder",
5284 event = "admitted",
5285 kind = "commitment_pin",
5286 responder_class = class.as_str(),
5287 source = %source,
5288 challenge_id = msg.request_id,
5289 request_response = rr_message_id.is_some(),
5290 dispatch_ms = received_at.elapsed().as_millis(),
5291 global_inflight = guard.global_inflight,
5292 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5293 peer_inflight = guard.peer_inflight,
5294 peer_limit = class.per_peer_limit(),
5295 "Audit responder request admitted"
5296 );
5297 let worker_started = Instant::now();
5298 let processing_started = Instant::now();
5299 let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
5300 protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
5301 |built| protocol::GetCommitmentByPinResponse::Found {
5302 commitment: built.commitment().clone(),
5303 },
5304 );
5305 let processing = processing_started.elapsed();
5306 let response_kind = commitment_pin_response_kind(&response);
5307 let response_send_started = Instant::now();
5308 let sent = send_replication_response_checked(
5309 source,
5310 &ctx.p2p_node,
5311 msg.request_id,
5312 ReplicationMessageBody::GetCommitmentByPinResponse(response),
5313 rr_message_id,
5314 None,
5315 )
5316 .await;
5317 let response_send = response_send_started.elapsed();
5318 log_audit_responder_completion(
5319 &ctx.audit_responder_metrics,
5320 *source,
5321 class,
5322 "commitment_pin",
5323 msg.request_id,
5324 1,
5325 response_kind,
5326 sent,
5327 received_at,
5328 worker_started,
5329 processing,
5330 response_send,
5331 );
5332 drop(guard);
5333 Ok(())
5334 }
5335 ReplicationMessageBody::FreshReplicationResponse(_)
5337 | ReplicationMessageBody::NeighborSyncResponse(_)
5338 | ReplicationMessageBody::VerificationResponse(_)
5339 | ReplicationMessageBody::FetchResponse(_)
5340 | ReplicationMessageBody::AuditResponse(_)
5341 | ReplicationMessageBody::SubtreeAuditResponse(_)
5342 | ReplicationMessageBody::SubtreeSliceResponse(_)
5343 | ReplicationMessageBody::GetCommitmentByPinResponse(_) => Ok(()),
5344 }
5345}
5346
5347async fn verify_payment_until_shutdown(
5367 payment_verifier: &Arc<PaymentVerifier>,
5368 key: &XorName,
5369 proof_of_payment: &[u8],
5370 context: VerificationContext,
5371 shutdown: &CancellationToken,
5372) -> Option<Result<crate::payment::PaymentStatus>> {
5373 tokio::select! {
5374 () = shutdown.cancelled() => None,
5375 result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
5376 Some(result)
5377 }
5378 }
5379}
5380
5381struct FreshOfferRejection {
5383 reason: String,
5385 penalise: bool,
5388}
5389
5390fn fresh_offer_structural_rejection(
5415 key: &XorName,
5416 data: &[u8],
5417 proof_of_payment: &[u8],
5418) -> Option<FreshOfferRejection> {
5419 if proof_of_payment.is_empty() {
5423 return Some(FreshOfferRejection {
5424 reason: "Missing proof of payment".to_string(),
5425 penalise: true,
5426 });
5427 }
5428
5429 if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
5438 return Some(FreshOfferRejection {
5439 reason: format!(
5440 "Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
5441 proof_of_payment.len(),
5442 ),
5443 penalise: true,
5444 });
5445 }
5446 if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
5447 return Some(FreshOfferRejection {
5448 reason: format!(
5449 "Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
5450 proof_of_payment.len(),
5451 ),
5452 penalise: true,
5453 });
5454 }
5455
5456 if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
5460 return Some(FreshOfferRejection {
5461 reason: format!(
5462 "Data size {} exceeds maximum chunk size {}",
5463 data.len(),
5464 crate::ant_protocol::MAX_CHUNK_SIZE,
5465 ),
5466 penalise: true,
5467 });
5468 }
5469
5470 let computed_key = crate::client::compute_address(data);
5483 if computed_key != *key {
5484 return Some(FreshOfferRejection {
5485 reason: format!(
5486 "Content address mismatch: expected {}, computed {}",
5487 hex::encode(key),
5488 hex::encode(computed_key),
5489 ),
5490 penalise: true,
5491 });
5492 }
5493
5494 None
5495}
5496
5497async fn refuse_fresh_offer(
5503 source: &PeerId,
5504 key: XorName,
5505 reason: String,
5506 ctx: &ReplicationMessageHandlerContext,
5507 request_id: u64,
5508 rr_message_id: Option<&str>,
5509) {
5510 send_replication_response(
5511 source,
5512 &ctx.p2p_node,
5513 request_id,
5514 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5515 key,
5516 reason,
5517 }),
5518 rr_message_id,
5519 )
5520 .await;
5521}
5522
5523async fn refuse_malformed_fresh_offer(
5529 source: &PeerId,
5530 key: XorName,
5531 rejection: FreshOfferRejection,
5532 ctx: &ReplicationMessageHandlerContext,
5533 request_id: u64,
5534 rr_message_id: Option<&str>,
5535) {
5536 if rejection.penalise {
5537 warn!(
5538 "Rejecting fresh offer for key {} from {source}: {}",
5539 hex::encode(key),
5540 rejection.reason
5541 );
5542 ctx.p2p_node
5543 .report_trust_event(
5544 source,
5545 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5546 )
5547 .await;
5548 } else {
5549 debug!(
5550 "Fresh offer for {} from {source} refused before admission: {}",
5551 hex::encode(key),
5552 rejection.reason
5553 );
5554 }
5555 refuse_fresh_offer(
5556 source,
5557 key,
5558 rejection.reason,
5559 ctx,
5560 request_id,
5561 rr_message_id,
5562 )
5563 .await;
5564}
5565
5566async fn refuse_stranded_fresh_offers(
5573 key: XorName,
5574 stranded: Vec<FreshOfferAttempt>,
5575 ctx: &ReplicationMessageHandlerContext,
5576) {
5577 for attempt in stranded {
5578 refuse_fresh_offer(
5579 &attempt.source,
5580 key,
5581 "Receiver at fresh-offer capacity".to_string(),
5582 ctx,
5583 attempt.request_id,
5584 attempt.rr_message_id.as_deref(),
5585 )
5586 .await;
5587 }
5588}
5589
5590async fn dispatch_fresh_offer(
5614 source: PeerId,
5615 offer: protocol::FreshReplicationOffer,
5616 ctx: &ReplicationMessageHandlerContext,
5617 request_id: u64,
5618 received_at: Instant,
5619 rr_message_id: Option<&str>,
5620) -> Result<()> {
5621 if let Some(rejection) =
5622 fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
5623 {
5624 refuse_malformed_fresh_offer(
5625 &source,
5626 offer.key,
5627 rejection,
5628 ctx,
5629 request_id,
5630 rr_message_id,
5631 )
5632 .await;
5633 return Ok(());
5634 }
5635
5636 let key = offer.key;
5646 let admission_outcome = FreshOfferEntryGuard::admit(
5647 &ctx.fresh_offer_in_flight,
5648 offer,
5649 source,
5650 request_id,
5651 rr_message_id.map(ToOwned::to_owned),
5652 received_at,
5653 );
5654 let mut entry = match admission_outcome {
5655 FreshOfferAdmission::Opened(entry) => entry,
5656 FreshOfferAdmission::Joined => {
5657 debug!(
5660 "Fresh offer for {} from {source} queued behind the handler already \
5661 holding the key",
5662 hex::encode(key)
5663 );
5664 return Ok(());
5665 }
5666 surplus => {
5669 debug!(
5670 "Fresh offer for {} from {source} refused: {}",
5671 hex::encode(key),
5672 surplus.surplus_reason()
5673 );
5674 refuse_fresh_offer(
5675 &source,
5676 key,
5677 "Duplicate offer already in flight".to_string(),
5678 ctx,
5679 request_id,
5680 rr_message_id,
5681 )
5682 .await;
5683 return Ok(());
5684 }
5685 };
5686
5687 let admission = match admit_bounded_responder(
5688 &ctx.fresh_offer_admission_semaphore,
5689 &ctx.fresh_offer_responder_inflight,
5690 &source,
5691 FRESH_OFFER_MAX_OUTSTANDING,
5692 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
5693 )
5694 .await
5695 {
5696 Ok(guard) => guard,
5697 Err(failure) => {
5698 audit_metrics::record_responder_admission_drop(
5699 ReplicationResponderClass::FreshOffer,
5700 failure.reason.into(),
5701 );
5702 warn!(
5709 responder_class = "fresh_offer",
5710 source = %source,
5711 key = %hex::encode(key),
5712 "Fresh offer refused at admission — this node will be penalised for the resulting absence: {failure}"
5713 );
5714 let stranded = entry.release();
5720 refuse_fresh_offer(
5721 &source,
5722 key,
5723 "Receiver at fresh-offer capacity".to_string(),
5724 ctx,
5725 request_id,
5726 rr_message_id,
5727 )
5728 .await;
5729 refuse_stranded_fresh_offers(key, stranded, ctx).await;
5730 return Ok(());
5731 }
5732 };
5733
5734 let ctx = ctx.clone();
5735 ctx.detached_task_tracker
5739 .clone()
5740 .spawn(run_fresh_offer_worker(key, entry, ctx, admission));
5741 Ok(())
5742}
5743
5744async fn run_fresh_offer_worker(
5760 key: XorName,
5761 mut entry: Box<FreshOfferEntryGuard>,
5762 ctx: ReplicationMessageHandlerContext,
5763 admission: ResponderGuard,
5764) {
5765 let _admission = admission;
5769 let received_at = entry.received_at();
5770 let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
5778 .acquire_owned()
5779 .await
5780 else {
5781 debug!(
5782 "Fresh offer for {} dropped: worker pool shut down",
5783 hex::encode(key)
5784 );
5785 return;
5786 };
5787 if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
5800 debug!(
5801 responder_class = "fresh_offer",
5802 key = %hex::encode(key),
5803 request_age_ms = received_at.elapsed().as_millis(),
5804 "Superseded fresh offer shed at dequeue"
5805 );
5806 return;
5807 }
5808
5809 let mut verdict = FreshOfferOutcome::Abandoned;
5810 while let Some(attempt) = entry.next_attempt() {
5811 match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
5812 Ok(outcome) => {
5813 verdict = outcome;
5814 match outcome {
5815 FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
5820 FreshOfferOutcome::ProofRejected => {}
5823 }
5824 }
5825 Err(e) => {
5826 debug!(
5827 "Fresh replication offer for {} from {} error: {e}",
5828 hex::encode(key),
5829 attempt.source
5830 );
5831 verdict = FreshOfferOutcome::Abandoned;
5832 break;
5833 }
5834 }
5835 }
5836
5837 let unreached = entry.release();
5841 if unreached.is_empty() {
5842 return;
5843 }
5844 let response = match verdict {
5845 FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
5846 FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
5847 FreshReplicationResponse::Rejected {
5848 key,
5849 reason: "Record could not be stored from any offered proof".to_string(),
5850 }
5851 }
5852 };
5853 for attempt in unreached {
5854 send_replication_response(
5855 &attempt.source,
5856 &ctx.p2p_node,
5857 attempt.request_id,
5858 ReplicationMessageBody::FreshReplicationResponse(response.clone()),
5859 attempt.rr_message_id.as_deref(),
5860 )
5861 .await;
5862 }
5863}
5864
5865#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5872enum FreshOfferOutcome {
5873 Settled,
5875 ProofRejected,
5878 Abandoned,
5881}
5882
5883#[allow(clippy::too_many_lines)]
5887async fn handle_fresh_offer(
5888 key: &XorName,
5889 data: &[u8],
5890 attempt: &FreshOfferAttempt,
5891 ctx: &ReplicationMessageHandlerContext,
5892) -> Result<FreshOfferOutcome> {
5893 let source = &attempt.source;
5894 let request_id = attempt.request_id;
5895 let rr_message_id = attempt.rr_message_id.as_deref();
5896 let p2p_node = &ctx.p2p_node;
5897 let config = &ctx.config;
5898 let self_id = *p2p_node.peer_id();
5899
5900 if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
5907 {
5908 if rejection.penalise {
5909 warn!(
5910 "Rejecting fresh offer for key {}: {}",
5911 hex::encode(key),
5912 rejection.reason
5913 );
5914 p2p_node
5915 .report_trust_event(
5916 source,
5917 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5918 )
5919 .await;
5920 }
5921 send_replication_response(
5922 source,
5923 p2p_node,
5924 request_id,
5925 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5926 key: *key,
5927 reason: rejection.reason,
5928 }),
5929 rr_message_id,
5930 )
5931 .await;
5932 return Ok(FreshOfferOutcome::ProofRejected);
5934 }
5935
5936 if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
5945 {
5946 send_replication_response(
5947 source,
5948 p2p_node,
5949 request_id,
5950 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5951 key: *key,
5952 reason: "Not in storage-admission range for this key".to_string(),
5953 }),
5954 rr_message_id,
5955 )
5956 .await;
5957 return Ok(FreshOfferOutcome::Abandoned);
5960 }
5961
5962 if let Err(e) = ctx.storage.check_capacity() {
5969 info!(
5970 target: "ant_node::storage::disk_precheck",
5971 key = %hex::encode(key),
5972 "Rejecting fresh replication offer before payment verification: {e}"
5973 );
5974 send_replication_response(
5975 source,
5976 p2p_node,
5977 request_id,
5978 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5979 key: *key,
5980 reason: e.to_string(),
5981 }),
5982 rr_message_id,
5983 )
5984 .await;
5985 return Ok(FreshOfferOutcome::Abandoned);
5987 }
5988
5989 let Some(verification) = verify_payment_until_shutdown(
5998 &ctx.payment_verifier,
5999 key,
6000 &attempt.proof_of_payment,
6001 fresh_offer_payment_context(),
6002 &ctx.shutdown,
6003 )
6004 .await
6005 else {
6006 debug!(
6007 "Fresh offer for {} from {source} abandoned: engine shutting down \
6008 during payment verification",
6009 hex::encode(key)
6010 );
6011 return Ok(FreshOfferOutcome::Abandoned);
6012 };
6013 match verification {
6014 Ok(status) if status.can_store() => {
6015 debug!("PoP validated for fresh offer key {}", hex::encode(key));
6016 }
6017 Ok(_) => {
6028 debug!(
6029 "Fresh offer for {} from {source}: no payment found for this proof",
6030 hex::encode(key)
6031 );
6032 send_replication_response(
6033 source,
6034 p2p_node,
6035 request_id,
6036 ReplicationMessageBody::FreshReplicationResponse(
6037 FreshReplicationResponse::Rejected {
6038 key: *key,
6039 reason: "Payment verification failed: payment required".to_string(),
6040 },
6041 ),
6042 rr_message_id,
6043 )
6044 .await;
6045 return Ok(FreshOfferOutcome::ProofRejected);
6046 }
6047 Err(e) => {
6052 warn!("PoP verification error for key {}: {e}", hex::encode(key));
6053 send_replication_response(
6054 source,
6055 p2p_node,
6056 request_id,
6057 ReplicationMessageBody::FreshReplicationResponse(
6058 FreshReplicationResponse::Rejected {
6059 key: *key,
6060 reason: format!("Payment verification error: {e}"),
6061 },
6062 ),
6063 rr_message_id,
6064 )
6065 .await;
6066 return Ok(FreshOfferOutcome::ProofRejected);
6067 }
6068 }
6069
6070 if let Err(e) = ctx.paid_list.insert(key).await {
6072 warn!("Failed to add key to PaidForList: {e}");
6073 }
6074
6075 match ctx.storage.put(key, data).await {
6077 Ok(_) => {
6078 send_replication_response(
6079 source,
6080 p2p_node,
6081 request_id,
6082 ReplicationMessageBody::FreshReplicationResponse(
6083 FreshReplicationResponse::Accepted { key: *key },
6084 ),
6085 rr_message_id,
6086 )
6087 .await;
6088 Ok(FreshOfferOutcome::Settled)
6089 }
6090 Err(e) => {
6091 send_replication_response(
6092 source,
6093 p2p_node,
6094 request_id,
6095 ReplicationMessageBody::FreshReplicationResponse(
6096 FreshReplicationResponse::Rejected {
6097 key: *key,
6098 reason: e.to_string(),
6099 },
6100 ),
6101 rr_message_id,
6102 )
6103 .await;
6104 Ok(FreshOfferOutcome::Abandoned)
6107 }
6108 }
6109}
6110
6111async fn dispatch_paid_notify(
6130 source: PeerId,
6131 notify: protocol::PaidNotify,
6132 ctx: &ReplicationMessageHandlerContext,
6133 received_at: Instant,
6134) -> Result<()> {
6135 let admission = match admit_bounded_responder(
6136 &ctx.paid_notify_admission_semaphore,
6137 &ctx.paid_notify_responder_inflight,
6138 &source,
6139 PAID_NOTIFY_MAX_OUTSTANDING,
6140 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
6141 )
6142 .await
6143 {
6144 Ok(guard) => guard,
6145 Err(failure) => {
6146 audit_metrics::record_responder_admission_drop(
6147 ReplicationResponderClass::PaidNotify,
6148 failure.reason.into(),
6149 );
6150 warn!(
6154 responder_class = "paid_notify",
6155 source = %source,
6156 key = %hex::encode(notify.key),
6157 "Paid notify dropped at admission — paid-list evidence lost until a verification cycle re-derives it: {failure}"
6158 );
6159 return Ok(());
6160 }
6161 };
6162
6163 let ctx = ctx.clone();
6164 let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
6165 let queue_max_age = ctx.config.neighbor_sync_interval_max;
6173 ctx.detached_task_tracker.clone().spawn(async move {
6174 let _admission = admission;
6175 let Ok(_worker) = worker_semaphore.acquire_owned().await else {
6178 debug!("Paid notify from {source} dropped: worker pool shut down");
6179 return;
6180 };
6181 if request_is_stale(received_at, queue_max_age) {
6182 debug!(
6183 responder_class = "paid_notify",
6184 source = %source,
6185 request_age_ms = received_at.elapsed().as_millis(),
6186 "Redundant paid notify shed at dequeue"
6187 );
6188 return;
6189 }
6190 if let Err(e) = handle_paid_notify(
6191 &source,
6192 ¬ify,
6193 &ctx.paid_list,
6194 &ctx.payment_verifier,
6195 &ctx.p2p_node,
6196 &ctx.config,
6197 &ctx.shutdown,
6198 )
6199 .await
6200 {
6201 debug!("Paid notify from {source} error: {e}");
6202 }
6203 });
6204
6205 Ok(())
6206}
6207
6208async fn handle_paid_notify(
6209 _source: &PeerId,
6210 notify: &protocol::PaidNotify,
6211 paid_list: &Arc<PaidList>,
6212 payment_verifier: &Arc<PaymentVerifier>,
6213 p2p_node: &Arc<P2PNode>,
6214 config: &ReplicationConfig,
6215 shutdown: &CancellationToken,
6216) -> Result<()> {
6217 let self_id = *p2p_node.peer_id();
6218
6219 if notify.proof_of_payment.is_empty() {
6221 return Ok(());
6222 }
6223
6224 if !admission::is_in_paid_close_group(
6226 &self_id,
6227 ¬ify.key,
6228 p2p_node,
6229 config.paid_list_close_group_size,
6230 )
6231 .await
6232 {
6233 return Ok(());
6234 }
6235
6236 let Some(verification) = verify_payment_until_shutdown(
6241 payment_verifier,
6242 ¬ify.key,
6243 ¬ify.proof_of_payment,
6244 paid_notify_payment_context(),
6245 shutdown,
6246 )
6247 .await
6248 else {
6249 debug!(
6250 "Paid notify for {} abandoned: engine shutting down during payment \
6251 verification",
6252 hex::encode(notify.key)
6253 );
6254 return Ok(());
6255 };
6256 match verification {
6257 Ok(status) if status.can_store() => {
6258 debug!(
6259 "PoP validated for paid notify key {}",
6260 hex::encode(notify.key)
6261 );
6262 }
6263 Ok(_) => {
6264 warn!(
6265 "Paid notify rejected: payment required for key {}",
6266 hex::encode(notify.key)
6267 );
6268 return Ok(());
6269 }
6270 Err(e) => {
6271 warn!(
6272 "PoP verification error for paid notify key {}: {e}",
6273 hex::encode(notify.key)
6274 );
6275 return Ok(());
6276 }
6277 }
6278
6279 if let Err(e) = paid_list.insert(¬ify.key).await {
6280 warn!("Failed to add paid notify key to PaidForList: {e}");
6281 }
6282
6283 Ok(())
6284}
6285
6286#[allow(clippy::too_many_arguments)]
6287async fn dispatch_neighbor_sync_request(
6288 source: PeerId,
6289 request: protocol::NeighborSyncRequest,
6290 ctx: &ReplicationMessageHandlerContext,
6291 is_bootstrapping: bool,
6292 my_commitment: Option<StorageCommitment>,
6293 request_id: u64,
6294 received_at: Instant,
6295 rr_message_id: Option<&str>,
6296) -> Result<()> {
6297 let guard = match admit_bounded_responder(
6298 &ctx.neighbor_sync_responder_admission_semaphore,
6299 &ctx.neighbor_sync_responder_inflight,
6300 &source,
6301 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
6302 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6303 )
6304 .await
6305 {
6306 Ok(guard) => guard,
6307 Err(failure) => {
6308 audit_metrics::record_responder_admission_drop(
6309 ReplicationResponderClass::NeighborSync,
6310 failure.reason.into(),
6311 );
6312 warn!(
6313 responder_class = "neighbor_sync",
6314 source = %source,
6315 "Neighbor-sync response dropped at admission: {failure}"
6316 );
6317 return Ok(());
6318 }
6319 };
6320
6321 let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
6322 let p2p_node = Arc::clone(&ctx.p2p_node);
6323 let storage = Arc::clone(&ctx.storage);
6324 let paid_list = Arc::clone(&ctx.paid_list);
6325 let queues = Arc::clone(&ctx.queues);
6326 let config = Arc::clone(&ctx.config);
6327 let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
6328 let sync_history = Arc::clone(&ctx.sync_history);
6329 let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
6330 let repair_proofs = Arc::clone(&ctx.repair_proofs);
6331 let request_timeout = ctx.config.verification_request_timeout;
6332 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6333 ctx.detached_task_tracker.spawn(async move {
6334 let _guard = guard;
6335 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6336 debug!(
6337 responder_class = "neighbor_sync",
6338 source = %source,
6339 "Neighbor-sync responder worker pool closed before dequeue"
6340 );
6341 return;
6342 };
6343 if request_is_stale(received_at, request_timeout) {
6344 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
6345 debug!(
6346 responder_class = "neighbor_sync",
6347 source = %source,
6348 request_age_ms = received_at.elapsed().as_millis(),
6349 "Stale neighbor-sync request shed at dequeue"
6350 );
6351 return;
6352 }
6353 if let Err(e) = handle_neighbor_sync_request(
6354 &source,
6355 &request,
6356 &p2p_node,
6357 &storage,
6358 &paid_list,
6359 &queues,
6360 &config,
6361 is_bootstrapping,
6362 &bootstrap_state,
6363 &sync_history,
6364 &sync_cycle_epoch,
6365 &repair_proofs,
6366 my_commitment,
6367 request_id,
6368 rr_message_id.as_deref(),
6369 )
6370 .await
6371 {
6372 debug!(source = %source, "Neighbor-sync request handling failed: {e}");
6373 }
6374 });
6375
6376 Ok(())
6377}
6378
6379#[allow(clippy::too_many_arguments)]
6380async fn handle_neighbor_sync_request(
6381 source: &PeerId,
6382 request: &protocol::NeighborSyncRequest,
6383 p2p_node: &Arc<P2PNode>,
6384 storage: &Arc<LmdbStorage>,
6385 paid_list: &Arc<PaidList>,
6386 queues: &Arc<RwLock<ReplicationQueues>>,
6387 config: &ReplicationConfig,
6388 is_bootstrapping: bool,
6389 bootstrap_state: &Arc<RwLock<BootstrapState>>,
6390 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
6391 sync_cycle_epoch: &Arc<RwLock<u64>>,
6392 repair_proofs: &Arc<RwLock<RepairProofs>>,
6393 my_commitment: Option<StorageCommitment>,
6394 request_id: u64,
6395 rr_message_id: Option<&str>,
6396) -> Result<()> {
6397 let self_id = *p2p_node.peer_id();
6398
6399 let (response, sent_replica_hints, sender_in_rt) =
6407 neighbor_sync::handle_sync_request_with_proofs(
6408 source,
6409 request,
6410 p2p_node,
6411 storage,
6412 paid_list,
6413 config,
6414 is_bootstrapping,
6415 my_commitment.clone(),
6416 )
6417 .await;
6418
6419 let response_sent = send_replication_response_checked(
6421 source,
6422 p2p_node,
6423 request_id,
6424 ReplicationMessageBody::NeighborSyncResponse(response),
6425 rr_message_id,
6426 None,
6427 )
6428 .await;
6429
6430 if !sender_in_rt {
6432 return Ok(());
6433 }
6434
6435 {
6438 let mut history = sync_history.write().await;
6439 let record = history.entry(*source).or_insert(PeerSyncRecord {
6440 last_sync: None,
6441 cycles_since_sync: 0,
6442 });
6443 record.last_sync = Some(Instant::now());
6444 record.cycles_since_sync = 0;
6445 }
6446
6447 if response_sent && !request.bootstrapping {
6448 record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
6449 .await;
6450 }
6451
6452 let outcome = admit_and_queue_hints(
6454 &self_id,
6455 source,
6456 &request.replica_hints,
6457 &request.paid_hints,
6458 p2p_node,
6459 config,
6460 storage,
6461 paid_list,
6462 queues,
6463 )
6464 .await;
6465
6466 if is_bootstrapping {
6471 let live_discovered = outcome.discovered.clone();
6472 let outcomes = [(*source, outcome)];
6473 publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
6474 }
6475
6476 Ok(())
6477}
6478
6479async fn handle_verification_request(
6480 source: &PeerId,
6481 request: &protocol::VerificationRequest,
6482 storage: &Arc<LmdbStorage>,
6483 paid_list: &Arc<PaidList>,
6484 p2p_node: &Arc<P2PNode>,
6485 request_id: u64,
6486 rr_message_id: Option<&str>,
6487) -> Result<()> {
6488 #[derive(Clone, Copy)]
6489 enum CachedPaidLookup {
6490 NotChecked,
6491 Checked(Option<bool>),
6492 }
6493
6494 #[derive(Clone, Copy)]
6495 struct CachedVerificationLookup {
6496 present: Option<bool>,
6497 paid: CachedPaidLookup,
6498 }
6499
6500 if verification_request_exceeds_limit(request.keys.len()) {
6501 warn!(
6502 "Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
6503 request.keys.len(),
6504 );
6505 send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6506 return Ok(());
6507 }
6508
6509 let requested_keys = request.keys.as_slice();
6510
6511 if request.paid_list_check_indices.len() > request.keys.len() {
6512 warn!(
6513 "Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
6514 request.paid_list_check_indices.len(),
6515 request.keys.len(),
6516 );
6517 send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6518 return Ok(());
6519 }
6520
6521 let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
6522 let paid_check_set: HashSet<u32> = request
6523 .paid_list_check_indices
6524 .iter()
6525 .copied()
6526 .filter(|&idx| {
6527 if idx >= keys_len {
6528 warn!(
6529 "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
6530 requested_keys.len(),
6531 );
6532 false
6533 } else {
6534 true
6535 }
6536 })
6537 .collect();
6538
6539 let mut results = Vec::with_capacity(requested_keys.len());
6540 let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
6541 for (i, key) in requested_keys.iter().enumerate() {
6542 let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
6543 let cached = lookup_cache.entry(*key).or_insert_with(|| {
6544 let present = match storage.exists(key) {
6545 Ok(present) => Some(present),
6546 Err(e) => {
6547 warn!(
6548 "Verification request from {source}: failed to check storage for {}: {e}",
6549 hex::encode(key)
6550 );
6551 None
6552 }
6553 };
6554 CachedVerificationLookup {
6555 present,
6556 paid: CachedPaidLookup::NotChecked,
6557 }
6558 });
6559
6560 if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
6561 cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
6562 Ok(paid) => Some(paid),
6563 Err(e) => {
6564 warn!(
6565 "Verification request from {source}: failed to check paid-list for {}: {e}",
6566 hex::encode(key)
6567 );
6568 None
6569 }
6570 });
6571 }
6572
6573 let paid = if needs_paid {
6574 match cached.paid {
6575 CachedPaidLookup::Checked(paid) => paid,
6576 CachedPaidLookup::NotChecked => None,
6577 }
6578 } else {
6579 None
6580 };
6581
6582 if cached.present.is_none() && paid.is_none() {
6583 continue;
6584 }
6585
6586 results.push(protocol::KeyVerificationResult {
6587 key: *key,
6588 present: cached.present.unwrap_or(false),
6589 paid,
6590 });
6591 }
6592
6593 send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
6594
6595 Ok(())
6596}
6597
6598async fn dispatch_verification_request(
6599 source: PeerId,
6600 request: protocol::VerificationRequest,
6601 ctx: &ReplicationMessageHandlerContext,
6602 request_id: u64,
6603 received_at: Instant,
6604 rr_message_id: Option<&str>,
6605) -> Result<()> {
6606 let guard = match admit_bounded_responder(
6607 &ctx.verification_responder_admission_semaphore,
6608 &ctx.verification_responder_inflight,
6609 &source,
6610 VERIFICATION_RESPONDER_MAX_OUTSTANDING,
6611 VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6612 )
6613 .await
6614 {
6615 Ok(guard) => guard,
6616 Err(failure) => {
6617 audit_metrics::record_responder_admission_drop(
6618 ReplicationResponderClass::Verification,
6619 failure.reason.into(),
6620 );
6621 warn!(
6622 responder_class = "verification",
6623 source = %source,
6624 "Verification response dropped at admission: {failure}"
6625 );
6626 return Ok(());
6627 }
6628 };
6629
6630 let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
6631 let storage = Arc::clone(&ctx.storage);
6632 let paid_list = Arc::clone(&ctx.paid_list);
6633 let p2p_node = Arc::clone(&ctx.p2p_node);
6634 let request_timeout = ctx.config.verification_request_timeout;
6635 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6636 ctx.detached_task_tracker.spawn(async move {
6637 let _guard = guard;
6638 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6639 debug!(
6640 responder_class = "verification",
6641 source = %source,
6642 "Verification responder worker pool closed before dequeue"
6643 );
6644 return;
6645 };
6646 if request_is_stale(received_at, request_timeout) {
6647 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
6648 debug!(
6649 responder_class = "verification",
6650 source = %source,
6651 request_age_ms = received_at.elapsed().as_millis(),
6652 "Stale verification request shed at dequeue"
6653 );
6654 return;
6655 }
6656 if let Err(e) = handle_verification_request(
6657 &source,
6658 &request,
6659 &storage,
6660 &paid_list,
6661 &p2p_node,
6662 request_id,
6663 rr_message_id.as_deref(),
6664 )
6665 .await
6666 {
6667 debug!(source = %source, "Verification request handling failed: {e}");
6668 }
6669 });
6670
6671 Ok(())
6672}
6673
6674const fn verification_request_exceeds_limit(key_count: usize) -> bool {
6675 key_count > MAX_INCOMING_VERIFICATION_KEYS
6676}
6677
6678async fn send_verification_results(
6679 source: &PeerId,
6680 p2p_node: &Arc<P2PNode>,
6681 request_id: u64,
6682 results: Vec<protocol::KeyVerificationResult>,
6683 rr_message_id: Option<&str>,
6684) {
6685 send_replication_response(
6686 source,
6687 p2p_node,
6688 request_id,
6689 ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
6690 rr_message_id,
6691 )
6692 .await;
6693}
6694
6695async fn dispatch_fetch_request(
6696 source: PeerId,
6697 request: protocol::FetchRequest,
6698 ctx: &ReplicationMessageHandlerContext,
6699 request_id: u64,
6700 received_at: Instant,
6701 rr_message_id: Option<&str>,
6702) -> Result<()> {
6703 let guard = match admit_bounded_responder(
6704 &ctx.fetch_responder_admission_semaphore,
6705 &ctx.fetch_responder_inflight,
6706 &source,
6707 FETCH_RESPONDER_MAX_OUTSTANDING,
6708 FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6709 )
6710 .await
6711 {
6712 Ok(guard) => guard,
6713 Err(failure) => {
6714 audit_metrics::record_responder_admission_drop(
6715 ReplicationResponderClass::Fetch,
6716 failure.reason.into(),
6717 );
6718 warn!(
6719 responder_class = "fetch",
6720 source = %source,
6721 "Fetch response dropped at admission: {failure}"
6722 );
6723 return Ok(());
6724 }
6725 };
6726
6727 let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
6728 let storage = Arc::clone(&ctx.storage);
6729 let p2p_node = Arc::clone(&ctx.p2p_node);
6730 let request_timeout = ctx.config.fetch_request_timeout;
6731 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6732 ctx.detached_task_tracker.spawn(async move {
6733 let _guard = guard;
6734 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6735 debug!(
6736 responder_class = "fetch",
6737 source = %source,
6738 "Fetch responder worker pool closed before dequeue"
6739 );
6740 return;
6741 };
6742 if request_is_stale(received_at, request_timeout) {
6743 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
6744 debug!(
6745 responder_class = "fetch",
6746 source = %source,
6747 request_age_ms = received_at.elapsed().as_millis(),
6748 "Stale fetch request shed at dequeue"
6749 );
6750 return;
6751 }
6752 if let Err(e) = handle_fetch_request(
6753 &source,
6754 &request,
6755 &storage,
6756 &p2p_node,
6757 request_id,
6758 rr_message_id.as_deref(),
6759 )
6760 .await
6761 {
6762 debug!(source = %source, "Fetch request handling failed: {e}");
6763 }
6764 });
6765
6766 Ok(())
6767}
6768
6769fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
6770 received_at.elapsed() >= timeout
6771}
6772
6773async fn handle_fetch_request(
6774 source: &PeerId,
6775 request: &protocol::FetchRequest,
6776 storage: &Arc<LmdbStorage>,
6777 p2p_node: &Arc<P2PNode>,
6778 request_id: u64,
6779 rr_message_id: Option<&str>,
6780) -> Result<()> {
6781 let response = match storage.get(&request.key).await {
6782 Ok(Some(data)) => protocol::FetchResponse::Success {
6783 key: request.key,
6784 data,
6785 },
6786 Ok(None) => protocol::FetchResponse::NotFound { key: request.key },
6787 Err(e) => protocol::FetchResponse::Error {
6788 key: request.key,
6789 reason: format!("{e}"),
6790 },
6791 };
6792
6793 send_replication_response(
6794 source,
6795 p2p_node,
6796 request_id,
6797 ReplicationMessageBody::FetchResponse(response),
6798 rr_message_id,
6799 )
6800 .await;
6801
6802 Ok(())
6803}
6804
6805struct AuditResponderCompletion {
6809 response_kind: &'static str,
6810 sent: bool,
6811 processing: Duration,
6812 response_send: Duration,
6813}
6814
6815async fn handle_audit_challenge_msg(
6816 source: &PeerId,
6817 challenge: &protocol::AuditChallenge,
6818 storage: &Arc<LmdbStorage>,
6819 p2p_node: &Arc<P2PNode>,
6820 is_bootstrapping: bool,
6821 reply: ReplyRoute<'_>,
6822) -> Result<AuditResponderCompletion> {
6823 #[allow(clippy::cast_possible_truncation)]
6824 let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
6825 info!(
6826 "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
6827 challenge.keys.len(),
6828 is_bootstrapping,
6829 reply.rr_message_id.is_some(),
6830 );
6831
6832 let processing_started = Instant::now();
6833 let response = audit::handle_audit_challenge(
6834 challenge,
6835 storage,
6836 p2p_node.peer_id(),
6837 is_bootstrapping,
6838 stored_chunks,
6839 )
6840 .await;
6841 let processing = processing_started.elapsed();
6842 let response_kind = audit_response_kind(&response);
6843
6844 let response_send_started = Instant::now();
6845 let sent = send_replication_response_checked(
6846 source,
6847 p2p_node,
6848 reply.request_id,
6849 ReplicationMessageBody::AuditResponse(response),
6850 reply.rr_message_id,
6851 Some(reply.protocol),
6852 )
6853 .await;
6854 let response_send = response_send_started.elapsed();
6855
6856 Ok(AuditResponderCompletion {
6857 response_kind,
6858 sent,
6859 processing,
6860 response_send,
6861 })
6862}
6863
6864#[allow(clippy::too_many_arguments)]
6865fn log_audit_responder_completion(
6866 metrics: &AuditResponderMetrics,
6867 source: PeerId,
6868 class: AuditResponderClass,
6869 kind: &'static str,
6870 challenge_id: u64,
6871 work_items: usize,
6872 response_kind: &'static str,
6873 sent: bool,
6874 received_at: Instant,
6875 worker_started: Instant,
6876 processing: Duration,
6877 response_send: Duration,
6878) {
6879 let dispatch = worker_started.saturating_duration_since(received_at);
6880 let total = received_at.elapsed();
6881 metrics.record_completed(source, processing, total, sent);
6882 if sent {
6883 info!(
6884 target: "ant_node::replication::audit_responder",
6885 event = "completed",
6886 kind,
6887 responder_class = class.as_str(),
6888 source = %source,
6889 challenge_id,
6890 work_items,
6891 response = response_kind,
6892 sent,
6893 dispatch_ms = dispatch.as_millis(),
6894 processing_ms = processing.as_millis(),
6895 response_send_ms = response_send.as_millis(),
6896 total_ms = total.as_millis(),
6897 "Audit responder request completed"
6898 );
6899 } else {
6900 warn!(
6901 target: "ant_node::replication::audit_responder",
6902 event = "completed",
6903 kind,
6904 responder_class = class.as_str(),
6905 source = %source,
6906 challenge_id,
6907 work_items,
6908 response = response_kind,
6909 sent,
6910 dispatch_ms = dispatch.as_millis(),
6911 processing_ms = processing.as_millis(),
6912 response_send_ms = response_send.as_millis(),
6913 total_ms = total.as_millis(),
6914 "Audit responder request completed without sending a reply"
6915 );
6916 }
6917}
6918
6919struct ReplyRoute<'a> {
6926 request_id: u64,
6928 rr_message_id: Option<&'a str>,
6931 protocol: &'static str,
6933}
6934
6935fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
6936 match response {
6937 protocol::AuditResponse::Digests { .. } => "digests",
6938 protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
6939 protocol::AuditResponse::Rejected { .. } => "rejected",
6940 }
6941}
6942
6943fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
6944 match response {
6945 protocol::SubtreeAuditResponse::Proof { .. } => "proof",
6946 protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
6947 protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
6948 }
6949}
6950
6951fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
6952 match response {
6953 protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
6954 protocol::SubtreeAuditResponse::Bootstrapping { .. }
6955 | protocol::SubtreeAuditResponse::Rejected { .. } => 0,
6956 }
6957}
6958
6959fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
6960 match response {
6961 protocol::SubtreeSliceResponse::Items { .. } => "items",
6962 protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
6963 protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
6964 }
6965}
6966
6967fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
6968 match response {
6969 protocol::GetCommitmentByPinResponse::Found { .. } => "found",
6970 protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
6971 }
6972}
6973
6974async fn send_replication_response(
6984 peer: &PeerId,
6985 p2p_node: &Arc<P2PNode>,
6986 request_id: u64,
6987 body: ReplicationMessageBody,
6988 rr_message_id: Option<&str>,
6989) {
6990 let _ =
6991 send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
6992 .await;
6993}
6994
6995async fn send_replication_response_checked(
7011 peer: &PeerId,
7012 p2p_node: &Arc<P2PNode>,
7013 request_id: u64,
7014 body: ReplicationMessageBody,
7015 rr_message_id: Option<&str>,
7016 protocol: Option<&'static str>,
7017) -> bool {
7018 let msg = ReplicationMessage { request_id, body };
7019 let encoded = match msg.encode() {
7020 Ok(data) => data,
7021 Err(e) => {
7022 warn!("Failed to encode replication response: {e}");
7023 return false;
7024 }
7025 };
7026 if matches!(
7032 msg.body,
7033 ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
7034 ) {
7035 protocol::record_served(peer, encoded.len());
7036 }
7037 let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
7038 let result = if let Some(msg_id) = rr_message_id {
7039 p2p_node
7040 .send_response(peer, protocol, msg_id, encoded)
7041 .await
7042 } else {
7043 p2p_node.send_message(peer, protocol, encoded, &[]).await
7044 };
7045 if let Err(e) = result {
7046 debug!("Failed to send replication response to {peer}: {e}");
7047 return false;
7048 }
7049 true
7050}
7051
7052async fn record_sent_replica_hints(
7053 peer: &PeerId,
7054 hints: &[neighbor_sync::SentReplicaHint],
7055 repair_proofs: &Arc<RwLock<RepairProofs>>,
7056 sync_cycle_epoch: &Arc<RwLock<u64>>,
7057) {
7058 if hints.is_empty() {
7059 return;
7060 }
7061
7062 let hinted_at_epoch = *sync_cycle_epoch.read().await;
7063 let mut proofs = repair_proofs.write().await;
7064 for hint in hints {
7065 if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
7066 debug!(
7067 "Recorded repair hint proof for peer {peer} and key {}",
7068 hex::encode(hint.key)
7069 );
7070 }
7071 }
7072}
7073
7074#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
7080async fn run_neighbor_sync_round(
7081 p2p_node: &Arc<P2PNode>,
7082 storage: &Arc<LmdbStorage>,
7083 paid_list: &Arc<PaidList>,
7084 queues: &Arc<RwLock<ReplicationQueues>>,
7085 config: &ReplicationConfig,
7086 sync_state: &Arc<RwLock<NeighborSyncState>>,
7087 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7088 sync_cycle_epoch: &Arc<RwLock<u64>>,
7089 repair_proofs: &Arc<RwLock<RepairProofs>>,
7090 is_bootstrapping: &Arc<RwLock<bool>>,
7091 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7092 commitment_state: &Arc<ResponderCommitmentState>,
7093 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7094 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7095 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7096 audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
7097 gossip_audit: &GossipAuditTrigger,
7098) {
7099 let self_id = *p2p_node.peer_id();
7100 let bootstrapping = *is_bootstrapping.read().await;
7101
7102 let cycle_complete = sync_state.read().await.is_cycle_complete();
7106 if cycle_complete {
7107 {
7111 let mut history = sync_history.write().await;
7112 for record in history.values_mut() {
7113 record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
7114 }
7115 }
7116 {
7117 let mut epoch = sync_cycle_epoch.write().await;
7118 *epoch = epoch.saturating_add(1);
7119 }
7120
7121 let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
7126 pruning::run_prune_pass_with_context(pruning::PrunePassContext {
7127 self_id: &self_id,
7128 storage,
7129 paid_list,
7130 p2p_node,
7131 config,
7132 sync_state,
7133 repair_proofs,
7134 allow_remote_prune_audits,
7135 commitment_state: Some(commitment_state),
7136 audit_challenge_coordinator,
7137 })
7138 .await;
7139
7140 let neighbors =
7142 neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
7143 .await;
7144
7145 let mut state = sync_state.write().await;
7147 if state.is_cycle_complete() {
7148 let old_sync_times = std::mem::take(&mut state.last_sync_times);
7152 let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
7153 let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
7154 let old_prune_cursor = state.prune_cursor;
7155 *state = NeighborSyncState::new_cycle(neighbors);
7156 state.last_sync_times = old_sync_times;
7157 state.bootstrap_claims = old_bootstrap_claims;
7158 state.bootstrap_claim_history = old_bootstrap_claim_history;
7159 state.prune_cursor = old_prune_cursor;
7160 }
7161 }
7162
7163 let batch = {
7165 let mut state = sync_state.write().await;
7166 neighbor_sync::select_sync_batch(
7167 &mut state,
7168 config.neighbor_sync_peer_count,
7169 config.neighbor_sync_cooldown,
7170 )
7171 };
7172
7173 if batch.is_empty() {
7174 return;
7175 }
7176
7177 debug!("Neighbor sync: syncing with {} peers", batch.len());
7178
7179 let my_commitment = commitment_state
7185 .current_for_gossip()
7186 .map(|b| b.commitment().clone());
7187
7188 let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
7189 &batch,
7190 storage,
7191 paid_list,
7192 p2p_node,
7193 config.close_group_size,
7194 config.paid_list_close_group_size,
7195 )
7196 .await;
7197
7198 for peer in &batch {
7200 let hints = hints_by_peer.remove(peer).unwrap_or_default();
7201 let outcome = neighbor_sync::sync_with_peer_with_hints(
7202 peer,
7203 p2p_node,
7204 config,
7205 bootstrapping,
7206 hints,
7207 my_commitment.clone(),
7208 )
7209 .await;
7210
7211 if let Some(outcome) = outcome {
7212 handle_sync_response(
7213 &self_id,
7214 peer,
7215 &outcome.response,
7216 &outcome.sent_replica_hints,
7217 p2p_node,
7218 config,
7219 bootstrapping,
7220 bootstrap_state,
7221 storage,
7222 paid_list,
7223 queues,
7224 sync_state,
7225 sync_history,
7226 sync_cycle_epoch,
7227 repair_proofs,
7228 last_commitment_by_peer,
7229 ever_capable_peers,
7230 sig_verify_attempts,
7231 gossip_audit,
7232 )
7233 .await;
7234 } else {
7235 let replacement = {
7237 let mut state = sync_state.write().await;
7238 neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
7239 };
7240
7241 if let Some(replacement_peer) = replacement {
7243 let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
7244 std::slice::from_ref(&replacement_peer),
7245 storage,
7246 paid_list,
7247 p2p_node,
7248 config.close_group_size,
7249 config.paid_list_close_group_size,
7250 )
7251 .await;
7252 let hints = replacement_hints
7253 .remove(&replacement_peer)
7254 .unwrap_or_default();
7255 let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
7256 &replacement_peer,
7257 p2p_node,
7258 config,
7259 bootstrapping,
7260 hints,
7261 my_commitment.clone(),
7262 )
7263 .await;
7264
7265 if let Some(outcome) = replacement_outcome {
7266 handle_sync_response(
7267 &self_id,
7268 &replacement_peer,
7269 &outcome.response,
7270 &outcome.sent_replica_hints,
7271 p2p_node,
7272 config,
7273 bootstrapping,
7274 bootstrap_state,
7275 storage,
7276 paid_list,
7277 queues,
7278 sync_state,
7279 sync_history,
7280 sync_cycle_epoch,
7281 repair_proofs,
7282 last_commitment_by_peer,
7283 ever_capable_peers,
7284 sig_verify_attempts,
7285 gossip_audit,
7286 )
7287 .await;
7288 }
7289 }
7290 }
7291 }
7292}
7293
7294#[allow(clippy::too_many_arguments)]
7297async fn handle_sync_response(
7298 self_id: &PeerId,
7299 peer: &PeerId,
7300 resp: &NeighborSyncResponse,
7301 sent_replica_hints: &[neighbor_sync::SentReplicaHint],
7302 p2p_node: &Arc<P2PNode>,
7303 config: &ReplicationConfig,
7304 bootstrapping: bool,
7305 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7306 storage: &Arc<LmdbStorage>,
7307 paid_list: &Arc<PaidList>,
7308 queues: &Arc<RwLock<ReplicationQueues>>,
7309 sync_state: &Arc<RwLock<NeighborSyncState>>,
7310 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7311 sync_cycle_epoch: &Arc<RwLock<u64>>,
7312 repair_proofs: &Arc<RwLock<RepairProofs>>,
7313 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7314 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7315 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7316 gossip_audit: &GossipAuditTrigger,
7317) {
7318 if let Some(target) = ingest_peer_commitment(
7324 peer,
7325 resp.commitment.as_ref(),
7326 p2p_node,
7327 last_commitment_by_peer,
7328 ever_capable_peers,
7329 sig_verify_attempts,
7330 )
7331 .await
7332 {
7333 maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
7334 }
7335
7336 {
7338 let mut state = sync_state.write().await;
7339 neighbor_sync::record_successful_sync(&mut state, peer);
7340 }
7341 {
7342 let mut history = sync_history.write().await;
7343 let record = history.entry(*peer).or_insert(PeerSyncRecord {
7344 last_sync: None,
7345 cycles_since_sync: 0,
7346 });
7347 record.last_sync = Some(Instant::now());
7348 record.cycles_since_sync = 0;
7349 }
7350
7351 if resp.bootstrapping {
7353 let should_report = {
7357 let now = Instant::now();
7358 let mut state = sync_state.write().await;
7359 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
7360 BootstrapClaimObservation::WithinGrace { .. } => false,
7361 BootstrapClaimObservation::PastGrace { first_seen } => {
7362 warn!(
7363 "Peer {peer} has been claiming bootstrap for {:?}, \
7364 exceeding grace period of {:?} — reporting abuse",
7365 now.duration_since(first_seen),
7366 config.bootstrap_claim_grace_period,
7367 );
7368 true
7369 }
7370 BootstrapClaimObservation::Repeated { first_seen } => {
7371 warn!(
7372 "Peer {peer} repeated bootstrap claim after previously stopping; \
7373 first claim was {:?} ago — reporting abuse",
7374 now.duration_since(first_seen),
7375 );
7376 true
7377 }
7378 }
7379 };
7380 if should_report {
7381 p2p_node
7382 .report_trust_event(
7383 peer,
7384 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7385 )
7386 .await;
7387 }
7388 } else {
7389 {
7392 let mut state = sync_state.write().await;
7393 state.clear_active_bootstrap_claim(peer);
7394 }
7395 record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
7396 let outcome = admit_and_queue_hints(
7397 self_id,
7398 peer,
7399 &resp.replica_hints,
7400 &resp.paid_hints,
7401 p2p_node,
7402 config,
7403 storage,
7404 paid_list,
7405 queues,
7406 )
7407 .await;
7408
7409 if bootstrapping {
7414 let live_discovered = outcome.discovered.clone();
7415 let outcomes = [(*peer, outcome)];
7416 publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
7417 .await;
7418 }
7419 }
7420}
7421
7422#[allow(clippy::too_many_arguments)]
7427struct AdmissionOutcome {
7435 discovered: HashSet<XorName>,
7436 capacity_rejected_count: usize,
7437 displaced: Vec<CapacityDisplacement>,
7438}
7439
7440async fn publish_bootstrap_admission_outcomes(
7451 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7452 outcomes: &[(PeerId, AdmissionOutcome)],
7453 live_discovered: &HashSet<XorName>,
7454) {
7455 let mut rejected_sources = HashSet::new();
7456 let mut clean_sources = HashSet::new();
7457 let mut displaced_keys = HashSet::new();
7458
7459 for (source, outcome) in outcomes {
7460 if outcome.capacity_rejected_count > 0 {
7461 rejected_sources.insert(*source);
7462 } else {
7463 clean_sources.insert(*source);
7464 }
7465 for displacement in &outcome.displaced {
7473 displaced_keys.insert(displacement.key);
7474 }
7475 }
7476 clean_sources.retain(|source| !rejected_sources.contains(source));
7477
7478 let now = Instant::now();
7479 let mut state = bootstrap_state.write().await;
7480 for key in displaced_keys {
7481 state.remove_key(&key);
7482 }
7483 state.pending_keys.extend(live_discovered);
7484 for source in clean_sources {
7485 state.capacity_rejected_sources.remove(&source);
7486 }
7487 for source in rejected_sources {
7488 state.note_capacity_rejected(source, now);
7491 }
7492}
7493
7494#[allow(clippy::too_many_arguments)]
7495async fn admit_and_queue_hints(
7496 self_id: &PeerId,
7497 source_peer: &PeerId,
7498 replica_hints: &[XorName],
7499 paid_hints: &[XorName],
7500 p2p_node: &Arc<P2PNode>,
7501 config: &ReplicationConfig,
7502 storage: &Arc<LmdbStorage>,
7503 paid_list: &Arc<PaidList>,
7504 queues: &Arc<RwLock<ReplicationQueues>>,
7505) -> AdmissionOutcome {
7506 let pending_keys: HashSet<XorName> = {
7507 let q = queues.read().await;
7508 q.pending_keys().into_iter().collect()
7509 };
7510
7511 let admitted = admission::admit_hints(
7512 self_id,
7513 replica_hints,
7514 paid_hints,
7515 p2p_node,
7516 config,
7517 storage,
7518 paid_list,
7519 &pending_keys,
7520 )
7521 .await;
7522
7523 let mut q = queues.write().await;
7524 queue_admitted_hints(source_peer, admitted, storage, &mut q)
7525}
7526
7527fn queue_admitted_hints(
7528 source_peer: &PeerId,
7529 admitted: admission::AdmissionResult,
7530 storage: &LmdbStorage,
7531 q: &mut ReplicationQueues,
7532) -> AdmissionOutcome {
7533 let mut discovered = HashSet::new();
7534 let mut capacity_rejected_count: usize = 0;
7535 let mut displaced = Vec::new();
7536 let now = Instant::now();
7537
7538 for key in admitted.replica_keys {
7539 if !storage.exists(&key).unwrap_or(false) {
7540 let result = q.add_pending_verify(
7541 key,
7542 VerificationEntry {
7543 state: VerificationState::PendingVerify,
7544 verified_sources: Vec::new(),
7545 tried_sources: HashSet::new(),
7546 created_at: now,
7547 next_verify_at: now,
7548 hint_sources: HashSet::from([*source_peer]),
7549 replica_hint_sources: HashSet::from([*source_peer]),
7552 },
7553 );
7554 match result {
7555 crate::replication::scheduling::AdmissionResult::Admitted => {
7556 discovered.insert(key);
7557 }
7558 crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7559 crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7560 capacity_rejected_count += 1;
7561 }
7562 }
7563 }
7564 }
7565
7566 for key in admitted.paid_only_keys {
7567 let result = q.add_pending_verify(
7568 key,
7569 VerificationEntry {
7570 state: VerificationState::PendingVerify,
7571 verified_sources: Vec::new(),
7572 tried_sources: HashSet::new(),
7573 created_at: now,
7574 next_verify_at: now,
7575 hint_sources: HashSet::from([*source_peer]),
7576 replica_hint_sources: HashSet::new(),
7579 },
7580 );
7581 match result {
7582 crate::replication::scheduling::AdmissionResult::Admitted => {
7583 discovered.insert(key);
7584 }
7585 crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7586 crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7587 capacity_rejected_count += 1;
7588 }
7589 }
7590 }
7591
7592 if capacity_rejected_count > 0 {
7593 debug!(
7594 "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
7595 rejected at queue capacity; source will need to re-hint after pending_verify drains"
7596 );
7597 }
7598
7599 displaced.extend(q.take_capacity_displacements());
7600
7601 AdmissionOutcome {
7602 discovered,
7603 capacity_rejected_count,
7604 displaced,
7605 }
7606}
7607
7608#[allow(clippy::too_many_lines)]
7614async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
7615 let cycle_started = Instant::now();
7616 let VerificationCycleContext {
7617 p2p_node,
7618 paid_list,
7619 storage,
7620 queues,
7621 config,
7622 bootstrap_state,
7623 is_bootstrapping,
7624 bootstrap_complete_notify,
7625 last_commitment_by_peer,
7626 ever_capable_peers,
7627 recent_provers,
7628 } = ctx;
7629
7630 expire_and_recheck_bootstrap_drain(
7635 bootstrap_state,
7636 queues,
7637 is_bootstrapping,
7638 bootstrap_complete_notify,
7639 config.capacity_rejected_max_age(),
7640 )
7641 .await;
7642
7643 if bootstrap_state.read().await.pending_peer_requests > 0 {
7647 return;
7648 }
7649
7650 let stale_pending_keys = {
7653 let mut q = queues.write().await;
7654 q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
7655 };
7656 if !stale_pending_keys.is_empty() {
7657 update_bootstrap_after_verification(
7658 &stale_pending_keys,
7659 bootstrap_state,
7660 queues,
7661 is_bootstrapping,
7662 bootstrap_complete_notify,
7663 )
7664 .await;
7665 }
7666
7667 let pending_keys = {
7668 let mut q = queues.write().await;
7669 if bootstrap_state.read().await.pending_peer_requests > 0 {
7675 return;
7676 }
7677 q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
7678 };
7679
7680 if pending_keys.is_empty() {
7681 return;
7682 }
7683 let initial_pending_count = pending_keys.len();
7684
7685 let self_id = *p2p_node.peer_id();
7686
7687 let mut local_paid_keys = Vec::new();
7692 let mut keys_needing_network = Vec::new();
7693 let mut terminal_keys: Vec<XorName> = Vec::new();
7694 {
7695 let mut q = queues.write().await;
7696 for key in &pending_keys {
7697 if paid_list.contains(key).unwrap_or(false) {
7698 if q.set_pending_state(key, VerificationState::PaidListVerified) {
7699 local_paid_keys.push(*key);
7700 }
7701 } else {
7702 keys_needing_network.push(*key);
7703 }
7704 }
7705 }
7706
7707 let mut local_paid_presence_probe_keys = Vec::new();
7713 if !local_paid_keys.is_empty() {
7714 let mut terminal_paid = Vec::new();
7715 for key in local_paid_keys {
7716 if storage.exists(&key).unwrap_or(false) {
7717 terminal_paid.push(key);
7718 } else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
7719 local_paid_presence_probe_keys.push(key);
7723 } else {
7724 terminal_paid.push(key);
7725 }
7726 }
7727
7728 if !terminal_paid.is_empty() {
7729 let mut q = queues.write().await;
7730 for key in terminal_paid {
7731 q.remove_pending(&key);
7732 terminal_keys.push(key);
7733 }
7734 }
7735 }
7736
7737 let local_paid_probe_count = local_paid_presence_probe_keys.len();
7738 let keys_needing_network_count = keys_needing_network.len();
7739
7740 if !local_paid_presence_probe_keys.is_empty() {
7744 let targets = quorum::compute_presence_targets(
7745 &local_paid_presence_probe_keys,
7746 p2p_node,
7747 config,
7748 &self_id,
7749 )
7750 .await;
7751 let evidence = quorum::run_verification_round(
7752 &local_paid_presence_probe_keys,
7753 &targets,
7754 p2p_node,
7755 config,
7756 )
7757 .await;
7758
7759 let mut q = queues.write().await;
7760 for key in local_paid_presence_probe_keys {
7761 if storage.exists(&key).unwrap_or(false) {
7762 q.remove_pending(&key);
7763 terminal_keys.push(key);
7764 continue;
7765 }
7766 let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
7767 quorum::present_sources_for_key(&key, ev, &targets)
7768 });
7769 if let Some(entry) = q.get_pending(&key) {
7770 add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
7771 }
7772 if sources.is_empty() {
7773 warn!(
7774 "Locally paid key {} has no responding holders yet; deferring retry",
7775 hex::encode(key)
7776 );
7777 q.defer_pending(&key, config.verification_request_timeout);
7778 } else {
7779 let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
7780 let _ = q.promote_pending_to_fetch(key, distance, sources);
7784 }
7785 }
7786 }
7787
7788 if !keys_needing_network.is_empty() {
7790 let targets =
7792 quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
7793 .await;
7794
7795 let evidence =
7796 quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
7797
7798 let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
7819 let map = last_commitment_by_peer.read().await;
7820 map.iter()
7821 .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
7824 .collect()
7825 };
7826 let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
7827 let provers_snapshot = recent_provers.read().await.clone();
7831 let mut locally_held: HashSet<XorName> = HashSet::new();
7841 for key in &keys_needing_network {
7842 if storage.exists(key).unwrap_or(false) {
7843 locally_held.insert(*key);
7844 }
7845 }
7846 let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
7847 if !locally_held.contains(key) {
7848 return true;
7854 }
7855 if !capable_peer_snapshot.contains(peer) {
7856 return true;
7863 }
7864 let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
7865 return false;
7871 };
7872 provers_snapshot.is_credited_holder(key, peer, hash)
7873 };
7874
7875 let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
7876 {
7877 let q = queues.read().await;
7878 for key in &keys_needing_network {
7879 let Some(ev) = evidence.get(key) else {
7880 continue;
7881 };
7882 if q.get_pending(key).is_none() {
7883 continue;
7884 }
7885 let outcome = quorum::evaluate_key_evidence_with_holder_check(
7886 key,
7887 ev,
7888 &targets,
7889 config,
7890 holder_credit,
7891 );
7892 evaluated.push((*key, outcome));
7893 }
7894 } let mut paid_insert_keys: Vec<XorName> = Vec::new();
7898 for (key, outcome) in &evaluated {
7899 if matches!(
7900 outcome,
7901 KeyVerificationOutcome::QuorumVerified { .. }
7902 | KeyVerificationOutcome::PaidListVerified { .. }
7903 ) {
7904 paid_insert_keys.push(*key);
7905 }
7906 }
7907 for key in &paid_insert_keys {
7908 if let Err(e) = paid_list.insert(key).await {
7909 warn!("Failed to add verified key to PaidForList: {e}");
7910 }
7911 }
7912
7913 let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
7923 for (key, outcome) in &evaluated {
7924 if matches!(
7925 outcome,
7926 KeyVerificationOutcome::QuorumVerified { .. }
7927 | KeyVerificationOutcome::PaidListVerified { .. }
7928 ) && !storage.exists(key).unwrap_or(false)
7929 && is_storage_admitted(&self_id, key, p2p_node, config).await
7930 {
7931 fetch_allowed_keys.insert(*key);
7932 }
7933 }
7934
7935 let mut bad_singleton_hints: HashMap<PeerId, usize> = HashMap::new();
7937 let mut q = queues.write().await;
7938 for (key, outcome) in evaluated {
7939 let replica_hint_sources = q
7940 .get_pending(&key)
7941 .map(|entry| entry.replica_hint_sources.clone())
7942 .unwrap_or_default();
7943 if let Some(ev) = evidence.get(&key) {
7944 if let Some(source) =
7945 punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
7946 {
7947 *bad_singleton_hints.entry(source).or_insert(0) += 1;
7948 }
7949 }
7950 match outcome {
7951 KeyVerificationOutcome::QuorumVerified { sources }
7952 | KeyVerificationOutcome::PaidListVerified { sources } => {
7953 let mut fetch_sources = sources;
7954 add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
7955 let fetch_eligible = fetch_allowed_keys.contains(&key);
7956 if fetch_eligible && !fetch_sources.is_empty() {
7957 let distance =
7958 crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
7959 let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
7963 } else if fetch_eligible && fetch_sources.is_empty() {
7966 warn!(
7967 "Verified storage-admitted key {} has no holders yet; deferring retry",
7968 hex::encode(key)
7969 );
7970 q.defer_pending(&key, config.verification_request_timeout);
7971 } else {
7972 q.remove_pending(&key);
7973 terminal_keys.push(key);
7974 }
7975 }
7976 KeyVerificationOutcome::QuorumFailed => {
7977 q.remove_pending(&key);
7978 terminal_keys.push(key);
7979 }
7980 KeyVerificationOutcome::QuorumInconclusive => {
7981 q.set_pending_state(&key, VerificationState::QuorumInconclusive);
7982 q.defer_pending(&key, config.verification_request_timeout);
7983 }
7984 }
7985 }
7986 drop(q);
7987
7988 for (peer, bad_hint_count) in bad_singleton_hints {
7989 let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
7990 warn!(
7991 "Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
7992 sole-source replica hints; \
7993 reporting {reports} bounded trust failure(s)"
7994 );
7995 for _ in 0..reports {
7996 p2p_node
7997 .report_trust_event(
7998 &peer,
7999 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8000 )
8001 .await;
8002 }
8003 }
8004 }
8005
8006 update_bootstrap_after_verification(
8009 &terminal_keys,
8010 bootstrap_state,
8011 queues,
8012 is_bootstrapping,
8013 bootstrap_complete_notify,
8014 )
8015 .await;
8016
8017 let (pending_after, fetch_after, in_flight_after) = {
8018 let q = queues.read().await;
8019 (
8020 q.pending_count(),
8021 q.fetch_queue_count(),
8022 q.in_flight_count(),
8023 )
8024 };
8025 let terminal_key_count = terminal_keys.len();
8026 let elapsed_ms = cycle_started.elapsed().as_millis();
8027
8028 if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
8029 info!(
8030 target: "ant_node::replication::verification",
8031 "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}",
8032 );
8033 } else {
8034 debug!(
8035 target: "ant_node::replication::verification",
8036 "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}",
8037 );
8038 }
8039}
8040
8041fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
8046 for source in replica_hint_sources {
8047 if !sources.contains(source) {
8048 sources.push(*source);
8049 }
8050 }
8051}
8052
8053fn punishable_singleton_replica_hint_source(
8058 replica_hint_sources: &HashSet<PeerId>,
8059 outcome: &KeyVerificationOutcome,
8060 evidence: &crate::replication::types::KeyVerificationEvidence,
8061) -> Option<PeerId> {
8062 if replica_hint_sources.len() != 1 {
8065 return None;
8066 }
8067 let source = *replica_hint_sources.iter().next()?;
8068 let rejected_by_close_group = matches!(outcome, KeyVerificationOutcome::QuorumFailed);
8069 let denied_possession = evidence.presence.get(&source) == Some(&PresenceEvidence::Absent);
8070
8071 (rejected_by_close_group || denied_possession).then_some(source)
8072}
8073
8074async fn update_bootstrap_after_verification(
8077 terminal_keys: &[XorName],
8078 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8079 queues: &Arc<RwLock<ReplicationQueues>>,
8080 is_bootstrapping: &Arc<RwLock<bool>>,
8081 bootstrap_complete_notify: &Arc<Notify>,
8082) {
8083 if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
8084 return;
8085 }
8086 {
8087 let mut bs = bootstrap_state.write().await;
8088 for key in terminal_keys {
8089 bs.remove_key(key);
8090 }
8091 }
8092 let q = queues.read().await;
8093 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8094 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8095 }
8096}
8097
8098async fn update_bootstrap_after_peer_removed(
8102 peer: &PeerId,
8103 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8104 queues: &Arc<RwLock<ReplicationQueues>>,
8105 is_bootstrapping: &Arc<RwLock<bool>>,
8106 bootstrap_complete_notify: &Arc<Notify>,
8107) {
8108 let orphaned_keys = queues.write().await.remove_hint_source(peer);
8109 let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
8110
8111 if !orphaned_keys.is_empty() {
8112 let mut state = bootstrap_state.write().await;
8113 for key in &orphaned_keys {
8114 state.remove_key(key);
8115 }
8116 }
8117
8118 if orphaned_keys.is_empty() && !cleared_rejection {
8119 return;
8120 }
8121 let q = queues.read().await;
8122 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8123 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8124 }
8125}
8126
8127async fn expire_and_recheck_bootstrap_drain(
8139 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8140 queues: &Arc<RwLock<ReplicationQueues>>,
8141 is_bootstrapping: &Arc<RwLock<bool>>,
8142 bootstrap_complete_notify: &Arc<Notify>,
8143 max_age: Duration,
8144) {
8145 if bootstrap_state.read().await.is_drained() {
8146 return;
8147 }
8148 bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
8149 let q = queues.read().await;
8150 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8151 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8152 }
8153}
8154
8155async fn complete_bootstrap(
8157 is_bootstrapping: &Arc<RwLock<bool>>,
8158 bootstrap_complete_notify: &Arc<Notify>,
8159) {
8160 *is_bootstrapping.write().await = false;
8161 bootstrap_complete_notify.notify_waiters();
8162 info!("Replication bootstrap complete");
8163}
8164
8165enum FetchResult {
8171 Stored,
8173 IntegrityFailed,
8175 SourceFailed,
8177 NoLongerResponsible,
8182}
8183
8184struct FetchOutcome {
8187 key: XorName,
8188 result: FetchResult,
8189}
8190
8191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8193enum FetchFollowUp {
8194 Terminal,
8198 RequeuedForVerification,
8200 RetryFrom(PeerId),
8202}
8203
8204#[allow(clippy::option_if_let_else)]
8217fn apply_fetch_result(
8218 q: &mut ReplicationQueues,
8219 key: &XorName,
8220 result: &FetchResult,
8221 verification_retry_after: Duration,
8222) -> FetchFollowUp {
8223 match result {
8224 FetchResult::Stored | FetchResult::NoLongerResponsible => {
8225 q.complete_fetch(key);
8226 FetchFollowUp::Terminal
8227 }
8228 FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
8229 if let Some(next_peer) = q.retry_fetch(key) {
8230 FetchFollowUp::RetryFrom(next_peer)
8231 } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
8232 FetchFollowUp::RequeuedForVerification
8233 } else {
8234 FetchFollowUp::Terminal
8235 }
8236 }
8237 }
8238}
8239
8240async fn is_storage_admitted(
8248 self_id: &PeerId,
8249 key: &XorName,
8250 p2p_node: &Arc<P2PNode>,
8251 config: &ReplicationConfig,
8252) -> bool {
8253 admission::is_responsible(
8254 self_id,
8255 key,
8256 p2p_node,
8257 storage_admission_width(config.close_group_size),
8258 )
8259 .await
8260}
8261
8262#[allow(clippy::too_many_lines)]
8263async fn execute_single_fetch(
8277 p2p_node: Arc<P2PNode>,
8278 storage: Arc<LmdbStorage>,
8279 config: Arc<ReplicationConfig>,
8280 key: XorName,
8281 source: PeerId,
8282) -> FetchOutcome {
8283 let self_id = *p2p_node.peer_id();
8284 if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8285 debug!(
8286 "Skipping fetch for {}: no longer in the storage-admission group",
8287 hex::encode(key)
8288 );
8289 return FetchOutcome {
8290 key,
8291 result: FetchResult::NoLongerResponsible,
8292 };
8293 }
8294
8295 let request = protocol::FetchRequest { key };
8296 let msg = ReplicationMessage {
8297 request_id: rand::thread_rng().gen::<u64>(),
8298 body: ReplicationMessageBody::FetchRequest(request),
8299 };
8300
8301 let encoded = match msg.encode() {
8302 Ok(data) => data,
8303 Err(e) => {
8304 warn!("Failed to encode fetch request: {e}");
8305 return FetchOutcome {
8306 key,
8307 result: FetchResult::SourceFailed,
8308 };
8309 }
8310 };
8311
8312 let result = p2p_node
8313 .send_request(
8314 &source,
8315 REPLICATION_PROTOCOL_ID,
8316 encoded,
8317 config.fetch_request_timeout,
8318 )
8319 .await;
8320
8321 match result {
8322 Ok(response) => {
8323 let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
8324 p2p_node
8325 .report_trust_event(
8326 &source,
8327 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8328 )
8329 .await;
8330 return FetchOutcome {
8331 key,
8332 result: FetchResult::SourceFailed,
8333 };
8334 };
8335
8336 match resp_msg.body {
8337 ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
8338 key: resp_key,
8339 data,
8340 }) => {
8341 if resp_key != key {
8346 warn!(
8347 "Fetch response key mismatch: requested {}, got {}",
8348 hex::encode(key),
8349 hex::encode(resp_key)
8350 );
8351 p2p_node
8352 .report_trust_event(
8353 &source,
8354 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8355 )
8356 .await;
8357 return FetchOutcome {
8358 key,
8359 result: FetchResult::IntegrityFailed,
8360 };
8361 }
8362
8363 if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
8367 warn!(
8368 "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
8369 hex::encode(resp_key),
8370 data.len(),
8371 crate::ant_protocol::MAX_CHUNK_SIZE,
8372 );
8373 p2p_node
8374 .report_trust_event(
8375 &source,
8376 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8377 )
8378 .await;
8379 return FetchOutcome {
8380 key,
8381 result: FetchResult::IntegrityFailed,
8382 };
8383 }
8384
8385 let computed = crate::client::compute_address(&data);
8387 if computed != resp_key {
8388 warn!(
8389 "Fetched record integrity check failed: expected {}, got {}",
8390 hex::encode(resp_key),
8391 hex::encode(computed)
8392 );
8393 p2p_node
8394 .report_trust_event(
8395 &source,
8396 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8397 )
8398 .await;
8399 return FetchOutcome {
8400 key,
8401 result: FetchResult::IntegrityFailed,
8402 };
8403 }
8404
8405 if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8412 debug!(
8413 "Fetched {} but responsibility lapsed in transit; not storing",
8414 hex::encode(key)
8415 );
8416 return FetchOutcome {
8417 key,
8418 result: FetchResult::NoLongerResponsible,
8419 };
8420 }
8421
8422 if let Err(e) = storage.put(&resp_key, &data).await {
8423 warn!(
8424 "Failed to store fetched record {}: {e}",
8425 hex::encode(resp_key)
8426 );
8427 return FetchOutcome {
8428 key,
8429 result: FetchResult::SourceFailed,
8430 };
8431 }
8432
8433 FetchOutcome {
8434 key,
8435 result: FetchResult::Stored,
8436 }
8437 }
8438 ReplicationMessageBody::FetchResponse(protocol::FetchResponse::NotFound {
8439 ..
8440 }) => {
8441 warn!(
8447 "Fetch: verified source {source} returned NotFound for {}",
8448 hex::encode(key)
8449 );
8450 p2p_node
8451 .report_trust_event(
8452 &source,
8453 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8454 )
8455 .await;
8456 FetchOutcome {
8457 key,
8458 result: FetchResult::SourceFailed,
8459 }
8460 }
8461 ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Error {
8462 reason,
8463 ..
8464 }) => {
8465 warn!(
8466 "Fetch: peer {source} returned error for {}: {reason}",
8467 hex::encode(key)
8468 );
8469 p2p_node
8470 .report_trust_event(
8471 &source,
8472 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8473 )
8474 .await;
8475 FetchOutcome {
8476 key,
8477 result: FetchResult::SourceFailed,
8478 }
8479 }
8480 _ => {
8481 p2p_node
8483 .report_trust_event(
8484 &source,
8485 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8486 )
8487 .await;
8488 FetchOutcome {
8489 key,
8490 result: FetchResult::SourceFailed,
8491 }
8492 }
8493 }
8494 }
8495 Err(e) => {
8496 debug!("Fetch request to {source} failed: {e}");
8497 FetchOutcome {
8500 key,
8501 result: FetchResult::SourceFailed,
8502 }
8503 }
8504 }
8505}
8506
8507fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
8523 confirmed_failed_keys.first().map_or_else(
8524 || "0x".to_string(),
8525 |k| format!("0x{}", hex::encode(&k[..8])),
8526 )
8527}
8528
8529async fn handle_subtree_failed_audit(
8536 challenged_peer: &PeerId,
8537 confirmed_failed_key_count: usize,
8538 reason: &AuditFailureReason,
8539 p2p_node: &Arc<P2PNode>,
8540 sync_state: &Arc<RwLock<NeighborSyncState>>,
8541 recent_provers: &Arc<RwLock<RecentProvers>>,
8542) {
8543 if matches!(reason, AuditFailureReason::Timeout) {
8544 debug!(
8545 "Audit timeout for {challenged_peer} fully graced \
8546 (subtree audit does not evict on timeout)"
8547 );
8548 return;
8549 }
8550
8551 let _ = confirmed_failed_key_count;
8554 {
8555 let mut state = sync_state.write().await;
8556 state.clear_active_bootstrap_claim(challenged_peer);
8557 }
8558 {
8559 let mut provers_guard = recent_provers.write().await;
8560 apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
8561 }
8562 p2p_node
8563 .report_trust_event(
8564 challenged_peer,
8565 TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
8566 )
8567 .await;
8568}
8569
8570async fn handle_subtree_audit_result(
8572 result: &AuditTickResult,
8573 p2p_node: &Arc<P2PNode>,
8574 sync_state: &Arc<RwLock<NeighborSyncState>>,
8575 recent_provers: &Arc<RwLock<RecentProvers>>,
8576 config: &ReplicationConfig,
8577) {
8578 match result {
8579 AuditTickResult::Passed {
8580 challenged_peer,
8581 keys_checked,
8582 } => {
8583 protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
8584 debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
8585 {
8588 let mut state = sync_state.write().await;
8589 state.clear_active_bootstrap_claim(challenged_peer);
8590 }
8591 p2p_node
8592 .report_trust_event(
8593 challenged_peer,
8594 TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
8595 )
8596 .await;
8597 }
8598 AuditTickResult::Failed {
8599 evidence,
8600 no_response_class,
8601 } => {
8602 if let FailureEvidence::AuditFailure {
8603 challenged_peer,
8604 confirmed_failed_keys,
8605 summary,
8606 reason,
8607 ..
8608 } = evidence
8609 {
8610 protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
8611 let first_failed_key = first_failed_key_label(confirmed_failed_keys);
8614 let audit_failure_class = no_response_class.unwrap_or("confirmed");
8615 error!(
8616 "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}",
8617 audit_failure_class,
8618 confirmed_failed_keys.len(),
8619 summary.challenged_keys,
8620 summary.absent_keys,
8621 summary.digest_mismatch_keys,
8622 );
8623 handle_subtree_failed_audit(
8627 challenged_peer,
8628 confirmed_failed_keys.len(),
8629 reason,
8630 p2p_node,
8631 sync_state,
8632 recent_provers,
8633 )
8634 .await;
8635 }
8636 }
8637 AuditTickResult::BootstrapClaim { peer } => {
8638 let should_report = {
8642 let now = Instant::now();
8643 let mut state = sync_state.write().await;
8644 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
8645 {
8646 BootstrapClaimObservation::WithinGrace { .. } => {
8647 debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
8648 false
8649 }
8650 BootstrapClaimObservation::PastGrace { first_seen } => {
8651 warn!(
8652 "Audit: peer {peer} claiming bootstrap past grace period \
8653 ({:?} > {:?}), reporting abuse",
8654 now.duration_since(first_seen),
8655 config.bootstrap_claim_grace_period,
8656 );
8657 true
8658 }
8659 BootstrapClaimObservation::Repeated { first_seen } => {
8660 warn!(
8661 "Audit: peer {peer} repeated bootstrap claim after previously \
8662 stopping; first claim was {:?} ago, reporting abuse",
8663 now.duration_since(first_seen),
8664 );
8665 true
8666 }
8667 }
8668 };
8669 if should_report {
8670 p2p_node
8671 .report_trust_event(
8672 peer,
8673 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8674 )
8675 .await;
8676 }
8677 }
8678 AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
8679 }
8680}
8681
8682fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
8690 !matches!(reason, AuditFailureReason::Timeout)
8691}
8692
8693#[allow(clippy::too_many_lines)]
8701async fn handle_audit_result(
8702 result: &AuditTickResult,
8703 p2p_node: &Arc<P2PNode>,
8704 sync_state: &Arc<RwLock<NeighborSyncState>>,
8705 config: &ReplicationConfig,
8706) {
8707 match result {
8708 AuditTickResult::Passed {
8709 challenged_peer,
8710 keys_checked,
8711 } => {
8712 protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
8713 debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
8714 {
8715 let mut state = sync_state.write().await;
8716 state.clear_active_bootstrap_claim(challenged_peer);
8717 }
8718 p2p_node
8719 .report_trust_event(
8720 challenged_peer,
8721 TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
8722 )
8723 .await;
8724 }
8725 AuditTickResult::Failed {
8726 evidence,
8727 no_response_class,
8728 } => {
8729 if let FailureEvidence::AuditFailure {
8730 challenged_peer,
8731 confirmed_failed_keys,
8732 summary,
8733 reason,
8734 ..
8735 } = evidence
8736 {
8737 protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
8738 let first_failed_key = first_failed_key_label(confirmed_failed_keys);
8739 let audit_failure_class = no_response_class.unwrap_or("confirmed");
8740 error!(
8741 "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}",
8742 audit_failure_class,
8743 confirmed_failed_keys.len(),
8744 summary.challenged_keys,
8745 summary.absent_keys,
8746 summary.digest_mismatch_keys,
8747 );
8748 if audit_failure_clears_bootstrap_claim(reason) {
8749 let mut state = sync_state.write().await;
8750 state.clear_active_bootstrap_claim(challenged_peer);
8751 } else {
8752 debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
8753 }
8754 p2p_node
8755 .report_trust_event(
8756 challenged_peer,
8757 TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
8758 )
8759 .await;
8760 }
8761 }
8762 AuditTickResult::BootstrapClaim { peer } => {
8763 let should_report = {
8764 let now = Instant::now();
8765 let mut state = sync_state.write().await;
8766 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
8767 {
8768 BootstrapClaimObservation::WithinGrace { .. } => {
8769 debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
8770 false
8771 }
8772 BootstrapClaimObservation::PastGrace { first_seen } => {
8773 warn!(
8774 "Audit: peer {peer} claiming bootstrap past grace period \
8775 ({:?} > {:?}), reporting abuse",
8776 now.duration_since(first_seen),
8777 config.bootstrap_claim_grace_period,
8778 );
8779 true
8780 }
8781 BootstrapClaimObservation::Repeated { first_seen } => {
8782 warn!(
8783 "Audit: peer {peer} repeated bootstrap claim after previously \
8784 stopping; first claim was {:?} ago, reporting abuse",
8785 now.duration_since(first_seen),
8786 );
8787 true
8788 }
8789 }
8790 };
8791 if should_report {
8792 p2p_node
8793 .report_trust_event(
8794 peer,
8795 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8796 )
8797 .await;
8798 }
8799 }
8800 AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
8801 }
8802}
8803
8804fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
8815 !matches!(reason, AuditFailureReason::Timeout)
8816}
8817
8818fn apply_audit_failure_credit_revocation(
8823 provers: &mut RecentProvers,
8824 challenged_peer: &PeerId,
8825 reason: &AuditFailureReason,
8826) {
8827 if audit_failure_revokes_holder_credit(reason) {
8828 provers.forget_peer(challenged_peer);
8829 }
8830}
8831
8832#[derive(Clone)]
8842struct GossipAuditTrigger {
8843 p2p_node: Arc<P2PNode>,
8844 config: Arc<ReplicationConfig>,
8845 recent_provers: Arc<RwLock<RecentProvers>>,
8846 sync_state: Arc<RwLock<NeighborSyncState>>,
8847 cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
8852 detached_task_tracker: TaskTracker,
8853 lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
8857}
8858
8859#[derive(Debug, Clone, Copy)]
8865struct AuditTarget {
8866 pin_hash: [u8; 32],
8867 key_count: u32,
8868}
8869
8870#[derive(Debug, Clone, Copy)]
8879pub struct MonetizedPinEvent {
8880 pub peer: PeerId,
8882 pub pin: [u8; 32],
8884 pub key_count: u32,
8886 pub quote_ts: SystemTime,
8891}
8892
8893fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
8901 let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
8902 let known = match map.get(peer) {
8903 Some(&last) => {
8904 if now.saturating_duration_since(last) < cooldown {
8905 return false;
8906 }
8907 true
8908 }
8909 None => false,
8910 };
8911 if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
8914 if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
8915 map.remove(&victim);
8916 }
8917 }
8918 map.insert(*peer, now);
8919 true
8920}
8921
8922fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
8928 let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
8929 map.get(peer).map_or(true, |&last| {
8930 now.saturating_duration_since(last) >= cooldown
8931 })
8932}
8933
8934fn audit_launch_decision(
8951 attempts: &mut HashMap<PeerId, Instant>,
8952 launched: &mut HashMap<PeerId, Instant>,
8953 peer: &PeerId,
8954 now: Instant,
8955 lottery_wins: bool,
8956) -> bool {
8957 if !cooldown_allows_audit(attempts, peer, now) {
8960 return false;
8961 }
8962 if !lottery_wins {
8965 return false;
8966 }
8967 cooldown_allows_audit(launched, peer, now)
8970}
8971
8972async fn maybe_trigger_gossip_audit(
8977 trigger: &GossipAuditTrigger,
8978 peer: &PeerId,
8979 target: AuditTarget,
8980) {
8981 let now = Instant::now();
8985 let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
8986 {
8987 let mut attempts = trigger.lottery_attempts.write().await;
8990 let mut launched = trigger.cooldown.write().await;
8991 if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
8992 return;
8993 }
8994 }
8995
8996 let detached_task_tracker = trigger.detached_task_tracker.clone();
8997 let trigger = trigger.clone();
8998 let peer = *peer;
8999 detached_task_tracker.spawn(async move {
9000 let credit = storage_commitment_audit::AuditCredit {
9001 recent_provers: &trigger.recent_provers,
9002 };
9003 let result = storage_commitment_audit::run_subtree_audit_with_origin(
9004 &trigger.p2p_node,
9005 &trigger.config,
9006 &peer,
9007 target.pin_hash,
9008 target.key_count,
9009 Some(&credit),
9010 storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9011 )
9012 .await;
9013 handle_subtree_audit_result(
9014 &result,
9015 &trigger.p2p_node,
9016 &trigger.sync_state,
9017 &trigger.recent_provers,
9018 &trigger.config,
9019 )
9020 .await;
9021 });
9022}
9023
9024async fn sig_verify_rate_limit_ok(
9033 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9034 source: &PeerId,
9035 now: Instant,
9036) -> bool {
9037 let mut attempts = sig_verify_attempts.write().await;
9038 if let Some(&last) = attempts.get(source) {
9039 if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9040 return false;
9041 }
9042 }
9043 if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9044 if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9045 attempts.remove(&victim);
9046 }
9047 }
9048 attempts.insert(*source, now);
9049 true
9050}
9051
9052async fn handle_commitment_downgrade(
9103 source: &PeerId,
9104 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9105) -> Option<AuditTarget> {
9106 let now = Instant::now();
9107 let cached = {
9108 let map = last_commitment_by_peer.read().await;
9109 map.get(source).and_then(|rec| {
9110 if !rec.commitment_capable {
9111 return None;
9112 }
9113 let last = rec.last_commitment()?;
9114 let pin = rec.commitment_hash()?;
9115 let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
9116 Some((pin, last.key_count, fresh))
9117 })
9118 };
9119 match cached {
9120 Some((pin, key_count, true)) => {
9121 warn!(
9122 "ingest_peer_commitment: commitment-capable peer {source} sent None \
9123 (downgrade attempt); auditing against its last cached commitment"
9124 );
9125 Some(AuditTarget {
9126 pin_hash: pin,
9127 key_count,
9128 })
9129 }
9130 Some((_, _, false)) => {
9131 if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
9138 let still_stale =
9139 now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
9140 if still_stale {
9141 rec.clear_commitment();
9142 debug!(
9143 "ingest_peer_commitment: capable peer {source} sent None and its cached \
9144 commitment aged past the answerability TTL; forgetting it"
9145 );
9146 }
9147 }
9148 None
9149 }
9150 None => None,
9151 }
9152}
9153
9154async fn ingest_peer_commitment(
9155 source: &PeerId,
9156 commitment: Option<&StorageCommitment>,
9157 p2p_node: &Arc<P2PNode>,
9158 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9159 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
9160 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9161) -> Option<AuditTarget> {
9162 let Some(c) = commitment else {
9163 return handle_commitment_downgrade(source, last_commitment_by_peer).await;
9164 };
9165 if !p2p_node.dht_manager().is_in_routing_table(source).await {
9174 debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
9175 return None;
9176 }
9177 if &c.sender_peer_id != source.as_bytes() {
9183 warn!(
9184 "ingest_peer_commitment: sender_peer_id mismatch from {source} \
9185 (dropped, possible relay attempt)"
9186 );
9187 return None;
9188 }
9189 let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
9194 if derived_peer_id != c.sender_peer_id {
9195 warn!(
9196 "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
9197 {source} (dropped, throwaway-key attack)"
9198 );
9199 return None;
9200 }
9201 let now = Instant::now();
9215 if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
9216 debug!(
9217 "ingest_peer_commitment: rate-limited sig verify from {source} \
9218 (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
9219 );
9220 return None;
9221 }
9222 if !crate::replication::commitment::verify_commitment_signature(c) {
9227 warn!(
9228 "ingest_peer_commitment: signature did not verify under embedded key for {source} \
9229 (dropped, forged commitment)"
9230 );
9231 return None;
9232 }
9233 let new_hash = commitment_hash(c);
9235 let mut map = last_commitment_by_peer.write().await;
9236 if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
9240 if let Some(victim) = map.keys().next().copied() {
9245 map.remove(&victim);
9246 warn!(
9247 "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
9248 evicted {victim} to admit {source}"
9249 );
9250 }
9251 }
9252 map.entry(*source)
9256 .and_modify(|r| {
9257 r.set_commitment(c.clone(), now);
9260 r.last_sig_verify_at = now;
9261 r.commitment_capable = true; })
9263 .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
9264 drop(map);
9265 {
9277 let mut set = ever_capable_peers.write().await;
9278 if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
9279 set.insert(*source);
9280 } else {
9281 warn!(
9282 "ingest_peer_commitment: ever_capable_peers at cap \
9283 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
9284 );
9285 }
9286 }
9287 new_hash.map(|pin_hash| AuditTarget {
9292 pin_hash,
9293 key_count: c.key_count,
9294 })
9295}
9296
9297async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
9305 let bytes = match tokio::fs::read(path).await {
9306 Ok(b) => b,
9307 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
9308 debug!(
9309 "Commitment retention: no snapshot at {} (fresh start)",
9310 path.display()
9311 );
9312 return;
9313 }
9314 Err(e) => {
9315 warn!(
9316 "Commitment retention: failed to read {}: {e}",
9317 path.display()
9318 );
9319 return;
9320 }
9321 };
9322 if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
9323 state.restore(&persisted);
9324 info!(
9325 "Commitment retention: reloaded {} slot(s) from {}",
9326 state.retained_slot_count(),
9327 path.display()
9328 );
9329 } else {
9330 warn!(
9331 "Commitment retention: corrupt snapshot at {}; starting with empty retention",
9332 path.display()
9333 );
9334 }
9335}
9336
9337async fn persist_retention_if_changed(
9343 state: &ResponderCommitmentState,
9344 path: &Path,
9345 last: &mut Option<Vec<u8>>,
9346) {
9347 let Some(bytes) = state.snapshot().to_bytes() else {
9348 warn!("Commitment retention: serialization failed; keeping previous snapshot");
9349 return;
9350 };
9351 if last.as_deref() == Some(bytes.as_slice()) {
9352 return;
9353 }
9354 if write_retention_atomic(path, bytes.clone()).await {
9355 *last = Some(bytes);
9356 }
9357}
9358
9359async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
9364 let path = path.to_path_buf();
9365 let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
9366 let tmp = path.with_extension("tmp");
9367 std::fs::write(&tmp, &bytes)?;
9368 std::fs::File::open(&tmp)?.sync_all()?;
9369 std::fs::rename(&tmp, &path)?;
9370 let dir = path
9374 .parent()
9375 .filter(|p| !p.as_os_str().is_empty())
9376 .unwrap_or_else(|| Path::new("."));
9377 std::fs::File::open(dir)?.sync_all()?;
9378 Ok(())
9379 })
9380 .await;
9381 match res {
9382 Ok(Ok(())) => true,
9383 Ok(Err(e)) => {
9384 warn!("Commitment retention: persist failed: {e}");
9385 false
9386 }
9387 Err(e) => {
9388 warn!("Commitment retention: persist task join failed: {e}");
9389 false
9390 }
9391 }
9392}
9393
9394async fn rebuild_and_rotate_commitment(
9407 storage: &Arc<LmdbStorage>,
9408 identity: &Arc<NodeIdentity>,
9409 state: &Arc<ResponderCommitmentState>,
9410 p2p: &Arc<P2PNode>,
9411 config: &Arc<ReplicationConfig>,
9412) -> Result<()> {
9413 let stored_keys = storage
9414 .all_keys()
9415 .await
9416 .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
9417
9418 let storage_empty = stored_keys.is_empty();
9429 let self_id = *p2p.peer_id();
9430 let mut keys = Vec::with_capacity(stored_keys.len());
9431 for k in stored_keys {
9432 if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
9433 keys.push(k);
9434 }
9435 }
9436
9437 if keys.is_empty() {
9438 if storage_empty {
9439 if state.retained_slot_count() > 0 {
9444 debug!("Commitment rotation: storage empty, clearing retained slots");
9445 state.clear_all();
9446 }
9447 return Ok(());
9448 }
9449 debug!(
9462 "Commitment rotation: no responsible keys to commit to; retiring current commitment \
9463 (stays answerable until its gossip TTL lapses, bytes still on disk)"
9464 );
9465 state.retire_current();
9466 return Ok(());
9467 }
9468
9469 let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
9473 if keys.len() > cap {
9474 warn!(
9475 "Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
9476 truncating — investigate as this likely means a misconfiguration",
9477 keys.len(),
9478 cap
9479 );
9480 }
9481
9482 let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
9501
9502 let candidate_tree = commitment::MerkleTree::build(entries)
9517 .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
9518 let candidate_root = candidate_tree.root();
9519 if let Some(current) = state.current() {
9520 if current.commitment().root == candidate_root {
9521 debug!(
9522 "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
9523 hex::encode(candidate_root)
9524 );
9525 state.age_out();
9532 return Ok(());
9533 }
9534 }
9535
9536 let sk_bytes = identity.secret_key_bytes().to_vec();
9537 let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
9538 .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
9539 let pk_bytes = identity.public_key().as_bytes().to_vec();
9540 let peer_id_bytes = *p2p.peer_id().as_bytes();
9541
9542 let built = commitment_state::BuiltCommitment::build_from_tree(
9543 candidate_tree,
9544 &peer_id_bytes,
9545 &sk,
9546 &pk_bytes,
9547 )
9548 .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
9549
9550 let hash = hex::encode(built.hash());
9551 let key_count = built.commitment().key_count;
9552 state.rotate(built);
9553 info!("Storage commitment rotated: hash={hash} key_count={key_count}");
9554 Ok(())
9555}
9556
9557#[cfg(test)]
9558#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
9559mod tests {
9560 use super::*;
9561 use super::{
9562 apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
9563 audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
9564 config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
9565 first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
9566 quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
9567 FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
9568 FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
9569 FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
9570 };
9571 use crate::payment::VerificationContext;
9572 use crate::replication::audit::AuditTickResult;
9573 use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
9574 use crate::replication::recent_provers::RecentProvers;
9575 use crate::replication::types::{AuditFailureReason, FailureEvidence};
9576 use lru::LruCache;
9577 use saorsa_core::identity::PeerId;
9578 use std::collections::HashMap;
9579 use std::num::NonZeroUsize;
9580 use std::sync::atomic::Ordering;
9581 use std::sync::Arc;
9582 use std::time::Duration;
9583 use std::time::Instant;
9584 use std::time::SystemTime;
9585
9586 #[test]
9587 fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
9588 for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
9589 assert_eq!(match_replication_protocol(id), Some((id, false)));
9590 assert_eq!(
9591 match_replication_protocol(&format!("{RR_PREFIX}{id}")),
9592 Some((id, true))
9593 );
9594 }
9595 assert_eq!(
9596 match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
9597 None
9598 );
9599 assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
9600 assert_eq!(match_replication_protocol(RR_PREFIX), None);
9601 }
9602
9603 #[test]
9604 fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
9605 use crate::replication::protocol::{
9606 AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
9607 SubtreeSliceChallenge,
9608 };
9609
9610 let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
9611 challenge_id: 1,
9612 nonce: [0u8; 32],
9613 challenged_peer_id: [0u8; 32],
9614 expected_commitment_hash: [0u8; 32],
9615 openings: vec![],
9616 });
9617 let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
9618 challenge_id: 1,
9619 nonce: [0u8; 32],
9620 challenged_peer_id: [0u8; 32],
9621 keys: vec![[0u8; 32]],
9622 });
9623 let digest_response =
9624 ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
9625 let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
9626 key: [0u8; 32],
9627 data: vec![],
9628 proof_of_payment: vec![],
9629 });
9630
9631 assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
9632 assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
9633
9634 for body in [&digest_challenge, &digest_response, &core] {
9635 assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
9636 assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
9637 }
9638
9639 for body in [&subtree, &digest_challenge, &digest_response, &core] {
9640 assert!(body_matches_protocol(body, response_protocol_for(body)));
9641 }
9642 }
9643
9644 fn test_peer(b: u8) -> PeerId {
9645 let mut bytes = [0u8; 32];
9646 bytes[0] = b;
9647 PeerId::from_bytes(bytes)
9648 }
9649
9650 fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
9654 protocol::FreshReplicationOffer {
9655 key: crate::client::compute_address(&data),
9656 data,
9657 proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
9658 }
9659 }
9660
9661 fn admit_test_offer(
9662 in_flight: &FreshOfferInFlight,
9663 offer: protocol::FreshReplicationOffer,
9664 source: PeerId,
9665 ) -> FreshOfferAdmission {
9666 FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
9667 }
9668
9669 #[test]
9670 fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
9671 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9672 let data = vec![0x11u8; 64];
9673
9674 let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
9675 let FreshOfferAdmission::Opened(entry) = opened else {
9676 panic!("first offer for a key should open the entry")
9677 };
9678
9679 assert!(
9682 matches!(
9683 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
9684 FreshOfferAdmission::Joined
9685 ),
9686 "a duplicate from a new source should queue its proof"
9687 );
9688 assert!(
9690 matches!(
9691 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
9692 FreshOfferAdmission::DuplicateSource
9693 ),
9694 "one source should hold at most one queued proof per key"
9695 );
9696
9697 drop(entry);
9699 assert!(
9700 matches!(
9701 admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
9702 FreshOfferAdmission::Opened(_)
9703 ),
9704 "a released key should be openable again"
9705 );
9706 }
9707
9708 #[test]
9709 fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
9710 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9711
9712 let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
9716 assert!(
9717 matches!(
9718 admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
9719 FreshOfferAdmission::Opened(_)
9720 ),
9721 "distinct keys should never block each other"
9722 );
9723 }
9724
9725 #[test]
9732 fn a_failing_proof_hands_the_key_to_the_next_sender() {
9733 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9734 let data = vec![0x5Au8; 128];
9735 let forger = test_peer(0xF0);
9736 let genuine = test_peer(0x0F);
9737
9738 let FreshOfferAdmission::Opened(mut entry) =
9739 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
9740 else {
9741 panic!("the first offer should open the entry");
9742 };
9743 assert!(
9744 matches!(
9745 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
9746 FreshOfferAdmission::Joined
9747 ),
9748 "the genuine sender must not be turned away by the forger"
9749 );
9750
9751 let first = entry
9752 .next_attempt()
9753 .expect("the opener's proof comes first");
9754 assert_eq!(first.source, forger);
9755
9756 let second = entry
9759 .next_attempt()
9760 .expect("a failed proof must not consume the key");
9761 assert_eq!(second.source, genuine);
9762 assert_eq!(
9763 second.proof_of_payment,
9764 vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
9765 );
9766 assert_eq!(
9767 entry.data(),
9768 data.as_slice(),
9769 "every proof is tried against the one copy of the bytes"
9770 );
9771
9772 assert!(entry.next_attempt().is_none());
9774 assert!(
9775 matches!(
9776 admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
9777 FreshOfferAdmission::Opened(_)
9778 ),
9779 "an exhausted entry should release its key"
9780 );
9781 }
9782
9783 #[test]
9792 fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
9793 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9794 let data = vec![0x3Du8; 32];
9795
9796 let FreshOfferAdmission::Opened(mut entry) =
9797 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
9798 else {
9799 panic!("the first offer should open the entry")
9800 };
9801
9802 let mut admitted = 1;
9806 for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
9807 let _ = entry.next_attempt();
9808 if matches!(
9809 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
9810 FreshOfferAdmission::Joined
9811 ) {
9812 admitted += 1;
9813 }
9814 }
9815
9816 assert!(
9817 admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
9818 "a key accepted {admitted} proofs over its lifetime, but the budget is \
9819 {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
9820 );
9821 }
9822
9823 #[test]
9824 fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
9825 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9826 let data = vec![0x2Cu8; 32];
9827
9828 let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
9831 for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
9832 let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
9833 assert!(
9834 matches!(
9835 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
9836 FreshOfferAdmission::Joined
9837 ),
9838 "sender {i} is within the legitimate close-group fan-out"
9839 );
9840 }
9841
9842 let surplus = test_peer(0xEE);
9843 assert!(
9844 matches!(
9845 admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
9846 FreshOfferAdmission::Full
9847 ),
9848 "past the cap a proof is surplus: enough are already queued to place the record"
9849 );
9850 }
9851
9852 #[test]
9853 fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
9854 assert!(!verification_request_exceeds_limit(
9855 config::MAX_VERIFICATION_KEYS_PER_CYCLE
9856 ));
9857 assert!(verification_request_exceeds_limit(
9858 config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
9859 ));
9860 }
9861
9862 #[tokio::test]
9865 async fn subtree_round1_limiter_cooldown_and_single_use_session() {
9866 let limiter = SubtreeRound1Limiter::new(
9867 Duration::from_secs(3600),
9868 config::MAX_CONCURRENT_SUBTREE_ROUND1,
9869 );
9870 let peer = test_peer(1);
9871
9872 let guard = limiter.admit(&peer).await;
9874 assert!(guard.is_some(), "first round-1 admitted");
9875 drop(guard);
9876 assert!(
9879 limiter.admit(&peer).await.is_none(),
9880 "second round-1 within cooldown is rate-dropped"
9881 );
9882 assert!(limiter.admit(&test_peer(2)).await.is_some());
9884
9885 let hash = [7u8; 32];
9887 let nonce = [9u8; 32];
9888 limiter.open_session(peer, 42, hash, nonce).await;
9889 assert!(!limiter.consume_session(&peer, 42, &hash, &[0u8; 32]).await);
9891 assert!(!limiter.consume_session(&peer, 42, &[0u8; 32], &nonce).await);
9892 assert!(!limiter.consume_session(&peer, 99, &hash, &nonce).await);
9894 assert!(limiter.consume_session(&peer, 42, &hash, &nonce).await);
9896 assert!(!limiter.consume_session(&peer, 42, &hash, &nonce).await);
9897 }
9898
9899 #[tokio::test]
9907 async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
9908 let limiter =
9910 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
9911 assert!(
9912 limiter.admit(&test_peer(1)).await.is_some(),
9913 "a node starts with budget in hand so it can serve audits at once"
9914 );
9915
9916 limiter
9920 .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
9921 .await;
9922
9923 for id in 2..8u8 {
9924 assert!(
9925 limiter.admit(&test_peer(id)).await.is_none(),
9926 "a never-seen peer must still be refused while the budget is spent"
9927 );
9928 }
9929 }
9930
9931 #[test]
9937 fn round1_work_budget_carries_debt_and_refills_over_time() {
9938 let now = Instant::now();
9939 let at = |secs: u64| {
9940 now.checked_add(Duration::from_secs(secs))
9941 .unwrap_or_else(Instant::now)
9942 };
9943 let mut budget = Round1WorkBudget {
9944 balance: 0,
9945 last_refill: now,
9946 };
9947 assert!(!budget.has_budget(now), "empty means empty");
9948
9949 budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
9952 assert!(
9953 !budget.has_budget(at(3)),
9954 "still in debt three seconds after an over-large proof"
9955 );
9956 assert!(
9957 budget.has_budget(at(5)),
9958 "the debt is worked off at the refill rate"
9959 );
9960
9961 budget.refill(at(24 * 60 * 60));
9963 assert_eq!(
9964 budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
9965 "refill is capped at the burst size"
9966 );
9967 }
9968
9969 #[tokio::test]
9977 async fn round1_pool_size_comes_from_config() {
9978 let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
9980 let held = limiter.admit(&test_peer(1)).await;
9981 assert!(held.is_some(), "the single configured slot is admitted");
9982 assert!(
9983 limiter.admit(&test_peer(2)).await.is_none(),
9984 "a second concurrent round 1 is refused at a configured pool of 1, \
9985 proving admission follows config rather than the compiled-in default"
9986 );
9987 drop(held);
9988 assert!(
9989 limiter.admit(&test_peer(2)).await.is_some(),
9990 "the slot is reusable once the first proof completes"
9991 );
9992 }
9993
9994 #[tokio::test]
9995 async fn round1_pool_size_of_zero_is_clamped_to_one() {
9996 let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
9997 assert!(
9998 limiter.admit(&test_peer(1)).await.is_some(),
9999 "a mis-set pool of 0 must still serve audits, not silently refuse every one"
10000 );
10001 }
10002
10003 fn test_key(b: u8) -> crate::ant_protocol::XorName {
10004 let mut k = [0u8; 32];
10005 k[0] = b;
10006 k
10007 }
10008
10009 #[test]
10010 fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
10011 let source = test_peer(0x91);
10012 let corroborator = test_peer(0x92);
10013 let mut evidence = types::KeyVerificationEvidence {
10014 presence: HashMap::from([(source, PresenceEvidence::Absent)]),
10015 paid_list: HashMap::new(),
10016 };
10017 let failed = KeyVerificationOutcome::QuorumFailed;
10018
10019 assert_eq!(
10020 punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10021 Some(source)
10022 );
10023 assert_eq!(
10024 punishable_singleton_replica_hint_source(
10025 &HashSet::from([source, corroborator]),
10026 &failed,
10027 &evidence,
10028 ),
10029 None,
10030 "corroborated hints must not use the sole-source penalty lane"
10031 );
10032 assert_eq!(
10033 punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
10034 None,
10035 "paid-list advertisements do not claim possession, so they leave the \
10036 replica-hint source set empty and cannot be penalized"
10037 );
10038
10039 evidence
10040 .presence
10041 .insert(source, PresenceEvidence::Unresolved);
10042 assert_eq!(
10043 punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10044 Some(source),
10045 "definitive close-group rejection is punishable without direct contradiction"
10046 );
10047 assert_eq!(
10048 punishable_singleton_replica_hint_source(
10049 &HashSet::from([source]),
10050 &KeyVerificationOutcome::QuorumInconclusive,
10051 &evidence,
10052 ),
10053 None,
10054 "timeouts and inconclusive evidence are neutral"
10055 );
10056
10057 evidence.presence.insert(source, PresenceEvidence::Absent);
10058 assert_eq!(
10059 punishable_singleton_replica_hint_source(
10060 &HashSet::from([source]),
10061 &KeyVerificationOutcome::QuorumVerified {
10062 sources: vec![corroborator],
10063 },
10064 &evidence,
10065 ),
10066 Some(source),
10067 "an explicit denial is punishable regardless of the overall outcome"
10068 );
10069 }
10070
10071 fn slice_challenge(
10075 challenge_id: u64,
10076 commitment_hash: [u8; 32],
10077 nonce: [u8; 32],
10078 ) -> protocol::SubtreeSliceChallenge {
10079 protocol::SubtreeSliceChallenge {
10080 challenge_id,
10081 nonce,
10082 challenged_peer_id: [0u8; 32],
10083 expected_commitment_hash: commitment_hash,
10084 openings: Vec::new(),
10085 }
10086 }
10087
10088 #[tokio::test]
10097 async fn capacity_refused_slice_challenge_preserves_round1_session() {
10098 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10099 let inflight = Arc::new(RwLock::new(HashMap::new()));
10100 let round1 =
10101 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10102 let peer = test_peer(0xB1);
10103 let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
10104 let challenge = slice_challenge(id, hash, nonce);
10105
10106 round1.open_session(peer, id, hash, nonce).await;
10107
10108 let mut hold = Vec::new();
10110 for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10111 match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
10112 .await
10113 {
10114 Ok(guard) => hold.push(guard),
10115 Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
10116 }
10117 }
10118
10119 let refused =
10120 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10121 assert!(
10122 matches!(refused, SliceAdmission::Capacity(_)),
10123 "a saturated peer share must refuse on capacity, not on session"
10124 );
10125
10126 drop(hold);
10128 let retried =
10129 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10130 assert!(
10131 matches!(retried, SliceAdmission::Admitted(_)),
10132 "the round-1 session must survive a capacity refusal so the retry succeeds"
10133 );
10134
10135 drop(retried);
10137 let replayed =
10138 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10139 assert!(
10140 matches!(replayed, SliceAdmission::NoSession),
10141 "a consumed session must not be replayable"
10142 );
10143 }
10144
10145 #[tokio::test]
10148 async fn unsessioned_slice_challenge_releases_its_admission_slot() {
10149 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10150 let inflight = Arc::new(RwLock::new(HashMap::new()));
10151 let round1 =
10152 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10153 let peer = test_peer(0xB2);
10154 let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
10155
10156 for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
10159 let outcome =
10160 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10161 assert!(
10162 matches!(outcome, SliceAdmission::NoSession),
10163 "no session was ever opened, so every attempt must miss"
10164 );
10165 }
10166
10167 assert_eq!(
10168 semaphore.available_permits(),
10169 MAX_CONCURRENT_AUDIT_RESPONSES,
10170 "every global permit must be returned"
10171 );
10172 assert!(
10173 inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
10174 "no per-peer slot may be left occupied"
10175 );
10176 }
10177
10178 #[test]
10179 fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
10180 assert!(!audit_failure_revokes_holder_credit(
10181 &AuditFailureReason::Timeout
10182 ));
10183 assert!(audit_failure_revokes_holder_credit(
10184 &AuditFailureReason::DigestMismatch
10185 ));
10186 }
10187
10188 #[tokio::test]
10189 async fn audit_responder_admission_reports_per_peer_cap_full() {
10190 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10191 let inflight = Arc::new(RwLock::new(HashMap::new()));
10192 let peer = test_peer(0xA1);
10193
10194 let mut guards = Vec::new();
10195 for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10196 match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
10197 .await
10198 {
10199 Ok(guard) => guards.push(guard),
10200 Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
10201 }
10202 }
10203
10204 let Err(err) =
10205 admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10206 else {
10207 panic!("admission should fail once per-peer cap is full");
10208 };
10209 assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
10210 assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
10211 assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10212 assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10213
10214 drop(guards);
10215 }
10216
10217 #[tokio::test]
10218 async fn audit_responder_admission_reports_global_pool_full() {
10219 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10220 let inflight = Arc::new(RwLock::new(HashMap::new()));
10221 let peer = test_peer(0xA2);
10222
10223 let mut held_global_permits = Vec::new();
10224 for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
10225 held_global_permits.push(
10226 Arc::clone(&semaphore)
10227 .try_acquire_owned()
10228 .expect("test should be able to exhaust the global pool"),
10229 );
10230 }
10231
10232 let Err(err) =
10233 admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10234 else {
10235 panic!("admission should fail once global pool is full");
10236 };
10237 assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
10238 assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
10239 assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10240 assert_eq!(err.peer_inflight, 0);
10241 assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10242
10243 drop(held_global_permits);
10244 }
10245
10246 #[tokio::test]
10247 async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
10248 let semaphore = Arc::new(Semaphore::new(1));
10249 let inflight = Arc::new(RwLock::new(HashMap::new()));
10250 let peer = test_peer(0xA3);
10251
10252 let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
10253 .await
10254 .expect("first responder should be admitted");
10255 assert_eq!(semaphore.available_permits(), 0);
10256 assert_eq!(inflight.read().await.get(&peer), Some(&1));
10257
10258 drop(guard);
10259 assert_eq!(semaphore.available_permits(), 1);
10260 assert!(!inflight.read().await.contains_key(&peer));
10261 }
10262
10263 #[tokio::test]
10264 async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
10265 let semaphore = Arc::new(Semaphore::new(1));
10266 let inflight = Arc::new(RwLock::new(HashMap::new()));
10267 let peer = test_peer(0xA4);
10268 let held_map = inflight.write().await;
10269
10270 let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
10271 assert!(
10272 tokio::time::timeout(Duration::from_millis(10), waiting)
10273 .await
10274 .is_err(),
10275 "admission should still be waiting for the peer map"
10276 );
10277
10278 drop(held_map);
10279 assert_eq!(semaphore.available_permits(), 1);
10280 assert!(!inflight.read().await.contains_key(&peer));
10281 }
10282
10283 #[test]
10284 fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
10285 let timeout = Duration::from_secs(1);
10286 let old_received_at = Instant::now()
10287 .checked_sub(timeout)
10288 .unwrap_or_else(Instant::now);
10289
10290 assert!(request_is_stale(old_received_at, timeout));
10291 assert!(!request_is_stale(Instant::now(), timeout));
10292 }
10293
10294 #[tokio::test]
10295 async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
10296 let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
10297 let inflight = Arc::new(RwLock::new(HashMap::new()));
10298 let first_peer = test_peer(0xB3);
10299 let second_peer = test_peer(0xB4);
10300
10301 let first_guard = admit_bounded_responder(
10302 &semaphore,
10303 &inflight,
10304 &first_peer,
10305 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10306 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10307 )
10308 .await
10309 .expect("first sync from a peer should be admitted");
10310 let duplicate = admit_bounded_responder(
10311 &semaphore,
10312 &inflight,
10313 &first_peer,
10314 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10315 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10316 )
10317 .await;
10318 let other_peer = admit_bounded_responder(
10319 &semaphore,
10320 &inflight,
10321 &second_peer,
10322 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10323 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10324 )
10325 .await;
10326
10327 assert!(matches!(
10328 duplicate,
10329 Err(ResponderAdmissionFailure {
10330 reason: ResponderRejectReason::PerPeerCapFull,
10331 ..
10332 })
10333 ));
10334 assert!(other_peer.is_ok());
10335 drop(first_guard);
10336 drop(other_peer);
10337 }
10338
10339 #[tokio::test]
10347 async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
10348 let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
10349 let inflight = Arc::new(RwLock::new(HashMap::new()));
10350 let flooder = test_peer(0xC1);
10351 let honest = test_peer(0xC2);
10352
10353 let mut held = Vec::new();
10354 for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
10355 held.push(
10356 admit_bounded_responder(
10357 &semaphore,
10358 &inflight,
10359 &flooder,
10360 FRESH_OFFER_MAX_OUTSTANDING,
10361 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10362 )
10363 .await
10364 .expect("offers within the per-peer share are admitted"),
10365 );
10366 }
10367
10368 let flooder_excess = admit_bounded_responder(
10369 &semaphore,
10370 &inflight,
10371 &flooder,
10372 FRESH_OFFER_MAX_OUTSTANDING,
10373 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10374 )
10375 .await;
10376 assert!(
10377 matches!(
10378 flooder_excess,
10379 Err(ResponderAdmissionFailure {
10380 reason: ResponderRejectReason::PerPeerCapFull,
10381 ..
10382 })
10383 ),
10384 "one source must not exceed its fresh-offer share"
10385 );
10386
10387 let honest_offer = admit_bounded_responder(
10388 &semaphore,
10389 &inflight,
10390 &honest,
10391 FRESH_OFFER_MAX_OUTSTANDING,
10392 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10393 )
10394 .await;
10395 assert!(
10396 honest_offer.is_ok(),
10397 "an honest sender must still be admitted while another peer floods"
10398 );
10399
10400 assert!(
10401 usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
10402 < FRESH_OFFER_MAX_OUTSTANDING,
10403 "the per-peer share must leave room for other sources"
10404 );
10405
10406 drop(held);
10407 drop(honest_offer);
10408 }
10409
10410 #[tokio::test]
10412 async fn paid_notify_admission_reserves_capacity_for_other_peers() {
10413 let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
10414 let inflight = Arc::new(RwLock::new(HashMap::new()));
10415 let flooder = test_peer(0xC3);
10416 let honest = test_peer(0xC4);
10417
10418 let mut held = Vec::new();
10419 for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
10420 held.push(
10421 admit_bounded_responder(
10422 &semaphore,
10423 &inflight,
10424 &flooder,
10425 PAID_NOTIFY_MAX_OUTSTANDING,
10426 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10427 )
10428 .await
10429 .expect("notifies within the per-peer share are admitted"),
10430 );
10431 }
10432
10433 assert!(
10434 matches!(
10435 admit_bounded_responder(
10436 &semaphore,
10437 &inflight,
10438 &flooder,
10439 PAID_NOTIFY_MAX_OUTSTANDING,
10440 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10441 )
10442 .await,
10443 Err(ResponderAdmissionFailure {
10444 reason: ResponderRejectReason::PerPeerCapFull,
10445 ..
10446 })
10447 ),
10448 "one source must not exceed its paid-notify share"
10449 );
10450 assert!(
10451 admit_bounded_responder(
10452 &semaphore,
10453 &inflight,
10454 &honest,
10455 PAID_NOTIFY_MAX_OUTSTANDING,
10456 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10457 )
10458 .await
10459 .is_ok(),
10460 "an honest sender must still be admitted while another peer floods"
10461 );
10462
10463 drop(held);
10464 }
10465
10466 #[test]
10474 fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
10475 let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
10476
10477 assert_eq!(
10478 FRESH_OFFER_MAX_OUTSTANDING - share,
10479 FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
10480 "a source holding none must always find a free slot"
10481 );
10482 assert!(
10483 share < FRESH_OFFER_MAX_OUTSTANDING,
10484 "one peer must not be able to take the whole pool"
10485 );
10486 assert!(
10490 share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
10491 "fresh offers are one-way bulk, not request/response — their share \
10492 must not be sized like the request classes'"
10493 );
10494 }
10495
10496 #[test]
10499 fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
10500 let key = test_key(0xC5);
10501
10502 let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
10503
10504 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
10505 .expect("an offer with no proof must be refused");
10506 assert!(
10507 rejection.penalise,
10508 "an honest sender always attaches a proof"
10509 );
10510
10511 let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
10514 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
10515 .expect("an undersized proof must be refused");
10516 assert!(
10517 rejection.penalise,
10518 "no honest sender constructs an undersized proof"
10519 );
10520 let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
10521 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
10522 .expect("an oversized proof must be refused");
10523 assert!(
10524 rejection.penalise,
10525 "no honest sender constructs an oversized proof"
10526 );
10527
10528 let rejection = fresh_offer_structural_rejection(
10529 &key,
10530 &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
10531 &valid_proof,
10532 )
10533 .expect("an oversized offer must be refused");
10534 assert!(
10535 rejection.penalise,
10536 "no honest sender constructs an oversized offer"
10537 );
10538
10539 let data = vec![0u8; 1];
10540 assert!(
10541 fresh_offer_structural_rejection(
10542 &crate::client::compute_address(&data),
10543 &data,
10544 &valid_proof
10545 )
10546 .is_none(),
10547 "a well-formed offer must reach admission"
10548 );
10549 }
10550
10551 #[test]
10560 fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
10561 let genuine_data = vec![0x5Au8; 128];
10562 let key = crate::client::compute_address(&genuine_data);
10563 let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
10564
10565 let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
10566 .expect("bytes that do not hash to the advertised key must be refused");
10567 assert!(
10568 rejection.penalise,
10569 "no honest sender offers bytes that do not hash to the advertised key"
10570 );
10571
10572 assert!(
10575 fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
10576 "the offer that actually carries the key's bytes must reach the entry"
10577 );
10578
10579 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10580 assert!(
10581 matches!(
10582 admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
10583 FreshOfferAdmission::Opened(_)
10584 ),
10585 "an offer refused on payload shape must leave the key openable"
10586 );
10587 }
10588
10589 #[tokio::test]
10590 async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
10591 let peer = test_peer(0xA5);
10592 let key = test_key(0xA5);
10593 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10594 let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
10595 let is_bootstrapping = Arc::new(RwLock::new(true));
10596 let bootstrap_complete_notify = Arc::new(Notify::new());
10597
10598 let now = Instant::now();
10599 queues.write().await.add_pending_verify(
10600 key,
10601 VerificationEntry {
10602 state: VerificationState::PendingVerify,
10603 verified_sources: Vec::new(),
10604 tried_sources: HashSet::new(),
10605 created_at: now,
10606 next_verify_at: now,
10607 hint_sources: HashSet::from([peer]),
10608 replica_hint_sources: HashSet::from([peer]),
10609 },
10610 );
10611 super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
10612 super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
10613 {
10614 let q = queues.read().await;
10615 assert!(
10616 !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
10617 "capacity rejection should initially block bootstrap drain"
10618 );
10619 }
10620
10621 update_bootstrap_after_peer_removed(
10622 &peer,
10623 &bootstrap_state,
10624 &queues,
10625 &is_bootstrapping,
10626 &bootstrap_complete_notify,
10627 )
10628 .await;
10629
10630 let state = bootstrap_state.read().await;
10631 assert!(state.capacity_rejected_sources.is_empty());
10632 assert!(state.pending_keys.is_empty());
10633 assert!(state.is_drained());
10634 drop(state);
10635 assert!(!*is_bootstrapping.read().await);
10636 }
10637
10638 #[tokio::test]
10642 async fn fairness_displacement_does_not_stamp_its_victim() {
10643 let displaced_owner = test_peer(0xB1);
10644 let incoming_source = test_peer(0xB2);
10645 let displaced_key = test_key(0xB1);
10646 let admitted_key = test_key(0xB2);
10647 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10648 {
10649 let mut state = bootstrap_state.write().await;
10650 state.pending_keys.insert(displaced_key);
10651 state
10652 .capacity_rejected_sources
10653 .insert(incoming_source, Instant::now());
10654 }
10655 let outcomes = [(
10656 incoming_source,
10657 AdmissionOutcome {
10658 discovered: HashSet::from([admitted_key]),
10659 capacity_rejected_count: 0,
10660 displaced: vec![CapacityDisplacement {
10661 key: displaced_key,
10662 owner: displaced_owner,
10663 }],
10664 },
10665 )];
10666
10667 publish_bootstrap_admission_outcomes(
10668 &bootstrap_state,
10669 &outcomes,
10670 &HashSet::from([admitted_key]),
10671 )
10672 .await;
10673
10674 let state = bootstrap_state.read().await;
10675 assert!(!state.pending_keys.contains(&displaced_key));
10676 assert!(state.pending_keys.contains(&admitted_key));
10677 assert!(
10678 !state
10679 .capacity_rejected_sources
10680 .contains_key(&displaced_owner),
10681 "the displaced owner must not be charged for our own fairness reclaim"
10682 );
10683 assert!(!state
10684 .capacity_rejected_sources
10685 .contains_key(&incoming_source));
10686 }
10687
10688 #[tokio::test]
10694 async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
10695 const REJECTION_ROUNDS: usize = 5;
10696
10697 let source = test_peer(0xB3);
10698 let key = test_key(0xB3);
10699 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10700
10701 let first_seen = {
10702 let outcomes = [(
10703 source,
10704 AdmissionOutcome {
10705 discovered: HashSet::new(),
10706 capacity_rejected_count: 1,
10707 displaced: Vec::new(),
10708 },
10709 )];
10710 publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
10711 .await;
10712 bootstrap_state
10713 .read()
10714 .await
10715 .capacity_rejected_sources
10716 .get(&source)
10717 .copied()
10718 .expect("first rejection recorded")
10719 };
10720
10721 for _ in 0..REJECTION_ROUNDS {
10722 let outcomes = [(
10723 source,
10724 AdmissionOutcome {
10725 discovered: HashSet::from([key]),
10726 capacity_rejected_count: 1,
10727 displaced: Vec::new(),
10728 },
10729 )];
10730 publish_bootstrap_admission_outcomes(
10731 &bootstrap_state,
10732 &outcomes,
10733 &HashSet::from([key]),
10734 )
10735 .await;
10736 }
10737
10738 let recorded = bootstrap_state
10739 .read()
10740 .await
10741 .capacity_rejected_sources
10742 .get(&source)
10743 .copied()
10744 .expect("debt still outstanding");
10745 assert_eq!(
10746 recorded, first_seen,
10747 "repeat rejections must not restart the expiry clock"
10748 );
10749 }
10750
10751 #[tokio::test]
10756 async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
10757 let peer = test_peer(0xA6);
10758 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10759 let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
10760 let is_bootstrapping = Arc::new(RwLock::new(true));
10761 let bootstrap_complete_notify = Arc::new(Notify::new());
10762
10763 super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
10766
10767 expire_and_recheck_bootstrap_drain(
10769 &bootstrap_state,
10770 &queues,
10771 &is_bootstrapping,
10772 &bootstrap_complete_notify,
10773 ReplicationConfig::default().capacity_rejected_max_age(),
10774 )
10775 .await;
10776 assert!(!bootstrap_state.read().await.is_drained());
10777 assert!(*is_bootstrapping.read().await);
10778
10779 expire_and_recheck_bootstrap_drain(
10781 &bootstrap_state,
10782 &queues,
10783 &is_bootstrapping,
10784 &bootstrap_complete_notify,
10785 Duration::ZERO,
10786 )
10787 .await;
10788 assert!(bootstrap_state.read().await.is_drained());
10789 assert!(!*is_bootstrapping.read().await);
10790 }
10791
10792 #[test]
10793 fn first_audit_terminal_outcomes_are_stable() {
10794 let peer = test_peer(1);
10795 let passed = AuditTickResult::Passed {
10796 challenged_peer: peer,
10797 keys_checked: 1,
10798 };
10799 let timed_out = AuditTickResult::Failed {
10800 evidence: FailureEvidence::AuditFailure {
10801 challenge_id: 1,
10802 challenged_peer: peer,
10803 confirmed_failed_keys: vec![test_key(1)],
10804 summary: crate::replication::types::AuditFailureSummary::default(),
10805 reason: AuditFailureReason::Timeout,
10806 },
10807 no_response_class: Some("timeout"),
10808 };
10809
10810 assert_eq!(
10811 first_audit_terminal_outcome(&passed),
10812 FirstAuditTerminalOutcome::Passed
10813 );
10814 assert_eq!(
10815 first_audit_terminal_outcome(&timed_out),
10816 FirstAuditTerminalOutcome::Timeout
10817 );
10818 assert_eq!(
10819 first_audit_terminal_outcome(&AuditTickResult::Idle),
10820 FirstAuditTerminalOutcome::Idle
10821 );
10822 assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
10823 assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
10824 assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
10825 assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
10826 assert_eq!(
10827 FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
10828 "insufficient_keys"
10829 );
10830 assert_eq!(
10831 FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
10832 "bootstrap_claim"
10833 );
10834 }
10835
10836 #[test]
10837 fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
10838 let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
10839 let mut rng = StdRng::seed_from_u64(7);
10840 let peer = test_peer(1);
10841 let base = MonetizedPinEvent {
10842 peer,
10843 pin: [1; 32],
10844 key_count: 100,
10845 quote_ts: SystemTime::now(),
10846 };
10847
10848 assert_eq!(
10850 coalesce_first_audit_event(&mut pending, base, true, &mut rng),
10851 FirstAuditQueueOutcome::Queued
10852 );
10853
10854 let lower = MonetizedPinEvent {
10856 pin: [2; 32],
10857 key_count: 50,
10858 ..base
10859 };
10860 assert_eq!(
10861 coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
10862 FirstAuditQueueOutcome::SuppressedLower
10863 );
10864 assert_eq!(
10865 pending.peek(&peer).map(|e| (e.pin, e.key_count)),
10866 Some(([1; 32], 100)),
10867 "the higher-count pin is retained"
10868 );
10869
10870 let higher = MonetizedPinEvent {
10872 pin: [3; 32],
10873 key_count: 400,
10874 ..base
10875 };
10876 assert_eq!(
10877 coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
10878 FirstAuditQueueOutcome::Coalesced
10879 );
10880 assert_eq!(
10881 pending.peek(&peer).map(|e| (e.pin, e.key_count)),
10882 Some(([3; 32], 400))
10883 );
10884
10885 let equal_newer = MonetizedPinEvent {
10887 pin: [4; 32],
10888 key_count: 400,
10889 ..base
10890 };
10891 assert_eq!(
10892 coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
10893 FirstAuditQueueOutcome::Coalesced
10894 );
10895 assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
10896 let equal_older = MonetizedPinEvent {
10898 pin: [5; 32],
10899 key_count: 400,
10900 ..base
10901 };
10902 assert_eq!(
10903 coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
10904 FirstAuditQueueOutcome::RetainedOnTie
10905 );
10906 assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
10907
10908 let other_peer = MonetizedPinEvent {
10910 peer: test_peer(2),
10911 pin: [6; 32],
10912 key_count: 100,
10913 ..base
10914 };
10915 assert_eq!(
10916 coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
10917 FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
10918 );
10919 assert_eq!(pending.len(), 1);
10920 assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
10921 }
10922
10923 #[test]
10926 fn first_audit_limiter_enforces_burst_then_refills() {
10927 let base = Instant::now();
10928 let mut limiter = FirstAuditLimiter::new(base);
10929 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
10930
10931 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
10933 let peer = test_peer(u8::try_from(i).expect("small burst"));
10934 assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
10935 limiter.commit_launch(peer, 10, base);
10936 }
10937 let extra = test_peer(0xEE);
10939 assert_eq!(
10940 limiter.assess(&extra, 10, base, 0),
10941 LimiterVerdict::RateDeferred
10942 );
10943
10944 let later = base + interval;
10946 assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
10947 limiter.commit_launch(extra, 10, later);
10948 let extra2 = test_peer(0xEF);
10949 assert_eq!(
10950 limiter.assess(&extra2, 10, later, 0),
10951 LimiterVerdict::RateDeferred
10952 );
10953 }
10954
10955 #[test]
10956 fn first_audit_limiter_refill_keeps_fractional_remainder() {
10957 let base = Instant::now();
10958 let mut limiter = FirstAuditLimiter::new(base);
10959 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
10960 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
10961 let peer = test_peer(u8::try_from(i).expect("small burst"));
10962 assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
10963 limiter.commit_launch(peer, 1, base);
10964 }
10965 let at_1_5 = base + interval + interval / 2;
10968 let p = test_peer(0xAA);
10969 assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
10970 limiter.commit_launch(p, 1, at_1_5);
10971 let at_2_0 = base + interval * 2;
10973 let q = test_peer(0xAB);
10974 assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
10975 }
10976
10977 #[test]
10978 fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
10979 let base = Instant::now();
10980 let mut limiter = FirstAuditLimiter::new(base);
10981 let peer = test_peer(1);
10982 assert_eq!(
10983 limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
10984 LimiterVerdict::RateDeferred
10985 );
10986 assert_eq!(
10988 limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
10989 LimiterVerdict::Admit
10990 );
10991 }
10992
10993 #[test]
10994 fn first_audit_limiter_assess_consumes_nothing() {
10995 let base = Instant::now();
10996 let mut limiter = FirstAuditLimiter::new(base);
10997 let peer = test_peer(3);
10998 for _ in 0..10 {
11002 assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
11003 }
11004 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11005 let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
11006 assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
11007 limiter.commit_launch(p, 5, base);
11008 }
11009 }
11010
11011 #[test]
11012 fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
11013 let base = Instant::now();
11014 let mut limiter = FirstAuditLimiter::new(base);
11015 let peer = test_peer(7);
11016 assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
11017 limiter.commit_launch(peer, 100, base);
11018
11019 let soon = base + Duration::from_secs(60);
11021 assert_eq!(
11022 limiter.assess(&peer, 100, soon, 0),
11023 LimiterVerdict::WindowDeduped
11024 );
11025 assert_eq!(
11027 limiter.assess(&peer, 150, soon, 0),
11028 LimiterVerdict::WindowDeduped
11029 );
11030 assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
11034
11035 let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
11037 assert_eq!(
11038 limiter.assess(&peer, 100, expired, 0),
11039 LimiterVerdict::Admit
11040 );
11041 }
11042
11043 #[test]
11044 fn first_audit_limiter_window_verdict_outranks_empty_budget() {
11045 let base = Instant::now();
11049 let mut limiter = FirstAuditLimiter::new(base);
11050 let peer = test_peer(9);
11051 assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11052 limiter.commit_launch(peer, 10, base);
11053 let other = test_peer(10);
11054 assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
11055 limiter.commit_launch(other, 10, base);
11056 assert_eq!(
11057 limiter.assess(&peer, 10, base, 0),
11058 LimiterVerdict::WindowDeduped
11059 );
11060 }
11061
11062 #[test]
11067 fn first_audit_horizon_prefilter_boundary() {
11068 let now = SystemTime::now();
11069 let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
11071 let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
11072 let boundary = now
11074 .checked_add(h)
11075 .and_then(|t| t.checked_sub(c))
11076 .expect("boundary time");
11077
11078 assert!(quote_within_audit_window(boundary, now));
11080 assert!(!quote_answerable_through_nominal_jitter(boundary, now));
11082
11083 let newer = boundary
11087 .checked_add(Duration::from_micros(1))
11088 .expect("newer");
11089 let older = boundary
11090 .checked_sub(Duration::from_micros(1))
11091 .expect("older");
11092 assert!(quote_answerable_through_nominal_jitter(newer, now));
11093 assert!(!quote_answerable_through_nominal_jitter(older, now));
11094
11095 let future = now
11098 .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
11099 .and_then(|t| t.checked_add(Duration::from_secs(60)))
11100 .expect("future");
11101 assert!(!quote_answerable_through_nominal_jitter(future, now));
11102 }
11103
11104 #[test]
11118 fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
11119 let obs = Arc::new(FirstAuditObservability::default());
11120 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11121 let peer = test_peer(1);
11122
11123 let dead_quote = SystemTime::now()
11124 .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11125 .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11126 .expect("past wall time");
11127 let stale_high = MonetizedPinEvent {
11128 peer,
11129 pin: [1; 32],
11130 key_count: 400,
11131 quote_ts: dead_quote,
11132 };
11133 scheduler.enqueue(stale_high, &obs);
11134 assert_eq!(scheduler.pending_len(), 1);
11135
11136 let fresh_lower = MonetizedPinEvent {
11138 peer,
11139 pin: [2; 32],
11140 key_count: 100,
11141 quote_ts: SystemTime::now(),
11142 };
11143 scheduler.enqueue(fresh_lower, &obs);
11144
11145 assert_eq!(scheduler.pending_len(), 1);
11146 assert_eq!(
11147 scheduler.pending.peek(&peer).map(|e| e.pin),
11148 Some([2; 32]),
11149 "the live nomination replaced the dead incumbent"
11150 );
11151 assert_eq!(
11152 obs.suppressed_lower.load(Ordering::Relaxed),
11153 0,
11154 "no self-erasure signal for displacing a dead pin"
11155 );
11156 assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
11157 assert_eq!(
11158 obs.outside_answerability_window.load(Ordering::Relaxed),
11159 1,
11160 "the dead incumbent is accounted as an expiry"
11161 );
11162 }
11163
11164 #[test]
11167 fn first_audit_live_incumbent_still_suppresses_lower_count() {
11168 let obs = Arc::new(FirstAuditObservability::default());
11169 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11170 let peer = test_peer(1);
11171
11172 let live_high = MonetizedPinEvent {
11173 peer,
11174 pin: [1; 32],
11175 key_count: 400,
11176 quote_ts: SystemTime::now(),
11177 };
11178 scheduler.enqueue(live_high, &obs);
11179 let cheaper = MonetizedPinEvent {
11180 peer,
11181 pin: [2; 32],
11182 key_count: 100,
11183 quote_ts: SystemTime::now(),
11184 };
11185 scheduler.enqueue(cheaper, &obs);
11186
11187 assert_eq!(scheduler.pending_len(), 1);
11188 assert_eq!(
11189 scheduler.pending.peek(&peer).map(|e| e.pin),
11190 Some([1; 32]),
11191 "the higher-count live pin is retained"
11192 );
11193 assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
11194 assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
11195 }
11196
11197 fn live_nomination(b: u8) -> MonetizedPinEvent {
11199 MonetizedPinEvent {
11200 peer: test_peer(b),
11201 pin: [b; 32],
11202 key_count: 100,
11203 quote_ts: SystemTime::now(),
11204 }
11205 }
11206
11207 #[test]
11215 fn first_audit_pending_cap_matches_strict_launch_horizon() {
11216 let quote_ts = SystemTime::now();
11217 assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
11219 let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
11220 let mut refill = 1u32;
11221 loop {
11222 let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
11223 let at = quote_ts + age;
11224 if !quote_answerable_through_nominal_jitter(quote_ts, at) {
11225 break;
11226 }
11227 usable += 1;
11228 refill += 1;
11229 assert!(refill < 10_000, "runaway horizon simulation");
11230 }
11231 assert_eq!(
11232 FIRST_AUDIT_PENDING_CAP, usable,
11233 "cap must match the simulated strict launch horizon"
11234 );
11235 }
11236
11237 #[test]
11241 fn first_audit_pending_cap_independent_of_dedup_cap() {
11242 let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11243 assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
11244 assert_eq!(
11245 scheduler.first_audited.cap().get(),
11246 MAX_LAST_COMMITMENT_BY_PEER
11247 );
11248 }
11249
11250 #[test]
11254 fn first_audit_admission_beyond_cap_displaces_and_counts() {
11255 let obs = Arc::new(FirstAuditObservability::default());
11256 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11257 let overflow: usize = 5;
11258 let total = FIRST_AUDIT_PENDING_CAP + overflow;
11259
11260 for i in 0..total {
11261 let b = u8::try_from(i + 1).expect("test peer count fits u8");
11262 scheduler.enqueue(live_nomination(b), &obs);
11263 }
11264
11265 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11266 assert_eq!(
11267 obs.capacity_evicted.load(Ordering::Relaxed),
11268 u64::try_from(overflow).expect("overflow fits u64"),
11269 "each admission past the cap displaces exactly one entry"
11270 );
11271 assert_eq!(
11272 obs.queued.load(Ordering::Relaxed),
11273 u64::try_from(total).expect("total fits u64"),
11274 "displacement is not an admission refusal"
11275 );
11276 let last = u8::try_from(total).expect("test peer count fits u8");
11278 assert!(
11279 scheduler.pending.peek(&test_peer(last)).is_some(),
11280 "the newest arrival always enters the sample"
11281 );
11282 }
11283
11284 #[test]
11294 fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
11295 let flood: usize = 60; assert!(FIRST_AUDIT_PENDING_CAP < flood);
11297 assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
11298
11299 let trials = 100u64;
11300 let mut survived = 0u32;
11301 let mut evicted = 0u32;
11302 for trial in 0..trials {
11303 let obs = Arc::new(FirstAuditObservability::default());
11304 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11305 scheduler.rng = StdRng::seed_from_u64(trial);
11309 scheduler.limiter.reserve_token();
11312 scheduler.limiter.reserve_token();
11313
11314 let target = test_peer(200);
11315 scheduler.enqueue(live_nomination(200), &obs);
11316 for i in 0..flood {
11317 let b = u8::try_from(i + 1).expect("flood peer fits u8");
11318 scheduler.enqueue(live_nomination(b), &obs);
11319 }
11320
11321 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11322 let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
11323 .expect("overflow count fits u64");
11324 assert_eq!(
11325 obs.capacity_evicted.load(Ordering::Relaxed),
11326 overflows,
11327 "every overflow past the cap is accounted, none silent"
11328 );
11329 if scheduler.pending.peek(&target).is_some() {
11330 survived += 1;
11331 } else {
11332 evicted += 1;
11333 }
11334 }
11335 assert!(
11340 survived > 0,
11341 "target must survive some ordered floods — deterministic eviction \
11342 would mean keep-newest retention regressed"
11343 );
11344 assert!(
11345 evicted > 0,
11346 "target must also be displaceable — otherwise overflow is refusing \
11347 admissions instead of sampling"
11348 );
11349 }
11350
11351 #[test]
11355 fn first_audit_overflow_reserves_before_destructive_eviction() {
11356 let obs = Arc::new(FirstAuditObservability::default());
11357 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11358 let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11359
11360 for i in 0..FIRST_AUDIT_PENDING_CAP {
11361 let b = u8::try_from(i + 1).expect("test peer count fits u8");
11362 scheduler.enqueue(live_nomination(b), &obs);
11363 }
11364 let overflowing = live_nomination(250);
11365 assert!(scheduler.would_displace(&overflowing));
11366
11367 assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
11369 assert!(
11370 !scheduler.would_displace(&overflowing),
11371 "a successful reservation frees the slot"
11372 );
11373 scheduler.enqueue(overflowing, &obs);
11374
11375 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11376 assert_eq!(
11377 obs.capacity_evicted.load(Ordering::Relaxed),
11378 0,
11379 "no destructive eviction when a launch opportunity existed"
11380 );
11381 }
11382
11383 #[test]
11388 fn first_audit_displaced_peer_may_be_renominated() {
11389 let obs = Arc::new(FirstAuditObservability::default());
11390 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11391 let total = FIRST_AUDIT_PENDING_CAP + 1;
11392
11393 for i in 0..total {
11394 let b = u8::try_from(i + 1).expect("test peer count fits u8");
11395 scheduler.enqueue(live_nomination(b), &obs);
11396 }
11397 assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
11398 let displaced = (1..=total)
11400 .map(|i| u8::try_from(i).expect("test peer count fits u8"))
11401 .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
11402 .expect("exactly one admitted peer was displaced");
11403
11404 scheduler.enqueue(live_nomination(displaced), &obs);
11405
11406 assert!(
11407 scheduler.pending.peek(&test_peer(displaced)).is_some(),
11408 "the displaced peer re-enters the sample"
11409 );
11410 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11411 assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
11412 assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
11413 assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
11414 }
11415
11416 #[test]
11421 fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
11422 let obs = Arc::new(FirstAuditObservability::default());
11423 let mono = Instant::now();
11424 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11425
11426 let dead_quote = SystemTime::now()
11427 .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11428 .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11429 .expect("past wall time");
11430 scheduler.enqueue(
11431 MonetizedPinEvent {
11432 peer: test_peer(1),
11433 pin: [1; 32],
11434 key_count: 100,
11435 quote_ts: dead_quote,
11436 },
11437 &obs,
11438 );
11439 scheduler.enqueue(
11440 MonetizedPinEvent {
11441 peer: test_peer(2),
11442 pin: [2; 32],
11443 key_count: 100,
11444 quote_ts: SystemTime::now(),
11445 },
11446 &obs,
11447 );
11448 assert_eq!(scheduler.pending_len(), 2);
11449
11450 scheduler.limiter.tokens = 0;
11453 let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11454 assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
11455 assert_eq!(
11456 scheduler.pending_len(),
11457 2,
11458 "budget-gated reserve scans nothing"
11459 );
11460
11461 let wall_now = SystemTime::now();
11462 assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
11463 assert_eq!(scheduler.pending_len(), 1);
11464 assert!(
11465 scheduler.pending.peek(&test_peer(2)).is_some(),
11466 "the live entry survives the sweep"
11467 );
11468 assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
11469 let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
11470 assert!(
11471 Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
11472 "the age gauge reflects only live work after the sweep"
11473 );
11474 }
11475
11476 #[test]
11477 #[allow(clippy::too_many_lines)]
11478 fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
11479 let obs = Arc::new(FirstAuditObservability::default());
11480 let mono = Instant::now();
11481 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11482
11483 let sentinel_peer = test_peer(0xAA);
11486 scheduler.limiter.promote(sentinel_peer, 500, mono);
11487 let sentinel_before = scheduler
11488 .limiter
11489 .recent
11490 .peek(&sentinel_peer)
11491 .copied()
11492 .expect("sentinel present");
11493
11494 let peer = test_peer(1);
11495 let a = MonetizedPinEvent {
11496 peer,
11497 pin: [1; 32],
11498 key_count: 100,
11499 quote_ts: SystemTime::now(), };
11501 scheduler.enqueue(a, &obs);
11502
11503 let tokens_before = scheduler.tokens();
11504 let lane_before = scheduler.oldest_first_lane;
11505 let launched_before = obs.launched.load(Ordering::Relaxed);
11506 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11507
11508 let inflight0 = obs.inflight.load(Ordering::Relaxed);
11510 assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
11511 assert_eq!(scheduler.reserved_peer(), Some(peer));
11512 assert_eq!(
11513 scheduler.tokens(),
11514 tokens_before - 1,
11515 "reserve consumes a token"
11516 );
11517 assert_eq!(
11518 obs.inflight.load(Ordering::Relaxed),
11519 1,
11520 "reserve holds a slot"
11521 );
11522
11523 let b = MonetizedPinEvent {
11527 peer,
11528 pin: [2; 32],
11529 key_count: 100,
11530 quote_ts: SystemTime::now(),
11531 };
11532 scheduler.enqueue(b, &obs);
11533 assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
11534 assert!(
11535 !scheduler.try_reserve(
11536 mono,
11537 obs.inflight.load(Ordering::Relaxed),
11538 Duration::ZERO,
11539 &cooldown,
11540 &obs
11541 ),
11542 "no second reservation while one is outstanding"
11543 );
11544
11545 let reservation = scheduler
11547 .take_due_reservation(mono)
11548 .expect("A is due at jitter 0");
11549 let wall_fail = a
11550 .quote_ts
11551 .checked_add(GOSSIP_ANSWERABILITY_TTL)
11552 .and_then(|t| t.checked_add(Duration::from_secs(1)))
11553 .expect("past-cutoff wall time");
11554 let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
11555 assert!(
11556 promoted.is_none(),
11557 "answerability lapsed -> cancelled, not promoted"
11558 );
11559
11560 assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
11562 assert!(
11563 scheduler.limiter.recent.peek(&peer).is_none(),
11564 "cancel stamps no per-peer window"
11565 );
11566 assert_eq!(
11567 scheduler.limiter.recent.peek(&sentinel_peer).copied(),
11568 Some(sentinel_before),
11569 "unrelated window sentinel untouched"
11570 );
11571 assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
11572 assert_eq!(
11573 scheduler.tokens(),
11574 tokens_before,
11575 "token refunded on cancel"
11576 );
11577 assert_eq!(
11578 obs.inflight.load(Ordering::Relaxed),
11579 0,
11580 "in-flight slot released"
11581 );
11582 assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
11583 assert_eq!(
11584 obs.launched.load(Ordering::Relaxed),
11585 launched_before,
11586 "no launch counted"
11587 );
11588 assert_eq!(
11589 obs.outside_answerability_window.load(Ordering::Relaxed),
11590 1,
11591 "the cancel reason is recorded"
11592 );
11593
11594 assert_eq!(
11598 scheduler.pending_len(),
11599 1,
11600 "successor still pending after cancel"
11601 );
11602 assert!(scheduler.reserved.is_none());
11603 assert!(scheduler.try_reserve(
11604 mono,
11605 obs.inflight.load(Ordering::Relaxed),
11606 Duration::ZERO,
11607 &cooldown,
11608 &obs
11609 ));
11610 assert_eq!(
11611 scheduler.reserved_peer(),
11612 Some(peer),
11613 "the retained successor becomes the next reservation"
11614 );
11615 }
11616
11617 #[test]
11623 fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
11624 let obs = Arc::new(FirstAuditObservability::default());
11625 let mono = Instant::now();
11626 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11627 let peer = test_peer(1);
11628
11629 let a = MonetizedPinEvent {
11631 peer,
11632 pin: [1; 32],
11633 key_count: 100,
11634 quote_ts: SystemTime::now(),
11635 };
11636 scheduler.enqueue(a, &obs);
11637 let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
11638 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
11639
11640 let b = MonetizedPinEvent {
11643 peer,
11644 pin: [2; 32],
11645 key_count: 400,
11646 quote_ts: SystemTime::now(),
11647 };
11648 scheduler.enqueue(b, &obs);
11649 assert_eq!(scheduler.pending_len(), 1);
11650
11651 let reservation = scheduler.take_due_reservation(mono).expect("due");
11654 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11655 cooldown.insert(peer, mono); let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
11657 assert!(promoted.is_none(), "cooldown race -> not promoted");
11658
11659 assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
11661 assert_eq!(
11662 scheduler.pending.peek(&peer).map(|e| e.pin),
11663 Some([2; 32]),
11664 "the newer successor B is retained, not the older reserved A"
11665 );
11666 assert!(scheduler.first_audited.is_empty());
11667 assert!(scheduler.limiter.recent.peek(&peer).is_none());
11668 }
11669
11670 #[test]
11675 fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
11676 let now = SystemTime::now();
11677 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11678 assert_eq!(
11679 scheduler.oldest_pending_quote_age_ms(now),
11680 0,
11681 "empty pending -> zero"
11682 );
11683
11684 for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
11686 let _ = coalesce_first_audit_event(
11687 &mut scheduler.pending,
11688 MonetizedPinEvent {
11689 peer: test_peer(peer_id),
11690 pin,
11691 key_count: 100,
11692 quote_ts: now - Duration::from_secs(secs),
11693 },
11694 true,
11695 &mut scheduler.rng,
11696 );
11697 }
11698 assert_eq!(
11699 scheduler.oldest_pending_quote_age_ms(now),
11700 10_000,
11701 "tracks the oldest (10s), not the newest (2s)"
11702 );
11703
11704 let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11706 let _ = coalesce_first_audit_event(
11707 &mut skewed.pending,
11708 MonetizedPinEvent {
11709 peer: test_peer(3),
11710 pin: [3; 32],
11711 key_count: 100,
11712 quote_ts: now + Duration::from_secs(5),
11713 },
11714 true,
11715 &mut skewed.rng,
11716 );
11717 assert_eq!(
11718 skewed.oldest_pending_quote_age_ms(now),
11719 0,
11720 "future quote_ts saturates to zero"
11721 );
11722 }
11723
11724 #[test]
11734 fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
11735 let mut pending: LruCache<PeerId, MonetizedPinEvent> =
11736 LruCache::new(NonZeroUsize::new(2).unwrap());
11737 let mut rng = StdRng::seed_from_u64(11);
11738 let victim = test_peer(1);
11739 let other = test_peer(2);
11740 let _ = coalesce_first_audit_event(
11742 &mut pending,
11743 MonetizedPinEvent {
11744 peer: victim,
11745 pin: [1; 32],
11746 key_count: 400,
11747 quote_ts: SystemTime::now(),
11748 },
11749 true,
11750 &mut rng,
11751 );
11752 let _ = coalesce_first_audit_event(
11753 &mut pending,
11754 MonetizedPinEvent {
11755 peer: other,
11756 pin: [9; 32],
11757 key_count: 100,
11758 quote_ts: SystemTime::now(),
11759 },
11760 true,
11761 &mut rng,
11762 );
11763 let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
11764 assert_eq!(
11765 order_before,
11766 vec![other, victim],
11767 "sanity: `other` is MRU, the victim is LRU"
11768 );
11769
11770 let mut suppressed = 0u64;
11772 for i in 0..8u8 {
11773 let out = coalesce_first_audit_event(
11774 &mut pending,
11775 MonetizedPinEvent {
11776 peer: victim,
11777 pin: [i; 32],
11778 key_count: 50,
11779 quote_ts: SystemTime::now(),
11780 },
11781 true,
11782 &mut rng,
11783 );
11784 assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
11785 suppressed += 1;
11786 }
11787 assert_eq!(suppressed, 8);
11788 assert_eq!(
11790 pending.peek(&victim).map(|e| (e.pin, e.key_count)),
11791 Some(([1; 32], 400))
11792 );
11793 let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
11796 assert_eq!(
11797 order_after, order_before,
11798 "the suppressed-lower flood must not have changed any recency position"
11799 );
11800 }
11801
11802 #[test]
11805 fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
11806 let obs = Arc::new(FirstAuditObservability::default());
11807 let mono = Instant::now();
11808 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11809 scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11811 let reserved_peer = test_peer(1);
11812 let other_peer = test_peer(2);
11813
11814 scheduler.enqueue(
11816 MonetizedPinEvent {
11817 peer: reserved_peer,
11818 pin: [1; 32],
11819 key_count: 100,
11820 quote_ts: SystemTime::now(),
11821 },
11822 &obs,
11823 );
11824 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
11825 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
11826
11827 scheduler.enqueue(
11829 MonetizedPinEvent {
11830 peer: other_peer,
11831 pin: [2; 32],
11832 key_count: 100,
11833 quote_ts: SystemTime::now(),
11834 },
11835 &obs,
11836 );
11837 assert_eq!(scheduler.pending_len(), 1);
11838
11839 let reservation = scheduler.take_due_reservation(mono).expect("due");
11841 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11842 cooldown.insert(reserved_peer, mono);
11843 let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
11844 assert!(scheduler
11845 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
11846 .is_none());
11847 assert_eq!(
11848 obs.capacity_evicted.load(Ordering::Relaxed),
11849 cap_before + 1,
11850 "the requeue eviction of a different peer is counted"
11851 );
11852 assert_eq!(
11853 scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
11854 Some([1; 32])
11855 );
11856 }
11857
11858 #[test]
11862 fn first_audit_pending_lower_count_does_not_replace_higher() {
11863 let obs = Arc::new(FirstAuditObservability::default());
11864 let mono = Instant::now();
11865 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11866 let peer = test_peer(1);
11867
11868 scheduler.enqueue(
11870 MonetizedPinEvent {
11871 peer,
11872 pin: [1; 32],
11873 key_count: 400,
11874 quote_ts: SystemTime::now(),
11875 },
11876 &obs,
11877 );
11878 scheduler.enqueue(
11880 MonetizedPinEvent {
11881 peer,
11882 pin: [2; 32],
11883 key_count: 100,
11884 quote_ts: SystemTime::now(),
11885 },
11886 &obs,
11887 );
11888
11889 assert_eq!(scheduler.pending_len(), 1);
11890 assert_eq!(
11891 scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11892 Some(([1; 32], 400)),
11893 "the inflated pin must not be erased by the cheaper successor"
11894 );
11895 assert_eq!(
11897 obs.suppressed_lower.load(Ordering::Relaxed),
11898 1,
11899 "the attempted cheaper-pin self-erasure is observable"
11900 );
11901
11902 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
11904 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
11905 let reservation = scheduler.take_due_reservation(mono).expect("due");
11906 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11907 let (event, _slot) = scheduler
11908 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
11909 .expect("promotes");
11910 assert_eq!((event.pin, event.key_count), ([1; 32], 400));
11911 }
11912
11913 #[test]
11918 fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
11919 let obs = Arc::new(FirstAuditObservability::default());
11920 let mono = Instant::now();
11921 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11922 let peer = test_peer(1);
11923
11924 scheduler.enqueue(
11926 MonetizedPinEvent {
11927 peer,
11928 pin: [1; 32],
11929 key_count: 400,
11930 quote_ts: SystemTime::now(),
11931 },
11932 &obs,
11933 );
11934 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
11935 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
11936
11937 scheduler.enqueue(
11940 MonetizedPinEvent {
11941 peer,
11942 pin: [2; 32],
11943 key_count: 100,
11944 quote_ts: SystemTime::now(),
11945 },
11946 &obs,
11947 );
11948 assert_eq!(scheduler.pending_len(), 1);
11949
11950 let reservation = scheduler.take_due_reservation(mono).expect("due");
11953 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11954 cooldown.insert(peer, mono);
11955 assert!(scheduler
11956 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
11957 .is_none());
11958
11959 assert_eq!(scheduler.pending_len(), 1);
11961 assert_eq!(
11962 scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11963 Some(([1; 32], 400)),
11964 "the inflated reserved pin must survive the requeue over the cheaper successor"
11965 );
11966 assert!(scheduler.first_audited.is_empty());
11967 assert!(scheduler.limiter.recent.peek(&peer).is_none());
11968
11969 let later = mono
11972 .checked_add(Duration::from_secs(
11973 config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
11974 ))
11975 .expect("later");
11976 let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
11977 assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
11978 let reservation = scheduler.take_due_reservation(later).expect("due");
11979 let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
11980 let (event, _slot) = scheduler
11981 .resolve(
11982 reservation,
11983 SystemTime::now(),
11984 later,
11985 &mut cooldown_later,
11986 &obs,
11987 )
11988 .expect("promotes after cooldown");
11989 assert_eq!((event.pin, event.key_count), ([1; 32], 400));
11990 }
11991
11992 #[test]
11997 fn first_audit_lane_alternates_across_promotions() {
11998 let obs = Arc::new(FirstAuditObservability::default());
11999 let mono = Instant::now();
12000 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12001 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12002
12003 let oldest_peer = test_peer(1);
12005 let newest_peer = test_peer(2);
12006 scheduler.enqueue(
12007 MonetizedPinEvent {
12008 peer: oldest_peer,
12009 pin: [1; 32],
12010 key_count: 100,
12011 quote_ts: SystemTime::now(),
12012 },
12013 &obs,
12014 );
12015 scheduler.enqueue(
12016 MonetizedPinEvent {
12017 peer: newest_peer,
12018 pin: [2; 32],
12019 key_count: 100,
12020 quote_ts: SystemTime::now(),
12021 },
12022 &obs,
12023 );
12024
12025 let mut launched_peers = Vec::new();
12026 for _ in 0..2 {
12027 assert!(scheduler.try_reserve(
12028 mono,
12029 obs.inflight.load(Ordering::Relaxed),
12030 Duration::ZERO,
12031 &cooldown,
12032 &obs
12033 ));
12034 let reservation = scheduler.take_due_reservation(mono).expect("due");
12035 let (event, _slot) = scheduler
12037 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12038 .expect("fresh in-window quote promotes");
12039 launched_peers.push(event.peer);
12040 }
12041
12042 assert_eq!(
12045 launched_peers,
12046 vec![newest_peer, oldest_peer],
12047 "consecutive promotions alternate newest-then-oldest lane"
12048 );
12049 }
12050
12051 #[test]
12052 fn first_audit_count_jump_boundaries() {
12053 assert!(!first_audit_count_jump(100, 150));
12055 assert!(first_audit_count_jump(100, 151));
12056 assert!(first_audit_count_jump(0, 1));
12058 assert!(!first_audit_count_jump(0, 0));
12059 assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
12061 }
12062
12063 #[test]
12069 fn first_audit_queue_drops_self_targeting_events() {
12070 let obs = Arc::new(FirstAuditObservability::default());
12071 let self_peer = test_peer(1);
12072 let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
12073 let self_event = MonetizedPinEvent {
12074 peer: self_peer,
12075 pin: [7; 32],
12076 key_count: 1,
12077 quote_ts: SystemTime::now(),
12078 };
12079
12080 scheduler.enqueue(self_event, &obs);
12081 assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
12082 assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
12083 assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
12084
12085 let remote_event = MonetizedPinEvent {
12087 peer: test_peer(2),
12088 pin: [8; 32],
12089 ..self_event
12090 };
12091 scheduler.enqueue(remote_event, &obs);
12092 assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
12093 assert_eq!(scheduler.pending_len(), 1);
12094 assert_eq!(
12095 obs.self_target_skipped.load(Ordering::Relaxed),
12096 1,
12097 "remote event must not count as a self-target skip"
12098 );
12099 }
12100
12101 #[test]
12102 fn fresh_offer_runs_store_admission_payment_checks() {
12103 let context = fresh_offer_payment_context();
12104 assert_eq!(context, VerificationContext::FreshReplication);
12105 assert!(context.is_store_admission());
12109 }
12110
12111 #[test]
12112 fn paid_notify_uses_paid_list_admission_payment_checks() {
12113 assert_eq!(
12114 paid_notify_payment_context(),
12115 VerificationContext::PaidListAdmission
12116 );
12117 }
12118
12119 #[test]
12123 fn monetized_quote_audit_window_fails_closed_both_ends() {
12124 let now = SystemTime::now();
12125 assert!(quote_within_audit_window(now, now));
12127 assert!(quote_within_audit_window(
12128 now + Duration::from_secs(60),
12129 now
12130 ));
12131 assert!(quote_within_audit_window(
12132 now - Duration::from_secs(3600),
12133 now
12134 ));
12135 assert!(!quote_within_audit_window(
12137 now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_secs(60),
12138 now
12139 ));
12140 assert!(!quote_within_audit_window(
12142 now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
12143 now
12144 ));
12145 }
12146
12147 #[tokio::test]
12148 async fn replication_branch_lagged_events_are_counted() {
12149 let before = audit_metrics::replication_event_lagged_total();
12150 let flow = handle_replication_event_recv_error(
12151 &tokio::sync::broadcast::error::RecvError::Lagged(3),
12152 );
12153 assert_eq!(flow, std::ops::ControlFlow::Continue(()));
12154 let after = audit_metrics::replication_event_lagged_total();
12155 assert_eq!(after.saturating_sub(before), 3);
12156 }
12157
12158 #[tokio::test]
12159 async fn replication_branch_closed_events_stop_the_loop() {
12160 let flow =
12161 handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
12162 assert_eq!(flow, std::ops::ControlFlow::Break(()));
12163 }
12164
12165 #[tokio::test]
12166 async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
12167 let (sender, mut receiver) = mpsc::channel(1);
12168 let dropped_body =
12169 ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
12170 keys: Vec::new(),
12171 paid_list_check_indices: Vec::new(),
12172 });
12173 let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12174 let first = InboundReplicationMessage {
12175 source: test_peer(0xC1),
12176 msg: ReplicationMessage {
12177 request_id: 1,
12178 body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
12179 key: test_key(1),
12180 }),
12181 },
12182 rr_message_id: None,
12183 received_at: Instant::now(),
12184 };
12185 let second = InboundReplicationMessage {
12186 source: test_peer(0xC2),
12187 msg: ReplicationMessage {
12188 request_id: 2,
12189 body: dropped_body.clone(),
12190 },
12191 rr_message_id: None,
12192 received_at: Instant::now(),
12193 };
12194
12195 assert!(try_enqueue_serial_message(&sender, first).is_ok());
12196 let dropped = try_enqueue_serial_message(&sender, second)
12197 .expect_err("a full serial queue must refuse the second message");
12198 assert_eq!(dropped.reason, SerialQueueDropReason::Full);
12199 assert_eq!(dropped.message_class, "verification_request");
12200 assert_eq!(dropped.queue_depth, 1);
12201 let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12202 assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
12203
12204 let queued = receiver
12205 .recv()
12206 .await
12207 .expect("first message should remain queued");
12208 assert_eq!(queued.msg.request_id, 1);
12209 assert!(receiver.try_recv().is_err());
12210 }
12211
12212 #[tokio::test]
12213 async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
12214 let peer = test_peer(0x44);
12215 let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
12216
12217 let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
12218 let mut digest_guards = Vec::new();
12219 for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
12220 let guard = admit_audit_responder(
12221 &semaphore,
12222 &digest_inflight,
12223 &peer,
12224 AuditResponderClass::Digest,
12225 )
12226 .await;
12227 assert!(guard.is_ok());
12228 digest_guards.push(guard);
12229 }
12230 assert!(
12231 admit_audit_responder(
12232 &semaphore,
12233 &digest_inflight,
12234 &peer,
12235 AuditResponderClass::Digest,
12236 )
12237 .await
12238 .is_err(),
12239 "digest class must stop at its documented per-source cap"
12240 );
12241 drop(digest_guards);
12242
12243 let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
12244 let mut subtree_guards = Vec::new();
12245 for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
12246 let guard = admit_audit_responder(
12247 &semaphore,
12248 &subtree_inflight,
12249 &peer,
12250 AuditResponderClass::Subtree,
12251 )
12252 .await;
12253 assert!(guard.is_ok());
12254 subtree_guards.push(guard);
12255 }
12256 assert!(
12257 admit_audit_responder(
12258 &semaphore,
12259 &subtree_inflight,
12260 &peer,
12261 AuditResponderClass::Subtree,
12262 )
12263 .await
12264 .is_err(),
12265 "subtree class must retain the deployed cap of two"
12266 );
12267 drop(subtree_guards);
12268 }
12269
12270 #[test]
12271 fn in_scope_audit_deadlines_share_one_formula() {
12272 let config = config::ReplicationConfig::default();
12273 for key_count in [1, 4, 16] {
12274 assert_eq!(
12275 audit::responsible_audit_response_timeout(&config, key_count),
12276 config.audit_response_timeout(key_count)
12277 );
12278 assert_eq!(
12279 pruning::prune_audit_response_timeout(&config, key_count),
12280 config.audit_response_timeout(key_count)
12281 );
12282 }
12283 assert_eq!(
12284 possession::possession_probe_response_timeout(&config),
12285 config.audit_response_timeout(1)
12286 );
12287 }
12288
12289 #[test]
12290 fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
12291 const EXISTING_SOURCE_ID: u8 = 1;
12292 const HINT_SENDER_ID: u8 = 2;
12293
12294 let existing_source = test_peer(EXISTING_SOURCE_ID);
12295 let hint_sender = test_peer(HINT_SENDER_ID);
12296 let mut sources = vec![existing_source];
12297
12298 let hint_sources = HashSet::from([hint_sender]);
12299 add_replica_hint_sources(&mut sources, &hint_sources);
12300 add_replica_hint_sources(&mut sources, &hint_sources);
12301
12302 add_replica_hint_sources(&mut sources, &HashSet::new());
12305
12306 assert_eq!(sources, vec![existing_source, hint_sender]);
12307 }
12308
12309 #[test]
12310 fn audit_timeout_preserves_active_bootstrap_claim() {
12311 assert!(!audit_failure_clears_bootstrap_claim(
12312 &AuditFailureReason::Timeout
12313 ));
12314 }
12315
12316 fn strike_peer(b: u8) -> PeerId {
12317 let mut bytes = [0u8; 32];
12318 bytes[0] = b;
12319 PeerId::from_bytes(bytes)
12320 }
12321
12322 #[test]
12326 fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
12327 let peer = strike_peer(1);
12328 let mut map: HashMap<PeerId, Instant> = HashMap::new();
12329 let t0 = Instant::now();
12330 assert!(cooldown_allows_audit(&mut map, &peer, t0));
12333 let mut passed = 1;
12334 for _ in 0..100 {
12335 if cooldown_allows_audit(&mut map, &peer, t0) {
12336 passed += 1;
12337 }
12338 }
12339 assert_eq!(
12340 passed, 1,
12341 "a flood at one instant must trigger exactly one audit"
12342 );
12343 }
12344
12345 #[test]
12366 fn losing_lottery_still_consumes_attempt_window() {
12367 let peer = strike_peer(3);
12371 let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12372 let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12373 let t0 = Instant::now();
12374
12375 assert!(
12378 !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
12379 "a losing ticket launches no audit"
12380 );
12381
12382 let mut audits = 0;
12387 for _ in 0..99 {
12388 if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
12389 audits += 1;
12390 }
12391 }
12392 assert_eq!(
12393 audits, 0,
12394 "a losing first ticket must consume the attempt window so no later \
12395 flooded message in the same window can audit"
12396 );
12397
12398 let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12401 assert!(
12402 audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
12403 "after the window a winning ticket audits again"
12404 );
12405 assert!(
12406 launched.contains_key(&peer),
12407 "a real launch stamps the shared cooldown"
12408 );
12409 }
12410
12411 #[test]
12419 fn losing_lottery_does_not_suppress_monetized_first_audit() {
12420 let peer = strike_peer(4);
12421 let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12422 let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12423 let t0 = Instant::now();
12424
12425 assert!(!audit_launch_decision(
12427 &mut attempts,
12428 &mut launched,
12429 &peer,
12430 t0,
12431 false
12432 ));
12433 assert!(
12437 cooldown_would_allow(&launched, &peer, t0),
12438 "reserve gate must not see a losing ticket as audit coverage"
12439 );
12440 assert!(
12441 cooldown_allows_audit(&mut launched, &peer, t0),
12442 "promotion must not be deferred by a losing ticket"
12443 );
12444
12445 let peer_won = strike_peer(5);
12448 assert!(audit_launch_decision(
12449 &mut attempts,
12450 &mut launched,
12451 &peer_won,
12452 t0,
12453 true
12454 ));
12455 assert!(
12456 !cooldown_would_allow(&launched, &peer_won, t0),
12457 "a real gossip audit still covers the peer for the window"
12458 );
12459 }
12460
12461 #[test]
12462 fn cooldown_lets_audit_through_after_the_window() {
12463 let peer = strike_peer(2);
12464 let mut map: HashMap<PeerId, Instant> = HashMap::new();
12465 let t0 = Instant::now();
12466 assert!(cooldown_allows_audit(&mut map, &peer, t0));
12467 let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
12469 assert!(!cooldown_allows_audit(&mut map, &peer, within));
12470 let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12472 assert!(cooldown_allows_audit(&mut map, &peer, after));
12473 }
12474
12475 #[test]
12476 fn cooldown_is_per_peer_independent() {
12477 let mut map: HashMap<PeerId, Instant> = HashMap::new();
12478 let t0 = Instant::now();
12479 for i in 0..20u8 {
12481 assert!(
12482 cooldown_allows_audit(&mut map, &strike_peer(i), t0),
12483 "peer {i} should be auditable independently"
12484 );
12485 }
12486 }
12487
12488 #[test]
12489 fn audit_on_gossip_constants_match_adr() {
12490 assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
12494 assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
12495 assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
12496 }
12497
12498 #[test]
12501 fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
12502 assert!(audit_failure_clears_bootstrap_claim(
12503 &AuditFailureReason::DigestMismatch
12504 ));
12505 assert!(audit_failure_revokes_holder_credit(
12506 &AuditFailureReason::DigestMismatch
12507 ));
12508 }
12509
12510 #[test]
12513 fn confirmed_failures_revoke_credit_timeout_does_not() {
12514 for reason in [
12515 AuditFailureReason::MalformedResponse,
12516 AuditFailureReason::DigestMismatch,
12517 AuditFailureReason::KeyAbsent,
12518 AuditFailureReason::Rejected,
12519 ] {
12520 assert!(
12521 audit_failure_revokes_holder_credit(&reason),
12522 "confirmed failure {reason:?} must revoke holder credit"
12523 );
12524 }
12525 assert!(
12526 !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
12527 "Timeout must NOT revoke credit (single dropped packet != storage loss)"
12528 );
12529 }
12530
12531 #[test]
12538 fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
12539 let peer = test_peer(0xAB);
12540 let key = test_key(1);
12541 let hash = [0xCD; 32];
12542
12543 let mut provers = RecentProvers::new();
12545 provers.record_proof(key, peer, hash, Instant::now());
12546 assert!(
12547 provers.is_credited_holder(&key, &peer, &hash),
12548 "precondition: peer credited before failure"
12549 );
12550 apply_audit_failure_credit_revocation(
12551 &mut provers,
12552 &peer,
12553 &AuditFailureReason::DigestMismatch,
12554 );
12555 assert!(
12556 !provers.is_credited_holder(&key, &peer, &hash),
12557 "DigestMismatch must strip the peer's holder credit"
12558 );
12559
12560 let mut provers_timeout = RecentProvers::new();
12562 provers_timeout.record_proof(key, peer, hash, Instant::now());
12563 apply_audit_failure_credit_revocation(
12564 &mut provers_timeout,
12565 &peer,
12566 &AuditFailureReason::Timeout,
12567 );
12568 assert!(
12569 provers_timeout.is_credited_holder(&key, &peer, &hash),
12570 "Timeout must retain holder credit (deliberate liveness cushion)"
12571 );
12572 }
12573
12574 #[test]
12575 fn decoded_audit_failures_clear_active_bootstrap_claim() {
12576 for reason in [
12577 AuditFailureReason::MalformedResponse,
12578 AuditFailureReason::DigestMismatch,
12579 AuditFailureReason::KeyAbsent,
12580 AuditFailureReason::Rejected,
12581 ] {
12582 assert!(
12583 audit_failure_clears_bootstrap_claim(&reason),
12584 "decoded non-bootstrap failure {reason:?} should clear active claim"
12585 );
12586 }
12587 }
12588
12589 #[test]
12590 fn first_failed_key_label_truncates_to_16_hex_chars() {
12591 let mut key = [0u8; 32];
12594 key[0] = 0x18;
12595 key[7] = 0xff;
12596 for byte in &mut key[8..] {
12599 *byte = 0xAA;
12600 }
12601 let label = first_failed_key_label(&[key]);
12602 assert_eq!(label, "0x18000000000000ff");
12604 assert_eq!(label.len(), "0x".len() + 16);
12605 }
12606
12607 #[test]
12608 fn first_failed_key_label_falls_back_when_empty() {
12609 assert_eq!(first_failed_key_label(&[]), "0x");
12613 }
12614
12615 #[test]
12616 fn first_failed_key_label_uses_first_key_only() {
12617 let first = [0x11u8; 32];
12618 let second = [0x22u8; 32];
12619 assert_eq!(
12620 first_failed_key_label(&[first, second]),
12621 format!("0x{}", hex::encode(&first[..8]))
12622 );
12623 }
12624
12625 fn drive_key_in_flight(
12638 q: &mut ReplicationQueues,
12639 key: XorName,
12640 sources: Vec<PeerId>,
12641 ) -> PeerId {
12642 let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
12643 let now = Instant::now();
12644 let entry = VerificationEntry {
12645 state: VerificationState::PendingVerify,
12646 verified_sources: Vec::new(),
12647 tried_sources: HashSet::new(),
12648 created_at: now,
12649 next_verify_at: now,
12650 hint_sources: HashSet::from([hinter]),
12651 replica_hint_sources: HashSet::from([hinter]),
12652 };
12653 assert!(q.add_pending_verify(key, entry).admitted());
12654 assert!(q.promote_pending_to_fetch(key, key, sources));
12655 let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
12656 let source = *candidate.sources.first().expect("candidate has a source");
12657 q.start_dequeued_fetch(candidate, source);
12658 source
12659 }
12660
12661 #[test]
12662 fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
12663 const RETRY_AFTER: Duration = Duration::from_secs(60);
12664
12665 let mut q = ReplicationQueues::new();
12666 let key = test_key(0xAB);
12667 drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
12668 assert_eq!(q.retry_reserved_slot_count(), 1);
12669
12670 let follow_up =
12671 apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
12672
12673 assert_eq!(
12674 follow_up,
12675 FetchFollowUp::Terminal,
12676 "lapsed responsibility must run the caller's terminal bootstrap accounting"
12677 );
12678 assert!(
12679 !q.contains_key(&key),
12680 "the key must leave every pipeline stage — alternate sources included"
12681 );
12682 assert_eq!(
12683 q.pending_count(),
12684 0,
12685 "a lapsed-responsibility key must not be requeued for verification"
12686 );
12687 assert_eq!(
12688 q.retry_reserved_slot_count(),
12689 0,
12690 "terminal exit must release the verification retry-slot reservation"
12691 );
12692 }
12693
12694 #[test]
12695 fn no_longer_responsible_shares_the_stored_terminal_path() {
12696 const RETRY_AFTER: Duration = Duration::from_secs(60);
12697
12698 for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
12702 let mut q = ReplicationQueues::new();
12703 let key = test_key(0xCD);
12704 drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
12705
12706 let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
12707
12708 assert_eq!(follow_up, FetchFollowUp::Terminal);
12709 assert!(!q.contains_key(&key));
12710 assert_eq!(q.retry_reserved_slot_count(), 0);
12711 }
12712 }
12713
12714 #[test]
12715 fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
12716 const RETRY_AFTER: Duration = Duration::from_secs(60);
12717
12718 let mut q = ReplicationQueues::new();
12719 let key = test_key(0xEF);
12720 let first = test_peer(0x04);
12721 let second = test_peer(0x05);
12722 drive_key_in_flight(&mut q, key, vec![first, second]);
12723
12724 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12725 assert_eq!(
12726 follow_up,
12727 FetchFollowUp::RetryFrom(second),
12728 "a failed source must not abandon the remaining verified sources"
12729 );
12730 assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
12731
12732 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12733 assert_eq!(
12734 follow_up,
12735 FetchFollowUp::RequeuedForVerification,
12736 "exhausted sources must restore the reserved verification entry"
12737 );
12738 assert_eq!(q.pending_count(), 1);
12739 assert_eq!(
12740 q.retry_reserved_slot_count(),
12741 0,
12742 "the reservation converts back into the pending entry itself"
12743 );
12744 }
12745
12746 #[test]
12747 fn source_failure_without_retry_metadata_is_terminal() {
12748 const RETRY_AFTER: Duration = Duration::from_secs(60);
12749
12750 let mut q = ReplicationQueues::new();
12753 let key = test_key(0x1F);
12754 let source = test_peer(0x06);
12755 assert!(q.enqueue_fetch(key, key, vec![source]));
12756 let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
12757 q.start_dequeued_fetch(candidate, source);
12758
12759 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12760
12761 assert_eq!(follow_up, FetchFollowUp::Terminal);
12762 assert!(!q.contains_key(&key));
12763 }
12764}