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