#![allow(clippy::significant_drop_tightening)]
pub mod admission;
pub mod audit;
pub mod audit_coordinator;
pub(crate) mod audit_metrics;
pub mod bootstrap;
pub mod commitment;
pub mod commitment_state;
pub mod config;
pub mod fresh;
pub mod neighbor_sync;
pub mod paid_list;
pub mod possession;
pub mod protocol;
pub mod pruning;
pub mod quorum;
pub mod recent_provers;
pub mod scheduling;
pub mod slice;
pub mod storage_commitment_audit;
pub mod subtree;
pub mod types;
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
use std::num::NonZeroUsize;
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
use lru::LruCache;
use std::pin::Pin;
use crate::logging::{debug, error, info, warn};
use futures::stream::FuturesUnordered;
use futures::{future::join_all, Future, StreamExt};
use parking_lot::Mutex;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use tokio::sync::broadcast::error::RecvError;
use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use crate::ant_protocol::XorName;
use crate::error::{Error, Result};
use crate::payment::{
PaymentVerifier, VerificationContext, MAX_PAYMENT_PROOF_SIZE_BYTES,
MIN_PAYMENT_PROOF_SIZE_BYTES,
};
use crate::replication::audit::AuditTickResult;
use crate::replication::audit_coordinator::AuditChallengeCoordinator;
use crate::replication::audit_metrics::{
AuditResponderClass, AuditResponderDropReason, AuditResponderMetrics,
ReplicationResponderClass, ResponderAdmissionCeiling,
};
use crate::replication::commitment::{commitment_hash, StorageCommitment};
use crate::replication::commitment_state::{
PeerCommitmentRecord, PersistedRetention, ResponderCommitmentState, GOSSIP_ANSWERABILITY_TTL,
};
use crate::replication::config::{
max_parallel_fetch, storage_admission_width, ReplicationConfig, MAX_AUDIT_RESPONSES_PER_PEER,
MAX_CONCURRENT_AUDIT_RESPONSES, MAX_CONCURRENT_REPLICATION_SENDS,
MAX_DIGEST_AUDIT_RESPONSES_PER_PEER, MAX_INCOMING_VERIFICATION_KEYS,
MAX_SUBTREE_ROUND1_PER_PEER, MAX_SUBTREE_SESSIONS, MAX_VERIFICATION_KEYS_PER_CYCLE,
REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID, SUBTREE_ROUND1_WORK_BURST_BYTES,
SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, SUBTREE_SESSION_TTL,
};
use crate::replication::paid_list::PaidList;
use crate::replication::protocol::{
FreshReplicationResponse, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
VerificationResponse,
};
use crate::replication::quorum::KeyVerificationOutcome;
use crate::replication::recent_provers::RecentProvers;
use crate::replication::scheduling::{CapacityDisplacement, DeferralOutcome, ReplicationQueues};
use crate::replication::types::{
AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence,
NeighborSyncState, PeerSyncRecord, PresenceEvidence, RepairProofs, VerificationEntry,
VerificationState,
};
use crate::storage::{CapacityVerdict, LmdbStorage};
use saorsa_core::identity::{NodeIdentity, PeerId};
use saorsa_core::{DhtNetworkEvent, P2PEvent, P2PNode, TrustEvent};
use saorsa_pqc::api::sig::{MlDsaSecretKey, MlDsaVariant};
static FIRST_AUDIT_INGRESS_DROPPED: AtomicU64 = AtomicU64::new(0);
pub(crate) fn note_monetized_ingress_drop() {
FIRST_AUDIT_INGRESS_DROPPED.fetch_add(1, Ordering::Relaxed);
}
#[derive(Default)]
struct FirstAuditObservability {
received: AtomicU64,
queued: AtomicU64,
coalesced: AtomicU64,
duplicates: AtomicU64,
capacity_evicted: AtomicU64,
self_target_skipped: AtomicU64,
suppressed_lower: AtomicU64,
cooldown_deferred_attempts: AtomicU64,
rate_deferred_attempts: AtomicU64,
window_deduped: AtomicU64,
launched: AtomicU64,
passed: AtomicU64,
timed_out: AtomicU64,
failed: AtomicU64,
bootstrap_claims: AtomicU64,
idle: AtomicU64,
insufficient_keys: AtomicU64,
outside_answerability_window: AtomicU64,
inflight: AtomicU64,
}
#[cfg(any(test, feature = "test-utils"))]
#[derive(Debug, Clone, Copy)]
pub struct FirstAuditStats {
pub received: u64,
pub queued: u64,
pub self_target_skipped: u64,
pub launched: u64,
pub passed: u64,
pub timed_out: u64,
pub failed: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FirstAuditTerminalOutcome {
Passed,
Timeout,
Failed,
BootstrapClaim,
Idle,
InsufficientKeys,
}
impl FirstAuditTerminalOutcome {
#[cfg(any(feature = "logging", test))]
const fn as_str(self) -> &'static str {
match self {
Self::Passed => "passed",
Self::Timeout => "timeout",
Self::Failed => "failed",
Self::BootstrapClaim => "bootstrap_claim",
Self::Idle => "idle",
Self::InsufficientKeys => "insufficient_keys",
}
}
}
fn first_audit_terminal_outcome(result: &AuditTickResult) -> FirstAuditTerminalOutcome {
match result {
AuditTickResult::Passed { .. } => FirstAuditTerminalOutcome::Passed,
AuditTickResult::Failed {
evidence:
FailureEvidence::AuditFailure {
reason: AuditFailureReason::Timeout,
..
},
..
} => FirstAuditTerminalOutcome::Timeout,
AuditTickResult::Failed { .. } => FirstAuditTerminalOutcome::Failed,
AuditTickResult::BootstrapClaim { .. } => FirstAuditTerminalOutcome::BootstrapClaim,
AuditTickResult::Idle => FirstAuditTerminalOutcome::Idle,
AuditTickResult::InsufficientKeys => FirstAuditTerminalOutcome::InsufficientKeys,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FirstAuditQueueOutcome {
Queued,
Coalesced,
SuppressedLower,
RetainedOnTie,
CapacityEvicted { peer: PeerId, pin: [u8; 32] },
}
fn coalesce_first_audit_event(
pending: &mut LruCache<PeerId, MonetizedPinEvent>,
incoming: MonetizedPinEvent,
incoming_is_newer: bool,
rng: &mut StdRng,
) -> FirstAuditQueueOutcome {
if let Some(existing) = pending.peek(&incoming.peer) {
if incoming.key_count < existing.key_count {
return FirstAuditQueueOutcome::SuppressedLower;
}
if incoming.key_count == existing.key_count && !incoming_is_newer {
return FirstAuditQueueOutcome::RetainedOnTie;
}
let _ = pending.push(incoming.peer, incoming);
return FirstAuditQueueOutcome::Coalesced;
}
if pending.len() >= pending.cap().get() {
let victim = {
let idx = rng.gen_range(0..pending.len());
pending.iter().nth(idx).map(|(p, _)| *p)
};
if let Some(victim_peer) = victim {
if let Some(evicted) = pending.pop(&victim_peer) {
let _ = pending.push(incoming.peer, incoming);
return FirstAuditQueueOutcome::CapacityEvicted {
peer: victim_peer,
pin: evicted.pin,
};
}
}
}
match pending.push(incoming.peer, incoming) {
None => FirstAuditQueueOutcome::Queued,
Some((evicted_peer, evicted)) => FirstAuditQueueOutcome::CapacityEvicted {
peer: evicted_peer,
pin: evicted.pin,
},
}
}
const FIRST_AUDIT_SEND_LATENCY_SLACK: Duration = Duration::from_secs(1);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct RecentFirstAudit {
launched_at: Instant,
key_count: u32,
}
struct FirstAuditInflightSlot(Arc<FirstAuditObservability>);
impl FirstAuditInflightSlot {
fn acquire(observability: &Arc<FirstAuditObservability>) -> Self {
observability.inflight.fetch_add(1, Ordering::Relaxed);
Self(Arc::clone(observability))
}
}
impl Drop for FirstAuditInflightSlot {
fn drop(&mut self) {
self.0.inflight.fetch_sub(1, Ordering::Relaxed);
}
}
const fn first_audit_count_jump(audited_count: u32, new_count: u32) -> bool {
(new_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_DEN
> (audited_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_NUM
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LimiterVerdict {
Admit,
RateDeferred,
WindowDeduped,
}
struct FirstAuditLimiter {
tokens: u32,
last_refill: Instant,
recent: LruCache<PeerId, RecentFirstAudit>,
}
impl FirstAuditLimiter {
fn new(now: Instant) -> Self {
Self {
tokens: config::FIRST_AUDIT_BUDGET_BURST,
last_refill: now,
recent: LruCache::new(
NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
),
}
}
fn window_allows(&self, peer: &PeerId, key_count: u32, now: Instant) -> bool {
self.recent.peek(peer).map_or(true, |prev| {
now.saturating_duration_since(prev.launched_at)
>= config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL
|| first_audit_count_jump(prev.key_count, key_count)
})
}
fn refill(&mut self, now: Instant) {
if self.tokens >= config::FIRST_AUDIT_BUDGET_BURST {
self.last_refill = now;
return;
}
let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
let elapsed = now.saturating_duration_since(self.last_refill);
let earned = elapsed.as_nanos() / interval.as_nanos().max(1);
if earned == 0 {
return;
}
let capacity_gap = u128::from(config::FIRST_AUDIT_BUDGET_BURST - self.tokens);
if earned >= capacity_gap {
self.tokens = config::FIRST_AUDIT_BUDGET_BURST;
self.last_refill = now;
} else {
self.tokens = self
.tokens
.saturating_add(u32::try_from(earned).unwrap_or(u32::MAX));
let advance = interval.saturating_mul(u32::try_from(earned).unwrap_or(u32::MAX));
self.last_refill = self.last_refill.checked_add(advance).unwrap_or(now);
}
}
fn assess(
&mut self,
peer: &PeerId,
key_count: u32,
now: Instant,
inflight: u64,
) -> LimiterVerdict {
if !self.window_allows(peer, key_count, now) {
return LimiterVerdict::WindowDeduped;
}
self.refill(now);
if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.tokens == 0 {
return LimiterVerdict::RateDeferred;
}
LimiterVerdict::Admit
}
fn reserve_token(&mut self) {
self.tokens = self.tokens.saturating_sub(1);
}
fn refund_token(&mut self) {
self.tokens = (self.tokens + 1).min(config::FIRST_AUDIT_BUDGET_BURST);
}
fn promote(&mut self, peer: PeerId, key_count: u32, now: Instant) {
self.recent.put(
peer,
RecentFirstAudit {
launched_at: now,
key_count,
},
);
}
#[cfg(test)]
fn commit_launch(&mut self, peer: PeerId, key_count: u32, now: Instant) {
self.reserve_token();
self.promote(peer, key_count, now);
}
}
fn quote_answerable_through_nominal_jitter(quote_ts: SystemTime, now: SystemTime) -> bool {
let Some(latest_send) = now
.checked_add(config::FIRST_AUDIT_LAUNCH_JITTER_MAX)
.and_then(|t| t.checked_add(FIRST_AUDIT_SEND_LATENCY_SLACK))
else {
return false;
};
quote_within_audit_window(quote_ts, now) && quote_within_audit_window(quote_ts, latest_send)
}
async fn open_first_audit_reservation(
scheduler: &mut FirstAuditScheduler,
cooldown: &RwLock<HashMap<PeerId, Instant>>,
observability: &Arc<FirstAuditObservability>,
) {
if scheduler.has_reservation() {
return;
}
let jitter = Duration::from_millis(rand::thread_rng().gen_range(
0..=u64::try_from(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_millis()).unwrap_or(u64::MAX),
));
let inflight = observability.inflight.load(Ordering::Relaxed);
let reserved = {
let cooldown = cooldown.read().await;
scheduler.try_reserve(Instant::now(), inflight, jitter, &cooldown, observability)
};
if reserved {
if let Some(peer) = scheduler.reserved_peer() {
debug!(
"First-audit scheduler: audit_trigger=first_monetized outcome=reserved peer={peer} pending={}",
scheduler.pending_len()
);
}
}
}
fn first_audit_far_future() -> Instant {
Instant::now()
.checked_add(Duration::from_secs(3600))
.unwrap_or_else(Instant::now)
}
struct FirstAuditReservation {
event: MonetizedPinEvent,
ready_at: Instant,
inflight: FirstAuditInflightSlot,
}
struct FirstAuditScheduler {
first_audited: LruCache<[u8; 32], ()>,
pending: LruCache<PeerId, MonetizedPinEvent>,
limiter: FirstAuditLimiter,
reserved: Option<FirstAuditReservation>,
oldest_first_lane: bool,
self_peer: PeerId,
rng: StdRng,
}
impl FirstAuditScheduler {
fn new(now: Instant, self_peer: PeerId) -> Self {
let dedup_cap = NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN);
let pending_cap = NonZeroUsize::new(FIRST_AUDIT_PENDING_CAP).unwrap_or(NonZeroUsize::MIN);
Self {
first_audited: LruCache::new(dedup_cap),
pending: LruCache::new(pending_cap),
limiter: FirstAuditLimiter::new(now),
reserved: None,
oldest_first_lane: false,
self_peer,
rng: StdRng::from_entropy(),
}
}
#[cfg_attr(not(feature = "logging"), allow(dead_code))]
fn pending_len(&self) -> usize {
self.pending.len()
}
#[cfg_attr(not(feature = "logging"), allow(dead_code))]
fn tokens(&self) -> u32 {
self.limiter.tokens
}
#[cfg_attr(not(feature = "logging"), allow(dead_code))]
fn oldest_pending_quote_age_ms(&self, now: SystemTime) -> u64 {
self.pending
.iter()
.map(|(_, e)| e.quote_ts)
.min()
.and_then(|oldest| now.duration_since(oldest).ok())
.map_or(0, |age| u64::try_from(age.as_millis()).unwrap_or(u64::MAX))
}
fn sweep_expired(&mut self, wall_now: SystemTime, obs: &Arc<FirstAuditObservability>) -> usize {
let expired: Vec<PeerId> = self
.pending
.iter()
.filter(|(_, event)| !quote_answerable_through_nominal_jitter(event.quote_ts, wall_now))
.map(|(peer, _)| *peer)
.collect();
for peer in &expired {
self.pending.pop(peer);
}
if !expired.is_empty() {
obs.outside_answerability_window.fetch_add(
u64::try_from(expired.len()).unwrap_or(u64::MAX),
Ordering::Relaxed,
);
}
expired.len()
}
fn has_reservation(&self) -> bool {
self.reserved.is_some()
}
fn would_displace(&self, event: &MonetizedPinEvent) -> bool {
self.pending.len() >= self.pending.cap().get() && self.pending.peek(&event.peer).is_none()
}
fn reserved_ready_at(&self) -> Option<Instant> {
self.reserved.as_ref().map(|r| r.ready_at)
}
fn reserved_peer(&self) -> Option<PeerId> {
self.reserved.as_ref().map(|r| r.event.peer)
}
fn enqueue(&mut self, event: MonetizedPinEvent, obs: &Arc<FirstAuditObservability>) {
if event.peer == self.self_peer {
obs.self_target_skipped.fetch_add(1, Ordering::Relaxed);
return;
}
if self.first_audited.contains(&event.pin) {
obs.duplicates.fetch_add(1, Ordering::Relaxed);
return;
}
let reserved_peer = self.reserved_peer();
let is_reserved_peer = reserved_peer == Some(event.peer);
if !is_reserved_peer
&& !self
.limiter
.window_allows(&event.peer, event.key_count, Instant::now())
{
obs.window_deduped.fetch_add(1, Ordering::Relaxed);
return;
}
let stale_incumbent = self.pending.peek(&event.peer).is_some_and(|existing| {
!quote_answerable_through_nominal_jitter(existing.quote_ts, SystemTime::now())
});
if stale_incumbent {
self.pending.pop(&event.peer);
obs.outside_answerability_window
.fetch_add(1, Ordering::Relaxed);
}
match coalesce_first_audit_event(&mut self.pending, event, true, &mut self.rng) {
FirstAuditQueueOutcome::Queued => {
obs.queued.fetch_add(1, Ordering::Relaxed);
}
FirstAuditQueueOutcome::Coalesced | FirstAuditQueueOutcome::RetainedOnTie => {
obs.coalesced.fetch_add(1, Ordering::Relaxed);
}
FirstAuditQueueOutcome::SuppressedLower => {
obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
}
FirstAuditQueueOutcome::CapacityEvicted { .. } => {
obs.queued.fetch_add(1, Ordering::Relaxed);
obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
}
}
}
fn try_reserve(
&mut self,
mono_now: Instant,
inflight: u64,
jitter: Duration,
cooldown: &HashMap<PeerId, Instant>,
obs: &Arc<FirstAuditObservability>,
) -> bool {
if self.reserved.is_some() || self.pending.is_empty() {
return false;
}
self.limiter.refill(mono_now);
if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.limiter.tokens == 0 {
obs.rate_deferred_attempts.fetch_add(1, Ordering::Relaxed);
return false;
}
let mut ordered: Vec<(usize, PeerId, MonetizedPinEvent)> = self
.pending
.iter()
.enumerate()
.map(|(i, (p, e))| (i, *p, *e))
.collect();
self.pending.clear();
if self.oldest_first_lane {
ordered.reverse();
}
let mut chosen: Option<MonetizedPinEvent> = None;
let mut kept: Vec<(usize, PeerId, MonetizedPinEvent)> = Vec::new();
for (idx, peer, event) in ordered {
if chosen.is_some() {
kept.push((idx, peer, event));
continue;
}
if self.first_audited.contains(&event.pin) {
obs.duplicates.fetch_add(1, Ordering::Relaxed);
continue; }
if !quote_answerable_through_nominal_jitter(event.quote_ts, SystemTime::now()) {
obs.outside_answerability_window
.fetch_add(1, Ordering::Relaxed);
continue; }
match self
.limiter
.assess(&peer, event.key_count, mono_now, inflight)
{
LimiterVerdict::WindowDeduped => {
obs.window_deduped.fetch_add(1, Ordering::Relaxed);
continue; }
LimiterVerdict::RateDeferred => {
kept.push((idx, peer, event));
continue; }
LimiterVerdict::Admit => {}
}
if !cooldown_would_allow(cooldown, &peer, mono_now) {
obs.cooldown_deferred_attempts
.fetch_add(1, Ordering::Relaxed);
kept.push((idx, peer, event));
continue; }
chosen = Some(event);
}
kept.sort_unstable_by_key(|(idx, _, _)| std::cmp::Reverse(*idx));
for (_, peer, event) in kept {
self.pending.put(peer, event);
}
let Some(event) = chosen else {
return false;
};
self.limiter.reserve_token();
let inflight_slot = FirstAuditInflightSlot::acquire(obs);
let ready_at = mono_now.checked_add(jitter).unwrap_or(mono_now);
self.reserved = Some(FirstAuditReservation {
event,
ready_at,
inflight: inflight_slot,
});
true
}
fn take_due_reservation(&mut self, mono_now: Instant) -> Option<FirstAuditReservation> {
if self
.reserved
.as_ref()
.is_some_and(|r| mono_now >= r.ready_at)
{
self.reserved.take()
} else {
None
}
}
fn resolve(
&mut self,
reservation: FirstAuditReservation,
wall_now: SystemTime,
mono_now: Instant,
cooldown: &mut HashMap<PeerId, Instant>,
obs: &Arc<FirstAuditObservability>,
) -> Option<(MonetizedPinEvent, FirstAuditInflightSlot)> {
let FirstAuditReservation {
event, inflight, ..
} = reservation;
if !quote_within_audit_window(event.quote_ts, wall_now) {
self.limiter.refund_token();
obs.outside_answerability_window
.fetch_add(1, Ordering::Relaxed);
drop(inflight);
return None; }
if !cooldown_allows_audit(cooldown, &event.peer, mono_now) {
self.limiter.refund_token();
obs.cooldown_deferred_attempts
.fetch_add(1, Ordering::Relaxed);
drop(inflight);
match coalesce_first_audit_event(&mut self.pending, event, false, &mut self.rng) {
FirstAuditQueueOutcome::CapacityEvicted { .. } => {
obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
}
FirstAuditQueueOutcome::SuppressedLower => {
obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
}
FirstAuditQueueOutcome::Queued
| FirstAuditQueueOutcome::Coalesced
| FirstAuditQueueOutcome::RetainedOnTie => {}
}
return None;
}
self.limiter.promote(event.peer, event.key_count, mono_now);
self.first_audited.put(event.pin, ());
self.oldest_first_lane = !self.oldest_first_lane;
obs.launched.fetch_add(1, Ordering::Relaxed);
Some((event, inflight))
}
}
const RR_PREFIX: &str = "/rr/";
const INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY: usize = 64;
const FRESH_OFFER_WORKER_LIMIT: usize = 4;
const FRESH_OFFER_MAX_OUTSTANDING: usize = 16;
const MAX_FRESH_OFFER_ATTEMPTS_PER_KEY: usize = crate::ant_protocol::CLOSE_GROUP_MAJORITY;
const FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES: usize = 4;
#[allow(clippy::cast_possible_truncation)]
const FRESH_OFFER_MAX_OUTSTANDING_PER_PEER: u32 =
(FRESH_OFFER_MAX_OUTSTANDING - FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES) as u32;
const PAID_NOTIFY_WORKER_LIMIT: usize = 2;
const PAID_NOTIFY_MAX_OUTSTANDING: usize = 64;
const PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER: u32 = 16;
const FETCH_RESPONDER_WORKER_LIMIT: usize = 3;
const FETCH_RESPONDER_MAX_OUTSTANDING: usize = FETCH_RESPONDER_WORKER_LIMIT * 4;
const FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 2;
const VERIFICATION_RESPONDER_WORKER_LIMIT: usize = 2;
const VERIFICATION_RESPONDER_MAX_OUTSTANDING: usize = VERIFICATION_RESPONDER_WORKER_LIMIT * 4;
const VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
const NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT: usize = 2;
const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING: usize = NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT * 4;
const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
fn match_replication_protocol(topic: &str) -> Option<(&'static str, bool)> {
for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
if topic == id {
return Some((id, false));
}
if let Some(rest) = topic.strip_prefix(RR_PREFIX) {
if rest == id {
return Some((id, true));
}
}
}
None
}
fn body_matches_protocol(body: &ReplicationMessageBody, protocol: &str) -> bool {
protocol == response_protocol_for(body)
}
fn response_protocol_for(body: &ReplicationMessageBody) -> &'static str {
if body.is_subtree_audit() {
SUBTREE_AUDIT_PROTOCOL_ID
} else {
REPLICATION_PROTOCOL_ID
}
}
fn fresh_offer_payment_context() -> VerificationContext {
VerificationContext::FreshReplication
}
fn paid_notify_payment_context() -> VerificationContext {
VerificationContext::PaidListAdmission
}
type FetchFuture = Pin<Box<dyn Future<Output = (XorName, Option<FetchOutcome>)> + Send>>;
type FreshOfferInFlight = Arc<Mutex<HashMap<XorName, FreshOfferEntry>>>;
struct FreshOfferAttempt {
source: PeerId,
proof_of_payment: Vec<u8>,
request_id: u64,
rr_message_id: Option<String>,
}
struct FreshOfferEntry {
pending: VecDeque<FreshOfferAttempt>,
sources: HashSet<PeerId>,
admitted: usize,
}
enum FreshOfferAdmission {
Opened(Box<FreshOfferEntryGuard>),
Joined,
Full,
DuplicateSource,
}
#[cfg(feature = "logging")]
impl FreshOfferAdmission {
const fn surplus_reason(&self) -> &'static str {
match self {
Self::DuplicateSource => "this source already has a proof queued",
Self::Full => "the key already holds its full complement of proofs",
Self::Opened(_) | Self::Joined => "not surplus",
}
}
}
struct FreshOfferEntryGuard {
in_flight: FreshOfferInFlight,
key: XorName,
data: Vec<u8>,
received_at: Instant,
holds_entry: bool,
}
impl FreshOfferEntryGuard {
fn admit(
in_flight: &FreshOfferInFlight,
offer: protocol::FreshReplicationOffer,
source: PeerId,
request_id: u64,
rr_message_id: Option<String>,
received_at: Instant,
) -> FreshOfferAdmission {
let key = offer.key;
let attempt = FreshOfferAttempt {
source,
proof_of_payment: offer.proof_of_payment,
request_id,
rr_message_id,
};
let mut in_flight_map = in_flight.lock();
if let Some(entry) = in_flight_map.get_mut(&key) {
if entry.sources.contains(&source) {
return FreshOfferAdmission::DuplicateSource;
}
if entry.admitted >= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
return FreshOfferAdmission::Full;
}
entry.admitted = entry.admitted.saturating_add(1);
entry.sources.insert(source);
entry.pending.push_back(attempt);
return FreshOfferAdmission::Joined;
}
let mut sources = HashSet::new();
sources.insert(source);
let mut pending = VecDeque::new();
pending.push_back(attempt);
in_flight_map.insert(
key,
FreshOfferEntry {
pending,
sources,
admitted: 1,
},
);
drop(in_flight_map);
FreshOfferAdmission::Opened(Box::new(Self {
in_flight: Arc::clone(in_flight),
key,
data: offer.data,
received_at,
holds_entry: true,
}))
}
fn data(&self) -> &[u8] {
&self.data
}
fn received_at(&self) -> Instant {
self.received_at
}
fn next_attempt(&mut self) -> Option<FreshOfferAttempt> {
let mut in_flight = self.in_flight.lock();
let Some(entry) = in_flight.get_mut(&self.key) else {
self.holds_entry = false;
return None;
};
if let Some(attempt) = entry.pending.pop_front() {
return Some(attempt);
}
in_flight.remove(&self.key);
self.holds_entry = false;
None
}
fn release(&mut self) -> Vec<FreshOfferAttempt> {
let mut in_flight = self.in_flight.lock();
self.holds_entry = false;
in_flight
.remove(&self.key)
.map(|entry| entry.pending.into_iter().collect())
.unwrap_or_default()
}
}
impl Drop for FreshOfferEntryGuard {
fn drop(&mut self) {
if self.holds_entry {
self.in_flight.lock().remove(&self.key);
}
}
}
struct VerificationCycleContext<'a> {
p2p_node: &'a Arc<P2PNode>,
paid_list: &'a Arc<PaidList>,
storage: &'a Arc<LmdbStorage>,
queues: &'a Arc<RwLock<ReplicationQueues>>,
config: &'a ReplicationConfig,
bootstrap_state: &'a Arc<RwLock<BootstrapState>>,
is_bootstrapping: &'a Arc<RwLock<bool>>,
bootstrap_complete_notify: &'a Arc<Notify>,
last_commitment_by_peer: &'a Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
ever_capable_peers: &'a Arc<RwLock<HashSet<PeerId>>>,
recent_provers: &'a Arc<RwLock<RecentProvers>>,
}
const FETCH_WORKER_POLL_MS: u64 = 100;
const VERIFICATION_WORKER_POLL_MS: u64 = 250;
const VERIFICATION_CYCLE_SLOW_LOG_MS: u128 = 500;
const REPLICATION_TRUST_WEIGHT: f64 = 1.0;
const MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE: usize = 3;
const BOOTSTRAP_DRAIN_CHECK_SECS: u64 = 5;
const SHUTDOWN_TASK_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
const COMMITMENT_ROTATION_INTERVAL_SECS: u64 = 3600;
const RETENTION_PERSIST_INTERVAL_SECS: u64 = 30;
const TRAFFIC_SUMMARY_INTERVAL_SECS: u64 = 300;
#[cfg(feature = "logging")]
const BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS: u64 = 60;
const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_secs(30 * 60);
fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
let too_future = quote_ts
.duration_since(now)
.is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
let too_old = now
.duration_since(quote_ts)
.is_ok_and(|age| age >= audit_cutoff);
!(too_future || too_old)
}
const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_secs(60);
const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
#[allow(clippy::cast_possible_truncation)] const FIRST_AUDIT_PENDING_CAP: usize = {
let strict_horizon_secs = GOSSIP_ANSWERABILITY_TTL
.as_secs()
.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN.as_secs())
.saturating_sub(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_secs())
.saturating_sub(FIRST_AUDIT_SEND_LATENCY_SLACK.as_secs());
let refills =
strict_horizon_secs.saturating_sub(1) / config::FIRST_AUDIT_LAUNCH_INTERVAL.as_secs();
(refills + config::FIRST_AUDIT_BUDGET_BURST as u64) as usize
};
const _: () = {
assert!(FIRST_AUDIT_PENDING_CAP >= 1);
assert!(FIRST_AUDIT_PENDING_CAP < MAX_LAST_COMMITMENT_BY_PEER);
};
const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
pub struct ReplicationEngine {
config: Arc<ReplicationConfig>,
p2p_node: Arc<P2PNode>,
storage: Arc<LmdbStorage>,
paid_list: Arc<PaidList>,
payment_verifier: Arc<PaymentVerifier>,
queues: Arc<RwLock<ReplicationQueues>>,
sync_state: Arc<RwLock<NeighborSyncState>>,
sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
gossip_lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
sync_cycle_epoch: Arc<RwLock<u64>>,
repair_proofs: Arc<RwLock<RepairProofs>>,
bootstrap_state: Arc<RwLock<BootstrapState>>,
is_bootstrapping: Arc<RwLock<bool>>,
sync_trigger: Arc<Notify>,
bootstrap_complete_notify: Arc<Notify>,
identity: Arc<NodeIdentity>,
commitment_state: Arc<ResponderCommitmentState>,
retention_path: PathBuf,
last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
recent_provers: Arc<RwLock<RecentProvers>>,
sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
send_semaphore: Arc<Semaphore>,
audit_responder_semaphore: Arc<Semaphore>,
audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
audit_responder_metrics: Arc<AuditResponderMetrics>,
audit_challenge_coordinator: Arc<AuditChallengeCoordinator>,
fetch_responder_worker_semaphore: Arc<Semaphore>,
fetch_responder_admission_semaphore: Arc<Semaphore>,
fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
verification_responder_worker_semaphore: Arc<Semaphore>,
verification_responder_admission_semaphore: Arc<Semaphore>,
verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
fresh_offer_worker_semaphore: Arc<Semaphore>,
fresh_offer_admission_semaphore: Arc<Semaphore>,
fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
fresh_offer_in_flight: FreshOfferInFlight,
paid_notify_worker_semaphore: Arc<Semaphore>,
paid_notify_admission_semaphore: Arc<Semaphore>,
paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
subtree_round1: SubtreeRound1Limiter,
fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
monetized_pin_tx: mpsc::Sender<MonetizedPinEvent>,
monetized_pin_rx: Option<mpsc::Receiver<MonetizedPinEvent>>,
first_audit_observability: Arc<FirstAuditObservability>,
shutdown: CancellationToken,
task_handles: Vec<JoinHandle<()>>,
detached_task_tracker: TaskTracker,
}
impl ReplicationEngine {
#[allow(clippy::too_many_arguments)]
pub async fn new(
config: ReplicationConfig,
p2p_node: Arc<P2PNode>,
storage: Arc<LmdbStorage>,
payment_verifier: Arc<PaymentVerifier>,
identity: Arc<NodeIdentity>,
root_dir: &Path,
fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
shutdown: CancellationToken,
) -> Result<Self> {
config.validate().map_err(Error::Config)?;
let paid_list = Arc::new(
PaidList::new(root_dir)
.await
.map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
);
let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
let config = Arc::new(config);
let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
let (monetized_pin_tx, monetized_pin_rx) =
mpsc::channel(config::FIRST_AUDIT_INGRESS_CAPACITY);
let engine = Self {
config: Arc::clone(&config),
p2p_node,
storage,
paid_list,
payment_verifier,
queues: Arc::new(RwLock::new(ReplicationQueues::new())),
sync_state: Arc::new(RwLock::new(initial_neighbors)),
sync_history: Arc::new(RwLock::new(HashMap::new())),
audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
gossip_lottery_attempts: Arc::new(RwLock::new(HashMap::new())),
sync_cycle_epoch: Arc::new(RwLock::new(0)),
repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
is_bootstrapping: Arc::new(RwLock::new(true)),
sync_trigger: Arc::new(Notify::new()),
bootstrap_complete_notify: Arc::new(Notify::new()),
identity,
commitment_state: Arc::new(ResponderCommitmentState::new()),
retention_path: root_dir.join("commitment_retention.bin"),
last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
audit_responder_metrics: Arc::new(AuditResponderMetrics::default()),
audit_challenge_coordinator: Arc::new(AuditChallengeCoordinator::new()),
fetch_responder_worker_semaphore: Arc::new(Semaphore::new(
FETCH_RESPONDER_WORKER_LIMIT,
)),
fetch_responder_admission_semaphore: Arc::new(Semaphore::new(
FETCH_RESPONDER_MAX_OUTSTANDING,
)),
fetch_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
verification_responder_worker_semaphore: Arc::new(Semaphore::new(
VERIFICATION_RESPONDER_WORKER_LIMIT,
)),
verification_responder_admission_semaphore: Arc::new(Semaphore::new(
VERIFICATION_RESPONDER_MAX_OUTSTANDING,
)),
verification_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
neighbor_sync_responder_worker_semaphore: Arc::new(Semaphore::new(
NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT,
)),
neighbor_sync_responder_admission_semaphore: Arc::new(Semaphore::new(
NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
)),
neighbor_sync_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
fresh_offer_worker_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_WORKER_LIMIT)),
fresh_offer_admission_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING)),
fresh_offer_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
fresh_offer_in_flight: Arc::new(Mutex::new(HashMap::new())),
paid_notify_worker_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_WORKER_LIMIT)),
paid_notify_admission_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING)),
paid_notify_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
subtree_round1: SubtreeRound1Limiter::new(
config.subtree_round1_responder_cooldown,
config.subtree_round1_max_concurrent,
),
fresh_write_rx: Some(fresh_write_rx),
possession_check_tx,
possession_check_rx: Some(possession_check_rx),
monetized_pin_tx,
monetized_pin_rx: Some(monetized_pin_rx),
first_audit_observability: Arc::new(FirstAuditObservability::default()),
shutdown,
task_handles: Vec::new(),
detached_task_tracker: TaskTracker::new(),
};
load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
Ok(engine)
}
#[must_use]
pub fn monetized_pin_sender(&self) -> mpsc::Sender<MonetizedPinEvent> {
self.monetized_pin_tx.clone()
}
#[must_use]
pub fn paid_list(&self) -> &Arc<PaidList> {
&self.paid_list
}
#[must_use]
pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
&self.commitment_state
}
#[must_use]
pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
&self.last_commitment_by_peer
}
#[must_use]
pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
&self.recent_provers
}
#[cfg(any(test, feature = "test-utils"))]
pub async fn rebuild_commitment_now(&self) -> Result<()> {
rebuild_and_rotate_commitment(
&self.storage,
&self.identity,
&self.commitment_state,
&self.p2p_node,
&self.config,
)
.await
}
#[cfg(any(feature = "test-utils", test))]
pub async fn inject_peer_commitment_for_test(
&self,
peer: &PeerId,
commitment: StorageCommitment,
) {
let now = Instant::now();
self.last_commitment_by_peer
.write()
.await
.insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
self.ever_capable_peers.write().await.insert(*peer);
}
#[cfg(any(test, feature = "test-utils"))]
pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
let now = Instant::now();
let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
let mut launched = self.audit_on_gossip_cooldown.write().await;
lottery_attempts.insert(*peer, now);
launched.remove(peer);
}
#[cfg(any(test, feature = "test-utils"))]
pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
let target = {
let map = self.last_commitment_by_peer.read().await;
map.get(peer)
.and_then(PeerCommitmentRecord::last_commitment)
.and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
};
let Some((pin, key_count)) = target else {
return audit::AuditTickResult::Idle;
};
let credit = storage_commitment_audit::AuditCredit {
recent_provers: &self.recent_provers,
};
storage_commitment_audit::run_subtree_audit(
&self.p2p_node,
&self.config,
peer,
pin,
key_count,
Some(&credit),
)
.await
}
#[cfg(any(test, feature = "test-utils"))]
#[must_use]
pub fn first_audit_stats(&self) -> FirstAuditStats {
let o = &self.first_audit_observability;
FirstAuditStats {
received: o.received.load(Ordering::Relaxed),
queued: o.queued.load(Ordering::Relaxed),
self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
launched: o.launched.load(Ordering::Relaxed),
passed: o.passed.load(Ordering::Relaxed),
timed_out: o.timed_out.load(Ordering::Relaxed),
failed: o.failed.load(Ordering::Relaxed),
}
}
#[cfg(any(test, feature = "test-utils"))]
pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
possession::run_possession_check(
key,
peers,
&self.p2p_node,
&self.storage,
&self.config,
&self.sync_state,
&self.audit_challenge_coordinator,
&self.shutdown,
)
.await;
}
#[cfg(any(test, feature = "test-utils"))]
pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
self.queues
.write()
.await
.enqueue_fetch(key, distance, sources)
}
#[cfg(any(test, feature = "test-utils"))]
pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
self.queues.read().await.contains_key(key)
}
#[cfg(any(test, feature = "test-utils"))]
pub async fn enqueue_pending_verify_for_test(&self, key: XorName, hinter: PeerId) -> bool {
let now = Instant::now();
let entry = VerificationEntry {
state: VerificationState::PendingVerify,
verified_sources: Vec::new(),
tried_sources: HashSet::new(),
created_at: now,
next_verify_at: now,
hint_sources: HashSet::from([hinter]),
replica_hint_sources: HashSet::from([hinter]),
unresolved_retries: 0,
no_holder_reported: false,
};
self.queues
.write()
.await
.add_pending_verify(key, entry)
.admitted()
}
#[cfg(any(test, feature = "test-utils"))]
pub async fn pending_verify_delay_for_test(&self, key: &XorName) -> Option<Duration> {
self.queues.read().await.get_pending(key).map(|entry| {
entry
.next_verify_at
.saturating_duration_since(Instant::now())
})
}
pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
if !self.task_handles.is_empty() {
error!("ReplicationEngine::start() called while already running — ignoring");
return;
}
info!("Starting replication engine");
self.start_message_handler();
self.start_neighbor_sync_loop();
self.start_self_lookup_loop();
self.start_audit_loop();
self.start_commitment_rotation_loop();
self.start_retention_persist_loop();
self.start_fetch_worker();
self.start_verification_worker();
self.start_bootstrap_sync(dht_events);
self.start_fresh_write_drainer();
self.start_possession_check_scheduler();
self.start_first_audit_drainer();
self.start_traffic_summary_loop();
#[cfg(feature = "logging")]
self.start_bootstrap_state_snapshot_loop();
#[cfg(feature = "logging")]
self.start_audit_responder_summary_loop();
info!(
"Replication engine started with {} background tasks",
self.task_handles.len()
);
}
pub async fn is_bootstrapping(&self) -> bool {
*self.is_bootstrapping.read().await
}
pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
let notified = self.bootstrap_complete_notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if !*self.is_bootstrapping.read().await {
return true;
}
tokio::time::timeout(timeout, notified).await.is_ok()
}
pub async fn shutdown(&mut self) {
self.shutdown.cancel();
for (i, mut handle) in self.task_handles.drain(..).enumerate() {
match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
Ok(Ok(())) => {}
Ok(Err(e)) if e.is_cancelled() => {}
Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
Err(_) => {
warn!(
"Replication task {i} did not stop within {}s, aborting",
SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
);
handle.abort();
match handle.await {
Ok(()) => {}
Err(e) if e.is_cancelled() => {}
Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
}
}
}
}
self.fresh_offer_worker_semaphore.close();
self.paid_notify_worker_semaphore.close();
self.fetch_responder_worker_semaphore.close();
self.verification_responder_worker_semaphore.close();
self.neighbor_sync_responder_worker_semaphore.close();
self.detached_task_tracker.close();
self.detached_task_tracker.wait().await;
self.storage.wait_idle().await;
self.paid_list.wait_idle().await;
}
pub fn trigger_neighbor_sync(&self) {
self.sync_trigger.notify_one();
}
pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
let peers = fresh::replicate_fresh(
key,
data,
proof_of_payment,
&self.p2p_node,
&self.paid_list,
&self.config,
&self.send_semaphore,
)
.await;
if !peers.is_empty() {
let _ = self
.possession_check_tx
.send(possession::PossessionCheckEvent { key: *key, peers });
}
}
fn start_fresh_write_drainer(&mut self) {
let Some(mut rx) = self.fresh_write_rx.take() else {
return;
};
let p2p = Arc::clone(&self.p2p_node);
let paid_list = Arc::clone(&self.paid_list);
let config = Arc::clone(&self.config);
let send_semaphore = Arc::clone(&self.send_semaphore);
let possession_tx = self.possession_check_tx.clone();
let shutdown = self.shutdown.clone();
let handle = tokio::spawn(async move {
loop {
tokio::select! {
() = shutdown.cancelled() => break,
event = rx.recv() => {
let Some(event) = event else { break };
let peers = fresh::replicate_fresh(
&event.key,
&event.data,
&event.payment_proof,
&p2p,
&paid_list,
&config,
&send_semaphore,
)
.await;
if !peers.is_empty() {
let _ = possession_tx.send(possession::PossessionCheckEvent {
key: event.key,
peers,
});
}
}
}
}
debug!("Fresh-write drainer shut down");
});
self.task_handles.push(handle);
}
fn start_possession_check_scheduler(&mut self) {
let Some(mut rx) = self.possession_check_rx.take() else {
return;
};
let p2p = Arc::clone(&self.p2p_node);
let storage = Arc::clone(&self.storage);
let config = Arc::clone(&self.config);
let sync_state = Arc::clone(&self.sync_state);
let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
let shutdown = self.shutdown.clone();
let detached_task_tracker = self.detached_task_tracker.clone();
let handle = tokio::spawn(async move {
loop {
tokio::select! {
() = shutdown.cancelled() => break,
event = rx.recv() => {
let Some(event) = event else { break };
let p2p = Arc::clone(&p2p);
let storage = Arc::clone(&storage);
let config = Arc::clone(&config);
let sync_state = Arc::clone(&sync_state);
let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
let shutdown = shutdown.clone();
let delay_min = config.possession_check_delay_min;
let delay_max = config.possession_check_delay_max;
detached_task_tracker.spawn(async move {
let delay = possession::random_delay(delay_min, delay_max);
tokio::select! {
() = shutdown.cancelled() => {}
() = async {
tokio::time::sleep(delay).await;
possession::run_possession_check(
event.key,
event.peers,
&p2p,
&storage,
&config,
&sync_state,
&audit_challenge_coordinator,
&shutdown,
)
.await;
} => {}
}
});
}
}
}
debug!("Possession-check scheduler shut down");
});
self.task_handles.push(handle);
}
#[allow(clippy::too_many_lines)]
fn start_first_audit_drainer(&mut self) {
let Some(mut rx) = self.monetized_pin_rx.take() else {
return;
};
let gossip_audit = GossipAuditTrigger {
p2p_node: Arc::clone(&self.p2p_node),
config: Arc::clone(&self.config),
recent_provers: Arc::clone(&self.recent_provers),
sync_state: Arc::clone(&self.sync_state),
cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
detached_task_tracker: self.detached_task_tracker.clone(),
lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
};
let shutdown = self.shutdown.clone();
let observability = Arc::clone(&self.first_audit_observability);
let self_peer = *self.p2p_node.peer_id();
let handle = tokio::spawn(async move {
let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut last_summary = Instant::now();
loop {
let promotion_due = scheduler
.reserved_ready_at()
.unwrap_or_else(first_audit_far_future);
tokio::select! {
() = shutdown.cancelled() => break,
event = rx.recv() => match event {
Some(e) => {
observability.received.fetch_add(1, Ordering::Relaxed);
if scheduler.would_displace(&e) {
open_first_audit_reservation(
&mut scheduler,
&gossip_audit.cooldown,
&observability,
)
.await;
}
scheduler.enqueue(e, &observability);
let mut drained = 1usize;
while drained < config::FIRST_AUDIT_DRAIN_BATCH {
match rx.try_recv() {
Ok(e) => {
observability.received.fetch_add(1, Ordering::Relaxed);
if scheduler.would_displace(&e) {
open_first_audit_reservation(
&mut scheduler,
&gossip_audit.cooldown,
&observability,
)
.await;
}
scheduler.enqueue(e, &observability);
drained += 1;
}
Err(_) => break,
}
}
}
None => break,
},
_ = tick.tick() => {}
() = tokio::time::sleep_until(promotion_due.into()) => {}
}
if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
let promoted = {
let mut cooldown = gossip_audit.cooldown.write().await;
scheduler.resolve(
reservation,
SystemTime::now(),
Instant::now(),
&mut cooldown,
&observability,
)
};
if let Some((event, inflight_slot)) = promoted {
debug!(
"First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
event.peer, hex::encode(event.pin), event.key_count,
observability.inflight.load(Ordering::Relaxed)
);
let trigger = gossip_audit.clone();
let audit_observability = Arc::clone(&observability);
let tracker = trigger.detached_task_tracker.clone();
tracker.spawn(async move {
let inflight_slot = inflight_slot;
let started = Instant::now();
let credit = storage_commitment_audit::AuditCredit {
recent_provers: &trigger.recent_provers,
};
let result = storage_commitment_audit::run_subtree_audit(
&trigger.p2p_node,
&trigger.config,
&event.peer,
event.pin,
event.key_count,
Some(&credit),
)
.await;
let outcome = first_audit_terminal_outcome(&result);
match outcome {
FirstAuditTerminalOutcome::Passed => {
audit_observability.passed.fetch_add(1, Ordering::Relaxed);
}
FirstAuditTerminalOutcome::Timeout => {
audit_observability
.timed_out
.fetch_add(1, Ordering::Relaxed);
}
FirstAuditTerminalOutcome::Failed => {
audit_observability.failed.fetch_add(1, Ordering::Relaxed);
}
FirstAuditTerminalOutcome::BootstrapClaim => {
audit_observability
.bootstrap_claims
.fetch_add(1, Ordering::Relaxed);
}
FirstAuditTerminalOutcome::Idle => {
audit_observability.idle.fetch_add(1, Ordering::Relaxed);
}
FirstAuditTerminalOutcome::InsufficientKeys => {
audit_observability
.insufficient_keys
.fetch_add(1, Ordering::Relaxed);
}
}
drop(inflight_slot);
debug!(
"First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
outcome.as_str(),
event.peer, hex::encode(event.pin), event.key_count,
started.elapsed().as_millis(),
audit_observability.inflight.load(Ordering::Relaxed)
);
handle_subtree_audit_result(
&result,
&trigger.p2p_node,
&trigger.sync_state,
&trigger.recent_provers,
&trigger.config,
)
.await;
});
}
}
open_first_audit_reservation(
&mut scheduler,
&gossip_audit.cooldown,
&observability,
)
.await;
if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
if swept > 0 {
debug!(
"First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
scheduler.pending_len()
);
}
info!(
"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={}",
FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
observability.received.load(Ordering::Relaxed),
observability.queued.load(Ordering::Relaxed),
observability.coalesced.load(Ordering::Relaxed),
observability.suppressed_lower.load(Ordering::Relaxed),
observability.duplicates.load(Ordering::Relaxed),
observability.capacity_evicted.load(Ordering::Relaxed),
observability.self_target_skipped.load(Ordering::Relaxed),
observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
observability.rate_deferred_attempts.load(Ordering::Relaxed),
observability.window_deduped.load(Ordering::Relaxed),
observability.launched.load(Ordering::Relaxed),
observability.passed.load(Ordering::Relaxed),
observability.timed_out.load(Ordering::Relaxed),
observability.failed.load(Ordering::Relaxed),
observability.bootstrap_claims.load(Ordering::Relaxed),
observability.idle.load(Ordering::Relaxed),
observability.insufficient_keys.load(Ordering::Relaxed),
observability.outside_answerability_window.load(Ordering::Relaxed),
scheduler.pending_len(),
FIRST_AUDIT_PENDING_CAP,
u8::from(scheduler.has_reservation()),
scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
observability.inflight.load(Ordering::Relaxed),
scheduler.tokens(),
);
last_summary = Instant::now();
}
}
debug!("First-audit drainer shut down");
});
self.task_handles.push(handle);
}
#[allow(clippy::too_many_lines)]
fn start_message_handler(&mut self) {
let mut p2p_events = self.p2p_node.subscribe_events();
let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
let p2p = Arc::clone(&self.p2p_node);
let storage = Arc::clone(&self.storage);
let paid_list = Arc::clone(&self.paid_list);
let payment_verifier = Arc::clone(&self.payment_verifier);
let queues = Arc::clone(&self.queues);
let config = Arc::clone(&self.config);
let shutdown = self.shutdown.clone();
let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
let bootstrap_state = Arc::clone(&self.bootstrap_state);
let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
let sync_history = Arc::clone(&self.sync_history);
let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
let repair_proofs = Arc::clone(&self.repair_proofs);
let sync_trigger = Arc::clone(&self.sync_trigger);
let my_commitment_state = Arc::clone(&self.commitment_state);
let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
let recent_provers = Arc::clone(&self.recent_provers);
let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
let sync_state = Arc::clone(&self.sync_state);
let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
let fetch_responder_admission_semaphore =
Arc::clone(&self.fetch_responder_admission_semaphore);
let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
let verification_responder_worker_semaphore =
Arc::clone(&self.verification_responder_worker_semaphore);
let verification_responder_admission_semaphore =
Arc::clone(&self.verification_responder_admission_semaphore);
let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
let neighbor_sync_responder_worker_semaphore =
Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
let neighbor_sync_responder_admission_semaphore =
Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
let detached_task_tracker = self.detached_task_tracker.clone();
let subtree_round1 = self.subtree_round1.clone();
let gossip_audit = GossipAuditTrigger {
p2p_node: Arc::clone(&p2p),
config: Arc::clone(&config),
recent_provers: Arc::clone(&recent_provers),
sync_state: Arc::clone(&sync_state),
cooldown: Arc::clone(&audit_on_gossip_cooldown),
detached_task_tracker: detached_task_tracker.clone(),
lottery_attempts: Arc::clone(&gossip_lottery_attempts),
};
let handler_context = ReplicationMessageHandlerContext {
p2p_node: Arc::clone(&p2p),
storage,
paid_list,
payment_verifier,
queues,
config: Arc::clone(&config),
is_bootstrapping,
bootstrap_state,
sync_history,
sync_cycle_epoch,
repair_proofs: Arc::clone(&repair_proofs),
last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
ever_capable_peers,
sig_verify_attempts: Arc::clone(&sig_verify_attempts),
my_commitment_state,
gossip_audit,
audit_responder_semaphore,
audit_responder_inflight,
audit_responder_metrics,
subtree_round1,
fetch_responder_worker_semaphore,
fetch_responder_admission_semaphore,
fetch_responder_inflight,
verification_responder_worker_semaphore,
verification_responder_admission_semaphore,
verification_responder_inflight,
neighbor_sync_responder_worker_semaphore,
neighbor_sync_responder_admission_semaphore,
neighbor_sync_responder_inflight,
fresh_offer_worker_semaphore,
fresh_offer_admission_semaphore,
fresh_offer_responder_inflight,
fresh_offer_in_flight,
paid_notify_worker_semaphore,
paid_notify_admission_semaphore,
paid_notify_responder_inflight,
shutdown: shutdown.clone(),
detached_task_tracker,
};
let (replication_tx, mut replication_rx) =
mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
let serial_context = handler_context.clone();
let serial_shutdown = shutdown.clone();
let serial_handle = tokio::spawn(async move {
loop {
tokio::select! {
() = serial_shutdown.cancelled() => break,
inbound = replication_rx.recv() => {
let Some(inbound) = inbound else { break };
let source = inbound.source;
match handle_replication_message(
&source,
inbound.msg,
&serial_context,
inbound.received_at,
inbound.rr_message_id.as_deref(),
)
.await
{
Ok(()) => {}
Err(e) => {
debug!("Replication message from {source} error: {e}");
}
}
}
}
}
debug!("Replication non-audit serial handler shut down");
});
self.task_handles.push(serial_handle);
let handle = tokio::spawn(async move {
loop {
tokio::select! {
() = shutdown.cancelled() => break,
event = p2p_events.recv() => {
let event = match event {
Ok(event) => event,
Err(error) => match handle_replication_event_recv_error(&error) {
ControlFlow::Continue(()) => continue,
ControlFlow::Break(()) => break,
},
};
let Some((source, payload, inbound_protocol, rr_message_id)) =
replication_payload_from_event(event)
else {
continue;
};
let received_at = Instant::now();
let msg = match ReplicationMessage::decode(&payload) {
Ok(msg) => msg,
Err(e) => {
debug!("Replication message from {source} decode error: {e}");
continue;
}
};
if !body_matches_protocol(&msg.body, inbound_protocol) {
debug!(
"Dropping replication body (variant {}) on protocol \
{inbound_protocol}: wrong id for its family \
(cross-version or misrouted)",
msg.body.variant_index()
);
continue;
}
if let Some(class) = audit_responder_class(&msg.body) {
handler_context
.audit_responder_metrics
.record_received(source, class);
}
let inbound = InboundReplicationMessage {
source,
msg,
rr_message_id,
received_at,
};
if matches!(
inbound.msg.body,
ReplicationMessageBody::AuditChallenge(_)
| ReplicationMessageBody::SubtreeAuditChallenge(_)
| ReplicationMessageBody::SubtreeSliceChallenge(_)
) {
let source = inbound.source;
match handle_replication_message(
&source,
inbound.msg,
&handler_context,
inbound.received_at,
inbound.rr_message_id.as_deref(),
)
.await
{
Ok(()) => {}
Err(e) => {
debug!("Replication message from {source} error: {e}");
}
}
continue;
}
if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
if dropped.audit_responder_class.is_some() {
handler_context
.audit_responder_metrics
.record_serial_queue_drop(dropped.source);
}
warn!(
message_class = dropped.message_class,
source = %dropped.source,
queue_depth = dropped.queue_depth,
reason = dropped.reason.as_str(),
"Replication serial-queue message dropped"
);
}
}
dht_event = dht_events.recv() => {
let dht_event = match dht_event {
Ok(event) => event,
Err(RecvError::Lagged(missed)) => {
warn!(
"Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
);
let self_id = *p2p.peer_id();
let neighbors = neighbor_sync::snapshot_close_neighbors(
&p2p,
&self_id,
config.neighbor_sync_scope,
)
.await;
let neighbor_set =
neighbors.iter().copied().collect::<HashSet<_>>();
let (requeued, sync_removals) = {
let mut state = sync_state.write().await;
let sync_removals =
state.retain_sync_peers(&neighbor_set);
let requeued = state.queue_priority_peers(neighbors);
(requeued, sync_removals)
};
if sync_removals > 0 {
debug!(
"Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
);
}
if requeued > 0 {
debug!(
"Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
);
sync_trigger.notify_one();
}
continue;
}
Err(RecvError::Closed) => {
warn!(
"DHT event stream closed on replication branch; stopping message handler"
);
break;
}
};
match dht_event {
DhtNetworkEvent::KClosestPeersChanged { old, new, .. } => {
let old_peers = old
.iter()
.take(config.neighbor_sync_scope)
.copied()
.collect::<HashSet<_>>();
let new_scoped = new
.iter()
.take(config.neighbor_sync_scope)
.copied()
.collect::<Vec<_>>();
let new_peers =
new_scoped.iter().copied().collect::<HashSet<_>>();
let entrants = new_scoped
.iter()
.copied()
.filter(|peer| !old_peers.contains(peer))
.collect::<Vec<_>>();
let entrant_count = entrants.len();
let (priority_insertions, sync_removals) = {
let mut state = sync_state.write().await;
let sync_removals = state.retain_sync_peers(&new_peers);
let priority_insertions = state.queue_priority_peers(entrants);
(priority_insertions, sync_removals)
};
if priority_insertions > 0 {
debug!(
"K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
);
} else {
debug!(
"K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
);
}
sync_trigger.notify_one();
}
DhtNetworkEvent::PeerRemoved { peer_id } => {
sync_state.write().await.remove_peer(&peer_id);
repair_proofs.write().await.remove_peer(&peer_id);
update_bootstrap_after_peer_removed(
&peer_id,
&handler_context.bootstrap_state,
&handler_context.queues,
&handler_context.is_bootstrapping,
&bootstrap_complete_notify,
)
.await;
last_commitment_by_peer.write().await.remove(&peer_id);
recent_provers.write().await.forget_peer(&peer_id);
sig_verify_attempts.write().await.remove(&peer_id);
audit_on_gossip_cooldown.write().await.remove(&peer_id);
gossip_lottery_attempts.write().await.remove(&peer_id);
}
_ => {}
}
}
}
}
debug!("Replication message handler shut down");
});
self.task_handles.push(handle);
}
fn start_neighbor_sync_loop(&mut self) {
let p2p = Arc::clone(&self.p2p_node);
let storage = Arc::clone(&self.storage);
let paid_list = Arc::clone(&self.paid_list);
let queues = Arc::clone(&self.queues);
let config = Arc::clone(&self.config);
let shutdown = self.shutdown.clone();
let sync_state = Arc::clone(&self.sync_state);
let sync_history = Arc::clone(&self.sync_history);
let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
let repair_proofs = Arc::clone(&self.repair_proofs);
let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
let bootstrap_state = Arc::clone(&self.bootstrap_state);
let sync_trigger = Arc::clone(&self.sync_trigger);
let commitment_state = Arc::clone(&self.commitment_state);
let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
let detached_task_tracker = self.detached_task_tracker.clone();
let gossip_audit = GossipAuditTrigger {
p2p_node: Arc::clone(&p2p),
config: Arc::clone(&config),
recent_provers: Arc::clone(&self.recent_provers),
sync_state: Arc::clone(&sync_state),
cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
detached_task_tracker,
lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
};
let handle = tokio::spawn(async move {
loop {
if !sync_state.read().await.has_priority_peers() {
let interval = config.random_neighbor_sync_interval();
tokio::select! {
() = shutdown.cancelled() => break,
() = tokio::time::sleep(interval) => {}
() = sync_trigger.notified() => {
debug!("Neighbor sync triggered by topology change");
}
}
}
tokio::select! {
() = shutdown.cancelled() => break,
() = run_neighbor_sync_round(
&p2p,
&storage,
&paid_list,
&queues,
&config,
&sync_state,
&sync_history,
&sync_cycle_epoch,
&repair_proofs,
&is_bootstrapping,
&bootstrap_state,
&commitment_state,
&last_commitment_by_peer,
&ever_capable_peers,
&sig_verify_attempts,
&audit_challenge_coordinator,
&gossip_audit,
) => {}
}
}
debug!("Neighbor sync loop shut down");
});
self.task_handles.push(handle);
}
fn start_self_lookup_loop(&mut self) {
let p2p = Arc::clone(&self.p2p_node);
let config = Arc::clone(&self.config);
let shutdown = self.shutdown.clone();
let handle = tokio::spawn(async move {
loop {
let interval = config.random_self_lookup_interval();
tokio::select! {
() = shutdown.cancelled() => break,
() = tokio::time::sleep(interval) => {
if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
debug!("Self-lookup failed: {e}");
}
}
}
}
debug!("Self-lookup loop shut down");
});
self.task_handles.push(handle);
}
fn start_audit_loop(&mut self) {
let p2p = Arc::clone(&self.p2p_node);
let storage = Arc::clone(&self.storage);
let config = Arc::clone(&self.config);
let shutdown = self.shutdown.clone();
let sync_history = Arc::clone(&self.sync_history);
let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
let repair_proofs = Arc::clone(&self.repair_proofs);
let bootstrap_state = Arc::clone(&self.bootstrap_state);
let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
let sync_state = Arc::clone(&self.sync_state);
let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
let handle = tokio::spawn(async move {
loop {
tokio::select! {
() = shutdown.cancelled() => return,
() = tokio::time::sleep(
std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
) => {
if bootstrap_state.read().await.is_drained() {
break;
}
}
}
}
{
let bootstrapping = *is_bootstrapping.read().await;
let result = {
let history = sync_history.read().await;
let current_sync_epoch = *sync_cycle_epoch.read().await;
audit::audit_tick_with_repair_proofs(
&p2p,
&storage,
&config,
&history,
&repair_proofs,
&audit_challenge_coordinator,
current_sync_epoch,
bootstrapping,
)
.await
};
handle_audit_result(&result, &p2p, &sync_state, &config).await;
}
loop {
let interval = config.random_audit_tick_interval();
tokio::select! {
() = shutdown.cancelled() => break,
() = tokio::time::sleep(interval) => {
let bootstrapping = *is_bootstrapping.read().await;
let result = {
let history = sync_history.read().await;
let current_sync_epoch = *sync_cycle_epoch.read().await;
audit::audit_tick_with_repair_proofs(
&p2p,
&storage,
&config,
&history,
&repair_proofs,
&audit_challenge_coordinator,
current_sync_epoch,
bootstrapping,
)
.await
};
handle_audit_result(&result, &p2p, &sync_state, &config).await;
}
}
}
debug!("Audit loop shut down");
});
self.task_handles.push(handle);
}
fn start_commitment_rotation_loop(&mut self) {
let storage = Arc::clone(&self.storage);
let identity = Arc::clone(&self.identity);
let commitment_state = Arc::clone(&self.commitment_state);
let shutdown = self.shutdown.clone();
let p2p = Arc::clone(&self.p2p_node);
let config = Arc::clone(&self.config);
let sync_trigger = Arc::clone(&self.sync_trigger);
let recent_provers = Arc::clone(&self.recent_provers);
let handle = tokio::spawn(async move {
if let Err(e) =
rebuild_and_rotate_commitment(&storage, &identity, &commitment_state, &p2p, &config)
.await
{
warn!("Initial commitment build failed: {e}");
} else {
sync_trigger.notify_one();
}
loop {
tokio::select! {
() = shutdown.cancelled() => break,
() = tokio::time::sleep(
std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
) => {
if let Err(e) = rebuild_and_rotate_commitment(
&storage,
&identity,
&commitment_state,
&p2p,
&config,
).await {
warn!("Commitment rotation failed: {e}");
}
let dropped = recent_provers.write().await.sweep_expired(
std::time::Instant::now()
);
if dropped > 0 {
debug!("recent_provers: swept {dropped} expired entries");
}
}
}
}
debug!("Commitment rotation loop shut down");
});
self.task_handles.push(handle);
}
fn start_retention_persist_loop(&mut self) {
let commitment_state = Arc::clone(&self.commitment_state);
let retention_path = self.retention_path.clone();
let shutdown = self.shutdown.clone();
let handle = tokio::spawn(async move {
let mut last: Option<Vec<u8>> = None;
persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
loop {
tokio::select! {
() = shutdown.cancelled() => {
persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
.await;
break;
}
() = tokio::time::sleep(std::time::Duration::from_secs(
RETENTION_PERSIST_INTERVAL_SECS,
)) => {
persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
.await;
}
}
}
debug!("Commitment retention persist loop shut down");
});
self.task_handles.push(handle);
}
fn start_traffic_summary_loop(&mut self) {
let shutdown = self.shutdown.clone();
let handle = tokio::spawn(async move {
loop {
tokio::select! {
() = shutdown.cancelled() => break,
() = tokio::time::sleep(std::time::Duration::from_secs(
TRAFFIC_SUMMARY_INTERVAL_SECS,
)) => {
protocol::log_traffic_summary();
protocol::log_served_peers_summary();
protocol::log_audit_outcome_summary();
audit_metrics::log_responder_admission_summary();
}
}
}
debug!("Replication traffic summary loop shut down");
});
self.task_handles.push(handle);
}
#[cfg(feature = "logging")]
fn start_bootstrap_state_snapshot_loop(&mut self) {
let shutdown = self.shutdown.clone();
let bootstrap_state = Arc::clone(&self.bootstrap_state);
let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
let started_at = Instant::now();
let handle = tokio::spawn(async move {
loop {
tokio::select! {
() = shutdown.cancelled() => break,
() = tokio::time::sleep(Duration::from_secs(
BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS,
)) => {
let (
drained,
pending_peer_requests,
pending_keys,
capacity_rejected_sources,
) = {
let state = bootstrap_state.read().await;
(
state.drained,
state.pending_peer_requests,
state.pending_keys.len(),
state.capacity_rejected_sources.len(),
)
};
let bootstrapping = *is_bootstrapping.read().await;
let snapshot_state = if drained && !bootstrapping {
"healthy"
} else if drained {
"drained_waiting_for_bootstrap_flag"
} else {
"pending"
};
info!(
drained,
pending_peer_requests,
pending_keys,
capacity_rejected_sources,
is_bootstrapping = bootstrapping,
snapshot_state,
uptime_secs = started_at.elapsed().as_secs(),
"Replication bootstrap state snapshot"
);
if drained && !bootstrapping {
info!(
"Replication bootstrap diagnostics reached healthy state; stopping periodic snapshots"
);
break;
}
}
}
}
debug!("Bootstrap state snapshot loop shut down");
});
self.task_handles.push(handle);
}
#[cfg(feature = "logging")]
fn start_audit_responder_summary_loop(&mut self) {
let shutdown = self.shutdown.clone();
let metrics = Arc::clone(&self.audit_responder_metrics);
let semaphore = Arc::clone(&self.audit_responder_semaphore);
let handle = tokio::spawn(async move {
let mut window_started = Instant::now();
loop {
tokio::select! {
() = shutdown.cancelled() => {
log_audit_responder_summary(
&metrics,
&semaphore,
window_started.elapsed(),
);
break;
}
() = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
log_audit_responder_summary(
&metrics,
&semaphore,
window_started.elapsed(),
);
window_started = Instant::now();
}
}
}
debug!("Audit responder summary loop shut down");
});
self.task_handles.push(handle);
}
#[allow(clippy::too_many_lines, clippy::option_if_let_else)]
fn start_fetch_worker(&mut self) {
let p2p = Arc::clone(&self.p2p_node);
let storage = Arc::clone(&self.storage);
let queues = Arc::clone(&self.queues);
let config = Arc::clone(&self.config);
let shutdown = self.shutdown.clone();
let bootstrap_state = Arc::clone(&self.bootstrap_state);
let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
let detached_task_tracker = self.detached_task_tracker.clone();
let concurrency = max_parallel_fetch();
info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
let handle = tokio::spawn(async move {
let mut in_flight = FuturesUnordered::<FetchFuture>::new();
loop {
{
let mut q = queues.write().await;
while in_flight.len() < concurrency {
let Some(candidate) = q.dequeue_fetch() else {
break;
};
let fetch_key = candidate.key;
let Some(&source) = candidate.sources.first() else {
warn!(
"Fetch candidate {} has no sources; requeueing for verification",
hex::encode(fetch_key)
);
let _ = q.requeue_candidate_for_verification(
candidate,
config.verification_request_timeout,
);
continue;
};
q.start_dequeued_fetch(candidate, source);
let p2p = Arc::clone(&p2p);
let storage = Arc::clone(&storage);
let config = Arc::clone(&config);
let token = shutdown.clone();
let tracker = detached_task_tracker.clone();
in_flight.push(Box::pin(async move {
let handle = tracker.spawn(async move {
tokio::select! {
() = token.cancelled() => FetchOutcome {
key: fetch_key,
result: FetchResult::SourceFailed,
},
outcome = execute_single_fetch(
p2p, storage, config, fetch_key, source,
) => outcome,
}
});
match handle.await {
Ok(outcome) => (outcome.key, Some(outcome)),
Err(e) => {
error!(
"Fetch task for {} panicked: {e}",
hex::encode(fetch_key)
);
(fetch_key, None)
}
}
}));
}
}
if in_flight.is_empty() {
tokio::select! {
() = shutdown.cancelled() => break,
() = tokio::time::sleep(
std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
) => continue,
}
}
tokio::select! {
() = shutdown.cancelled() => break,
Some((key, maybe_outcome)) = in_flight.next() => {
let mut q = queues.write().await;
let terminal = if let Some(outcome) = maybe_outcome {
match apply_fetch_result(
&mut q,
&key,
&outcome.result,
config.verification_request_timeout,
) {
FetchFollowUp::Terminal => true,
FetchFollowUp::RequeuedForVerification => false,
FetchFollowUp::RetryFrom(next_peer) => {
let p2p = Arc::clone(&p2p);
let storage = Arc::clone(&storage);
let config = Arc::clone(&config);
let token = shutdown.clone();
let tracker = detached_task_tracker.clone();
let fetch_key = key;
in_flight.push(Box::pin(async move {
let handle = tracker.spawn(async move {
tokio::select! {
() = token.cancelled() => FetchOutcome {
key: fetch_key,
result: FetchResult::SourceFailed,
},
outcome = execute_single_fetch(
p2p, storage, config, fetch_key, next_peer,
) => outcome,
}
});
match handle.await {
Ok(outcome) => (outcome.key, Some(outcome)),
Err(e) => {
error!(
"Fetch task for {} panicked: {e}",
hex::encode(fetch_key)
);
(fetch_key, None)
}
}
}));
false
}
}
} else {
!q.requeue_fetch_for_verification(
&key,
config.verification_request_timeout,
)
};
if terminal {
drop(q); if !bootstrap_state.read().await.is_drained() {
bootstrap_state.write().await.remove_key(&key);
let q = queues.read().await;
if bootstrap::check_bootstrap_drained(
&bootstrap_state,
&q,
)
.await
{
complete_bootstrap(
&is_bootstrapping,
&bootstrap_complete_notify,
).await;
}
}
}
}
}
}
while in_flight.next().await.is_some() {}
debug!("Fetch worker shut down");
});
self.task_handles.push(handle);
}
fn start_verification_worker(&mut self) {
let p2p = Arc::clone(&self.p2p_node);
let storage = Arc::clone(&self.storage);
let queues = Arc::clone(&self.queues);
let paid_list = Arc::clone(&self.paid_list);
let config = Arc::clone(&self.config);
let shutdown = self.shutdown.clone();
let bootstrap_state = Arc::clone(&self.bootstrap_state);
let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
let recent_provers = Arc::clone(&self.recent_provers);
let handle = tokio::spawn(async move {
loop {
tokio::select! {
() = shutdown.cancelled() => break,
() = tokio::time::sleep(
std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
) => {
let ctx = VerificationCycleContext {
p2p_node: &p2p,
paid_list: &paid_list,
storage: &storage,
queues: &queues,
config: &config,
bootstrap_state: &bootstrap_state,
is_bootstrapping: &is_bootstrapping,
bootstrap_complete_notify: &bootstrap_complete_notify,
last_commitment_by_peer: &last_commitment_by_peer,
ever_capable_peers: &ever_capable_peers,
recent_provers: &recent_provers,
};
run_verification_cycle(ctx).await;
}
}
}
debug!("Verification worker shut down");
});
self.task_handles.push(handle);
}
#[allow(clippy::too_many_lines)]
fn start_bootstrap_sync(
&mut self,
dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
) {
let p2p = Arc::clone(&self.p2p_node);
let storage = Arc::clone(&self.storage);
let paid_list = Arc::clone(&self.paid_list);
let queues = Arc::clone(&self.queues);
let config = Arc::clone(&self.config);
let shutdown = self.shutdown.clone();
let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
let bootstrap_state = Arc::clone(&self.bootstrap_state);
let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
let repair_proofs = Arc::clone(&self.repair_proofs);
let my_commitment_state = Arc::clone(&self.commitment_state);
let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
let handle = tokio::spawn(async move {
let gate = bootstrap::wait_for_bootstrap_complete(
dht_events,
config.bootstrap_complete_timeout_secs,
&shutdown,
)
.await;
if gate == bootstrap::BootstrapGateResult::Shutdown {
return;
}
let self_id = *p2p.peer_id();
let neighbors =
neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
.await;
if neighbors.is_empty() {
info!("Bootstrap sync: no close neighbors found, marking drained");
bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
return;
}
let neighbor_count = neighbors.len();
info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
if shutdown.is_cancelled() {
break;
}
let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
batch,
&storage,
&paid_list,
&p2p,
config.close_group_size,
config.paid_list_close_group_size,
)
.await;
bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
let bootstrapping = *is_bootstrapping.read().await;
let sync_futures = batch.iter().map(|peer| {
let peer = *peer;
let hints = hints_by_peer.remove(&peer).unwrap_or_default();
let commitment = my_commitment_state
.current_for_gossip()
.map(|binding| binding.commitment().clone());
let p2p = &p2p;
let config = &config;
async move {
let outcome = neighbor_sync::sync_with_peer_with_hints(
&peer,
p2p,
config,
bootstrapping,
hints,
commitment,
)
.await;
(peer, outcome)
}
});
let completed = join_all(sync_futures).await;
for (peer, outcome) in &completed {
if let Some(outcome) = outcome {
ingest_peer_commitment(
peer,
outcome.response.commitment.as_ref(),
&p2p,
&last_commitment_by_peer,
&ever_capable_peers,
&sig_verify_attempts,
)
.await;
if !outcome.response.bootstrapping {
record_sent_replica_hints(
peer,
&outcome.sent_replica_hints,
&repair_proofs,
&sync_cycle_epoch,
)
.await;
}
}
}
let pending_keys: HashSet<XorName> = {
let q = queues.read().await;
q.pending_keys().into_iter().collect()
};
let admission_futures = completed.iter().map(|(_, outcome)| async {
match outcome {
Some(outcome) if !outcome.response.bootstrapping => Some(
admission::admit_hints(
&self_id,
&outcome.response.replica_hints,
&outcome.response.paid_hints,
&p2p,
&config,
&storage,
&paid_list,
&pending_keys,
)
.await,
),
_ => None,
}
});
let admitted = join_all(admission_futures).await;
let (batch_outcomes, batch_discovered) = {
let mut q = queues.write().await;
let outcomes = completed
.iter()
.zip(admitted)
.filter_map(|((peer, _), admitted)| {
admitted.map(|admitted| {
(
*peer,
queue_admitted_hints(peer, admitted, &storage, &mut q),
)
})
})
.collect::<Vec<_>>();
let live_discovered = outcomes
.iter()
.flat_map(|(_, outcome)| outcome.discovered.iter().copied())
.filter(|key| q.contains_key(key))
.collect::<HashSet<_>>();
(outcomes, live_discovered)
};
publish_bootstrap_admission_outcomes(
&bootstrap_state,
&batch_outcomes,
&batch_discovered,
)
.await;
bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
}
{
let q = queues.read().await;
if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
}
}
info!("Bootstrap sync completed");
});
self.task_handles.push(handle);
}
}
#[cfg(feature = "logging")]
fn log_audit_responder_summary(
metrics: &AuditResponderMetrics,
semaphore: &Semaphore,
window: Duration,
) {
let snapshot = metrics.take_snapshot();
if snapshot.origins.is_empty() {
return;
}
let total = snapshot.total;
let [digest_received, subtree_received, byte_received, commitment_pin_received] =
total.received_by_class;
let global_inflight =
MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
info!(
target: "ant_node::replication::audit_responder",
window_ms = window.as_millis(),
source_count = snapshot.origins.len(),
received = total.received(),
digest_received,
subtree_received,
byte_received,
commitment_pin_received,
admitted = total.admitted,
global_pool_drops = total.global_pool_drops,
per_peer_cap_drops = total.per_peer_cap_drops,
serial_queue_drops = total.serial_queue_drops,
completed = total.completed,
send_failures = total.send_failures,
processing_avg_ms = total.processing_avg_ms(),
processing_max_ms = total.processing_max_ms,
total_avg_ms = total.total_avg_ms(),
total_max_ms = total.total_max_ms,
global_inflight,
global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
peak_global_inflight = total.peak_global_inflight,
"Audit responder summary"
);
for (index, origin) in snapshot
.origins
.iter()
.take(config::AUDIT_RESPONDER_TOP_ORIGINS)
.enumerate()
{
let Some(source) = origin.source else {
continue;
};
let [digest_received, subtree_received, byte_received, commitment_pin_received] =
origin.received_by_class;
info!(
target: "ant_node::replication::audit_responder",
rank = index + 1,
source = %source,
received = origin.received(),
digest_received,
subtree_received,
byte_received,
commitment_pin_received,
admitted = origin.admitted,
global_pool_drops = origin.global_pool_drops,
per_peer_cap_drops = origin.per_peer_cap_drops,
serial_queue_drops = origin.serial_queue_drops,
completed = origin.completed,
send_failures = origin.send_failures,
processing_avg_ms = origin.processing_avg_ms(),
processing_max_ms = origin.processing_max_ms,
total_avg_ms = origin.total_avg_ms(),
total_max_ms = origin.total_max_ms,
peak_global_inflight = origin.peak_global_inflight,
peak_peer_inflight = origin.peak_peer_inflight,
"Audit responder top origin"
);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ResponderRejectReason {
GlobalPoolFull,
PerPeerCapFull,
}
impl ResponderRejectReason {
fn as_str(self) -> &'static str {
match self {
Self::GlobalPoolFull => "global_pool_full",
Self::PerPeerCapFull => "per_peer_cap_full",
}
}
}
impl From<ResponderRejectReason> for AuditResponderDropReason {
fn from(reason: ResponderRejectReason) -> Self {
match reason {
ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
}
}
}
impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
fn from(reason: ResponderRejectReason) -> Self {
match reason {
ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
}
}
}
#[must_use]
pub fn fresh_offer_admission_refusals() -> u64 {
audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
}
#[must_use]
pub fn paid_notify_admission_refusals() -> u64 {
audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
}
#[must_use]
pub fn fresh_offer_refusals_global_pool() -> u64 {
audit_metrics::responder_admission_drops_by_ceiling(
ReplicationResponderClass::FreshOffer,
ResponderAdmissionCeiling::GlobalPool,
)
}
#[must_use]
pub fn fresh_offer_refusals_per_peer_share() -> u64 {
audit_metrics::responder_admission_drops_by_ceiling(
ReplicationResponderClass::FreshOffer,
ResponderAdmissionCeiling::PerPeerShare,
)
}
#[derive(Debug, Clone, Copy)]
struct ResponderAdmissionFailure {
reason: ResponderRejectReason,
global_inflight: usize,
global_limit: usize,
peer_inflight: u32,
peer_limit: u32,
}
impl fmt::Display for ResponderAdmissionFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
self.reason.as_str(),
self.global_inflight,
self.global_limit,
self.peer_inflight,
self.peer_limit,
)
}
}
struct ResponderGuard {
_permit: tokio::sync::OwnedSemaphorePermit,
_peer_slot: PeerResponderSlot,
global_inflight: usize,
peer_inflight: u32,
}
type AuditResponderGuard = ResponderGuard;
type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
struct PeerResponderSlot {
inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
peer: PeerId,
}
#[derive(Clone)]
struct ReplicationMessageHandlerContext {
p2p_node: Arc<P2PNode>,
storage: Arc<LmdbStorage>,
paid_list: Arc<PaidList>,
payment_verifier: Arc<PaymentVerifier>,
queues: Arc<RwLock<ReplicationQueues>>,
config: Arc<ReplicationConfig>,
is_bootstrapping: Arc<RwLock<bool>>,
bootstrap_state: Arc<RwLock<BootstrapState>>,
sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
sync_cycle_epoch: Arc<RwLock<u64>>,
repair_proofs: Arc<RwLock<RepairProofs>>,
last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
my_commitment_state: Arc<ResponderCommitmentState>,
gossip_audit: GossipAuditTrigger,
audit_responder_semaphore: Arc<Semaphore>,
audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
audit_responder_metrics: Arc<AuditResponderMetrics>,
subtree_round1: SubtreeRound1Limiter,
fetch_responder_worker_semaphore: Arc<Semaphore>,
fetch_responder_admission_semaphore: Arc<Semaphore>,
fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
verification_responder_worker_semaphore: Arc<Semaphore>,
verification_responder_admission_semaphore: Arc<Semaphore>,
verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
fresh_offer_worker_semaphore: Arc<Semaphore>,
fresh_offer_admission_semaphore: Arc<Semaphore>,
fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
fresh_offer_in_flight: FreshOfferInFlight,
paid_notify_worker_semaphore: Arc<Semaphore>,
paid_notify_admission_semaphore: Arc<Semaphore>,
paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
shutdown: CancellationToken,
detached_task_tracker: TaskTracker,
}
struct InboundReplicationMessage {
source: PeerId,
msg: ReplicationMessage,
rr_message_id: Option<String>,
received_at: Instant,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SerialQueueDropReason {
Full,
Closed,
}
#[cfg(feature = "logging")]
impl SerialQueueDropReason {
const fn as_str(self) -> &'static str {
match self {
Self::Full => "full",
Self::Closed => "closed",
}
}
}
#[derive(Debug, Clone, Copy)]
#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
struct SerialQueueDrop {
source: PeerId,
message_class: &'static str,
audit_responder_class: Option<AuditResponderClass>,
queue_depth: usize,
reason: SerialQueueDropReason,
}
fn try_enqueue_serial_message(
sender: &mpsc::Sender<InboundReplicationMessage>,
inbound: InboundReplicationMessage,
) -> std::result::Result<(), SerialQueueDrop> {
let source = inbound.source;
let message_class = replication_message_class(&inbound.msg.body);
let audit_responder_class = audit_responder_class(&inbound.msg.body);
let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
sender.try_send(inbound).map_err(|error| {
let (reason, dropped) = match error {
mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
};
audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
SerialQueueDrop {
source,
message_class,
audit_responder_class,
queue_depth,
reason,
}
})
}
const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
match body {
ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
ReplicationMessageBody::PaidNotify(_) => "paid_notify",
ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
ReplicationMessageBody::VerificationRequest(_) => "verification_request",
ReplicationMessageBody::VerificationResponse(_) => "verification_response",
ReplicationMessageBody::FetchRequest(_) => "fetch_request",
ReplicationMessageBody::FetchResponse(_) => "fetch_response",
ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
ReplicationMessageBody::AuditResponse(_) => "audit_response",
ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
}
}
const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
match body {
ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
_ => None,
}
}
impl AuditResponderClass {
const fn per_peer_limit(self) -> u32 {
match self {
Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
}
}
}
fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
match error {
RecvError::Lagged(missed) => {
audit_metrics::record_replication_event_lagged(*missed);
warn!(
"Missed {missed} P2P events on replication branch (broadcast lag); \
replication messages may have been dropped before dispatch"
);
ControlFlow::Continue(())
}
RecvError::Closed => {
warn!("P2P event stream closed on replication branch; stopping message handler");
ControlFlow::Break(())
}
}
}
fn replication_payload_from_event(
event: P2PEvent,
) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
let P2PEvent::Message {
topic,
source: Some(source),
data,
..
} = event
else {
return None;
};
let (matched_id, is_rr) = match_replication_protocol(&topic)?;
if !is_rr {
return Some((source, data, matched_id, None));
}
if is_rr {
return P2PNode::parse_request_envelope(&data)
.filter(|(_, is_resp, _)| !is_resp)
.map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
}
None
}
impl Drop for PeerResponderSlot {
fn drop(&mut self) {
let peer = self.peer;
if let Ok(mut map) = self.inflight.try_write() {
if let Some(n) = map.get_mut(&peer) {
*n = n.saturating_sub(1);
if *n == 0 {
map.remove(&peer);
}
}
return;
}
if let Ok(handle) = tokio::runtime::Handle::try_current() {
let inflight = Arc::clone(&self.inflight);
handle.spawn(async move {
let mut map = inflight.write().await;
if let Some(n) = map.get_mut(&peer) {
*n = n.saturating_sub(1);
if *n == 0 {
map.remove(&peer);
}
}
});
}
}
}
async fn admit_bounded_responder(
semaphore: &Arc<Semaphore>,
inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
source: &PeerId,
global_limit: usize,
peer_limit: u32,
) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
let admitted_peer_inflight = {
let mut map = inflight.write().await;
let entry = map.entry(*source).or_insert(0);
if *entry >= peer_limit {
let peer_inflight = *entry;
drop(map);
return Err(ResponderAdmissionFailure {
reason: ResponderRejectReason::PerPeerCapFull,
global_inflight: global_inflight(semaphore),
global_limit,
peer_inflight,
peer_limit,
});
}
*entry += 1;
*entry
};
let peer_slot = PeerResponderSlot {
inflight: Arc::clone(inflight),
peer: *source,
};
let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
return Err(ResponderAdmissionFailure {
reason: ResponderRejectReason::GlobalPoolFull,
global_inflight: global_inflight(semaphore),
global_limit,
peer_inflight: admitted_peer_inflight.saturating_sub(1),
peer_limit,
});
};
Ok(ResponderGuard {
_permit: permit,
_peer_slot: peer_slot,
global_inflight: global_inflight(semaphore),
peer_inflight: admitted_peer_inflight,
})
}
struct SubtreeSession {
commitment_hash: [u8; 32],
nonce: [u8; 32],
inserted: Instant,
}
struct Round1WorkBudget {
balance: i64,
last_refill: Instant,
}
impl Round1WorkBudget {
const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
const NANOS_PER_SEC: i64 = 1_000_000_000;
fn new() -> Self {
Self {
balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
last_refill: Instant::now(),
}
}
fn refill(&mut self, now: Instant) {
let elapsed = now.saturating_duration_since(self.last_refill);
self.last_refill = now;
let whole_secs = i64::try_from(elapsed.as_secs())
.unwrap_or(i64::MAX)
.saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
let sub_sec = i64::from(elapsed.subsec_nanos())
.saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
/ Self::NANOS_PER_SEC;
self.balance = self
.balance
.saturating_add(whole_secs.saturating_add(sub_sec))
.min(SUBTREE_ROUND1_WORK_BURST_BYTES);
}
fn has_budget(&mut self, now: Instant) -> bool {
self.refill(now);
self.balance > 0
}
fn charge(&mut self, bytes: i64, now: Instant) {
self.refill(now);
self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
}
}
#[derive(Clone)]
struct SubtreeRound1Limiter {
semaphore: Arc<Semaphore>,
max_concurrent: usize,
inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
cooldown_interval: Duration,
sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
work: Arc<RwLock<Round1WorkBudget>>,
}
impl SubtreeRound1Limiter {
fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
let max_concurrent = max_concurrent.max(1);
Self {
semaphore: Arc::new(Semaphore::new(max_concurrent)),
max_concurrent,
inflight: Arc::new(RwLock::new(HashMap::new())),
cooldown: Arc::new(RwLock::new(HashMap::new())),
cooldown_interval,
sessions: Arc::new(RwLock::new(HashMap::new())),
work: Arc::new(RwLock::new(Round1WorkBudget::new())),
}
}
async fn charge_work(&self, content_bytes: i64) {
self.work
.write()
.await
.charge(content_bytes, Instant::now());
}
async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
let guard = admit_bounded_responder(
&self.semaphore,
&self.inflight,
source,
self.max_concurrent,
MAX_SUBTREE_ROUND1_PER_PEER,
)
.await
.ok()?;
if !self.work.write().await.has_budget(Instant::now()) {
return None; }
let now = Instant::now();
let mut cooldown = self.cooldown.write().await;
if let Some(&last) = cooldown.get(source) {
if now.duration_since(last) < self.cooldown_interval {
return None; }
}
cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
if cooldown.len() >= MAX_SUBTREE_SESSIONS {
if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
cooldown.remove(&oldest);
}
}
cooldown.insert(*source, now);
Some(guard)
}
async fn open_session(
&self,
source: PeerId,
challenge_id: u64,
commitment_hash: [u8; 32],
nonce: [u8; 32],
) {
let now = Instant::now();
let mut sessions = self.sessions.write().await;
sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
if sessions.len() >= MAX_SUBTREE_SESSIONS {
if let Some(oldest) = sessions
.iter()
.min_by_key(|(_, e)| e.inserted)
.map(|(k, _)| *k)
{
sessions.remove(&oldest);
}
}
sessions.insert(
(source, challenge_id),
SubtreeSession {
commitment_hash,
nonce,
inserted: now,
},
);
}
async fn consume_session(
&self,
source: &PeerId,
challenge_id: u64,
commitment_hash: &[u8; 32],
nonce: &[u8; 32],
) -> bool {
let mut sessions = self.sessions.write().await;
let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
&& &e.commitment_hash == commitment_hash
&& &e.nonce == nonce
});
if matches {
sessions.remove(&(*source, challenge_id));
}
matches
}
}
enum SliceAdmission {
Admitted(AuditResponderGuard),
Capacity(AuditResponderAdmissionFailure),
NoSession,
}
async fn admit_slice_challenge(
semaphore: &Arc<Semaphore>,
inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
round1: &SubtreeRound1Limiter,
source: &PeerId,
challenge: &protocol::SubtreeSliceChallenge,
) -> SliceAdmission {
let guard =
match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
Ok(guard) => guard,
Err(failure) => return SliceAdmission::Capacity(failure),
};
if !round1
.consume_session(
source,
challenge.challenge_id,
&challenge.expected_commitment_hash,
&challenge.nonce,
)
.await
{
drop(guard);
return SliceAdmission::NoSession;
}
SliceAdmission::Admitted(guard)
}
async fn admit_audit_responder(
semaphore: &Arc<Semaphore>,
inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
source: &PeerId,
class: AuditResponderClass,
) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
let peer_limit = class.per_peer_limit();
admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
}
#[allow(clippy::too_many_lines)]
async fn handle_replication_message(
source: &PeerId,
msg: ReplicationMessage,
ctx: &ReplicationMessageHandlerContext,
received_at: Instant,
rr_message_id: Option<&str>,
) -> Result<()> {
match msg.body {
ReplicationMessageBody::FreshReplicationOffer(offer) => {
dispatch_fresh_offer(
*source,
offer,
ctx,
msg.request_id,
received_at,
rr_message_id,
)
.await
}
ReplicationMessageBody::PaidNotify(notify) => {
dispatch_paid_notify(*source, notify, ctx, received_at).await
}
ReplicationMessageBody::NeighborSyncRequest(request) => {
let bootstrapping = *ctx.is_bootstrapping.read().await;
if let Some(target) = ingest_peer_commitment(
source,
request.commitment.as_ref(),
&ctx.p2p_node,
&ctx.last_commitment_by_peer,
&ctx.ever_capable_peers,
&ctx.sig_verify_attempts,
)
.await
{
maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
}
dispatch_neighbor_sync_request(
*source,
request,
ctx,
bootstrapping,
ctx.my_commitment_state
.current_for_gossip()
.map(|b| b.commitment().clone()),
msg.request_id,
received_at,
rr_message_id,
)
.await
}
ReplicationMessageBody::VerificationRequest(request) => {
dispatch_verification_request(
*source,
request,
ctx,
msg.request_id,
received_at,
rr_message_id,
)
.await
}
ReplicationMessageBody::FetchRequest(request) => {
dispatch_fetch_request(
*source,
request,
ctx,
msg.request_id,
received_at,
rr_message_id,
)
.await
}
ReplicationMessageBody::AuditChallenge(challenge) => {
let class = AuditResponderClass::Digest;
let guard = match admit_audit_responder(
&ctx.audit_responder_semaphore,
&ctx.audit_responder_inflight,
source,
class,
)
.await
{
Ok(guard) => guard,
Err(failure) => {
protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
audit_metrics::record_admission_drop(class);
ctx.audit_responder_metrics
.record_drop(*source, failure.reason.into());
warn!(
target: "ant_node::replication::audit_responder",
event = "admission_dropped",
kind = "responsible",
responder_class = class.as_str(),
source = %source,
challenge_id = challenge.challenge_id,
key_count = challenge.keys.len(),
request_response = rr_message_id.is_some(),
dispatch_ms = received_at.elapsed().as_millis(),
reason = failure.reason.as_str(),
global_inflight = failure.global_inflight,
global_limit = failure.global_limit,
peer_inflight = failure.peer_inflight,
peer_limit = failure.peer_limit,
"Audit responder admission dropped"
);
return Ok(());
}
};
let admission_global_inflight = guard.global_inflight;
let admission_peer_inflight = guard.peer_inflight;
ctx.audit_responder_metrics.record_admitted(
*source,
admission_global_inflight,
admission_peer_inflight,
);
info!(
target: "ant_node::replication::audit_responder",
event = "admitted",
kind = "responsible",
responder_class = class.as_str(),
source = %source,
challenge_id = challenge.challenge_id,
key_count = challenge.keys.len(),
request_response = rr_message_id.is_some(),
dispatch_ms = received_at.elapsed().as_millis(),
global_inflight = admission_global_inflight,
global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
peer_inflight = admission_peer_inflight,
peer_limit = class.per_peer_limit(),
"Audit responder request admitted"
);
let bootstrapping = *ctx.is_bootstrapping.read().await;
let dispatch_latency = received_at.elapsed();
audit_metrics::record_digest_dispatch_latency(dispatch_latency);
debug!(
audit_type = "digest_responder",
dispatch_latency_ms = dispatch_latency.as_millis(),
source = %source,
"Audit challenge dispatch latency measured"
);
let storage = Arc::clone(&ctx.storage);
let p2p_node = Arc::clone(&ctx.p2p_node);
let source = *source;
let request_id = msg.request_id;
let rr_message_id = rr_message_id.map(ToOwned::to_owned);
let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
ctx.detached_task_tracker.spawn(async move {
let _guard = guard; let worker_started = Instant::now();
match handle_audit_challenge_msg(
&source,
&challenge,
&storage,
&p2p_node,
bootstrapping,
ReplyRoute {
request_id,
rr_message_id: rr_message_id.as_deref(),
protocol: REPLICATION_PROTOCOL_ID,
},
)
.await
{
Ok(completion) => log_audit_responder_completion(
&responder_metrics,
source,
class,
"responsible",
challenge.challenge_id,
challenge.keys.len(),
completion.response_kind,
completion.sent,
received_at,
worker_started,
completion.processing,
completion.response_send,
),
Err(e) => debug!("Audit challenge from {source} error: {e}"),
}
});
Ok(())
}
ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
let class = AuditResponderClass::Subtree;
info!(
"Audit challenge received: kind=subtree source={source} request_response={}",
rr_message_id.is_some(),
);
let Some(guard) = ctx.subtree_round1.admit(source).await else {
protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
warn!(
target: "ant_node::replication::audit_responder",
event = "admission_dropped",
kind = "subtree",
responder_class = class.as_str(),
source = %source,
challenge_id = challenge.challenge_id,
request_response = rr_message_id.is_some(),
dispatch_ms = received_at.elapsed().as_millis(),
reason = "heavy_pool_cooldown_or_work_budget",
"Audit responder admission dropped"
);
return Ok(());
};
let admission_global_inflight = guard.global_inflight;
let admission_peer_inflight = guard.peer_inflight;
ctx.audit_responder_metrics.record_admitted(
*source,
admission_global_inflight,
admission_peer_inflight,
);
info!(
target: "ant_node::replication::audit_responder",
event = "admitted",
kind = "subtree",
responder_class = class.as_str(),
source = %source,
challenge_id = challenge.challenge_id,
request_response = rr_message_id.is_some(),
dispatch_ms = received_at.elapsed().as_millis(),
global_inflight = admission_global_inflight,
global_limit = ctx.subtree_round1.max_concurrent,
peer_inflight = admission_peer_inflight,
peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
"Audit responder request admitted"
);
let bootstrapping = *ctx.is_bootstrapping.read().await;
let storage = Arc::clone(&ctx.storage);
let p2p_node = Arc::clone(&ctx.p2p_node);
let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
let source = *source;
let request_id = msg.request_id;
let rr_message_id = rr_message_id.map(ToOwned::to_owned);
let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
let subtree_round1 = ctx.subtree_round1.clone();
ctx.detached_task_tracker.spawn(async move {
let _guard = guard; let worker_started = Instant::now();
let processing_started = Instant::now();
let storage_commitment_audit::Round1Work {
response,
content_bytes,
} = storage_commitment_audit::handle_subtree_challenge_measured(
&challenge,
&storage,
p2p_node.peer_id(),
bootstrapping,
Some(&my_commitment_state),
)
.await;
let processing = processing_started.elapsed();
subtree_round1.charge_work(content_bytes).await;
if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
{
subtree_round1
.open_session(
source,
challenge.challenge_id,
challenge.expected_commitment_hash,
challenge.nonce,
)
.await;
}
let response_kind = subtree_audit_response_kind(&response);
let work_items = subtree_audit_response_work_items(&response);
let response_send_started = Instant::now();
let sent = send_replication_response_checked(
&source,
&p2p_node,
request_id,
ReplicationMessageBody::SubtreeAuditResponse(response),
rr_message_id.as_deref(),
None,
)
.await;
let response_send = response_send_started.elapsed();
log_audit_responder_completion(
&responder_metrics,
source,
class,
"subtree",
challenge.challenge_id,
work_items,
response_kind,
sent,
received_at,
worker_started,
processing,
response_send,
);
});
Ok(())
}
ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
let class = AuditResponderClass::Byte;
info!(
"Audit challenge received: kind=slice source={source} request_response={}",
rr_message_id.is_some(),
);
let guard = match admit_slice_challenge(
&ctx.audit_responder_semaphore,
&ctx.audit_responder_inflight,
&ctx.subtree_round1,
source,
&challenge,
)
.await
{
SliceAdmission::Admitted(guard) => guard,
SliceAdmission::Capacity(failure) => {
protocol::record_audit_drop(protocol::AuditDropKind::Slice);
audit_metrics::record_admission_drop(class);
ctx.audit_responder_metrics
.record_drop(*source, failure.reason.into());
warn!(
target: "ant_node::replication::audit_responder",
event = "admission_dropped",
kind = "byte",
responder_class = class.as_str(),
source = %source,
challenge_id = challenge.challenge_id,
key_count = challenge.openings.len(),
request_response = rr_message_id.is_some(),
dispatch_ms = received_at.elapsed().as_millis(),
reason = failure.reason.as_str(),
global_inflight = failure.global_inflight,
global_limit = failure.global_limit,
peer_inflight = failure.peer_inflight,
peer_limit = failure.peer_limit,
"Audit responder admission dropped"
);
return Ok(());
}
SliceAdmission::NoSession => {
protocol::record_audit_drop(protocol::AuditDropKind::Slice);
debug!(
"Slice challenge without a live round-1 session source={source} \
challenge_id={} → Transient reject",
challenge.challenge_id
);
send_replication_response_checked(
source,
&ctx.p2p_node,
msg.request_id,
ReplicationMessageBody::SubtreeSliceResponse(
protocol::SubtreeSliceResponse::Rejected {
challenge_id: challenge.challenge_id,
kind: protocol::RejectKind::Transient,
reason: "no live round-1 session".to_string(),
},
),
rr_message_id,
None,
)
.await;
return Ok(());
}
};
let admission_global_inflight = guard.global_inflight;
let admission_peer_inflight = guard.peer_inflight;
ctx.audit_responder_metrics.record_admitted(
*source,
admission_global_inflight,
admission_peer_inflight,
);
info!(
target: "ant_node::replication::audit_responder",
event = "admitted",
kind = "byte",
responder_class = class.as_str(),
source = %source,
challenge_id = challenge.challenge_id,
key_count = challenge.openings.len(),
request_response = rr_message_id.is_some(),
dispatch_ms = received_at.elapsed().as_millis(),
global_inflight = admission_global_inflight,
global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
peer_inflight = admission_peer_inflight,
peer_limit = class.per_peer_limit(),
"Audit responder request admitted"
);
let bootstrapping = *ctx.is_bootstrapping.read().await;
let storage = Arc::clone(&ctx.storage);
let p2p_node = Arc::clone(&ctx.p2p_node);
let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
let source = *source;
let request_id = msg.request_id;
let rr_message_id = rr_message_id.map(ToOwned::to_owned);
let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
ctx.detached_task_tracker.spawn(async move {
let _guard = guard; let worker_started = Instant::now();
let processing_started = Instant::now();
let response = storage_commitment_audit::handle_subtree_slice_challenge(
&challenge,
&storage,
p2p_node.peer_id(),
bootstrapping,
Some(&my_commitment_state),
)
.await;
let processing = processing_started.elapsed();
let response_kind = subtree_slice_response_kind(&response);
let response_send_started = Instant::now();
let sent = send_replication_response_checked(
&source,
&p2p_node,
request_id,
ReplicationMessageBody::SubtreeSliceResponse(response),
rr_message_id.as_deref(),
None,
)
.await;
let response_send = response_send_started.elapsed();
log_audit_responder_completion(
&responder_metrics,
source,
class,
"byte",
challenge.challenge_id,
challenge.openings.len(),
response_kind,
sent,
received_at,
worker_started,
processing,
response_send,
);
});
Ok(())
}
ReplicationMessageBody::GetCommitmentByPin(ref request) => {
let class = AuditResponderClass::CommitmentPin;
let guard = match admit_audit_responder(
&ctx.audit_responder_semaphore,
&ctx.audit_responder_inflight,
source,
class,
)
.await
{
Ok(guard) => guard,
Err(failure) => {
audit_metrics::record_admission_drop(class);
ctx.audit_responder_metrics
.record_drop(*source, failure.reason.into());
warn!(
target: "ant_node::replication::audit_responder",
event = "admission_dropped",
kind = "commitment_pin",
responder_class = class.as_str(),
source = %source,
challenge_id = msg.request_id,
request_response = rr_message_id.is_some(),
dispatch_ms = received_at.elapsed().as_millis(),
reason = failure.reason.as_str(),
global_inflight = failure.global_inflight,
global_limit = failure.global_limit,
peer_inflight = failure.peer_inflight,
peer_limit = failure.peer_limit,
"Audit responder admission dropped"
);
return Ok(());
}
};
ctx.audit_responder_metrics.record_admitted(
*source,
guard.global_inflight,
guard.peer_inflight,
);
info!(
target: "ant_node::replication::audit_responder",
event = "admitted",
kind = "commitment_pin",
responder_class = class.as_str(),
source = %source,
challenge_id = msg.request_id,
request_response = rr_message_id.is_some(),
dispatch_ms = received_at.elapsed().as_millis(),
global_inflight = guard.global_inflight,
global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
peer_inflight = guard.peer_inflight,
peer_limit = class.per_peer_limit(),
"Audit responder request admitted"
);
let worker_started = Instant::now();
let processing_started = Instant::now();
let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
|built| protocol::GetCommitmentByPinResponse::Found {
commitment: built.commitment().clone(),
},
);
let processing = processing_started.elapsed();
let response_kind = commitment_pin_response_kind(&response);
let response_send_started = Instant::now();
let sent = send_replication_response_checked(
source,
&ctx.p2p_node,
msg.request_id,
ReplicationMessageBody::GetCommitmentByPinResponse(response),
rr_message_id,
None,
)
.await;
let response_send = response_send_started.elapsed();
log_audit_responder_completion(
&ctx.audit_responder_metrics,
*source,
class,
"commitment_pin",
msg.request_id,
1,
response_kind,
sent,
received_at,
worker_started,
processing,
response_send,
);
drop(guard);
Ok(())
}
ReplicationMessageBody::FreshReplicationResponse(_)
| ReplicationMessageBody::NeighborSyncResponse(_)
| ReplicationMessageBody::VerificationResponse(_)
| ReplicationMessageBody::FetchResponse(_)
| ReplicationMessageBody::AuditResponse(_)
| ReplicationMessageBody::SubtreeAuditResponse(_)
| ReplicationMessageBody::SubtreeSliceResponse(_)
| ReplicationMessageBody::GetCommitmentByPinResponse(_) => Ok(()),
}
}
async fn verify_payment_until_shutdown(
payment_verifier: &Arc<PaymentVerifier>,
key: &XorName,
proof_of_payment: &[u8],
context: VerificationContext,
shutdown: &CancellationToken,
) -> Option<Result<crate::payment::PaymentStatus>> {
tokio::select! {
() = shutdown.cancelled() => None,
result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
Some(result)
}
}
}
struct FreshOfferRejection {
reason: String,
penalise: bool,
}
fn fresh_offer_structural_rejection(
key: &XorName,
data: &[u8],
proof_of_payment: &[u8],
) -> Option<FreshOfferRejection> {
if proof_of_payment.is_empty() {
return Some(FreshOfferRejection {
reason: "Missing proof of payment".to_string(),
penalise: true,
});
}
if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
return Some(FreshOfferRejection {
reason: format!(
"Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
proof_of_payment.len(),
),
penalise: true,
});
}
if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
return Some(FreshOfferRejection {
reason: format!(
"Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
proof_of_payment.len(),
),
penalise: true,
});
}
if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
return Some(FreshOfferRejection {
reason: format!(
"Data size {} exceeds maximum chunk size {}",
data.len(),
crate::ant_protocol::MAX_CHUNK_SIZE,
),
penalise: true,
});
}
let computed_key = crate::client::compute_address(data);
if computed_key != *key {
return Some(FreshOfferRejection {
reason: format!(
"Content address mismatch: expected {}, computed {}",
hex::encode(key),
hex::encode(computed_key),
),
penalise: true,
});
}
None
}
async fn refuse_fresh_offer(
source: &PeerId,
key: XorName,
reason: String,
ctx: &ReplicationMessageHandlerContext,
request_id: u64,
rr_message_id: Option<&str>,
) {
send_replication_response(
source,
&ctx.p2p_node,
request_id,
ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
key,
reason,
}),
rr_message_id,
)
.await;
}
async fn refuse_malformed_fresh_offer(
source: &PeerId,
key: XorName,
rejection: FreshOfferRejection,
ctx: &ReplicationMessageHandlerContext,
request_id: u64,
rr_message_id: Option<&str>,
) {
if rejection.penalise {
warn!(
"Rejecting fresh offer for key {} from {source}: {}",
hex::encode(key),
rejection.reason
);
ctx.p2p_node
.report_trust_event(
source,
TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
)
.await;
} else {
debug!(
"Fresh offer for {} from {source} refused before admission: {}",
hex::encode(key),
rejection.reason
);
}
refuse_fresh_offer(
source,
key,
rejection.reason,
ctx,
request_id,
rr_message_id,
)
.await;
}
async fn refuse_stranded_fresh_offers(
key: XorName,
stranded: Vec<FreshOfferAttempt>,
ctx: &ReplicationMessageHandlerContext,
) {
for attempt in stranded {
refuse_fresh_offer(
&attempt.source,
key,
"Receiver at fresh-offer capacity".to_string(),
ctx,
attempt.request_id,
attempt.rr_message_id.as_deref(),
)
.await;
}
}
async fn dispatch_fresh_offer(
source: PeerId,
offer: protocol::FreshReplicationOffer,
ctx: &ReplicationMessageHandlerContext,
request_id: u64,
received_at: Instant,
rr_message_id: Option<&str>,
) -> Result<()> {
if let Some(rejection) =
fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
{
refuse_malformed_fresh_offer(
&source,
offer.key,
rejection,
ctx,
request_id,
rr_message_id,
)
.await;
return Ok(());
}
let key = offer.key;
let admission_outcome = FreshOfferEntryGuard::admit(
&ctx.fresh_offer_in_flight,
offer,
source,
request_id,
rr_message_id.map(ToOwned::to_owned),
received_at,
);
let mut entry = match admission_outcome {
FreshOfferAdmission::Opened(entry) => entry,
FreshOfferAdmission::Joined => {
debug!(
"Fresh offer for {} from {source} queued behind the handler already \
holding the key",
hex::encode(key)
);
return Ok(());
}
surplus => {
debug!(
"Fresh offer for {} from {source} refused: {}",
hex::encode(key),
surplus.surplus_reason()
);
refuse_fresh_offer(
&source,
key,
"Duplicate offer already in flight".to_string(),
ctx,
request_id,
rr_message_id,
)
.await;
return Ok(());
}
};
let admission = match admit_bounded_responder(
&ctx.fresh_offer_admission_semaphore,
&ctx.fresh_offer_responder_inflight,
&source,
FRESH_OFFER_MAX_OUTSTANDING,
FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
)
.await
{
Ok(guard) => guard,
Err(failure) => {
audit_metrics::record_responder_admission_drop(
ReplicationResponderClass::FreshOffer,
failure.reason.into(),
);
warn!(
responder_class = "fresh_offer",
source = %source,
key = %hex::encode(key),
penalty_suspended = config::close_group_storage_penalty_suspended(),
"Fresh offer refused at admission; the resulting absence is recorded \
against this node, and penalised unless the release withholds it: \
{failure}"
);
let stranded = entry.release();
refuse_fresh_offer(
&source,
key,
"Receiver at fresh-offer capacity".to_string(),
ctx,
request_id,
rr_message_id,
)
.await;
refuse_stranded_fresh_offers(key, stranded, ctx).await;
return Ok(());
}
};
let ctx = ctx.clone();
ctx.detached_task_tracker
.clone()
.spawn(run_fresh_offer_worker(key, entry, ctx, admission));
Ok(())
}
async fn run_fresh_offer_worker(
key: XorName,
mut entry: Box<FreshOfferEntryGuard>,
ctx: ReplicationMessageHandlerContext,
admission: ResponderGuard,
) {
let _admission = admission;
let received_at = entry.received_at();
let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
.acquire_owned()
.await
else {
debug!(
"Fresh offer for {} dropped: worker pool shut down",
hex::encode(key)
);
return;
};
if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
debug!(
responder_class = "fresh_offer",
key = %hex::encode(key),
request_age_ms = received_at.elapsed().as_millis(),
"Superseded fresh offer shed at dequeue"
);
return;
}
let mut verdict = FreshOfferOutcome::Abandoned;
while let Some(attempt) = entry.next_attempt() {
match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
Ok(outcome) => {
verdict = outcome;
match outcome {
FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
FreshOfferOutcome::ProofRejected => {}
}
}
Err(e) => {
debug!(
"Fresh replication offer for {} from {} error: {e}",
hex::encode(key),
attempt.source
);
verdict = FreshOfferOutcome::Abandoned;
break;
}
}
}
let unreached = entry.release();
if unreached.is_empty() {
return;
}
let response = match verdict {
FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
FreshReplicationResponse::Rejected {
key,
reason: "Record could not be stored from any offered proof".to_string(),
}
}
};
for attempt in unreached {
send_replication_response(
&attempt.source,
&ctx.p2p_node,
attempt.request_id,
ReplicationMessageBody::FreshReplicationResponse(response.clone()),
attempt.rr_message_id.as_deref(),
)
.await;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FreshOfferOutcome {
Settled,
ProofRejected,
Abandoned,
}
#[allow(clippy::too_many_lines)]
async fn handle_fresh_offer(
key: &XorName,
data: &[u8],
attempt: &FreshOfferAttempt,
ctx: &ReplicationMessageHandlerContext,
) -> Result<FreshOfferOutcome> {
let source = &attempt.source;
let request_id = attempt.request_id;
let rr_message_id = attempt.rr_message_id.as_deref();
let p2p_node = &ctx.p2p_node;
let config = &ctx.config;
let self_id = *p2p_node.peer_id();
if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
{
if rejection.penalise {
warn!(
"Rejecting fresh offer for key {}: {}",
hex::encode(key),
rejection.reason
);
p2p_node
.report_trust_event(
source,
TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
)
.await;
}
send_replication_response(
source,
p2p_node,
request_id,
ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
key: *key,
reason: rejection.reason,
}),
rr_message_id,
)
.await;
return Ok(FreshOfferOutcome::ProofRejected);
}
if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
{
send_replication_response(
source,
p2p_node,
request_id,
ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
key: *key,
reason: "Not in storage-admission range for this key".to_string(),
}),
rr_message_id,
)
.await;
return Ok(FreshOfferOutcome::Abandoned);
}
if let Err(e) = ctx.storage.check_capacity() {
info!(
target: "ant_node::storage::disk_precheck",
key = %hex::encode(key),
"Rejecting fresh replication offer before payment verification: {e}"
);
send_replication_response(
source,
p2p_node,
request_id,
ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
key: *key,
reason: e.to_string(),
}),
rr_message_id,
)
.await;
return Ok(FreshOfferOutcome::Abandoned);
}
let Some(verification) = verify_payment_until_shutdown(
&ctx.payment_verifier,
key,
&attempt.proof_of_payment,
fresh_offer_payment_context(),
&ctx.shutdown,
)
.await
else {
debug!(
"Fresh offer for {} from {source} abandoned: engine shutting down \
during payment verification",
hex::encode(key)
);
return Ok(FreshOfferOutcome::Abandoned);
};
match verification {
Ok(status) if status.can_store() => {
debug!("PoP validated for fresh offer key {}", hex::encode(key));
}
Ok(_) => {
debug!(
"Fresh offer for {} from {source}: no payment found for this proof",
hex::encode(key)
);
send_replication_response(
source,
p2p_node,
request_id,
ReplicationMessageBody::FreshReplicationResponse(
FreshReplicationResponse::Rejected {
key: *key,
reason: "Payment verification failed: payment required".to_string(),
},
),
rr_message_id,
)
.await;
return Ok(FreshOfferOutcome::ProofRejected);
}
Err(e) => {
warn!("PoP verification error for key {}: {e}", hex::encode(key));
send_replication_response(
source,
p2p_node,
request_id,
ReplicationMessageBody::FreshReplicationResponse(
FreshReplicationResponse::Rejected {
key: *key,
reason: format!("Payment verification error: {e}"),
},
),
rr_message_id,
)
.await;
return Ok(FreshOfferOutcome::ProofRejected);
}
}
if let Err(e) = ctx.paid_list.insert(key).await {
warn!("Failed to add key to PaidForList: {e}");
}
match ctx.storage.put(key, data).await {
Ok(_) => {
send_replication_response(
source,
p2p_node,
request_id,
ReplicationMessageBody::FreshReplicationResponse(
FreshReplicationResponse::Accepted { key: *key },
),
rr_message_id,
)
.await;
Ok(FreshOfferOutcome::Settled)
}
Err(e) => {
send_replication_response(
source,
p2p_node,
request_id,
ReplicationMessageBody::FreshReplicationResponse(
FreshReplicationResponse::Rejected {
key: *key,
reason: e.to_string(),
},
),
rr_message_id,
)
.await;
Ok(FreshOfferOutcome::Abandoned)
}
}
}
async fn dispatch_paid_notify(
source: PeerId,
notify: protocol::PaidNotify,
ctx: &ReplicationMessageHandlerContext,
received_at: Instant,
) -> Result<()> {
let admission = match admit_bounded_responder(
&ctx.paid_notify_admission_semaphore,
&ctx.paid_notify_responder_inflight,
&source,
PAID_NOTIFY_MAX_OUTSTANDING,
PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
)
.await
{
Ok(guard) => guard,
Err(failure) => {
audit_metrics::record_responder_admission_drop(
ReplicationResponderClass::PaidNotify,
failure.reason.into(),
);
warn!(
responder_class = "paid_notify",
source = %source,
key = %hex::encode(notify.key),
"Paid notify dropped at admission — paid-list evidence lost until a verification cycle re-derives it: {failure}"
);
return Ok(());
}
};
let ctx = ctx.clone();
let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
let queue_max_age = ctx.config.neighbor_sync_interval_max;
ctx.detached_task_tracker.clone().spawn(async move {
let _admission = admission;
let Ok(_worker) = worker_semaphore.acquire_owned().await else {
debug!("Paid notify from {source} dropped: worker pool shut down");
return;
};
if request_is_stale(received_at, queue_max_age) {
debug!(
responder_class = "paid_notify",
source = %source,
request_age_ms = received_at.elapsed().as_millis(),
"Redundant paid notify shed at dequeue"
);
return;
}
if let Err(e) = handle_paid_notify(
&source,
¬ify,
&ctx.paid_list,
&ctx.payment_verifier,
&ctx.p2p_node,
&ctx.config,
&ctx.shutdown,
)
.await
{
debug!("Paid notify from {source} error: {e}");
}
});
Ok(())
}
async fn handle_paid_notify(
_source: &PeerId,
notify: &protocol::PaidNotify,
paid_list: &Arc<PaidList>,
payment_verifier: &Arc<PaymentVerifier>,
p2p_node: &Arc<P2PNode>,
config: &ReplicationConfig,
shutdown: &CancellationToken,
) -> Result<()> {
let self_id = *p2p_node.peer_id();
if notify.proof_of_payment.is_empty() {
return Ok(());
}
if !admission::is_in_paid_close_group(
&self_id,
¬ify.key,
p2p_node,
config.paid_list_close_group_size,
)
.await
{
return Ok(());
}
let Some(verification) = verify_payment_until_shutdown(
payment_verifier,
¬ify.key,
¬ify.proof_of_payment,
paid_notify_payment_context(),
shutdown,
)
.await
else {
debug!(
"Paid notify for {} abandoned: engine shutting down during payment \
verification",
hex::encode(notify.key)
);
return Ok(());
};
match verification {
Ok(status) if status.can_store() => {
debug!(
"PoP validated for paid notify key {}",
hex::encode(notify.key)
);
}
Ok(_) => {
warn!(
"Paid notify rejected: payment required for key {}",
hex::encode(notify.key)
);
return Ok(());
}
Err(e) => {
warn!(
"PoP verification error for paid notify key {}: {e}",
hex::encode(notify.key)
);
return Ok(());
}
}
if let Err(e) = paid_list.insert(¬ify.key).await {
warn!("Failed to add paid notify key to PaidForList: {e}");
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn dispatch_neighbor_sync_request(
source: PeerId,
request: protocol::NeighborSyncRequest,
ctx: &ReplicationMessageHandlerContext,
is_bootstrapping: bool,
my_commitment: Option<StorageCommitment>,
request_id: u64,
received_at: Instant,
rr_message_id: Option<&str>,
) -> Result<()> {
let guard = match admit_bounded_responder(
&ctx.neighbor_sync_responder_admission_semaphore,
&ctx.neighbor_sync_responder_inflight,
&source,
NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
)
.await
{
Ok(guard) => guard,
Err(failure) => {
audit_metrics::record_responder_admission_drop(
ReplicationResponderClass::NeighborSync,
failure.reason.into(),
);
warn!(
responder_class = "neighbor_sync",
source = %source,
"Neighbor-sync response dropped at admission: {failure}"
);
return Ok(());
}
};
let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
let p2p_node = Arc::clone(&ctx.p2p_node);
let storage = Arc::clone(&ctx.storage);
let paid_list = Arc::clone(&ctx.paid_list);
let queues = Arc::clone(&ctx.queues);
let config = Arc::clone(&ctx.config);
let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
let sync_history = Arc::clone(&ctx.sync_history);
let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
let repair_proofs = Arc::clone(&ctx.repair_proofs);
let request_timeout = ctx.config.verification_request_timeout;
let rr_message_id = rr_message_id.map(ToOwned::to_owned);
ctx.detached_task_tracker.spawn(async move {
let _guard = guard;
let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
debug!(
responder_class = "neighbor_sync",
source = %source,
"Neighbor-sync responder worker pool closed before dequeue"
);
return;
};
if request_is_stale(received_at, request_timeout) {
audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
debug!(
responder_class = "neighbor_sync",
source = %source,
request_age_ms = received_at.elapsed().as_millis(),
"Stale neighbor-sync request shed at dequeue"
);
return;
}
if let Err(e) = handle_neighbor_sync_request(
&source,
&request,
&p2p_node,
&storage,
&paid_list,
&queues,
&config,
is_bootstrapping,
&bootstrap_state,
&sync_history,
&sync_cycle_epoch,
&repair_proofs,
my_commitment,
request_id,
rr_message_id.as_deref(),
)
.await
{
debug!(source = %source, "Neighbor-sync request handling failed: {e}");
}
});
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn handle_neighbor_sync_request(
source: &PeerId,
request: &protocol::NeighborSyncRequest,
p2p_node: &Arc<P2PNode>,
storage: &Arc<LmdbStorage>,
paid_list: &Arc<PaidList>,
queues: &Arc<RwLock<ReplicationQueues>>,
config: &ReplicationConfig,
is_bootstrapping: bool,
bootstrap_state: &Arc<RwLock<BootstrapState>>,
sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
sync_cycle_epoch: &Arc<RwLock<u64>>,
repair_proofs: &Arc<RwLock<RepairProofs>>,
my_commitment: Option<StorageCommitment>,
request_id: u64,
rr_message_id: Option<&str>,
) -> Result<()> {
let self_id = *p2p_node.peer_id();
let (response, sent_replica_hints, sender_in_rt) =
neighbor_sync::handle_sync_request_with_proofs(
source,
request,
p2p_node,
storage,
paid_list,
config,
is_bootstrapping,
my_commitment.clone(),
)
.await;
let response_sent = send_replication_response_checked(
source,
p2p_node,
request_id,
ReplicationMessageBody::NeighborSyncResponse(response),
rr_message_id,
None,
)
.await;
if !sender_in_rt {
return Ok(());
}
{
let mut history = sync_history.write().await;
let record = history.entry(*source).or_insert(PeerSyncRecord {
last_sync: None,
cycles_since_sync: 0,
});
record.last_sync = Some(Instant::now());
record.cycles_since_sync = 0;
}
if response_sent && !request.bootstrapping {
record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
.await;
}
let outcome = admit_and_queue_hints(
&self_id,
source,
&request.replica_hints,
&request.paid_hints,
p2p_node,
config,
storage,
paid_list,
queues,
)
.await;
if is_bootstrapping {
let live_discovered = outcome.discovered.clone();
let outcomes = [(*source, outcome)];
publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
}
Ok(())
}
#[cfg(any(test, feature = "test-utils"))]
type VerificationWatch = HashMap<XorName, HashMap<PeerId, usize>>;
#[cfg(any(test, feature = "test-utils"))]
static VERIFICATION_WATCH: std::sync::OnceLock<std::sync::RwLock<VerificationWatch>> =
std::sync::OnceLock::new();
#[cfg(any(test, feature = "test-utils"))]
fn verification_watch() -> &'static std::sync::RwLock<VerificationWatch> {
VERIFICATION_WATCH.get_or_init(|| std::sync::RwLock::new(HashMap::new()))
}
#[cfg(any(test, feature = "test-utils"))]
pub fn watch_verification_requests_for_test(keys: &[XorName]) {
if let Ok(mut watch) = verification_watch().write() {
watch.clear();
for key in keys {
watch.insert(*key, HashMap::new());
}
}
}
#[cfg(any(test, feature = "test-utils"))]
pub(crate) fn record_verification_request_sent(requester: &PeerId, keys: &[XorName]) {
match verification_watch().read() {
Ok(watch) if watch.is_empty() => return,
Ok(watch) if !keys.iter().any(|key| watch.contains_key(key)) => return,
Ok(_) => {}
Err(_) => return,
}
if let Ok(mut watch) = verification_watch().write() {
for key in keys {
if let Some(by_peer) = watch.get_mut(key) {
*by_peer.entry(*requester).or_insert(0) += 1;
}
}
}
}
#[cfg(any(test, feature = "test-utils"))]
#[must_use]
pub fn verification_requests_for_key_from_for_test(requester: &PeerId, key: &XorName) -> usize {
verification_watch().read().map_or(0, |watch| {
watch
.get(key)
.and_then(|by_peer| by_peer.get(requester))
.copied()
.unwrap_or(0)
})
}
async fn handle_verification_request(
source: &PeerId,
request: &protocol::VerificationRequest,
storage: &Arc<LmdbStorage>,
paid_list: &Arc<PaidList>,
p2p_node: &Arc<P2PNode>,
request_id: u64,
rr_message_id: Option<&str>,
) -> Result<()> {
#[derive(Clone, Copy)]
enum CachedPaidLookup {
NotChecked,
Checked(Option<bool>),
}
#[derive(Clone, Copy)]
struct CachedVerificationLookup {
present: Option<bool>,
paid: CachedPaidLookup,
}
if verification_request_exceeds_limit(request.keys.len()) {
warn!(
"Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
request.keys.len(),
);
send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
return Ok(());
}
let requested_keys = request.keys.as_slice();
if request.paid_list_check_indices.len() > request.keys.len() {
warn!(
"Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
request.paid_list_check_indices.len(),
request.keys.len(),
);
send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
return Ok(());
}
let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
let paid_check_set: HashSet<u32> = request
.paid_list_check_indices
.iter()
.copied()
.filter(|&idx| {
if idx >= keys_len {
warn!(
"Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
requested_keys.len(),
);
false
} else {
true
}
})
.collect();
let mut results = Vec::with_capacity(requested_keys.len());
let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
for (i, key) in requested_keys.iter().enumerate() {
let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
let cached = lookup_cache.entry(*key).or_insert_with(|| {
let present = match storage.exists(key) {
Ok(present) => Some(present),
Err(e) => {
warn!(
"Verification request from {source}: failed to check storage for {}: {e}",
hex::encode(key)
);
None
}
};
CachedVerificationLookup {
present,
paid: CachedPaidLookup::NotChecked,
}
});
if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
Ok(paid) => Some(paid),
Err(e) => {
warn!(
"Verification request from {source}: failed to check paid-list for {}: {e}",
hex::encode(key)
);
None
}
});
}
let paid = if needs_paid {
match cached.paid {
CachedPaidLookup::Checked(paid) => paid,
CachedPaidLookup::NotChecked => None,
}
} else {
None
};
if cached.present.is_none() && paid.is_none() {
continue;
}
results.push(protocol::KeyVerificationResult {
key: *key,
present: cached.present.unwrap_or(false),
paid,
});
}
send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
Ok(())
}
async fn dispatch_verification_request(
source: PeerId,
request: protocol::VerificationRequest,
ctx: &ReplicationMessageHandlerContext,
request_id: u64,
received_at: Instant,
rr_message_id: Option<&str>,
) -> Result<()> {
let guard = match admit_bounded_responder(
&ctx.verification_responder_admission_semaphore,
&ctx.verification_responder_inflight,
&source,
VERIFICATION_RESPONDER_MAX_OUTSTANDING,
VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
)
.await
{
Ok(guard) => guard,
Err(failure) => {
audit_metrics::record_responder_admission_drop(
ReplicationResponderClass::Verification,
failure.reason.into(),
);
warn!(
responder_class = "verification",
source = %source,
"Verification response dropped at admission: {failure}"
);
return Ok(());
}
};
let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
let storage = Arc::clone(&ctx.storage);
let paid_list = Arc::clone(&ctx.paid_list);
let p2p_node = Arc::clone(&ctx.p2p_node);
let request_timeout = ctx.config.verification_request_timeout;
let rr_message_id = rr_message_id.map(ToOwned::to_owned);
ctx.detached_task_tracker.spawn(async move {
let _guard = guard;
let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
debug!(
responder_class = "verification",
source = %source,
"Verification responder worker pool closed before dequeue"
);
return;
};
if request_is_stale(received_at, request_timeout) {
audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
debug!(
responder_class = "verification",
source = %source,
request_age_ms = received_at.elapsed().as_millis(),
"Stale verification request shed at dequeue"
);
return;
}
if let Err(e) = handle_verification_request(
&source,
&request,
&storage,
&paid_list,
&p2p_node,
request_id,
rr_message_id.as_deref(),
)
.await
{
debug!(source = %source, "Verification request handling failed: {e}");
}
});
Ok(())
}
const fn verification_request_exceeds_limit(key_count: usize) -> bool {
key_count > MAX_INCOMING_VERIFICATION_KEYS
}
async fn send_verification_results(
source: &PeerId,
p2p_node: &Arc<P2PNode>,
request_id: u64,
results: Vec<protocol::KeyVerificationResult>,
rr_message_id: Option<&str>,
) {
send_replication_response(
source,
p2p_node,
request_id,
ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
rr_message_id,
)
.await;
}
async fn dispatch_fetch_request(
source: PeerId,
request: protocol::FetchRequest,
ctx: &ReplicationMessageHandlerContext,
request_id: u64,
received_at: Instant,
rr_message_id: Option<&str>,
) -> Result<()> {
let guard = match admit_bounded_responder(
&ctx.fetch_responder_admission_semaphore,
&ctx.fetch_responder_inflight,
&source,
FETCH_RESPONDER_MAX_OUTSTANDING,
FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
)
.await
{
Ok(guard) => guard,
Err(failure) => {
audit_metrics::record_responder_admission_drop(
ReplicationResponderClass::Fetch,
failure.reason.into(),
);
warn!(
responder_class = "fetch",
source = %source,
"Fetch response dropped at admission: {failure}"
);
return Ok(());
}
};
let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
let storage = Arc::clone(&ctx.storage);
let p2p_node = Arc::clone(&ctx.p2p_node);
let request_timeout = ctx.config.fetch_request_timeout;
let rr_message_id = rr_message_id.map(ToOwned::to_owned);
ctx.detached_task_tracker.spawn(async move {
let _guard = guard;
let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
debug!(
responder_class = "fetch",
source = %source,
"Fetch responder worker pool closed before dequeue"
);
return;
};
if request_is_stale(received_at, request_timeout) {
audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
debug!(
responder_class = "fetch",
source = %source,
request_age_ms = received_at.elapsed().as_millis(),
"Stale fetch request shed at dequeue"
);
return;
}
if let Err(e) = handle_fetch_request(
&source,
&request,
&storage,
&p2p_node,
request_id,
rr_message_id.as_deref(),
)
.await
{
debug!(source = %source, "Fetch request handling failed: {e}");
}
});
Ok(())
}
fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
received_at.elapsed() >= timeout
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FetchFault {
UnheldChunk,
ResponderFault,
}
fn fetch_fault_for(response: &protocol::FetchResponse) -> Option<FetchFault> {
match response {
protocol::FetchResponse::Success { .. } => None,
protocol::FetchResponse::NotFound { .. } => Some(FetchFault::UnheldChunk),
protocol::FetchResponse::Error { .. } => Some(FetchFault::ResponderFault),
}
}
async fn charge_fetch_fault(
p2p_node: &Arc<P2PNode>,
source: &PeerId,
fault: FetchFault,
lane: &'static str,
) {
match fault {
FetchFault::UnheldChunk => {
config::penalise_unheld_close_group_chunk(
p2p_node,
source,
lane,
REPLICATION_TRUST_WEIGHT,
)
.await;
}
FetchFault::ResponderFault => {
p2p_node
.report_trust_event(
source,
TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
)
.await;
}
}
}
fn fetch_response_for(key: XorName, read: Result<Option<Vec<u8>>>) -> protocol::FetchResponse {
match read {
Ok(Some(data)) => protocol::FetchResponse::Success { key, data },
Ok(None) => protocol::FetchResponse::NotFound { key },
Err(e) => protocol::FetchResponse::Error {
key,
reason: format!("{e}"),
},
}
}
async fn handle_fetch_request(
source: &PeerId,
request: &protocol::FetchRequest,
storage: &Arc<LmdbStorage>,
p2p_node: &Arc<P2PNode>,
request_id: u64,
rr_message_id: Option<&str>,
) -> Result<()> {
let response = fetch_response_for(request.key, storage.get(&request.key).await);
send_replication_response(
source,
p2p_node,
request_id,
ReplicationMessageBody::FetchResponse(response),
rr_message_id,
)
.await;
Ok(())
}
struct AuditResponderCompletion {
response_kind: &'static str,
sent: bool,
processing: Duration,
response_send: Duration,
}
async fn handle_audit_challenge_msg(
source: &PeerId,
challenge: &protocol::AuditChallenge,
storage: &Arc<LmdbStorage>,
p2p_node: &Arc<P2PNode>,
is_bootstrapping: bool,
reply: ReplyRoute<'_>,
) -> Result<AuditResponderCompletion> {
#[allow(clippy::cast_possible_truncation)]
let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
info!(
"Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
challenge.keys.len(),
is_bootstrapping,
reply.rr_message_id.is_some(),
);
let processing_started = Instant::now();
let response = audit::handle_audit_challenge(
challenge,
storage,
p2p_node.peer_id(),
is_bootstrapping,
stored_chunks,
)
.await;
let processing = processing_started.elapsed();
let response_kind = audit_response_kind(&response);
let response_send_started = Instant::now();
let sent = send_replication_response_checked(
source,
p2p_node,
reply.request_id,
ReplicationMessageBody::AuditResponse(response),
reply.rr_message_id,
Some(reply.protocol),
)
.await;
let response_send = response_send_started.elapsed();
Ok(AuditResponderCompletion {
response_kind,
sent,
processing,
response_send,
})
}
#[allow(clippy::too_many_arguments)]
fn log_audit_responder_completion(
metrics: &AuditResponderMetrics,
source: PeerId,
class: AuditResponderClass,
kind: &'static str,
challenge_id: u64,
work_items: usize,
response_kind: &'static str,
sent: bool,
received_at: Instant,
worker_started: Instant,
processing: Duration,
response_send: Duration,
) {
let dispatch = worker_started.saturating_duration_since(received_at);
let total = received_at.elapsed();
metrics.record_completed(source, processing, total, sent);
if sent {
info!(
target: "ant_node::replication::audit_responder",
event = "completed",
kind,
responder_class = class.as_str(),
source = %source,
challenge_id,
work_items,
response = response_kind,
sent,
dispatch_ms = dispatch.as_millis(),
processing_ms = processing.as_millis(),
response_send_ms = response_send.as_millis(),
total_ms = total.as_millis(),
"Audit responder request completed"
);
} else {
warn!(
target: "ant_node::replication::audit_responder",
event = "completed",
kind,
responder_class = class.as_str(),
source = %source,
challenge_id,
work_items,
response = response_kind,
sent,
dispatch_ms = dispatch.as_millis(),
processing_ms = processing.as_millis(),
response_send_ms = response_send.as_millis(),
total_ms = total.as_millis(),
"Audit responder request completed without sending a reply"
);
}
}
struct ReplyRoute<'a> {
request_id: u64,
rr_message_id: Option<&'a str>,
protocol: &'static str,
}
fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
match response {
protocol::AuditResponse::Digests { .. } => "digests",
protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
protocol::AuditResponse::Rejected { .. } => "rejected",
}
}
fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
match response {
protocol::SubtreeAuditResponse::Proof { .. } => "proof",
protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
}
}
fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
match response {
protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
protocol::SubtreeAuditResponse::Bootstrapping { .. }
| protocol::SubtreeAuditResponse::Rejected { .. } => 0,
}
}
fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
match response {
protocol::SubtreeSliceResponse::Items { .. } => "items",
protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
}
}
fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
match response {
protocol::GetCommitmentByPinResponse::Found { .. } => "found",
protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
}
}
async fn send_replication_response(
peer: &PeerId,
p2p_node: &Arc<P2PNode>,
request_id: u64,
body: ReplicationMessageBody,
rr_message_id: Option<&str>,
) {
let _ =
send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
.await;
}
async fn send_replication_response_checked(
peer: &PeerId,
p2p_node: &Arc<P2PNode>,
request_id: u64,
body: ReplicationMessageBody,
rr_message_id: Option<&str>,
protocol: Option<&'static str>,
) -> bool {
let msg = ReplicationMessage { request_id, body };
let encoded = match msg.encode() {
Ok(data) => data,
Err(e) => {
warn!("Failed to encode replication response: {e}");
return false;
}
};
if matches!(
msg.body,
ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
) {
protocol::record_served(peer, encoded.len());
}
let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
let result = if let Some(msg_id) = rr_message_id {
p2p_node
.send_response(peer, protocol, msg_id, encoded)
.await
} else {
p2p_node.send_message(peer, protocol, encoded, &[]).await
};
if let Err(e) = result {
debug!("Failed to send replication response to {peer}: {e}");
return false;
}
true
}
async fn record_sent_replica_hints(
peer: &PeerId,
hints: &[neighbor_sync::SentReplicaHint],
repair_proofs: &Arc<RwLock<RepairProofs>>,
sync_cycle_epoch: &Arc<RwLock<u64>>,
) {
if hints.is_empty() {
return;
}
let hinted_at_epoch = *sync_cycle_epoch.read().await;
let mut proofs = repair_proofs.write().await;
for hint in hints {
if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
debug!(
"Recorded repair hint proof for peer {peer} and key {}",
hex::encode(hint.key)
);
}
}
}
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
async fn run_neighbor_sync_round(
p2p_node: &Arc<P2PNode>,
storage: &Arc<LmdbStorage>,
paid_list: &Arc<PaidList>,
queues: &Arc<RwLock<ReplicationQueues>>,
config: &ReplicationConfig,
sync_state: &Arc<RwLock<NeighborSyncState>>,
sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
sync_cycle_epoch: &Arc<RwLock<u64>>,
repair_proofs: &Arc<RwLock<RepairProofs>>,
is_bootstrapping: &Arc<RwLock<bool>>,
bootstrap_state: &Arc<RwLock<BootstrapState>>,
commitment_state: &Arc<ResponderCommitmentState>,
last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
gossip_audit: &GossipAuditTrigger,
) {
let self_id = *p2p_node.peer_id();
let bootstrapping = *is_bootstrapping.read().await;
let cycle_complete = sync_state.read().await.is_cycle_complete();
if cycle_complete {
{
let mut history = sync_history.write().await;
for record in history.values_mut() {
record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
}
}
{
let mut epoch = sync_cycle_epoch.write().await;
*epoch = epoch.saturating_add(1);
}
let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
pruning::run_prune_pass_with_context(pruning::PrunePassContext {
self_id: &self_id,
storage,
paid_list,
p2p_node,
config,
sync_state,
repair_proofs,
allow_remote_prune_audits,
commitment_state: Some(commitment_state),
audit_challenge_coordinator,
})
.await;
let neighbors =
neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
.await;
let mut state = sync_state.write().await;
if state.is_cycle_complete() {
let old_sync_times = std::mem::take(&mut state.last_sync_times);
let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
let old_prune_cursor = state.prune_cursor;
*state = NeighborSyncState::new_cycle(neighbors);
state.last_sync_times = old_sync_times;
state.bootstrap_claims = old_bootstrap_claims;
state.bootstrap_claim_history = old_bootstrap_claim_history;
state.prune_cursor = old_prune_cursor;
}
}
let batch = {
let mut state = sync_state.write().await;
neighbor_sync::select_sync_batch(
&mut state,
config.neighbor_sync_peer_count,
config.neighbor_sync_cooldown,
)
};
if batch.is_empty() {
return;
}
debug!("Neighbor sync: syncing with {} peers", batch.len());
let my_commitment = commitment_state
.current_for_gossip()
.map(|b| b.commitment().clone());
let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
&batch,
storage,
paid_list,
p2p_node,
config.close_group_size,
config.paid_list_close_group_size,
)
.await;
for peer in &batch {
let hints = hints_by_peer.remove(peer).unwrap_or_default();
let outcome = neighbor_sync::sync_with_peer_with_hints(
peer,
p2p_node,
config,
bootstrapping,
hints,
my_commitment.clone(),
)
.await;
if let Some(outcome) = outcome {
handle_sync_response(
&self_id,
peer,
&outcome.response,
&outcome.sent_replica_hints,
p2p_node,
config,
bootstrapping,
bootstrap_state,
storage,
paid_list,
queues,
sync_state,
sync_history,
sync_cycle_epoch,
repair_proofs,
last_commitment_by_peer,
ever_capable_peers,
sig_verify_attempts,
gossip_audit,
)
.await;
} else {
let replacement = {
let mut state = sync_state.write().await;
neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
};
if let Some(replacement_peer) = replacement {
let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
std::slice::from_ref(&replacement_peer),
storage,
paid_list,
p2p_node,
config.close_group_size,
config.paid_list_close_group_size,
)
.await;
let hints = replacement_hints
.remove(&replacement_peer)
.unwrap_or_default();
let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
&replacement_peer,
p2p_node,
config,
bootstrapping,
hints,
my_commitment.clone(),
)
.await;
if let Some(outcome) = replacement_outcome {
handle_sync_response(
&self_id,
&replacement_peer,
&outcome.response,
&outcome.sent_replica_hints,
p2p_node,
config,
bootstrapping,
bootstrap_state,
storage,
paid_list,
queues,
sync_state,
sync_history,
sync_cycle_epoch,
repair_proofs,
last_commitment_by_peer,
ever_capable_peers,
sig_verify_attempts,
gossip_audit,
)
.await;
}
}
}
}
}
#[allow(clippy::too_many_arguments)]
async fn handle_sync_response(
self_id: &PeerId,
peer: &PeerId,
resp: &NeighborSyncResponse,
sent_replica_hints: &[neighbor_sync::SentReplicaHint],
p2p_node: &Arc<P2PNode>,
config: &ReplicationConfig,
bootstrapping: bool,
bootstrap_state: &Arc<RwLock<BootstrapState>>,
storage: &Arc<LmdbStorage>,
paid_list: &Arc<PaidList>,
queues: &Arc<RwLock<ReplicationQueues>>,
sync_state: &Arc<RwLock<NeighborSyncState>>,
sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
sync_cycle_epoch: &Arc<RwLock<u64>>,
repair_proofs: &Arc<RwLock<RepairProofs>>,
last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
gossip_audit: &GossipAuditTrigger,
) {
if let Some(target) = ingest_peer_commitment(
peer,
resp.commitment.as_ref(),
p2p_node,
last_commitment_by_peer,
ever_capable_peers,
sig_verify_attempts,
)
.await
{
maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
}
{
let mut state = sync_state.write().await;
neighbor_sync::record_successful_sync(&mut state, peer);
}
{
let mut history = sync_history.write().await;
let record = history.entry(*peer).or_insert(PeerSyncRecord {
last_sync: None,
cycles_since_sync: 0,
});
record.last_sync = Some(Instant::now());
record.cycles_since_sync = 0;
}
if resp.bootstrapping {
let should_report = {
let now = Instant::now();
let mut state = sync_state.write().await;
match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
BootstrapClaimObservation::WithinGrace { .. } => false,
BootstrapClaimObservation::PastGrace { first_seen } => {
warn!(
"Peer {peer} has been claiming bootstrap for {:?}, \
exceeding grace period of {:?} — reporting abuse",
now.duration_since(first_seen),
config.bootstrap_claim_grace_period,
);
true
}
BootstrapClaimObservation::Repeated { first_seen } => {
warn!(
"Peer {peer} repeated bootstrap claim after previously stopping; \
first claim was {:?} ago — reporting abuse",
now.duration_since(first_seen),
);
true
}
}
};
if should_report {
p2p_node
.report_trust_event(
peer,
TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
)
.await;
}
} else {
{
let mut state = sync_state.write().await;
state.clear_active_bootstrap_claim(peer);
}
record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
let outcome = admit_and_queue_hints(
self_id,
peer,
&resp.replica_hints,
&resp.paid_hints,
p2p_node,
config,
storage,
paid_list,
queues,
)
.await;
if bootstrapping {
let live_discovered = outcome.discovered.clone();
let outcomes = [(*peer, outcome)];
publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
.await;
}
}
}
#[allow(clippy::too_many_arguments)]
struct AdmissionOutcome {
discovered: HashSet<XorName>,
capacity_rejected_count: usize,
displaced: Vec<CapacityDisplacement>,
}
async fn publish_bootstrap_admission_outcomes(
bootstrap_state: &Arc<RwLock<BootstrapState>>,
outcomes: &[(PeerId, AdmissionOutcome)],
live_discovered: &HashSet<XorName>,
) {
let mut rejected_sources = HashSet::new();
let mut clean_sources = HashSet::new();
let mut displaced_keys = HashSet::new();
for (source, outcome) in outcomes {
if outcome.capacity_rejected_count > 0 {
rejected_sources.insert(*source);
} else {
clean_sources.insert(*source);
}
for displacement in &outcome.displaced {
displaced_keys.insert(displacement.key);
}
}
clean_sources.retain(|source| !rejected_sources.contains(source));
let now = Instant::now();
let mut state = bootstrap_state.write().await;
for key in displaced_keys {
state.remove_key(&key);
}
state.pending_keys.extend(live_discovered);
for source in clean_sources {
state.capacity_rejected_sources.remove(&source);
}
for source in rejected_sources {
state.note_capacity_rejected(source, now);
}
}
#[allow(clippy::too_many_arguments)]
async fn admit_and_queue_hints(
self_id: &PeerId,
source_peer: &PeerId,
replica_hints: &[XorName],
paid_hints: &[XorName],
p2p_node: &Arc<P2PNode>,
config: &ReplicationConfig,
storage: &Arc<LmdbStorage>,
paid_list: &Arc<PaidList>,
queues: &Arc<RwLock<ReplicationQueues>>,
) -> AdmissionOutcome {
let pending_keys: HashSet<XorName> = {
let q = queues.read().await;
q.pending_keys().into_iter().collect()
};
let admitted = admission::admit_hints(
self_id,
replica_hints,
paid_hints,
p2p_node,
config,
storage,
paid_list,
&pending_keys,
)
.await;
let mut q = queues.write().await;
queue_admitted_hints(source_peer, admitted, storage, &mut q)
}
fn queue_admitted_hints(
source_peer: &PeerId,
admitted: admission::AdmissionResult,
storage: &LmdbStorage,
q: &mut ReplicationQueues,
) -> AdmissionOutcome {
let mut discovered = HashSet::new();
let mut capacity_rejected_count: usize = 0;
let mut displaced = Vec::new();
let now = Instant::now();
for key in admitted.replica_keys {
if !storage.exists(&key).unwrap_or(false) {
let result = q.add_pending_verify(
key,
VerificationEntry {
state: VerificationState::PendingVerify,
verified_sources: Vec::new(),
tried_sources: HashSet::new(),
created_at: now,
next_verify_at: now,
hint_sources: HashSet::from([*source_peer]),
replica_hint_sources: HashSet::from([*source_peer]),
unresolved_retries: 0,
no_holder_reported: false,
},
);
match result {
crate::replication::scheduling::AdmissionResult::Admitted => {
discovered.insert(key);
}
crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
crate::replication::scheduling::AdmissionResult::CapacityRejected => {
capacity_rejected_count += 1;
}
}
}
}
for key in admitted.paid_only_keys {
let result = q.add_pending_verify(
key,
VerificationEntry {
state: VerificationState::PendingVerify,
verified_sources: Vec::new(),
tried_sources: HashSet::new(),
created_at: now,
next_verify_at: now,
hint_sources: HashSet::from([*source_peer]),
replica_hint_sources: HashSet::new(),
unresolved_retries: 0,
no_holder_reported: false,
},
);
match result {
crate::replication::scheduling::AdmissionResult::Admitted => {
discovered.insert(key);
}
crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
crate::replication::scheduling::AdmissionResult::CapacityRejected => {
capacity_rejected_count += 1;
}
}
}
if capacity_rejected_count > 0 {
debug!(
"admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
rejected at queue capacity; source will need to re-hint after pending_verify drains"
);
}
displaced.extend(q.take_capacity_displacements());
AdmissionOutcome {
discovered,
capacity_rejected_count,
displaced,
}
}
#[allow(clippy::too_many_lines)]
async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
let cycle_started = Instant::now();
let VerificationCycleContext {
p2p_node,
paid_list,
storage,
queues,
config,
bootstrap_state,
is_bootstrapping,
bootstrap_complete_notify,
last_commitment_by_peer,
ever_capable_peers,
recent_provers,
} = ctx;
expire_and_recheck_bootstrap_drain(
bootstrap_state,
queues,
is_bootstrapping,
bootstrap_complete_notify,
config.capacity_rejected_max_age(),
)
.await;
if bootstrap_state.read().await.pending_peer_requests > 0 {
return;
}
let stale_pending_keys = {
let mut q = queues.write().await;
q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
};
if !stale_pending_keys.is_empty() {
update_bootstrap_after_verification(
&stale_pending_keys,
bootstrap_state,
queues,
is_bootstrapping,
bootstrap_complete_notify,
)
.await;
}
let pending_keys = {
let mut q = queues.write().await;
if bootstrap_state.read().await.pending_peer_requests > 0 {
return;
}
q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
};
if pending_keys.is_empty() {
return;
}
let initial_pending_count = pending_keys.len();
let write_blocked = storage.capacity_verdict() == CapacityVerdict::Full;
let mut capacity_deferred_probe = 0usize;
let mut capacity_deferred_promote = 0usize;
let self_id = *p2p_node.peer_id();
let mut local_paid_keys = Vec::new();
let mut keys_needing_network = Vec::new();
let mut terminal_keys: Vec<XorName> = Vec::new();
{
let mut q = queues.write().await;
for key in &pending_keys {
if paid_list.contains(key).unwrap_or(false) {
if q.set_pending_state(key, VerificationState::PaidListVerified) {
local_paid_keys.push(*key);
}
} else {
keys_needing_network.push(*key);
}
}
}
let mut local_paid_presence_probe_keys = Vec::new();
if !local_paid_keys.is_empty() {
let mut terminal_paid = Vec::new();
for key in local_paid_keys {
if storage.exists(&key).unwrap_or(false) {
terminal_paid.push(key);
} else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
local_paid_presence_probe_keys.push(key);
} else {
terminal_paid.push(key);
}
}
if !terminal_paid.is_empty() {
let mut q = queues.write().await;
for key in terminal_paid {
q.remove_pending(&key);
terminal_keys.push(key);
}
}
if write_blocked && !local_paid_presence_probe_keys.is_empty() {
let mut q = queues.write().await;
for key in std::mem::take(&mut local_paid_presence_probe_keys) {
if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
capacity_deferred_probe += 1;
}
}
}
}
let local_paid_probe_count = local_paid_presence_probe_keys.len();
let keys_needing_network_count = keys_needing_network.len();
let mut no_holder_deferrals = 0usize;
if !local_paid_presence_probe_keys.is_empty() {
let targets = quorum::compute_presence_targets(
&local_paid_presence_probe_keys,
p2p_node,
config,
&self_id,
)
.await;
let evidence = quorum::run_verification_round(
&local_paid_presence_probe_keys,
&targets,
p2p_node,
config,
)
.await;
let mut q = queues.write().await;
for key in local_paid_presence_probe_keys {
if storage.exists(&key).unwrap_or(false) {
q.remove_pending(&key);
terminal_keys.push(key);
continue;
}
let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
quorum::present_sources_for_key(&key, ev, &targets)
});
if let Some(entry) = q.get_pending(&key) {
add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
}
if sources.is_empty() {
no_holder_deferrals += 1;
let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
let first_report = q.claim_no_holder_report(&key);
report_unresolved_deferral("Locally paid key", &key, outcome, first_report);
} else {
q.clear_unresolved(&key);
let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
let _ = q.promote_pending_to_fetch(key, distance, sources);
}
}
}
if !keys_needing_network.is_empty() {
let targets =
quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
.await;
let evidence =
quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
let map = last_commitment_by_peer.read().await;
map.iter()
.filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
.collect()
};
let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
let provers_snapshot = recent_provers.read().await.clone();
let mut locally_held: HashSet<XorName> = HashSet::new();
for key in &keys_needing_network {
if storage.exists(key).unwrap_or(false) {
locally_held.insert(*key);
}
}
let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
if !locally_held.contains(key) {
return true;
}
if !capable_peer_snapshot.contains(peer) {
return true;
}
let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
return false;
};
provers_snapshot.is_credited_holder(key, peer, hash)
};
let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
{
let q = queues.read().await;
for key in &keys_needing_network {
let Some(ev) = evidence.get(key) else {
continue;
};
if q.get_pending(key).is_none() {
continue;
}
let outcome = quorum::evaluate_key_evidence_with_holder_check(
key,
ev,
&targets,
config,
holder_credit,
);
evaluated.push((*key, outcome));
}
}
let mut paid_insert_keys: Vec<XorName> = Vec::new();
for (key, outcome) in &evaluated {
if matches!(
outcome,
KeyVerificationOutcome::QuorumVerified { .. }
| KeyVerificationOutcome::PaidListVerified { .. }
) {
paid_insert_keys.push(*key);
}
}
for key in &paid_insert_keys {
if let Err(e) = paid_list.insert(key).await {
warn!("Failed to add verified key to PaidForList: {e}");
}
}
let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
for (key, outcome) in &evaluated {
if matches!(
outcome,
KeyVerificationOutcome::QuorumVerified { .. }
| KeyVerificationOutcome::PaidListVerified { .. }
) && !storage.exists(key).unwrap_or(false)
&& is_storage_admitted(&self_id, key, p2p_node, config).await
{
fetch_allowed_keys.insert(*key);
}
}
let mut bad_singleton_hints: HashMap<(PeerId, SingletonHintFault), usize> = HashMap::new();
let mut q = queues.write().await;
for (key, outcome) in evaluated {
let replica_hint_sources = q
.get_pending(&key)
.map(|entry| entry.replica_hint_sources.clone())
.unwrap_or_default();
if let Some(ev) = evidence.get(&key) {
if let Some(source) =
punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
{
*bad_singleton_hints.entry(source).or_insert(0) += 1;
}
}
match outcome {
KeyVerificationOutcome::QuorumVerified { sources }
| KeyVerificationOutcome::PaidListVerified { sources } => {
let mut fetch_sources = sources;
add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
let fetch_eligible = fetch_allowed_keys.contains(&key);
if fetch_eligible && write_blocked {
if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
capacity_deferred_promote += 1;
}
} else if fetch_eligible && !fetch_sources.is_empty() {
q.clear_unresolved(&key);
let distance =
crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
} else if fetch_eligible && fetch_sources.is_empty() {
no_holder_deferrals += 1;
let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
let first_report = q.claim_no_holder_report(&key);
report_unresolved_deferral(
"Verified storage-admitted key",
&key,
outcome,
first_report,
);
} else {
q.remove_pending(&key);
terminal_keys.push(key);
}
}
KeyVerificationOutcome::QuorumFailed => {
q.remove_pending(&key);
terminal_keys.push(key);
}
KeyVerificationOutcome::QuorumInconclusive => {
q.set_pending_state(&key, VerificationState::QuorumInconclusive);
let _ = q.defer_unresolved(&key, config.verification_request_timeout);
}
}
}
drop(q);
for ((peer, fault), bad_hint_count) in bad_singleton_hints {
let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
warn!(
"Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
sole-source replica hints ({fault:?}); \
reporting {reports} bounded trust failure(s)"
);
for _ in 0..reports {
match fault {
SingletonHintFault::RejectedByCloseGroup => {
p2p_node
.report_trust_event(
&peer,
TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
)
.await;
}
SingletonHintFault::DeniedPossession => {
config::penalise_unheld_close_group_chunk(
p2p_node,
&peer,
"replica_hint_denied_possession",
REPLICATION_TRUST_WEIGHT,
)
.await;
}
}
}
}
}
update_bootstrap_after_verification(
&terminal_keys,
bootstrap_state,
queues,
is_bootstrapping,
bootstrap_complete_notify,
)
.await;
let (pending_after, fetch_after, in_flight_after) = {
let q = queues.read().await;
(
q.pending_count(),
q.fetch_queue_count(),
q.in_flight_count(),
)
};
let terminal_key_count = terminal_keys.len();
let elapsed_ms = cycle_started.elapsed().as_millis();
if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
info!(
target: "ant_node::replication::verification",
"Slow replication verification cycle: pending_start={initial_pending_count}, capacity_deferred_probe={capacity_deferred_probe}, capacity_deferred_promote={capacity_deferred_promote}, local_paid_probe={local_paid_probe_count}, network_verify={keys_needing_network_count}, terminal={terminal_key_count}, no_holders={no_holder_deferrals}, pending_after={pending_after}, fetch_after={fetch_after}, in_flight_after={in_flight_after}, elapsed_ms={elapsed_ms}",
);
} else {
debug!(
target: "ant_node::replication::verification",
"Replication verification cycle: pending_start={initial_pending_count}, capacity_deferred_probe={capacity_deferred_probe}, capacity_deferred_promote={capacity_deferred_promote}, local_paid_probe={local_paid_probe_count}, network_verify={keys_needing_network_count}, terminal={terminal_key_count}, no_holders={no_holder_deferrals}, pending_after={pending_after}, fetch_after={fetch_after}, in_flight_after={in_flight_after}, elapsed_ms={elapsed_ms}",
);
}
}
fn report_unresolved_deferral(
what: &str,
key: &XorName,
outcome: Option<DeferralOutcome>,
first_report: bool,
) {
let Some(outcome) = outcome else {
return;
};
if first_report {
warn!(
"{what} {} has no responding holders yet; deferring retry",
hex::encode(key)
);
} else {
debug!(
"{what} {} still has no responding holders after {} attempts; \
retrying in {}s",
hex::encode(key),
outcome.attempt,
outcome.retry_after.as_secs()
);
}
}
fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
for source in replica_hint_sources {
if !sources.contains(source) {
sources.push(*source);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum SingletonHintFault {
RejectedByCloseGroup,
DeniedPossession,
}
fn punishable_singleton_replica_hint_source(
replica_hint_sources: &HashSet<PeerId>,
outcome: &KeyVerificationOutcome,
evidence: &crate::replication::types::KeyVerificationEvidence,
) -> Option<(PeerId, SingletonHintFault)> {
if replica_hint_sources.len() != 1 {
return None;
}
let source = *replica_hint_sources.iter().next()?;
if matches!(outcome, KeyVerificationOutcome::QuorumFailed) {
return Some((source, SingletonHintFault::RejectedByCloseGroup));
}
if evidence.presence.get(&source) == Some(&PresenceEvidence::Absent) {
return Some((source, SingletonHintFault::DeniedPossession));
}
None
}
async fn update_bootstrap_after_verification(
terminal_keys: &[XorName],
bootstrap_state: &Arc<RwLock<BootstrapState>>,
queues: &Arc<RwLock<ReplicationQueues>>,
is_bootstrapping: &Arc<RwLock<bool>>,
bootstrap_complete_notify: &Arc<Notify>,
) {
if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
return;
}
{
let mut bs = bootstrap_state.write().await;
for key in terminal_keys {
bs.remove_key(key);
}
}
let q = queues.read().await;
if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
}
}
async fn update_bootstrap_after_peer_removed(
peer: &PeerId,
bootstrap_state: &Arc<RwLock<BootstrapState>>,
queues: &Arc<RwLock<ReplicationQueues>>,
is_bootstrapping: &Arc<RwLock<bool>>,
bootstrap_complete_notify: &Arc<Notify>,
) {
let orphaned_keys = queues.write().await.remove_hint_source(peer);
let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
if !orphaned_keys.is_empty() {
let mut state = bootstrap_state.write().await;
for key in &orphaned_keys {
state.remove_key(key);
}
}
if orphaned_keys.is_empty() && !cleared_rejection {
return;
}
let q = queues.read().await;
if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
}
}
async fn expire_and_recheck_bootstrap_drain(
bootstrap_state: &Arc<RwLock<BootstrapState>>,
queues: &Arc<RwLock<ReplicationQueues>>,
is_bootstrapping: &Arc<RwLock<bool>>,
bootstrap_complete_notify: &Arc<Notify>,
max_age: Duration,
) {
if bootstrap_state.read().await.is_drained() {
return;
}
bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
let q = queues.read().await;
if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
}
}
async fn complete_bootstrap(
is_bootstrapping: &Arc<RwLock<bool>>,
bootstrap_complete_notify: &Arc<Notify>,
) {
*is_bootstrapping.write().await = false;
bootstrap_complete_notify.notify_waiters();
info!("Replication bootstrap complete");
}
enum FetchResult {
Stored,
IntegrityFailed,
SourceFailed,
LocalWriteFailed,
AlreadyHeld,
NoLongerResponsible,
}
struct FetchOutcome {
key: XorName,
result: FetchResult,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FetchFollowUp {
Terminal,
RequeuedForVerification,
RetryFrom(PeerId),
}
#[allow(clippy::option_if_let_else)]
fn apply_fetch_result(
q: &mut ReplicationQueues,
key: &XorName,
result: &FetchResult,
verification_retry_after: Duration,
) -> FetchFollowUp {
match result {
FetchResult::Stored | FetchResult::NoLongerResponsible | FetchResult::AlreadyHeld => {
q.complete_fetch(key);
FetchFollowUp::Terminal
}
FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
if let Some(next_peer) = q.retry_fetch(key) {
FetchFollowUp::RetryFrom(next_peer)
} else if q.requeue_fetch_for_verification(key, verification_retry_after) {
FetchFollowUp::RequeuedForVerification
} else {
FetchFollowUp::Terminal
}
}
FetchResult::LocalWriteFailed => {
if q.requeue_fetch_for_verification(key, verification_retry_after) {
FetchFollowUp::RequeuedForVerification
} else {
FetchFollowUp::Terminal
}
}
}
}
async fn is_storage_admitted(
self_id: &PeerId,
key: &XorName,
p2p_node: &Arc<P2PNode>,
config: &ReplicationConfig,
) -> bool {
admission::is_responsible(
self_id,
key,
p2p_node,
storage_admission_width(config.close_group_size),
)
.await
}
#[allow(clippy::too_many_lines)]
async fn execute_single_fetch(
p2p_node: Arc<P2PNode>,
storage: Arc<LmdbStorage>,
config: Arc<ReplicationConfig>,
key: XorName,
source: PeerId,
) -> FetchOutcome {
let self_id = *p2p_node.peer_id();
if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
debug!(
"Skipping fetch for {}: no longer in the storage-admission group",
hex::encode(key)
);
return FetchOutcome {
key,
result: FetchResult::NoLongerResponsible,
};
}
if storage.exists(&key).unwrap_or(false) {
debug!(
"Skipping fetch for {}: already held locally",
hex::encode(key)
);
return FetchOutcome {
key,
result: FetchResult::AlreadyHeld,
};
}
if let Err(e) = storage.check_capacity() {
debug!(
"Skipping fetch for {}: local storage cannot accept a write: {e}",
hex::encode(key)
);
return FetchOutcome {
key,
result: FetchResult::LocalWriteFailed,
};
}
let request = protocol::FetchRequest { key };
let msg = ReplicationMessage {
request_id: rand::thread_rng().gen::<u64>(),
body: ReplicationMessageBody::FetchRequest(request),
};
let encoded = match msg.encode() {
Ok(data) => data,
Err(e) => {
warn!("Failed to encode fetch request: {e}");
return FetchOutcome {
key,
result: FetchResult::SourceFailed,
};
}
};
let result = p2p_node
.send_request(
&source,
REPLICATION_PROTOCOL_ID,
encoded,
config.fetch_request_timeout,
)
.await;
match result {
Ok(response) => {
let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
p2p_node
.report_trust_event(
&source,
TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
)
.await;
return FetchOutcome {
key,
result: FetchResult::SourceFailed,
};
};
match resp_msg.body {
ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
key: resp_key,
data,
}) => {
if resp_key != key {
warn!(
"Fetch response key mismatch: requested {}, got {}",
hex::encode(key),
hex::encode(resp_key)
);
p2p_node
.report_trust_event(
&source,
TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
)
.await;
return FetchOutcome {
key,
result: FetchResult::IntegrityFailed,
};
}
if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
warn!(
"Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
hex::encode(resp_key),
data.len(),
crate::ant_protocol::MAX_CHUNK_SIZE,
);
p2p_node
.report_trust_event(
&source,
TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
)
.await;
return FetchOutcome {
key,
result: FetchResult::IntegrityFailed,
};
}
let computed = crate::client::compute_address(&data);
if computed != resp_key {
warn!(
"Fetched record integrity check failed: expected {}, got {}",
hex::encode(resp_key),
hex::encode(computed)
);
p2p_node
.report_trust_event(
&source,
TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
)
.await;
return FetchOutcome {
key,
result: FetchResult::IntegrityFailed,
};
}
if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
debug!(
"Fetched {} but responsibility lapsed in transit; not storing",
hex::encode(key)
);
return FetchOutcome {
key,
result: FetchResult::NoLongerResponsible,
};
}
if let Err(e) = storage.put(&resp_key, &data).await {
warn!(
"Failed to store fetched record {}: {e}",
hex::encode(resp_key)
);
return FetchOutcome {
key,
result: FetchResult::LocalWriteFailed,
};
}
FetchOutcome {
key,
result: FetchResult::Stored,
}
}
ReplicationMessageBody::FetchResponse(
ref response @ (protocol::FetchResponse::NotFound { .. }
| protocol::FetchResponse::Error { .. }),
) => {
if let protocol::FetchResponse::Error { reason, .. } = response {
warn!(
"Fetch: peer {source} returned error for {}: {reason}",
hex::encode(key)
);
} else {
warn!(
"Fetch: verified source {source} returned NotFound for {}",
hex::encode(key)
);
}
if let Some(fault) = fetch_fault_for(response) {
let lane = match fault {
FetchFault::UnheldChunk => "fetch_not_found",
FetchFault::ResponderFault => "fetch_error",
};
charge_fetch_fault(&p2p_node, &source, fault, lane).await;
}
FetchOutcome {
key,
result: FetchResult::SourceFailed,
}
}
_ => {
p2p_node
.report_trust_event(
&source,
TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
)
.await;
FetchOutcome {
key,
result: FetchResult::SourceFailed,
}
}
}
}
Err(e) => {
debug!("Fetch request to {source} failed: {e}");
FetchOutcome {
key,
result: FetchResult::SourceFailed,
}
}
}
}
fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
confirmed_failed_keys.first().map_or_else(
|| "0x".to_string(),
|k| format!("0x{}", hex::encode(&k[..8])),
)
}
async fn handle_subtree_failed_audit(
challenged_peer: &PeerId,
confirmed_failed_key_count: usize,
reason: &AuditFailureReason,
p2p_node: &Arc<P2PNode>,
sync_state: &Arc<RwLock<NeighborSyncState>>,
recent_provers: &Arc<RwLock<RecentProvers>>,
) {
if matches!(reason, AuditFailureReason::Timeout) {
debug!(
"Audit timeout for {challenged_peer} fully graced \
(subtree audit does not evict on timeout)"
);
return;
}
let _ = confirmed_failed_key_count;
{
let mut state = sync_state.write().await;
state.clear_active_bootstrap_claim(challenged_peer);
}
{
let mut provers_guard = recent_provers.write().await;
apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
}
p2p_node
.report_trust_event(
challenged_peer,
TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
)
.await;
}
async fn handle_subtree_audit_result(
result: &AuditTickResult,
p2p_node: &Arc<P2PNode>,
sync_state: &Arc<RwLock<NeighborSyncState>>,
recent_provers: &Arc<RwLock<RecentProvers>>,
config: &ReplicationConfig,
) {
match result {
AuditTickResult::Passed {
challenged_peer,
keys_checked,
} => {
protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
{
let mut state = sync_state.write().await;
state.clear_active_bootstrap_claim(challenged_peer);
}
p2p_node
.report_trust_event(
challenged_peer,
TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
)
.await;
}
AuditTickResult::Failed {
evidence,
no_response_class,
} => {
if let FailureEvidence::AuditFailure {
challenged_peer,
confirmed_failed_keys,
summary,
reason,
..
} = evidence
{
protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
let first_failed_key = first_failed_key_label(confirmed_failed_keys);
let audit_failure_class = no_response_class.unwrap_or("confirmed");
error!(
"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}",
audit_failure_class,
confirmed_failed_keys.len(),
summary.challenged_keys,
summary.absent_keys,
summary.digest_mismatch_keys,
);
handle_subtree_failed_audit(
challenged_peer,
confirmed_failed_keys.len(),
reason,
p2p_node,
sync_state,
recent_provers,
)
.await;
}
}
AuditTickResult::BootstrapClaim { peer } => {
let should_report = {
let now = Instant::now();
let mut state = sync_state.write().await;
match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
{
BootstrapClaimObservation::WithinGrace { .. } => {
debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
false
}
BootstrapClaimObservation::PastGrace { first_seen } => {
warn!(
"Audit: peer {peer} claiming bootstrap past grace period \
({:?} > {:?}), reporting abuse",
now.duration_since(first_seen),
config.bootstrap_claim_grace_period,
);
true
}
BootstrapClaimObservation::Repeated { first_seen } => {
warn!(
"Audit: peer {peer} repeated bootstrap claim after previously \
stopping; first claim was {:?} ago, reporting abuse",
now.duration_since(first_seen),
);
true
}
}
};
if should_report {
p2p_node
.report_trust_event(
peer,
TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
)
.await;
}
}
AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
}
}
fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
!matches!(reason, AuditFailureReason::Timeout)
}
#[allow(clippy::too_many_lines)]
async fn handle_audit_result(
result: &AuditTickResult,
p2p_node: &Arc<P2PNode>,
sync_state: &Arc<RwLock<NeighborSyncState>>,
config: &ReplicationConfig,
) {
match result {
AuditTickResult::Passed {
challenged_peer,
keys_checked,
} => {
protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
{
let mut state = sync_state.write().await;
state.clear_active_bootstrap_claim(challenged_peer);
}
p2p_node
.report_trust_event(
challenged_peer,
TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
)
.await;
}
AuditTickResult::Failed {
evidence,
no_response_class,
} => {
if let FailureEvidence::AuditFailure {
challenged_peer,
confirmed_failed_keys,
summary,
reason,
..
} = evidence
{
protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
let first_failed_key = first_failed_key_label(confirmed_failed_keys);
let audit_failure_class = no_response_class.unwrap_or("confirmed");
error!(
"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}",
audit_failure_class,
confirmed_failed_keys.len(),
summary.challenged_keys,
summary.absent_keys,
summary.digest_mismatch_keys,
);
if audit_failure_clears_bootstrap_claim(reason) {
let mut state = sync_state.write().await;
state.clear_active_bootstrap_claim(challenged_peer);
} else {
debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
}
config::penalise_unheld_close_group_chunk(
p2p_node,
challenged_peer,
crate::replication::audit_metrics::AuditType::ResponsibleChunk.as_str(),
config::AUDIT_FAILURE_TRUST_WEIGHT,
)
.await;
}
}
AuditTickResult::BootstrapClaim { peer } => {
let should_report = {
let now = Instant::now();
let mut state = sync_state.write().await;
match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
{
BootstrapClaimObservation::WithinGrace { .. } => {
debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
false
}
BootstrapClaimObservation::PastGrace { first_seen } => {
warn!(
"Audit: peer {peer} claiming bootstrap past grace period \
({:?} > {:?}), reporting abuse",
now.duration_since(first_seen),
config.bootstrap_claim_grace_period,
);
true
}
BootstrapClaimObservation::Repeated { first_seen } => {
warn!(
"Audit: peer {peer} repeated bootstrap claim after previously \
stopping; first claim was {:?} ago, reporting abuse",
now.duration_since(first_seen),
);
true
}
}
};
if should_report {
p2p_node
.report_trust_event(
peer,
TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
)
.await;
}
}
AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
}
}
fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
!matches!(reason, AuditFailureReason::Timeout)
}
fn apply_audit_failure_credit_revocation(
provers: &mut RecentProvers,
challenged_peer: &PeerId,
reason: &AuditFailureReason,
) {
if audit_failure_revokes_holder_credit(reason) {
provers.forget_peer(challenged_peer);
}
}
#[derive(Clone)]
struct GossipAuditTrigger {
p2p_node: Arc<P2PNode>,
config: Arc<ReplicationConfig>,
recent_provers: Arc<RwLock<RecentProvers>>,
sync_state: Arc<RwLock<NeighborSyncState>>,
cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
detached_task_tracker: TaskTracker,
lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
}
#[derive(Debug, Clone, Copy)]
struct AuditTarget {
pin_hash: [u8; 32],
key_count: u32,
}
#[derive(Debug, Clone, Copy)]
pub struct MonetizedPinEvent {
pub peer: PeerId,
pub pin: [u8; 32],
pub key_count: u32,
pub quote_ts: SystemTime,
}
fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
let known = match map.get(peer) {
Some(&last) => {
if now.saturating_duration_since(last) < cooldown {
return false;
}
true
}
None => false,
};
if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
map.remove(&victim);
}
}
map.insert(*peer, now);
true
}
fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
map.get(peer).map_or(true, |&last| {
now.saturating_duration_since(last) >= cooldown
})
}
fn audit_launch_decision(
attempts: &mut HashMap<PeerId, Instant>,
launched: &mut HashMap<PeerId, Instant>,
peer: &PeerId,
now: Instant,
lottery_wins: bool,
) -> bool {
if !cooldown_allows_audit(attempts, peer, now) {
return false;
}
if !lottery_wins {
return false;
}
cooldown_allows_audit(launched, peer, now)
}
async fn maybe_trigger_gossip_audit(
trigger: &GossipAuditTrigger,
peer: &PeerId,
target: AuditTarget,
) {
let now = Instant::now();
let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
{
let mut attempts = trigger.lottery_attempts.write().await;
let mut launched = trigger.cooldown.write().await;
if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
return;
}
}
let detached_task_tracker = trigger.detached_task_tracker.clone();
let trigger = trigger.clone();
let peer = *peer;
detached_task_tracker.spawn(async move {
let credit = storage_commitment_audit::AuditCredit {
recent_provers: &trigger.recent_provers,
};
let result = storage_commitment_audit::run_subtree_audit_with_origin(
&trigger.p2p_node,
&trigger.config,
&peer,
target.pin_hash,
target.key_count,
Some(&credit),
storage_commitment_audit::SubtreeAuditOrigin::Gossip,
)
.await;
handle_subtree_audit_result(
&result,
&trigger.p2p_node,
&trigger.sync_state,
&trigger.recent_provers,
&trigger.config,
)
.await;
});
}
async fn sig_verify_rate_limit_ok(
sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
source: &PeerId,
now: Instant,
) -> bool {
let mut attempts = sig_verify_attempts.write().await;
if let Some(&last) = attempts.get(source) {
if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
return false;
}
}
if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
attempts.remove(&victim);
}
}
attempts.insert(*source, now);
true
}
async fn handle_commitment_downgrade(
source: &PeerId,
last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
) -> Option<AuditTarget> {
let now = Instant::now();
let cached = {
let map = last_commitment_by_peer.read().await;
map.get(source).and_then(|rec| {
if !rec.commitment_capable {
return None;
}
let last = rec.last_commitment()?;
let pin = rec.commitment_hash()?;
let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
Some((pin, last.key_count, fresh))
})
};
match cached {
Some((pin, key_count, true)) => {
warn!(
"ingest_peer_commitment: commitment-capable peer {source} sent None \
(downgrade attempt); auditing against its last cached commitment"
);
Some(AuditTarget {
pin_hash: pin,
key_count,
})
}
Some((_, _, false)) => {
if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
let still_stale =
now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
if still_stale {
rec.clear_commitment();
debug!(
"ingest_peer_commitment: capable peer {source} sent None and its cached \
commitment aged past the answerability TTL; forgetting it"
);
}
}
None
}
None => None,
}
}
async fn ingest_peer_commitment(
source: &PeerId,
commitment: Option<&StorageCommitment>,
p2p_node: &Arc<P2PNode>,
last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
) -> Option<AuditTarget> {
let Some(c) = commitment else {
return handle_commitment_downgrade(source, last_commitment_by_peer).await;
};
if !p2p_node.dht_manager().is_in_routing_table(source).await {
debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
return None;
}
if &c.sender_peer_id != source.as_bytes() {
warn!(
"ingest_peer_commitment: sender_peer_id mismatch from {source} \
(dropped, possible relay attempt)"
);
return None;
}
let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
if derived_peer_id != c.sender_peer_id {
warn!(
"ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
{source} (dropped, throwaway-key attack)"
);
return None;
}
let now = Instant::now();
if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
debug!(
"ingest_peer_commitment: rate-limited sig verify from {source} \
(< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
);
return None;
}
if !crate::replication::commitment::verify_commitment_signature(c) {
warn!(
"ingest_peer_commitment: signature did not verify under embedded key for {source} \
(dropped, forged commitment)"
);
return None;
}
let new_hash = commitment_hash(c);
let mut map = last_commitment_by_peer.write().await;
if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
if let Some(victim) = map.keys().next().copied() {
map.remove(&victim);
warn!(
"ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
evicted {victim} to admit {source}"
);
}
}
map.entry(*source)
.and_modify(|r| {
r.set_commitment(c.clone(), now);
r.last_sig_verify_at = now;
r.commitment_capable = true; })
.or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
drop(map);
{
let mut set = ever_capable_peers.write().await;
if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
set.insert(*source);
} else {
warn!(
"ingest_peer_commitment: ever_capable_peers at cap \
({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
);
}
}
new_hash.map(|pin_hash| AuditTarget {
pin_hash,
key_count: c.key_count,
})
}
async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
let bytes = match tokio::fs::read(path).await {
Ok(b) => b,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
debug!(
"Commitment retention: no snapshot at {} (fresh start)",
path.display()
);
return;
}
Err(e) => {
warn!(
"Commitment retention: failed to read {}: {e}",
path.display()
);
return;
}
};
if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
state.restore(&persisted);
info!(
"Commitment retention: reloaded {} slot(s) from {}",
state.retained_slot_count(),
path.display()
);
} else {
warn!(
"Commitment retention: corrupt snapshot at {}; starting with empty retention",
path.display()
);
}
}
async fn persist_retention_if_changed(
state: &ResponderCommitmentState,
path: &Path,
last: &mut Option<Vec<u8>>,
) {
let Some(bytes) = state.snapshot().to_bytes() else {
warn!("Commitment retention: serialization failed; keeping previous snapshot");
return;
};
if last.as_deref() == Some(bytes.as_slice()) {
return;
}
if write_retention_atomic(path, bytes.clone()).await {
*last = Some(bytes);
}
}
async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
let path = path.to_path_buf();
let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, &bytes)?;
std::fs::File::open(&tmp)?.sync_all()?;
std::fs::rename(&tmp, &path)?;
let dir = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
std::fs::File::open(dir)?.sync_all()?;
Ok(())
})
.await;
match res {
Ok(Ok(())) => true,
Ok(Err(e)) => {
warn!("Commitment retention: persist failed: {e}");
false
}
Err(e) => {
warn!("Commitment retention: persist task join failed: {e}");
false
}
}
}
async fn rebuild_and_rotate_commitment(
storage: &Arc<LmdbStorage>,
identity: &Arc<NodeIdentity>,
state: &Arc<ResponderCommitmentState>,
p2p: &Arc<P2PNode>,
config: &Arc<ReplicationConfig>,
) -> Result<()> {
let stored_keys = storage
.all_keys()
.await
.map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
let storage_empty = stored_keys.is_empty();
let self_id = *p2p.peer_id();
let mut keys = Vec::with_capacity(stored_keys.len());
for k in stored_keys {
if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
keys.push(k);
}
}
if keys.is_empty() {
if storage_empty {
if state.retained_slot_count() > 0 {
debug!("Commitment rotation: storage empty, clearing retained slots");
state.clear_all();
}
return Ok(());
}
debug!(
"Commitment rotation: no responsible keys to commit to; retiring current commitment \
(stays answerable until its gossip TTL lapses, bytes still on disk)"
);
state.retire_current();
return Ok(());
}
let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
if keys.len() > cap {
warn!(
"Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
truncating — investigate as this likely means a misconfiguration",
keys.len(),
cap
);
}
let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
let candidate_tree = commitment::MerkleTree::build(entries)
.map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
let candidate_root = candidate_tree.root();
if let Some(current) = state.current() {
if current.commitment().root == candidate_root {
debug!(
"Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
hex::encode(candidate_root)
);
state.age_out();
return Ok(());
}
}
let sk_bytes = identity.secret_key_bytes().to_vec();
let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
.map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
let pk_bytes = identity.public_key().as_bytes().to_vec();
let peer_id_bytes = *p2p.peer_id().as_bytes();
let built = commitment_state::BuiltCommitment::build_from_tree(
candidate_tree,
&peer_id_bytes,
&sk,
&pk_bytes,
)
.map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
let hash = hex::encode(built.hash());
let key_count = built.commitment().key_count;
state.rotate(built);
info!("Storage commitment rotated: hash={hash} key_count={key_count}");
Ok(())
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
#[test]
fn a_missing_chunk_and_a_failed_read_are_different_faults() {
let key = [7u8; 32];
assert_eq!(
fetch_fault_for(&protocol::FetchResponse::NotFound { key }),
Some(FetchFault::UnheldChunk)
);
assert_eq!(
fetch_fault_for(&protocol::FetchResponse::Error {
key,
reason: "read failed".to_string(),
}),
Some(FetchFault::ResponderFault)
);
assert_eq!(
fetch_fault_for(&protocol::FetchResponse::Success {
key,
data: vec![1, 2, 3],
}),
None
);
}
#[tokio::test]
async fn a_missing_key_reads_as_a_plain_miss_and_a_failed_read_as_a_fault() {
let dir = tempfile::tempdir().expect("temp dir");
let storage = LmdbStorage::new(crate::storage::LmdbStorageConfig {
root_dir: dir.path().to_path_buf(),
verify_on_read: true,
max_map_size: 0,
disk_reserve: 0,
})
.await
.expect("open store");
let absent = [9u8; 32];
assert!(
matches!(storage.get(&absent).await, Ok(None)),
"a chunk this node does not hold must read as a plain miss, not a fault"
);
assert!(matches!(
fetch_response_for(absent, Ok(None)),
protocol::FetchResponse::NotFound { .. }
));
assert!(matches!(
fetch_response_for(absent, Ok(Some(vec![1, 2, 3]))),
protocol::FetchResponse::Success { .. }
));
assert!(matches!(
fetch_response_for(
absent,
Err(crate::error::Error::Storage("read failed".into()))
),
protocol::FetchResponse::Error { .. }
));
}
use super::*;
use super::{
apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
};
use crate::payment::VerificationContext;
use crate::replication::audit::AuditTickResult;
use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
use crate::replication::recent_provers::RecentProvers;
use crate::replication::types::{AuditFailureReason, FailureEvidence};
use lru::LruCache;
use saorsa_core::identity::PeerId;
use std::collections::HashMap;
use std::num::NonZeroUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use std::time::SystemTime;
#[test]
fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
assert_eq!(match_replication_protocol(id), Some((id, false)));
assert_eq!(
match_replication_protocol(&format!("{RR_PREFIX}{id}")),
Some((id, true))
);
}
assert_eq!(
match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
None
);
assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
assert_eq!(match_replication_protocol(RR_PREFIX), None);
}
#[test]
fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
use crate::replication::protocol::{
AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
SubtreeSliceChallenge,
};
let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
challenge_id: 1,
nonce: [0u8; 32],
challenged_peer_id: [0u8; 32],
expected_commitment_hash: [0u8; 32],
openings: vec![],
});
let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
challenge_id: 1,
nonce: [0u8; 32],
challenged_peer_id: [0u8; 32],
keys: vec![[0u8; 32]],
});
let digest_response =
ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
key: [0u8; 32],
data: vec![],
proof_of_payment: vec![],
});
assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
for body in [&digest_challenge, &digest_response, &core] {
assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
}
for body in [&subtree, &digest_challenge, &digest_response, &core] {
assert!(body_matches_protocol(body, response_protocol_for(body)));
}
}
fn test_peer(b: u8) -> PeerId {
let mut bytes = [0u8; 32];
bytes[0] = b;
PeerId::from_bytes(bytes)
}
fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
protocol::FreshReplicationOffer {
key: crate::client::compute_address(&data),
data,
proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
}
}
fn admit_test_offer(
in_flight: &FreshOfferInFlight,
offer: protocol::FreshReplicationOffer,
source: PeerId,
) -> FreshOfferAdmission {
FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
}
#[test]
fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
let data = vec![0x11u8; 64];
let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
let FreshOfferAdmission::Opened(entry) = opened else {
panic!("first offer for a key should open the entry")
};
assert!(
matches!(
admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
FreshOfferAdmission::Joined
),
"a duplicate from a new source should queue its proof"
);
assert!(
matches!(
admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
FreshOfferAdmission::DuplicateSource
),
"one source should hold at most one queued proof per key"
);
drop(entry);
assert!(
matches!(
admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
FreshOfferAdmission::Opened(_)
),
"a released key should be openable again"
);
}
#[test]
fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
assert!(
matches!(
admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
FreshOfferAdmission::Opened(_)
),
"distinct keys should never block each other"
);
}
#[test]
fn a_failing_proof_hands_the_key_to_the_next_sender() {
let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
let data = vec![0x5Au8; 128];
let forger = test_peer(0xF0);
let genuine = test_peer(0x0F);
let FreshOfferAdmission::Opened(mut entry) =
admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
else {
panic!("the first offer should open the entry");
};
assert!(
matches!(
admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
FreshOfferAdmission::Joined
),
"the genuine sender must not be turned away by the forger"
);
let first = entry
.next_attempt()
.expect("the opener's proof comes first");
assert_eq!(first.source, forger);
let second = entry
.next_attempt()
.expect("a failed proof must not consume the key");
assert_eq!(second.source, genuine);
assert_eq!(
second.proof_of_payment,
vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
);
assert_eq!(
entry.data(),
data.as_slice(),
"every proof is tried against the one copy of the bytes"
);
assert!(entry.next_attempt().is_none());
assert!(
matches!(
admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
FreshOfferAdmission::Opened(_)
),
"an exhausted entry should release its key"
);
}
#[test]
fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
let data = vec![0x3Du8; 32];
let FreshOfferAdmission::Opened(mut entry) =
admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
else {
panic!("the first offer should open the entry")
};
let mut admitted = 1;
for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
let _ = entry.next_attempt();
if matches!(
admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
FreshOfferAdmission::Joined
) {
admitted += 1;
}
}
assert!(
admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
"a key accepted {admitted} proofs over its lifetime, but the budget is \
{MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
);
}
#[test]
fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
let data = vec![0x2Cu8; 32];
let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
assert!(
matches!(
admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
FreshOfferAdmission::Joined
),
"sender {i} is within the legitimate close-group fan-out"
);
}
let surplus = test_peer(0xEE);
assert!(
matches!(
admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
FreshOfferAdmission::Full
),
"past the cap a proof is surplus: enough are already queued to place the record"
);
}
#[test]
fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
assert!(!verification_request_exceeds_limit(
config::MAX_VERIFICATION_KEYS_PER_CYCLE
));
assert!(verification_request_exceeds_limit(
config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
));
}
#[tokio::test]
async fn subtree_round1_limiter_cooldown_and_single_use_session() {
let limiter = SubtreeRound1Limiter::new(
Duration::from_secs(3600),
config::MAX_CONCURRENT_SUBTREE_ROUND1,
);
let peer = test_peer(1);
let guard = limiter.admit(&peer).await;
assert!(guard.is_some(), "first round-1 admitted");
drop(guard);
assert!(
limiter.admit(&peer).await.is_none(),
"second round-1 within cooldown is rate-dropped"
);
assert!(limiter.admit(&test_peer(2)).await.is_some());
let hash = [7u8; 32];
let nonce = [9u8; 32];
limiter.open_session(peer, 42, hash, nonce).await;
assert!(!limiter.consume_session(&peer, 42, &hash, &[0u8; 32]).await);
assert!(!limiter.consume_session(&peer, 42, &[0u8; 32], &nonce).await);
assert!(!limiter.consume_session(&peer, 99, &hash, &nonce).await);
assert!(limiter.consume_session(&peer, 42, &hash, &nonce).await);
assert!(!limiter.consume_session(&peer, 42, &hash, &nonce).await);
}
#[tokio::test]
async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
let limiter =
SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
assert!(
limiter.admit(&test_peer(1)).await.is_some(),
"a node starts with budget in hand so it can serve audits at once"
);
limiter
.charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
.await;
for id in 2..8u8 {
assert!(
limiter.admit(&test_peer(id)).await.is_none(),
"a never-seen peer must still be refused while the budget is spent"
);
}
}
#[test]
fn round1_work_budget_carries_debt_and_refills_over_time() {
let now = Instant::now();
let at = |secs: u64| {
now.checked_add(Duration::from_secs(secs))
.unwrap_or_else(Instant::now)
};
let mut budget = Round1WorkBudget {
balance: 0,
last_refill: now,
};
assert!(!budget.has_budget(now), "empty means empty");
budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
assert!(
!budget.has_budget(at(3)),
"still in debt three seconds after an over-large proof"
);
assert!(
budget.has_budget(at(5)),
"the debt is worked off at the refill rate"
);
budget.refill(at(24 * 60 * 60));
assert_eq!(
budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
"refill is capped at the burst size"
);
}
#[tokio::test]
async fn round1_pool_size_comes_from_config() {
let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
let held = limiter.admit(&test_peer(1)).await;
assert!(held.is_some(), "the single configured slot is admitted");
assert!(
limiter.admit(&test_peer(2)).await.is_none(),
"a second concurrent round 1 is refused at a configured pool of 1, \
proving admission follows config rather than the compiled-in default"
);
drop(held);
assert!(
limiter.admit(&test_peer(2)).await.is_some(),
"the slot is reusable once the first proof completes"
);
}
#[tokio::test]
async fn round1_pool_size_of_zero_is_clamped_to_one() {
let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
assert!(
limiter.admit(&test_peer(1)).await.is_some(),
"a mis-set pool of 0 must still serve audits, not silently refuse every one"
);
}
fn test_key(b: u8) -> crate::ant_protocol::XorName {
let mut k = [0u8; 32];
k[0] = b;
k
}
#[test]
fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
let source = test_peer(0x91);
let corroborator = test_peer(0x92);
let mut evidence = types::KeyVerificationEvidence {
presence: HashMap::from([(source, PresenceEvidence::Absent)]),
paid_list: HashMap::new(),
};
let failed = KeyVerificationOutcome::QuorumFailed;
assert_eq!(
punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
Some((source, SingletonHintFault::RejectedByCloseGroup)),
"a close-group rejection outranks the denial: the key does not exist, which is \
a bad hint however the sender's own disk is doing"
);
assert_eq!(
punishable_singleton_replica_hint_source(
&HashSet::from([source, corroborator]),
&failed,
&evidence,
),
None,
"corroborated hints must not use the sole-source penalty lane"
);
assert_eq!(
punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
None,
"paid-list advertisements do not claim possession, so they leave the \
replica-hint source set empty and cannot be penalized"
);
evidence
.presence
.insert(source, PresenceEvidence::Unresolved);
assert_eq!(
punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
Some((source, SingletonHintFault::RejectedByCloseGroup)),
"definitive close-group rejection is punishable without direct contradiction"
);
assert_eq!(
punishable_singleton_replica_hint_source(
&HashSet::from([source]),
&KeyVerificationOutcome::QuorumInconclusive,
&evidence,
),
None,
"timeouts and inconclusive evidence are neutral"
);
evidence.presence.insert(source, PresenceEvidence::Absent);
assert_eq!(
punishable_singleton_replica_hint_source(
&HashSet::from([source]),
&KeyVerificationOutcome::QuorumVerified {
sources: vec![corroborator],
},
&evidence,
),
Some((source, SingletonHintFault::DeniedPossession)),
"an explicit denial is punishable regardless of the overall outcome, and is \
classified separately because it is a statement about the sender's own \
storage rather than about the key"
);
}
fn slice_challenge(
challenge_id: u64,
commitment_hash: [u8; 32],
nonce: [u8; 32],
) -> protocol::SubtreeSliceChallenge {
protocol::SubtreeSliceChallenge {
challenge_id,
nonce,
challenged_peer_id: [0u8; 32],
expected_commitment_hash: commitment_hash,
openings: Vec::new(),
}
}
#[tokio::test]
async fn capacity_refused_slice_challenge_preserves_round1_session() {
let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
let inflight = Arc::new(RwLock::new(HashMap::new()));
let round1 =
SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
let peer = test_peer(0xB1);
let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
let challenge = slice_challenge(id, hash, nonce);
round1.open_session(peer, id, hash, nonce).await;
let mut hold = Vec::new();
for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
.await
{
Ok(guard) => hold.push(guard),
Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
}
}
let refused =
admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
assert!(
matches!(refused, SliceAdmission::Capacity(_)),
"a saturated peer share must refuse on capacity, not on session"
);
drop(hold);
let retried =
admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
assert!(
matches!(retried, SliceAdmission::Admitted(_)),
"the round-1 session must survive a capacity refusal so the retry succeeds"
);
drop(retried);
let replayed =
admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
assert!(
matches!(replayed, SliceAdmission::NoSession),
"a consumed session must not be replayable"
);
}
#[tokio::test]
async fn unsessioned_slice_challenge_releases_its_admission_slot() {
let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
let inflight = Arc::new(RwLock::new(HashMap::new()));
let round1 =
SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
let peer = test_peer(0xB2);
let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
let outcome =
admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
assert!(
matches!(outcome, SliceAdmission::NoSession),
"no session was ever opened, so every attempt must miss"
);
}
assert_eq!(
semaphore.available_permits(),
MAX_CONCURRENT_AUDIT_RESPONSES,
"every global permit must be returned"
);
assert!(
inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
"no per-peer slot may be left occupied"
);
}
#[test]
fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
assert!(!audit_failure_revokes_holder_credit(
&AuditFailureReason::Timeout
));
assert!(audit_failure_revokes_holder_credit(
&AuditFailureReason::DigestMismatch
));
}
#[tokio::test]
async fn audit_responder_admission_reports_per_peer_cap_full() {
let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
let inflight = Arc::new(RwLock::new(HashMap::new()));
let peer = test_peer(0xA1);
let mut guards = Vec::new();
for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
.await
{
Ok(guard) => guards.push(guard),
Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
}
}
let Err(err) =
admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
else {
panic!("admission should fail once per-peer cap is full");
};
assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
drop(guards);
}
#[tokio::test]
async fn audit_responder_admission_reports_global_pool_full() {
let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
let inflight = Arc::new(RwLock::new(HashMap::new()));
let peer = test_peer(0xA2);
let mut held_global_permits = Vec::new();
for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
held_global_permits.push(
Arc::clone(&semaphore)
.try_acquire_owned()
.expect("test should be able to exhaust the global pool"),
);
}
let Err(err) =
admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
else {
panic!("admission should fail once global pool is full");
};
assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
assert_eq!(err.peer_inflight, 0);
assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
drop(held_global_permits);
}
#[tokio::test]
async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
let semaphore = Arc::new(Semaphore::new(1));
let inflight = Arc::new(RwLock::new(HashMap::new()));
let peer = test_peer(0xA3);
let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
.await
.expect("first responder should be admitted");
assert_eq!(semaphore.available_permits(), 0);
assert_eq!(inflight.read().await.get(&peer), Some(&1));
drop(guard);
assert_eq!(semaphore.available_permits(), 1);
assert!(!inflight.read().await.contains_key(&peer));
}
#[tokio::test]
async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
let semaphore = Arc::new(Semaphore::new(1));
let inflight = Arc::new(RwLock::new(HashMap::new()));
let peer = test_peer(0xA4);
let held_map = inflight.write().await;
let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
assert!(
tokio::time::timeout(Duration::from_millis(10), waiting)
.await
.is_err(),
"admission should still be waiting for the peer map"
);
drop(held_map);
assert_eq!(semaphore.available_permits(), 1);
assert!(!inflight.read().await.contains_key(&peer));
}
#[test]
fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
let timeout = Duration::from_secs(1);
let old_received_at = Instant::now()
.checked_sub(timeout)
.unwrap_or_else(Instant::now);
assert!(request_is_stale(old_received_at, timeout));
assert!(!request_is_stale(Instant::now(), timeout));
}
#[tokio::test]
async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
let inflight = Arc::new(RwLock::new(HashMap::new()));
let first_peer = test_peer(0xB3);
let second_peer = test_peer(0xB4);
let first_guard = admit_bounded_responder(
&semaphore,
&inflight,
&first_peer,
NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
)
.await
.expect("first sync from a peer should be admitted");
let duplicate = admit_bounded_responder(
&semaphore,
&inflight,
&first_peer,
NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
)
.await;
let other_peer = admit_bounded_responder(
&semaphore,
&inflight,
&second_peer,
NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
)
.await;
assert!(matches!(
duplicate,
Err(ResponderAdmissionFailure {
reason: ResponderRejectReason::PerPeerCapFull,
..
})
));
assert!(other_peer.is_ok());
drop(first_guard);
drop(other_peer);
}
#[tokio::test]
async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
let inflight = Arc::new(RwLock::new(HashMap::new()));
let flooder = test_peer(0xC1);
let honest = test_peer(0xC2);
let mut held = Vec::new();
for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
held.push(
admit_bounded_responder(
&semaphore,
&inflight,
&flooder,
FRESH_OFFER_MAX_OUTSTANDING,
FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
)
.await
.expect("offers within the per-peer share are admitted"),
);
}
let flooder_excess = admit_bounded_responder(
&semaphore,
&inflight,
&flooder,
FRESH_OFFER_MAX_OUTSTANDING,
FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
)
.await;
assert!(
matches!(
flooder_excess,
Err(ResponderAdmissionFailure {
reason: ResponderRejectReason::PerPeerCapFull,
..
})
),
"one source must not exceed its fresh-offer share"
);
let honest_offer = admit_bounded_responder(
&semaphore,
&inflight,
&honest,
FRESH_OFFER_MAX_OUTSTANDING,
FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
)
.await;
assert!(
honest_offer.is_ok(),
"an honest sender must still be admitted while another peer floods"
);
assert!(
usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
< FRESH_OFFER_MAX_OUTSTANDING,
"the per-peer share must leave room for other sources"
);
drop(held);
drop(honest_offer);
}
#[tokio::test]
async fn paid_notify_admission_reserves_capacity_for_other_peers() {
let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
let inflight = Arc::new(RwLock::new(HashMap::new()));
let flooder = test_peer(0xC3);
let honest = test_peer(0xC4);
let mut held = Vec::new();
for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
held.push(
admit_bounded_responder(
&semaphore,
&inflight,
&flooder,
PAID_NOTIFY_MAX_OUTSTANDING,
PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
)
.await
.expect("notifies within the per-peer share are admitted"),
);
}
assert!(
matches!(
admit_bounded_responder(
&semaphore,
&inflight,
&flooder,
PAID_NOTIFY_MAX_OUTSTANDING,
PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
)
.await,
Err(ResponderAdmissionFailure {
reason: ResponderRejectReason::PerPeerCapFull,
..
})
),
"one source must not exceed its paid-notify share"
);
assert!(
admit_bounded_responder(
&semaphore,
&inflight,
&honest,
PAID_NOTIFY_MAX_OUTSTANDING,
PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
)
.await
.is_ok(),
"an honest sender must still be admitted while another peer floods"
);
drop(held);
}
#[test]
fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
assert_eq!(
FRESH_OFFER_MAX_OUTSTANDING - share,
FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
"a source holding none must always find a free slot"
);
assert!(
share < FRESH_OFFER_MAX_OUTSTANDING,
"one peer must not be able to take the whole pool"
);
assert!(
share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
"fresh offers are one-way bulk, not request/response — their share \
must not be sized like the request classes'"
);
}
#[test]
fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
let key = test_key(0xC5);
let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
.expect("an offer with no proof must be refused");
assert!(
rejection.penalise,
"an honest sender always attaches a proof"
);
let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
.expect("an undersized proof must be refused");
assert!(
rejection.penalise,
"no honest sender constructs an undersized proof"
);
let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
.expect("an oversized proof must be refused");
assert!(
rejection.penalise,
"no honest sender constructs an oversized proof"
);
let rejection = fresh_offer_structural_rejection(
&key,
&vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
&valid_proof,
)
.expect("an oversized offer must be refused");
assert!(
rejection.penalise,
"no honest sender constructs an oversized offer"
);
let data = vec![0u8; 1];
assert!(
fresh_offer_structural_rejection(
&crate::client::compute_address(&data),
&data,
&valid_proof
)
.is_none(),
"a well-formed offer must reach admission"
);
}
#[test]
fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
let genuine_data = vec![0x5Au8; 128];
let key = crate::client::compute_address(&genuine_data);
let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
.expect("bytes that do not hash to the advertised key must be refused");
assert!(
rejection.penalise,
"no honest sender offers bytes that do not hash to the advertised key"
);
assert!(
fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
"the offer that actually carries the key's bytes must reach the entry"
);
let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
assert!(
matches!(
admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
FreshOfferAdmission::Opened(_)
),
"an offer refused on payload shape must leave the key openable"
);
}
#[tokio::test]
async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
let peer = test_peer(0xA5);
let key = test_key(0xA5);
let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
let is_bootstrapping = Arc::new(RwLock::new(true));
let bootstrap_complete_notify = Arc::new(Notify::new());
let now = Instant::now();
queues.write().await.add_pending_verify(
key,
VerificationEntry {
state: VerificationState::PendingVerify,
verified_sources: Vec::new(),
tried_sources: HashSet::new(),
created_at: now,
next_verify_at: now,
hint_sources: HashSet::from([peer]),
replica_hint_sources: HashSet::from([peer]),
unresolved_retries: 0,
no_holder_reported: false,
},
);
super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
{
let q = queues.read().await;
assert!(
!super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
"capacity rejection should initially block bootstrap drain"
);
}
update_bootstrap_after_peer_removed(
&peer,
&bootstrap_state,
&queues,
&is_bootstrapping,
&bootstrap_complete_notify,
)
.await;
let state = bootstrap_state.read().await;
assert!(state.capacity_rejected_sources.is_empty());
assert!(state.pending_keys.is_empty());
assert!(state.is_drained());
drop(state);
assert!(!*is_bootstrapping.read().await);
}
#[tokio::test]
async fn fairness_displacement_does_not_stamp_its_victim() {
let displaced_owner = test_peer(0xB1);
let incoming_source = test_peer(0xB2);
let displaced_key = test_key(0xB1);
let admitted_key = test_key(0xB2);
let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
{
let mut state = bootstrap_state.write().await;
state.pending_keys.insert(displaced_key);
state
.capacity_rejected_sources
.insert(incoming_source, Instant::now());
}
let outcomes = [(
incoming_source,
AdmissionOutcome {
discovered: HashSet::from([admitted_key]),
capacity_rejected_count: 0,
displaced: vec![CapacityDisplacement {
key: displaced_key,
owner: displaced_owner,
}],
},
)];
publish_bootstrap_admission_outcomes(
&bootstrap_state,
&outcomes,
&HashSet::from([admitted_key]),
)
.await;
let state = bootstrap_state.read().await;
assert!(!state.pending_keys.contains(&displaced_key));
assert!(state.pending_keys.contains(&admitted_key));
assert!(
!state
.capacity_rejected_sources
.contains_key(&displaced_owner),
"the displaced owner must not be charged for our own fairness reclaim"
);
assert!(!state
.capacity_rejected_sources
.contains_key(&incoming_source));
}
#[tokio::test]
async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
const REJECTION_ROUNDS: usize = 5;
let source = test_peer(0xB3);
let key = test_key(0xB3);
let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
let first_seen = {
let outcomes = [(
source,
AdmissionOutcome {
discovered: HashSet::new(),
capacity_rejected_count: 1,
displaced: Vec::new(),
},
)];
publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
.await;
bootstrap_state
.read()
.await
.capacity_rejected_sources
.get(&source)
.copied()
.expect("first rejection recorded")
};
for _ in 0..REJECTION_ROUNDS {
let outcomes = [(
source,
AdmissionOutcome {
discovered: HashSet::from([key]),
capacity_rejected_count: 1,
displaced: Vec::new(),
},
)];
publish_bootstrap_admission_outcomes(
&bootstrap_state,
&outcomes,
&HashSet::from([key]),
)
.await;
}
let recorded = bootstrap_state
.read()
.await
.capacity_rejected_sources
.get(&source)
.copied()
.expect("debt still outstanding");
assert_eq!(
recorded, first_seen,
"repeat rejections must not restart the expiry clock"
);
}
#[tokio::test]
async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
let peer = test_peer(0xA6);
let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
let is_bootstrapping = Arc::new(RwLock::new(true));
let bootstrap_complete_notify = Arc::new(Notify::new());
super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
expire_and_recheck_bootstrap_drain(
&bootstrap_state,
&queues,
&is_bootstrapping,
&bootstrap_complete_notify,
ReplicationConfig::default().capacity_rejected_max_age(),
)
.await;
assert!(!bootstrap_state.read().await.is_drained());
assert!(*is_bootstrapping.read().await);
expire_and_recheck_bootstrap_drain(
&bootstrap_state,
&queues,
&is_bootstrapping,
&bootstrap_complete_notify,
Duration::ZERO,
)
.await;
assert!(bootstrap_state.read().await.is_drained());
assert!(!*is_bootstrapping.read().await);
}
#[test]
fn first_audit_terminal_outcomes_are_stable() {
let peer = test_peer(1);
let passed = AuditTickResult::Passed {
challenged_peer: peer,
keys_checked: 1,
};
let timed_out = AuditTickResult::Failed {
evidence: FailureEvidence::AuditFailure {
challenge_id: 1,
challenged_peer: peer,
confirmed_failed_keys: vec![test_key(1)],
summary: crate::replication::types::AuditFailureSummary::default(),
reason: AuditFailureReason::Timeout,
},
no_response_class: Some("timeout"),
};
assert_eq!(
first_audit_terminal_outcome(&passed),
FirstAuditTerminalOutcome::Passed
);
assert_eq!(
first_audit_terminal_outcome(&timed_out),
FirstAuditTerminalOutcome::Timeout
);
assert_eq!(
first_audit_terminal_outcome(&AuditTickResult::Idle),
FirstAuditTerminalOutcome::Idle
);
assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
assert_eq!(
FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
"insufficient_keys"
);
assert_eq!(
FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
"bootstrap_claim"
);
}
#[test]
fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
let mut rng = StdRng::seed_from_u64(7);
let peer = test_peer(1);
let base = MonetizedPinEvent {
peer,
pin: [1; 32],
key_count: 100,
quote_ts: SystemTime::now(),
};
assert_eq!(
coalesce_first_audit_event(&mut pending, base, true, &mut rng),
FirstAuditQueueOutcome::Queued
);
let lower = MonetizedPinEvent {
pin: [2; 32],
key_count: 50,
..base
};
assert_eq!(
coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
FirstAuditQueueOutcome::SuppressedLower
);
assert_eq!(
pending.peek(&peer).map(|e| (e.pin, e.key_count)),
Some(([1; 32], 100)),
"the higher-count pin is retained"
);
let higher = MonetizedPinEvent {
pin: [3; 32],
key_count: 400,
..base
};
assert_eq!(
coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
FirstAuditQueueOutcome::Coalesced
);
assert_eq!(
pending.peek(&peer).map(|e| (e.pin, e.key_count)),
Some(([3; 32], 400))
);
let equal_newer = MonetizedPinEvent {
pin: [4; 32],
key_count: 400,
..base
};
assert_eq!(
coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
FirstAuditQueueOutcome::Coalesced
);
assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
let equal_older = MonetizedPinEvent {
pin: [5; 32],
key_count: 400,
..base
};
assert_eq!(
coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
FirstAuditQueueOutcome::RetainedOnTie
);
assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
let other_peer = MonetizedPinEvent {
peer: test_peer(2),
pin: [6; 32],
key_count: 100,
..base
};
assert_eq!(
coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
);
assert_eq!(pending.len(), 1);
assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
}
#[test]
fn first_audit_limiter_enforces_burst_then_refills() {
let base = Instant::now();
let mut limiter = FirstAuditLimiter::new(base);
let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
let peer = test_peer(u8::try_from(i).expect("small burst"));
assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
limiter.commit_launch(peer, 10, base);
}
let extra = test_peer(0xEE);
assert_eq!(
limiter.assess(&extra, 10, base, 0),
LimiterVerdict::RateDeferred
);
let later = base + interval;
assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
limiter.commit_launch(extra, 10, later);
let extra2 = test_peer(0xEF);
assert_eq!(
limiter.assess(&extra2, 10, later, 0),
LimiterVerdict::RateDeferred
);
}
#[test]
fn first_audit_limiter_refill_keeps_fractional_remainder() {
let base = Instant::now();
let mut limiter = FirstAuditLimiter::new(base);
let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
let peer = test_peer(u8::try_from(i).expect("small burst"));
assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
limiter.commit_launch(peer, 1, base);
}
let at_1_5 = base + interval + interval / 2;
let p = test_peer(0xAA);
assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
limiter.commit_launch(p, 1, at_1_5);
let at_2_0 = base + interval * 2;
let q = test_peer(0xAB);
assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
}
#[test]
fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
let base = Instant::now();
let mut limiter = FirstAuditLimiter::new(base);
let peer = test_peer(1);
assert_eq!(
limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
LimiterVerdict::RateDeferred
);
assert_eq!(
limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
LimiterVerdict::Admit
);
}
#[test]
fn first_audit_limiter_assess_consumes_nothing() {
let base = Instant::now();
let mut limiter = FirstAuditLimiter::new(base);
let peer = test_peer(3);
for _ in 0..10 {
assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
}
for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
limiter.commit_launch(p, 5, base);
}
}
#[test]
fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
let base = Instant::now();
let mut limiter = FirstAuditLimiter::new(base);
let peer = test_peer(7);
assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
limiter.commit_launch(peer, 100, base);
let soon = base + Duration::from_secs(60);
assert_eq!(
limiter.assess(&peer, 100, soon, 0),
LimiterVerdict::WindowDeduped
);
assert_eq!(
limiter.assess(&peer, 150, soon, 0),
LimiterVerdict::WindowDeduped
);
assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
assert_eq!(
limiter.assess(&peer, 100, expired, 0),
LimiterVerdict::Admit
);
}
#[test]
fn first_audit_limiter_window_verdict_outranks_empty_budget() {
let base = Instant::now();
let mut limiter = FirstAuditLimiter::new(base);
let peer = test_peer(9);
assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
limiter.commit_launch(peer, 10, base);
let other = test_peer(10);
assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
limiter.commit_launch(other, 10, base);
assert_eq!(
limiter.assess(&peer, 10, base, 0),
LimiterVerdict::WindowDeduped
);
}
#[test]
fn first_audit_horizon_prefilter_boundary() {
let now = SystemTime::now();
let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
let boundary = now
.checked_add(h)
.and_then(|t| t.checked_sub(c))
.expect("boundary time");
assert!(quote_within_audit_window(boundary, now));
assert!(!quote_answerable_through_nominal_jitter(boundary, now));
let newer = boundary
.checked_add(Duration::from_micros(1))
.expect("newer");
let older = boundary
.checked_sub(Duration::from_micros(1))
.expect("older");
assert!(quote_answerable_through_nominal_jitter(newer, now));
assert!(!quote_answerable_through_nominal_jitter(older, now));
let future = now
.checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
.and_then(|t| t.checked_add(Duration::from_secs(60)))
.expect("future");
assert!(!quote_answerable_through_nominal_jitter(future, now));
}
#[test]
fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
let obs = Arc::new(FirstAuditObservability::default());
let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
let peer = test_peer(1);
let dead_quote = SystemTime::now()
.checked_sub(GOSSIP_ANSWERABILITY_TTL)
.and_then(|t| t.checked_sub(Duration::from_secs(60)))
.expect("past wall time");
let stale_high = MonetizedPinEvent {
peer,
pin: [1; 32],
key_count: 400,
quote_ts: dead_quote,
};
scheduler.enqueue(stale_high, &obs);
assert_eq!(scheduler.pending_len(), 1);
let fresh_lower = MonetizedPinEvent {
peer,
pin: [2; 32],
key_count: 100,
quote_ts: SystemTime::now(),
};
scheduler.enqueue(fresh_lower, &obs);
assert_eq!(scheduler.pending_len(), 1);
assert_eq!(
scheduler.pending.peek(&peer).map(|e| e.pin),
Some([2; 32]),
"the live nomination replaced the dead incumbent"
);
assert_eq!(
obs.suppressed_lower.load(Ordering::Relaxed),
0,
"no self-erasure signal for displacing a dead pin"
);
assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
assert_eq!(
obs.outside_answerability_window.load(Ordering::Relaxed),
1,
"the dead incumbent is accounted as an expiry"
);
}
#[test]
fn first_audit_live_incumbent_still_suppresses_lower_count() {
let obs = Arc::new(FirstAuditObservability::default());
let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
let peer = test_peer(1);
let live_high = MonetizedPinEvent {
peer,
pin: [1; 32],
key_count: 400,
quote_ts: SystemTime::now(),
};
scheduler.enqueue(live_high, &obs);
let cheaper = MonetizedPinEvent {
peer,
pin: [2; 32],
key_count: 100,
quote_ts: SystemTime::now(),
};
scheduler.enqueue(cheaper, &obs);
assert_eq!(scheduler.pending_len(), 1);
assert_eq!(
scheduler.pending.peek(&peer).map(|e| e.pin),
Some([1; 32]),
"the higher-count live pin is retained"
);
assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
}
fn live_nomination(b: u8) -> MonetizedPinEvent {
MonetizedPinEvent {
peer: test_peer(b),
pin: [b; 32],
key_count: 100,
quote_ts: SystemTime::now(),
}
}
#[test]
fn first_audit_pending_cap_matches_strict_launch_horizon() {
let quote_ts = SystemTime::now();
assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
let mut refill = 1u32;
loop {
let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
let at = quote_ts + age;
if !quote_answerable_through_nominal_jitter(quote_ts, at) {
break;
}
usable += 1;
refill += 1;
assert!(refill < 10_000, "runaway horizon simulation");
}
assert_eq!(
FIRST_AUDIT_PENDING_CAP, usable,
"cap must match the simulated strict launch horizon"
);
}
#[test]
fn first_audit_pending_cap_independent_of_dedup_cap() {
let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
assert_eq!(
scheduler.first_audited.cap().get(),
MAX_LAST_COMMITMENT_BY_PEER
);
}
#[test]
fn first_audit_admission_beyond_cap_displaces_and_counts() {
let obs = Arc::new(FirstAuditObservability::default());
let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
let overflow: usize = 5;
let total = FIRST_AUDIT_PENDING_CAP + overflow;
for i in 0..total {
let b = u8::try_from(i + 1).expect("test peer count fits u8");
scheduler.enqueue(live_nomination(b), &obs);
}
assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
assert_eq!(
obs.capacity_evicted.load(Ordering::Relaxed),
u64::try_from(overflow).expect("overflow fits u64"),
"each admission past the cap displaces exactly one entry"
);
assert_eq!(
obs.queued.load(Ordering::Relaxed),
u64::try_from(total).expect("total fits u64"),
"displacement is not an admission refusal"
);
let last = u8::try_from(total).expect("test peer count fits u8");
assert!(
scheduler.pending.peek(&test_peer(last)).is_some(),
"the newest arrival always enters the sample"
);
}
#[test]
fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
let flood: usize = 60; assert!(FIRST_AUDIT_PENDING_CAP < flood);
assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
let trials = 100u64;
let mut survived = 0u32;
let mut evicted = 0u32;
for trial in 0..trials {
let obs = Arc::new(FirstAuditObservability::default());
let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
scheduler.rng = StdRng::seed_from_u64(trial);
scheduler.limiter.reserve_token();
scheduler.limiter.reserve_token();
let target = test_peer(200);
scheduler.enqueue(live_nomination(200), &obs);
for i in 0..flood {
let b = u8::try_from(i + 1).expect("flood peer fits u8");
scheduler.enqueue(live_nomination(b), &obs);
}
assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
.expect("overflow count fits u64");
assert_eq!(
obs.capacity_evicted.load(Ordering::Relaxed),
overflows,
"every overflow past the cap is accounted, none silent"
);
if scheduler.pending.peek(&target).is_some() {
survived += 1;
} else {
evicted += 1;
}
}
assert!(
survived > 0,
"target must survive some ordered floods — deterministic eviction \
would mean keep-newest retention regressed"
);
assert!(
evicted > 0,
"target must also be displaceable — otherwise overflow is refusing \
admissions instead of sampling"
);
}
#[test]
fn first_audit_overflow_reserves_before_destructive_eviction() {
let obs = Arc::new(FirstAuditObservability::default());
let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
let cooldown: HashMap<PeerId, Instant> = HashMap::new();
for i in 0..FIRST_AUDIT_PENDING_CAP {
let b = u8::try_from(i + 1).expect("test peer count fits u8");
scheduler.enqueue(live_nomination(b), &obs);
}
let overflowing = live_nomination(250);
assert!(scheduler.would_displace(&overflowing));
assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
assert!(
!scheduler.would_displace(&overflowing),
"a successful reservation frees the slot"
);
scheduler.enqueue(overflowing, &obs);
assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
assert_eq!(
obs.capacity_evicted.load(Ordering::Relaxed),
0,
"no destructive eviction when a launch opportunity existed"
);
}
#[test]
fn first_audit_displaced_peer_may_be_renominated() {
let obs = Arc::new(FirstAuditObservability::default());
let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
let total = FIRST_AUDIT_PENDING_CAP + 1;
for i in 0..total {
let b = u8::try_from(i + 1).expect("test peer count fits u8");
scheduler.enqueue(live_nomination(b), &obs);
}
assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
let displaced = (1..=total)
.map(|i| u8::try_from(i).expect("test peer count fits u8"))
.find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
.expect("exactly one admitted peer was displaced");
scheduler.enqueue(live_nomination(displaced), &obs);
assert!(
scheduler.pending.peek(&test_peer(displaced)).is_some(),
"the displaced peer re-enters the sample"
);
assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
}
#[test]
fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
let obs = Arc::new(FirstAuditObservability::default());
let mono = Instant::now();
let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
let dead_quote = SystemTime::now()
.checked_sub(GOSSIP_ANSWERABILITY_TTL)
.and_then(|t| t.checked_sub(Duration::from_secs(60)))
.expect("past wall time");
scheduler.enqueue(
MonetizedPinEvent {
peer: test_peer(1),
pin: [1; 32],
key_count: 100,
quote_ts: dead_quote,
},
&obs,
);
scheduler.enqueue(
MonetizedPinEvent {
peer: test_peer(2),
pin: [2; 32],
key_count: 100,
quote_ts: SystemTime::now(),
},
&obs,
);
assert_eq!(scheduler.pending_len(), 2);
scheduler.limiter.tokens = 0;
let cooldown: HashMap<PeerId, Instant> = HashMap::new();
assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
assert_eq!(
scheduler.pending_len(),
2,
"budget-gated reserve scans nothing"
);
let wall_now = SystemTime::now();
assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
assert_eq!(scheduler.pending_len(), 1);
assert!(
scheduler.pending.peek(&test_peer(2)).is_some(),
"the live entry survives the sweep"
);
assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
assert!(
Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
"the age gauge reflects only live work after the sweep"
);
}
#[test]
#[allow(clippy::too_many_lines)]
fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
let obs = Arc::new(FirstAuditObservability::default());
let mono = Instant::now();
let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
let sentinel_peer = test_peer(0xAA);
scheduler.limiter.promote(sentinel_peer, 500, mono);
let sentinel_before = scheduler
.limiter
.recent
.peek(&sentinel_peer)
.copied()
.expect("sentinel present");
let peer = test_peer(1);
let a = MonetizedPinEvent {
peer,
pin: [1; 32],
key_count: 100,
quote_ts: SystemTime::now(), };
scheduler.enqueue(a, &obs);
let tokens_before = scheduler.tokens();
let lane_before = scheduler.oldest_first_lane;
let launched_before = obs.launched.load(Ordering::Relaxed);
let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
let inflight0 = obs.inflight.load(Ordering::Relaxed);
assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
assert_eq!(scheduler.reserved_peer(), Some(peer));
assert_eq!(
scheduler.tokens(),
tokens_before - 1,
"reserve consumes a token"
);
assert_eq!(
obs.inflight.load(Ordering::Relaxed),
1,
"reserve holds a slot"
);
let b = MonetizedPinEvent {
peer,
pin: [2; 32],
key_count: 100,
quote_ts: SystemTime::now(),
};
scheduler.enqueue(b, &obs);
assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
assert!(
!scheduler.try_reserve(
mono,
obs.inflight.load(Ordering::Relaxed),
Duration::ZERO,
&cooldown,
&obs
),
"no second reservation while one is outstanding"
);
let reservation = scheduler
.take_due_reservation(mono)
.expect("A is due at jitter 0");
let wall_fail = a
.quote_ts
.checked_add(GOSSIP_ANSWERABILITY_TTL)
.and_then(|t| t.checked_add(Duration::from_secs(1)))
.expect("past-cutoff wall time");
let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
assert!(
promoted.is_none(),
"answerability lapsed -> cancelled, not promoted"
);
assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
assert!(
scheduler.limiter.recent.peek(&peer).is_none(),
"cancel stamps no per-peer window"
);
assert_eq!(
scheduler.limiter.recent.peek(&sentinel_peer).copied(),
Some(sentinel_before),
"unrelated window sentinel untouched"
);
assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
assert_eq!(
scheduler.tokens(),
tokens_before,
"token refunded on cancel"
);
assert_eq!(
obs.inflight.load(Ordering::Relaxed),
0,
"in-flight slot released"
);
assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
assert_eq!(
obs.launched.load(Ordering::Relaxed),
launched_before,
"no launch counted"
);
assert_eq!(
obs.outside_answerability_window.load(Ordering::Relaxed),
1,
"the cancel reason is recorded"
);
assert_eq!(
scheduler.pending_len(),
1,
"successor still pending after cancel"
);
assert!(scheduler.reserved.is_none());
assert!(scheduler.try_reserve(
mono,
obs.inflight.load(Ordering::Relaxed),
Duration::ZERO,
&cooldown,
&obs
));
assert_eq!(
scheduler.reserved_peer(),
Some(peer),
"the retained successor becomes the next reservation"
);
}
#[test]
fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
let obs = Arc::new(FirstAuditObservability::default());
let mono = Instant::now();
let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
let peer = test_peer(1);
let a = MonetizedPinEvent {
peer,
pin: [1; 32],
key_count: 100,
quote_ts: SystemTime::now(),
};
scheduler.enqueue(a, &obs);
let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
let b = MonetizedPinEvent {
peer,
pin: [2; 32],
key_count: 400,
quote_ts: SystemTime::now(),
};
scheduler.enqueue(b, &obs);
assert_eq!(scheduler.pending_len(), 1);
let reservation = scheduler.take_due_reservation(mono).expect("due");
let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
cooldown.insert(peer, mono); let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
assert!(promoted.is_none(), "cooldown race -> not promoted");
assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
assert_eq!(
scheduler.pending.peek(&peer).map(|e| e.pin),
Some([2; 32]),
"the newer successor B is retained, not the older reserved A"
);
assert!(scheduler.first_audited.is_empty());
assert!(scheduler.limiter.recent.peek(&peer).is_none());
}
#[test]
fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
let now = SystemTime::now();
let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
assert_eq!(
scheduler.oldest_pending_quote_age_ms(now),
0,
"empty pending -> zero"
);
for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
let _ = coalesce_first_audit_event(
&mut scheduler.pending,
MonetizedPinEvent {
peer: test_peer(peer_id),
pin,
key_count: 100,
quote_ts: now - Duration::from_secs(secs),
},
true,
&mut scheduler.rng,
);
}
assert_eq!(
scheduler.oldest_pending_quote_age_ms(now),
10_000,
"tracks the oldest (10s), not the newest (2s)"
);
let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
let _ = coalesce_first_audit_event(
&mut skewed.pending,
MonetizedPinEvent {
peer: test_peer(3),
pin: [3; 32],
key_count: 100,
quote_ts: now + Duration::from_secs(5),
},
true,
&mut skewed.rng,
);
assert_eq!(
skewed.oldest_pending_quote_age_ms(now),
0,
"future quote_ts saturates to zero"
);
}
#[test]
fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
let mut pending: LruCache<PeerId, MonetizedPinEvent> =
LruCache::new(NonZeroUsize::new(2).unwrap());
let mut rng = StdRng::seed_from_u64(11);
let victim = test_peer(1);
let other = test_peer(2);
let _ = coalesce_first_audit_event(
&mut pending,
MonetizedPinEvent {
peer: victim,
pin: [1; 32],
key_count: 400,
quote_ts: SystemTime::now(),
},
true,
&mut rng,
);
let _ = coalesce_first_audit_event(
&mut pending,
MonetizedPinEvent {
peer: other,
pin: [9; 32],
key_count: 100,
quote_ts: SystemTime::now(),
},
true,
&mut rng,
);
let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
assert_eq!(
order_before,
vec![other, victim],
"sanity: `other` is MRU, the victim is LRU"
);
let mut suppressed = 0u64;
for i in 0..8u8 {
let out = coalesce_first_audit_event(
&mut pending,
MonetizedPinEvent {
peer: victim,
pin: [i; 32],
key_count: 50,
quote_ts: SystemTime::now(),
},
true,
&mut rng,
);
assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
suppressed += 1;
}
assert_eq!(suppressed, 8);
assert_eq!(
pending.peek(&victim).map(|e| (e.pin, e.key_count)),
Some(([1; 32], 400))
);
let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
assert_eq!(
order_after, order_before,
"the suppressed-lower flood must not have changed any recency position"
);
}
#[test]
fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
let obs = Arc::new(FirstAuditObservability::default());
let mono = Instant::now();
let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
let reserved_peer = test_peer(1);
let other_peer = test_peer(2);
scheduler.enqueue(
MonetizedPinEvent {
peer: reserved_peer,
pin: [1; 32],
key_count: 100,
quote_ts: SystemTime::now(),
},
&obs,
);
let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
scheduler.enqueue(
MonetizedPinEvent {
peer: other_peer,
pin: [2; 32],
key_count: 100,
quote_ts: SystemTime::now(),
},
&obs,
);
assert_eq!(scheduler.pending_len(), 1);
let reservation = scheduler.take_due_reservation(mono).expect("due");
let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
cooldown.insert(reserved_peer, mono);
let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
assert!(scheduler
.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
.is_none());
assert_eq!(
obs.capacity_evicted.load(Ordering::Relaxed),
cap_before + 1,
"the requeue eviction of a different peer is counted"
);
assert_eq!(
scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
Some([1; 32])
);
}
#[test]
fn first_audit_pending_lower_count_does_not_replace_higher() {
let obs = Arc::new(FirstAuditObservability::default());
let mono = Instant::now();
let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
let peer = test_peer(1);
scheduler.enqueue(
MonetizedPinEvent {
peer,
pin: [1; 32],
key_count: 400,
quote_ts: SystemTime::now(),
},
&obs,
);
scheduler.enqueue(
MonetizedPinEvent {
peer,
pin: [2; 32],
key_count: 100,
quote_ts: SystemTime::now(),
},
&obs,
);
assert_eq!(scheduler.pending_len(), 1);
assert_eq!(
scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
Some(([1; 32], 400)),
"the inflated pin must not be erased by the cheaper successor"
);
assert_eq!(
obs.suppressed_lower.load(Ordering::Relaxed),
1,
"the attempted cheaper-pin self-erasure is observable"
);
let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
let reservation = scheduler.take_due_reservation(mono).expect("due");
let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
let (event, _slot) = scheduler
.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
.expect("promotes");
assert_eq!((event.pin, event.key_count), ([1; 32], 400));
}
#[test]
fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
let obs = Arc::new(FirstAuditObservability::default());
let mono = Instant::now();
let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
let peer = test_peer(1);
scheduler.enqueue(
MonetizedPinEvent {
peer,
pin: [1; 32],
key_count: 400,
quote_ts: SystemTime::now(),
},
&obs,
);
let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
scheduler.enqueue(
MonetizedPinEvent {
peer,
pin: [2; 32],
key_count: 100,
quote_ts: SystemTime::now(),
},
&obs,
);
assert_eq!(scheduler.pending_len(), 1);
let reservation = scheduler.take_due_reservation(mono).expect("due");
let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
cooldown.insert(peer, mono);
assert!(scheduler
.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
.is_none());
assert_eq!(scheduler.pending_len(), 1);
assert_eq!(
scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
Some(([1; 32], 400)),
"the inflated reserved pin must survive the requeue over the cheaper successor"
);
assert!(scheduler.first_audited.is_empty());
assert!(scheduler.limiter.recent.peek(&peer).is_none());
let later = mono
.checked_add(Duration::from_secs(
config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
))
.expect("later");
let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
let reservation = scheduler.take_due_reservation(later).expect("due");
let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
let (event, _slot) = scheduler
.resolve(
reservation,
SystemTime::now(),
later,
&mut cooldown_later,
&obs,
)
.expect("promotes after cooldown");
assert_eq!((event.pin, event.key_count), ([1; 32], 400));
}
#[test]
fn first_audit_lane_alternates_across_promotions() {
let obs = Arc::new(FirstAuditObservability::default());
let mono = Instant::now();
let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
let oldest_peer = test_peer(1);
let newest_peer = test_peer(2);
scheduler.enqueue(
MonetizedPinEvent {
peer: oldest_peer,
pin: [1; 32],
key_count: 100,
quote_ts: SystemTime::now(),
},
&obs,
);
scheduler.enqueue(
MonetizedPinEvent {
peer: newest_peer,
pin: [2; 32],
key_count: 100,
quote_ts: SystemTime::now(),
},
&obs,
);
let mut launched_peers = Vec::new();
for _ in 0..2 {
assert!(scheduler.try_reserve(
mono,
obs.inflight.load(Ordering::Relaxed),
Duration::ZERO,
&cooldown,
&obs
));
let reservation = scheduler.take_due_reservation(mono).expect("due");
let (event, _slot) = scheduler
.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
.expect("fresh in-window quote promotes");
launched_peers.push(event.peer);
}
assert_eq!(
launched_peers,
vec![newest_peer, oldest_peer],
"consecutive promotions alternate newest-then-oldest lane"
);
}
#[test]
fn first_audit_count_jump_boundaries() {
assert!(!first_audit_count_jump(100, 150));
assert!(first_audit_count_jump(100, 151));
assert!(first_audit_count_jump(0, 1));
assert!(!first_audit_count_jump(0, 0));
assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
}
#[test]
fn first_audit_queue_drops_self_targeting_events() {
let obs = Arc::new(FirstAuditObservability::default());
let self_peer = test_peer(1);
let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
let self_event = MonetizedPinEvent {
peer: self_peer,
pin: [7; 32],
key_count: 1,
quote_ts: SystemTime::now(),
};
scheduler.enqueue(self_event, &obs);
assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
let remote_event = MonetizedPinEvent {
peer: test_peer(2),
pin: [8; 32],
..self_event
};
scheduler.enqueue(remote_event, &obs);
assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
assert_eq!(scheduler.pending_len(), 1);
assert_eq!(
obs.self_target_skipped.load(Ordering::Relaxed),
1,
"remote event must not count as a self-target skip"
);
}
#[test]
fn fresh_offer_runs_store_admission_payment_checks() {
let context = fresh_offer_payment_context();
assert_eq!(context, VerificationContext::FreshReplication);
assert!(context.is_store_admission());
}
#[test]
fn paid_notify_uses_paid_list_admission_payment_checks() {
assert_eq!(
paid_notify_payment_context(),
VerificationContext::PaidListAdmission
);
}
#[test]
fn monetized_quote_audit_window_fails_closed_both_ends() {
let now = SystemTime::now();
assert!(quote_within_audit_window(now, now));
assert!(quote_within_audit_window(
now + Duration::from_secs(60),
now
));
assert!(quote_within_audit_window(
now - Duration::from_secs(3600),
now
));
assert!(!quote_within_audit_window(
now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_secs(60),
now
));
assert!(!quote_within_audit_window(
now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
now
));
}
#[tokio::test]
async fn replication_branch_lagged_events_are_counted() {
let before = audit_metrics::replication_event_lagged_total();
let flow = handle_replication_event_recv_error(
&tokio::sync::broadcast::error::RecvError::Lagged(3),
);
assert_eq!(flow, std::ops::ControlFlow::Continue(()));
let after = audit_metrics::replication_event_lagged_total();
assert_eq!(after.saturating_sub(before), 3);
}
#[tokio::test]
async fn replication_branch_closed_events_stop_the_loop() {
let flow =
handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
assert_eq!(flow, std::ops::ControlFlow::Break(()));
}
#[tokio::test]
async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
let (sender, mut receiver) = mpsc::channel(1);
let dropped_body =
ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
keys: Vec::new(),
paid_list_check_indices: Vec::new(),
});
let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
let first = InboundReplicationMessage {
source: test_peer(0xC1),
msg: ReplicationMessage {
request_id: 1,
body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
key: test_key(1),
}),
},
rr_message_id: None,
received_at: Instant::now(),
};
let second = InboundReplicationMessage {
source: test_peer(0xC2),
msg: ReplicationMessage {
request_id: 2,
body: dropped_body.clone(),
},
rr_message_id: None,
received_at: Instant::now(),
};
assert!(try_enqueue_serial_message(&sender, first).is_ok());
let dropped = try_enqueue_serial_message(&sender, second)
.expect_err("a full serial queue must refuse the second message");
assert_eq!(dropped.reason, SerialQueueDropReason::Full);
assert_eq!(dropped.message_class, "verification_request");
assert_eq!(dropped.queue_depth, 1);
let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
let queued = receiver
.recv()
.await
.expect("first message should remain queued");
assert_eq!(queued.msg.request_id, 1);
assert!(receiver.try_recv().is_err());
}
#[tokio::test]
async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
let peer = test_peer(0x44);
let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
let mut digest_guards = Vec::new();
for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
let guard = admit_audit_responder(
&semaphore,
&digest_inflight,
&peer,
AuditResponderClass::Digest,
)
.await;
assert!(guard.is_ok());
digest_guards.push(guard);
}
assert!(
admit_audit_responder(
&semaphore,
&digest_inflight,
&peer,
AuditResponderClass::Digest,
)
.await
.is_err(),
"digest class must stop at its documented per-source cap"
);
drop(digest_guards);
let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
let mut subtree_guards = Vec::new();
for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
let guard = admit_audit_responder(
&semaphore,
&subtree_inflight,
&peer,
AuditResponderClass::Subtree,
)
.await;
assert!(guard.is_ok());
subtree_guards.push(guard);
}
assert!(
admit_audit_responder(
&semaphore,
&subtree_inflight,
&peer,
AuditResponderClass::Subtree,
)
.await
.is_err(),
"subtree class must retain the deployed cap of two"
);
drop(subtree_guards);
}
#[test]
fn in_scope_audit_deadlines_share_one_formula() {
let config = config::ReplicationConfig::default();
for key_count in [1, 4, 16] {
assert_eq!(
audit::responsible_audit_response_timeout(&config, key_count),
config.audit_response_timeout(key_count)
);
assert_eq!(
pruning::prune_audit_response_timeout(&config, key_count),
config.audit_response_timeout(key_count)
);
}
assert_eq!(
possession::possession_probe_response_timeout(&config),
config.audit_response_timeout(1)
);
}
#[test]
fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
const EXISTING_SOURCE_ID: u8 = 1;
const HINT_SENDER_ID: u8 = 2;
let existing_source = test_peer(EXISTING_SOURCE_ID);
let hint_sender = test_peer(HINT_SENDER_ID);
let mut sources = vec![existing_source];
let hint_sources = HashSet::from([hint_sender]);
add_replica_hint_sources(&mut sources, &hint_sources);
add_replica_hint_sources(&mut sources, &hint_sources);
add_replica_hint_sources(&mut sources, &HashSet::new());
assert_eq!(sources, vec![existing_source, hint_sender]);
}
#[test]
fn audit_timeout_preserves_active_bootstrap_claim() {
assert!(!audit_failure_clears_bootstrap_claim(
&AuditFailureReason::Timeout
));
}
fn strike_peer(b: u8) -> PeerId {
let mut bytes = [0u8; 32];
bytes[0] = b;
PeerId::from_bytes(bytes)
}
#[test]
fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
let peer = strike_peer(1);
let mut map: HashMap<PeerId, Instant> = HashMap::new();
let t0 = Instant::now();
assert!(cooldown_allows_audit(&mut map, &peer, t0));
let mut passed = 1;
for _ in 0..100 {
if cooldown_allows_audit(&mut map, &peer, t0) {
passed += 1;
}
}
assert_eq!(
passed, 1,
"a flood at one instant must trigger exactly one audit"
);
}
#[test]
fn losing_lottery_still_consumes_attempt_window() {
let peer = strike_peer(3);
let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
let mut launched: HashMap<PeerId, Instant> = HashMap::new();
let t0 = Instant::now();
assert!(
!audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
"a losing ticket launches no audit"
);
let mut audits = 0;
for _ in 0..99 {
if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
audits += 1;
}
}
assert_eq!(
audits, 0,
"a losing first ticket must consume the attempt window so no later \
flooded message in the same window can audit"
);
let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
assert!(
audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
"after the window a winning ticket audits again"
);
assert!(
launched.contains_key(&peer),
"a real launch stamps the shared cooldown"
);
}
#[test]
fn losing_lottery_does_not_suppress_monetized_first_audit() {
let peer = strike_peer(4);
let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
let mut launched: HashMap<PeerId, Instant> = HashMap::new();
let t0 = Instant::now();
assert!(!audit_launch_decision(
&mut attempts,
&mut launched,
&peer,
t0,
false
));
assert!(
cooldown_would_allow(&launched, &peer, t0),
"reserve gate must not see a losing ticket as audit coverage"
);
assert!(
cooldown_allows_audit(&mut launched, &peer, t0),
"promotion must not be deferred by a losing ticket"
);
let peer_won = strike_peer(5);
assert!(audit_launch_decision(
&mut attempts,
&mut launched,
&peer_won,
t0,
true
));
assert!(
!cooldown_would_allow(&launched, &peer_won, t0),
"a real gossip audit still covers the peer for the window"
);
}
#[test]
fn cooldown_lets_audit_through_after_the_window() {
let peer = strike_peer(2);
let mut map: HashMap<PeerId, Instant> = HashMap::new();
let t0 = Instant::now();
assert!(cooldown_allows_audit(&mut map, &peer, t0));
let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
assert!(!cooldown_allows_audit(&mut map, &peer, within));
let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
assert!(cooldown_allows_audit(&mut map, &peer, after));
}
#[test]
fn cooldown_is_per_peer_independent() {
let mut map: HashMap<PeerId, Instant> = HashMap::new();
let t0 = Instant::now();
for i in 0..20u8 {
assert!(
cooldown_allows_audit(&mut map, &strike_peer(i), t0),
"peer {i} should be auditable independently"
);
}
}
#[test]
fn audit_on_gossip_constants_match_adr() {
assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
}
#[test]
fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
assert!(audit_failure_clears_bootstrap_claim(
&AuditFailureReason::DigestMismatch
));
assert!(audit_failure_revokes_holder_credit(
&AuditFailureReason::DigestMismatch
));
}
#[test]
fn confirmed_failures_revoke_credit_timeout_does_not() {
for reason in [
AuditFailureReason::MalformedResponse,
AuditFailureReason::DigestMismatch,
AuditFailureReason::KeyAbsent,
AuditFailureReason::Rejected,
] {
assert!(
audit_failure_revokes_holder_credit(&reason),
"confirmed failure {reason:?} must revoke holder credit"
);
}
assert!(
!audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
"Timeout must NOT revoke credit (single dropped packet != storage loss)"
);
}
#[test]
fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
let peer = test_peer(0xAB);
let key = test_key(1);
let hash = [0xCD; 32];
let mut provers = RecentProvers::new();
provers.record_proof(key, peer, hash, Instant::now());
assert!(
provers.is_credited_holder(&key, &peer, &hash),
"precondition: peer credited before failure"
);
apply_audit_failure_credit_revocation(
&mut provers,
&peer,
&AuditFailureReason::DigestMismatch,
);
assert!(
!provers.is_credited_holder(&key, &peer, &hash),
"DigestMismatch must strip the peer's holder credit"
);
let mut provers_timeout = RecentProvers::new();
provers_timeout.record_proof(key, peer, hash, Instant::now());
apply_audit_failure_credit_revocation(
&mut provers_timeout,
&peer,
&AuditFailureReason::Timeout,
);
assert!(
provers_timeout.is_credited_holder(&key, &peer, &hash),
"Timeout must retain holder credit (deliberate liveness cushion)"
);
}
#[test]
fn decoded_audit_failures_clear_active_bootstrap_claim() {
for reason in [
AuditFailureReason::MalformedResponse,
AuditFailureReason::DigestMismatch,
AuditFailureReason::KeyAbsent,
AuditFailureReason::Rejected,
] {
assert!(
audit_failure_clears_bootstrap_claim(&reason),
"decoded non-bootstrap failure {reason:?} should clear active claim"
);
}
}
#[test]
fn first_failed_key_label_truncates_to_16_hex_chars() {
let mut key = [0u8; 32];
key[0] = 0x18;
key[7] = 0xff;
for byte in &mut key[8..] {
*byte = 0xAA;
}
let label = first_failed_key_label(&[key]);
assert_eq!(label, "0x18000000000000ff");
assert_eq!(label.len(), "0x".len() + 16);
}
#[test]
fn first_failed_key_label_falls_back_when_empty() {
assert_eq!(first_failed_key_label(&[]), "0x");
}
#[test]
fn first_failed_key_label_uses_first_key_only() {
let first = [0x11u8; 32];
let second = [0x22u8; 32];
assert_eq!(
first_failed_key_label(&[first, second]),
format!("0x{}", hex::encode(&first[..8]))
);
}
fn drive_key_in_flight(
q: &mut ReplicationQueues,
key: XorName,
sources: Vec<PeerId>,
) -> PeerId {
let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
let now = Instant::now();
let entry = VerificationEntry {
state: VerificationState::PendingVerify,
verified_sources: Vec::new(),
tried_sources: HashSet::new(),
created_at: now,
next_verify_at: now,
hint_sources: HashSet::from([hinter]),
replica_hint_sources: HashSet::from([hinter]),
unresolved_retries: 0,
no_holder_reported: false,
};
assert!(q.add_pending_verify(key, entry).admitted());
assert!(q.promote_pending_to_fetch(key, key, sources));
let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
let source = *candidate.sources.first().expect("candidate has a source");
q.start_dequeued_fetch(candidate, source);
source
}
#[test]
fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
const RETRY_AFTER: Duration = Duration::from_secs(60);
let mut q = ReplicationQueues::new();
let key = test_key(0xAB);
drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
assert_eq!(q.retry_reserved_slot_count(), 1);
let follow_up =
apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
assert_eq!(
follow_up,
FetchFollowUp::Terminal,
"lapsed responsibility must run the caller's terminal bootstrap accounting"
);
assert!(
!q.contains_key(&key),
"the key must leave every pipeline stage — alternate sources included"
);
assert_eq!(
q.pending_count(),
0,
"a lapsed-responsibility key must not be requeued for verification"
);
assert_eq!(
q.retry_reserved_slot_count(),
0,
"terminal exit must release the verification retry-slot reservation"
);
}
#[test]
fn no_longer_responsible_shares_the_stored_terminal_path() {
const RETRY_AFTER: Duration = Duration::from_secs(60);
for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
let mut q = ReplicationQueues::new();
let key = test_key(0xCD);
drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
assert_eq!(follow_up, FetchFollowUp::Terminal);
assert!(!q.contains_key(&key));
assert_eq!(q.retry_reserved_slot_count(), 0);
}
}
#[test]
fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
const RETRY_AFTER: Duration = Duration::from_secs(60);
let mut q = ReplicationQueues::new();
let key = test_key(0xEF);
let first = test_peer(0x04);
let second = test_peer(0x05);
drive_key_in_flight(&mut q, key, vec![first, second]);
let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
assert_eq!(
follow_up,
FetchFollowUp::RetryFrom(second),
"a failed source must not abandon the remaining verified sources"
);
assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
assert_eq!(
follow_up,
FetchFollowUp::RequeuedForVerification,
"exhausted sources must restore the reserved verification entry"
);
assert_eq!(q.pending_count(), 1);
assert_eq!(
q.retry_reserved_slot_count(),
0,
"the reservation converts back into the pending entry itself"
);
}
#[test]
fn source_failure_without_retry_metadata_is_terminal() {
const RETRY_AFTER: Duration = Duration::from_secs(60);
let mut q = ReplicationQueues::new();
let key = test_key(0x1F);
let source = test_peer(0x06);
assert!(q.enqueue_fetch(key, key, vec![source]));
let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
q.start_dequeued_fetch(candidate, source);
let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
assert_eq!(follow_up, FetchFollowUp::Terminal);
assert!(!q.contains_key(&key));
}
#[test]
fn already_held_key_leaves_the_pipeline_terminally() {
const RETRY_AFTER: Duration = Duration::from_secs(60);
let mut q = ReplicationQueues::new();
let key = test_key(0x4C);
let source = test_peer(0x0B);
drive_key_in_flight(&mut q, key, vec![source, test_peer(0x0C)]);
let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::AlreadyHeld, RETRY_AFTER);
assert_eq!(
follow_up,
FetchFollowUp::Terminal,
"holding the key already discharges the duty, so the key must leave \
the pipeline exactly as a completed fetch does — requeueing it \
would re-verify a key that needs nothing"
);
assert!(!q.contains_key(&key));
assert_eq!(
q.retry_reserved_slot_count(),
0,
"the terminal path must release the retry-slot reservation, or the \
owner's verification budget leaks"
);
}
#[test]
fn local_write_failure_does_not_conscript_the_remaining_sources() {
const RETRY_AFTER: Duration = Duration::from_secs(60);
let mut q = ReplicationQueues::new();
let key = test_key(0x2A);
let first = test_peer(0x07);
let second = test_peer(0x08);
let third = test_peer(0x09);
drive_key_in_flight(&mut q, key, vec![first, second, third]);
let follow_up =
apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
assert_eq!(
follow_up,
FetchFollowUp::RequeuedForVerification,
"a local write failure must go straight back to verification: the two \
untried sources would each re-upload the same chunk into the same \
full disk, and neither of them did anything wrong"
);
assert_eq!(q.in_flight_count(), 0);
assert_eq!(
q.pending_count(),
1,
"the key must come back — capacity frees up, and a stranded key is \
a replica this node silently stops owing"
);
assert_eq!(q.retry_reserved_slot_count(), 0);
}
#[test]
fn local_write_failure_without_retry_metadata_is_terminal() {
const RETRY_AFTER: Duration = Duration::from_secs(60);
let mut q = ReplicationQueues::new();
let key = test_key(0x3B);
let source = test_peer(0x0A);
assert!(q.enqueue_fetch(key, key, vec![source]));
let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
q.start_dequeued_fetch(candidate, source);
let follow_up =
apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
assert_eq!(follow_up, FetchFollowUp::Terminal);
assert!(!q.contains_key(&key));
assert_eq!(q.retry_reserved_slot_count(), 0);
}
}