ant_node/replication/mod.rs
1//! Replication subsystem for the Autonomi network.
2//!
3//! Implements Kademlia-style replication with:
4//! - Fresh replication with `PoP` verification
5//! - Neighbor sync with round-robin cycle management
6//! - Batched quorum verification
7//! - Storage audit protocol (anti-outsourcing)
8//! - `PaidForList` persistence and convergence
9//! - Responsibility pruning with hysteresis
10
11// The replication engine intentionally holds `RwLock` read guards across await
12// boundaries (e.g. reading sync_history while calling audit_tick). Clippy's
13// nursery lint `significant_drop_tightening` flags these, but the guards must
14// remain live for the duration of the call.
15#![allow(clippy::significant_drop_tightening)]
16
17pub mod admission;
18pub mod audit;
19pub mod audit_coordinator;
20pub(crate) mod audit_metrics;
21pub mod bootstrap;
22pub mod commitment;
23pub mod commitment_state;
24pub mod config;
25pub mod fresh;
26pub mod neighbor_sync;
27pub mod paid_list;
28pub mod possession;
29pub mod protocol;
30pub mod pruning;
31pub mod quorum;
32pub mod recent_provers;
33pub mod scheduling;
34pub mod slice;
35pub mod storage_commitment_audit;
36pub mod subtree;
37pub mod types;
38
39use std::collections::{HashMap, HashSet, VecDeque};
40use std::fmt;
41use std::num::NonZeroUsize;
42use std::ops::ControlFlow;
43use std::path::{Path, PathBuf};
44use std::sync::atomic::{AtomicU64, Ordering};
45use std::sync::Arc;
46use std::time::{Duration, Instant, SystemTime};
47
48use lru::LruCache;
49use std::pin::Pin;
50
51use crate::logging::{debug, error, info, warn};
52use futures::stream::FuturesUnordered;
53use futures::{future::join_all, Future, StreamExt};
54use parking_lot::Mutex;
55use rand::rngs::StdRng;
56use rand::{Rng, SeedableRng};
57use tokio::sync::broadcast::error::RecvError;
58use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
59use tokio::task::JoinHandle;
60use tokio_util::sync::CancellationToken;
61use tokio_util::task::TaskTracker;
62
63use crate::ant_protocol::XorName;
64use crate::error::{Error, Result};
65use crate::payment::{
66 PaymentVerifier, VerificationContext, MAX_PAYMENT_PROOF_SIZE_BYTES,
67 MIN_PAYMENT_PROOF_SIZE_BYTES,
68};
69use crate::replication::audit::AuditTickResult;
70use crate::replication::audit_coordinator::AuditChallengeCoordinator;
71use crate::replication::audit_metrics::{
72 AuditResponderClass, AuditResponderDropReason, AuditResponderMetrics,
73 ReplicationResponderClass, ResponderAdmissionCeiling,
74};
75use crate::replication::commitment::{commitment_hash, StorageCommitment};
76use crate::replication::commitment_state::{
77 PeerCommitmentRecord, PersistedRetention, ResponderCommitmentState, GOSSIP_ANSWERABILITY_TTL,
78};
79use crate::replication::config::{
80 max_parallel_fetch, storage_admission_width, ReplicationConfig, MAX_AUDIT_RESPONSES_PER_PEER,
81 MAX_CONCURRENT_AUDIT_RESPONSES, MAX_CONCURRENT_REPLICATION_SENDS,
82 MAX_DIGEST_AUDIT_RESPONSES_PER_PEER, MAX_INCOMING_VERIFICATION_KEYS,
83 MAX_SUBTREE_ROUND1_PER_PEER, MAX_SUBTREE_SESSIONS, MAX_VERIFICATION_KEYS_PER_CYCLE,
84 REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID, SUBTREE_ROUND1_WORK_BURST_BYTES,
85 SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, SUBTREE_SESSION_TTL,
86};
87use crate::replication::paid_list::PaidList;
88use crate::replication::protocol::{
89 FreshReplicationResponse, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
90 VerificationResponse,
91};
92use crate::replication::quorum::KeyVerificationOutcome;
93use crate::replication::recent_provers::RecentProvers;
94use crate::replication::scheduling::{CapacityDisplacement, DeferralOutcome, ReplicationQueues};
95use crate::replication::types::{
96 AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence,
97 NeighborSyncState, PeerSyncRecord, PresenceEvidence, RepairProofs, VerificationEntry,
98 VerificationState,
99};
100use crate::storage::{CapacityVerdict, LmdbStorage};
101use saorsa_core::identity::{NodeIdentity, PeerId};
102use saorsa_core::{DhtNetworkEvent, P2PEvent, P2PNode, TrustEvent};
103use saorsa_pqc::api::sig::{MlDsaSecretKey, MlDsaVariant};
104
105/// Count of monetized-pin nominations DROPPED at the bounded ingress channel
106/// because it was full (Amendment 2). Process-global because the producer is
107/// the payment verifier (a different module) and the drop happens before the
108/// per-drainer `received` counter. A non-zero value is the rollout signal that
109/// nomination ingress is saturating — benign (penalty-free, lottery/next-
110/// payment covered) but worth watching. `Closed` (engine shut down) is not
111/// counted: it is not a saturation signal.
112static FIRST_AUDIT_INGRESS_DROPPED: AtomicU64 = AtomicU64::new(0);
113
114/// Record one ingress-full drop. Called by the payment verifier's `try_send`
115/// sites; read by the drainer's periodic summary.
116pub(crate) fn note_monetized_ingress_drop() {
117 FIRST_AUDIT_INGRESS_DROPPED.fetch_add(1, Ordering::Relaxed);
118}
119
120#[derive(Default)]
121struct FirstAuditObservability {
122 received: AtomicU64,
123 queued: AtomicU64,
124 coalesced: AtomicU64,
125 duplicates: AtomicU64,
126 capacity_evicted: AtomicU64,
127 /// An event targeting the local peer itself, dropped at ingress: the node
128 /// cannot network-audit itself (no dialable address for the local peer).
129 self_target_skipped: AtomicU64,
130 /// A strictly-lower-count same-peer nomination that was dropped so a
131 /// higher-count pending pin survived. A sustained rise is the signal of an
132 /// attempted "erase the inflated pin with a cheaper one" self-suppression.
133 suppressed_lower: AtomicU64,
134 cooldown_deferred_attempts: AtomicU64,
135 rate_deferred_attempts: AtomicU64,
136 window_deduped: AtomicU64,
137 launched: AtomicU64,
138 passed: AtomicU64,
139 timed_out: AtomicU64,
140 failed: AtomicU64,
141 bootstrap_claims: AtomicU64,
142 idle: AtomicU64,
143 insufficient_keys: AtomicU64,
144 outside_answerability_window: AtomicU64,
145 inflight: AtomicU64,
146}
147
148/// Test-only snapshot of the first-audit scheduler counters.
149///
150/// Lets e2e tests assert on the scheduler's decisions (e.g. that a
151/// self-targeting monetized pin was dropped and never launched) instead of
152/// scraping log lines.
153#[cfg(any(test, feature = "test-utils"))]
154#[derive(Debug, Clone, Copy)]
155pub struct FirstAuditStats {
156 /// Events ingested from the monetized-pin channel.
157 pub received: u64,
158 /// Events accepted into the pending first-audit queue.
159 pub queued: u64,
160 /// Events dropped because they targeted the local peer.
161 pub self_target_skipped: u64,
162 /// Audits launched.
163 pub launched: u64,
164 /// Launched audits that passed.
165 pub passed: u64,
166 /// Launched audits that timed out (non-response lane).
167 pub timed_out: u64,
168 /// Launched audits that ended in a confirmed failure.
169 pub failed: u64,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173enum FirstAuditTerminalOutcome {
174 Passed,
175 Timeout,
176 Failed,
177 BootstrapClaim,
178 Idle,
179 InsufficientKeys,
180}
181
182impl FirstAuditTerminalOutcome {
183 #[cfg(any(feature = "logging", test))]
184 const fn as_str(self) -> &'static str {
185 match self {
186 Self::Passed => "passed",
187 Self::Timeout => "timeout",
188 Self::Failed => "failed",
189 Self::BootstrapClaim => "bootstrap_claim",
190 Self::Idle => "idle",
191 Self::InsufficientKeys => "insufficient_keys",
192 }
193 }
194}
195
196fn first_audit_terminal_outcome(result: &AuditTickResult) -> FirstAuditTerminalOutcome {
197 match result {
198 AuditTickResult::Passed { .. } => FirstAuditTerminalOutcome::Passed,
199 AuditTickResult::Failed {
200 evidence:
201 FailureEvidence::AuditFailure {
202 reason: AuditFailureReason::Timeout,
203 ..
204 },
205 ..
206 } => FirstAuditTerminalOutcome::Timeout,
207 AuditTickResult::Failed { .. } => FirstAuditTerminalOutcome::Failed,
208 AuditTickResult::BootstrapClaim { .. } => FirstAuditTerminalOutcome::BootstrapClaim,
209 AuditTickResult::Idle => FirstAuditTerminalOutcome::Idle,
210 AuditTickResult::InsufficientKeys => FirstAuditTerminalOutcome::InsufficientKeys,
211 }
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215enum FirstAuditQueueOutcome {
216 /// New peer inserted with free capacity.
217 Queued,
218 /// Collapsed with an existing same-peer entry; the incoming won (higher
219 /// count, or equal count and newer) and replaced it.
220 Coalesced,
221 /// Collapsed with an existing same-peer entry; the incoming LOST because it
222 /// had a STRICTLY LOWER count and was dropped, leaving the higher-count pin
223 /// in place. This is the attempted cheaper-pin self-erasure signal.
224 SuppressedLower,
225 /// Collapsed with an existing same-peer entry of EQUAL count; the incoming
226 /// lost the freshness tie (it was not the newer of the two) and the
227 /// existing entry was retained. Benign, not an attack signal.
228 RetainedOnTie,
229 /// A DIFFERENT peer's entry was displaced from the capped pending queue
230 /// (random victim) to make room.
231 CapacityEvicted { peer: PeerId, pin: [u8; 32] },
232}
233
234/// Coalesce a monetized nomination into the per-peer pending queue with a
235/// SECURITY-AWARE rule (ADR-0004 Amendment 2): keep the pin that most needs
236/// auditing — the HIGHEST committed key count for that peer, newest on a tie.
237///
238/// A strictly-lower-count incoming must NOT displace a higher-count pending pin,
239/// otherwise a peer can erase an inflated (audit-worthy) commitment by simply
240/// monetizing a cheaper one right after — and a sidecar-only inflated pin has no
241/// gossip-lottery backstop. When the incoming loses, the retained entry's LRU
242/// recency is left UNTOUCHED (via `peek`), so a flood of low-count nominations
243/// cannot promote the retained pin's lane position.
244///
245/// `incoming_is_newer` distinguishes ordinary enqueue (the incoming arrived
246/// last, so it wins an equal-count tie for freshness) from a cooldown-race
247/// requeue of an older reserved event (the pending successor is newer, so it
248/// wins the tie).
249fn coalesce_first_audit_event(
250 pending: &mut LruCache<PeerId, MonetizedPinEvent>,
251 incoming: MonetizedPinEvent,
252 incoming_is_newer: bool,
253 rng: &mut StdRng,
254) -> FirstAuditQueueOutcome {
255 if let Some(existing) = pending.peek(&incoming.peer) {
256 // Strictly lower -> the incoming loses and is dropped WITHOUT touching
257 // the retained pin's recency (the security-relevant self-erasure case).
258 if incoming.key_count < existing.key_count {
259 return FirstAuditQueueOutcome::SuppressedLower;
260 }
261 // Equal count -> keep the fresher; an older incoming loses a benign tie.
262 if incoming.key_count == existing.key_count && !incoming_is_newer {
263 return FirstAuditQueueOutcome::RetainedOnTie;
264 }
265 // Strictly higher, or equal-and-newer: the incoming wins. `push` updates
266 // the value and bumps MRU; replacing an existing key never evicts a
267 // different peer.
268 let _ = pending.push(incoming.peer, incoming);
269 return FirstAuditQueueOutcome::Coalesced;
270 }
271 // No same-peer entry. At capacity, displace a UNIFORMLY RANDOM incumbent,
272 // never the LRU: deterministic keep-newest would let an ordered batch of
273 // `cap` distinct-peer nominations flush a chosen target before any launch
274 // lane sees it, cutting the eviction cost from probabilistic to exact. A
275 // random victim caps an attacker's per-nomination eviction probability at
276 // `1/cap` regardless of arrival order or timing, so suppressing a specific
277 // target with confidence `1-e` costs ~`cap*ln(1/e)` distinct-peer paid
278 // nominations and is never certain (ADR-0004 Amendment 4).
279 if pending.len() >= pending.cap().get() {
280 let victim = {
281 let idx = rng.gen_range(0..pending.len());
282 pending.iter().nth(idx).map(|(p, _)| *p)
283 };
284 if let Some(victim_peer) = victim {
285 if let Some(evicted) = pending.pop(&victim_peer) {
286 let _ = pending.push(incoming.peer, incoming);
287 return FirstAuditQueueOutcome::CapacityEvicted {
288 peer: victim_peer,
289 pin: evicted.pin,
290 };
291 }
292 }
293 }
294 match pending.push(incoming.peer, incoming) {
295 None => FirstAuditQueueOutcome::Queued,
296 // Unreachable: the random-displacement branch above guarantees
297 // `len < cap` here (the caller holds `&mut`, so no concurrent insert
298 // exists). Kept so any future logic error surfaces as an ACCOUNTED
299 // eviction rather than silent loss — but note this arm would be
300 // LRU-order, not random, so it must stay unreachable.
301 Some((evicted_peer, evicted)) => FirstAuditQueueOutcome::CapacityEvicted {
302 peer: evicted_peer,
303 pin: evicted.pin,
304 },
305 }
306}
307
308/// ADR-0004 Amendment 2 (E′): slack added to the max launch jitter when
309/// prefiltering a nomination's answerability at schedule time, covering the
310/// spawn/dispatch latency between the timer firing and the wire challenge so a
311/// jitter==MAX pin is not admitted only to fail the authoritative check by a
312/// few milliseconds. Tiny against the multi-hour answerability window.
313const FIRST_AUDIT_SEND_LATENCY_SLACK: Duration = Duration::from_secs(1);
314
315/// A first audit the limiter recently launched at a peer: when, and the
316/// committed key count that was audited (for the count-jump override).
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318struct RecentFirstAudit {
319 launched_at: Instant,
320 key_count: u32,
321}
322
323/// Holds one first-audit in-flight slot; decrements the gauge on drop so a
324/// panicking or cancelled audit task can never leak a slot and wedge the
325/// [`config::FIRST_AUDIT_MAX_INFLIGHT`] cap shut.
326struct FirstAuditInflightSlot(Arc<FirstAuditObservability>);
327
328impl FirstAuditInflightSlot {
329 fn acquire(observability: &Arc<FirstAuditObservability>) -> Self {
330 observability.inflight.fetch_add(1, Ordering::Relaxed);
331 Self(Arc::clone(observability))
332 }
333}
334
335impl Drop for FirstAuditInflightSlot {
336 fn drop(&mut self) {
337 self.0.inflight.fetch_sub(1, Ordering::Relaxed);
338 }
339}
340
341/// ADR-0004 Amendment 2: whether `new_count` exceeds `audited_count` by more
342/// than the [`config::FIRST_AUDIT_COUNT_JUMP_NUM`]/
343/// [`config::FIRST_AUDIT_COUNT_JUMP_DEN`] ratio (`new > old * NUM / DEN`,
344/// overflow-free integer math). A jump re-nominates a peer despite a recent
345/// first audit: an inflated SIDECAR-ONLY pin is visible to payment verifiers
346/// only, so no gossip-lottery audit can ever cover it.
347const fn first_audit_count_jump(audited_count: u32, new_count: u32) -> bool {
348 (new_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_DEN
349 > (audited_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_NUM
350}
351
352/// The launch limiter's verdict for one pending monetized pin.
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354enum LimiterVerdict {
355 /// Within budget and window: the caller may reserve a launch (and consumes
356 /// a token via [`FirstAuditLimiter::reserve_token`] only if it does).
357 Admit,
358 /// Launch-rate budget or in-flight cap exhausted. Penalty-free: keep the
359 /// pin pending and retry on a later tick.
360 RateDeferred,
361 /// The peer had a first audit within
362 /// [`config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL`] and the new pin's count
363 /// shows no [`first_audit_count_jump`]. Drop the nomination (the
364 /// gossip-lottery re-audit path is unaffected).
365 WindowDeduped,
366}
367
368/// ADR-0004 Amendment 2: the first-audit launch limiter — a token bucket
369/// (launch rate), an in-flight cap, and a per-peer re-audit window that
370/// survives pin rotation.
371///
372/// This is the load-bearing aggregate bound the original scheduler lacked:
373/// fleet-wide first-audit pressure becomes `nodes x refill-rate` instead of
374/// `uploads x pinned-quotes-per-proof x verifying-storers`. Pure over passed
375/// `now`/`inflight` values so every decision is unit-testable without a
376/// runtime.
377struct FirstAuditLimiter {
378 /// Launch tokens available, at most [`config::FIRST_AUDIT_BUDGET_BURST`].
379 tokens: u32,
380 /// Refill anchor. While the bucket is full this tracks `now` (a full
381 /// bucket accrues nothing); while below capacity it advances only by
382 /// whole refill intervals so fractional elapsed time is never lost.
383 last_refill: Instant,
384 /// Peers given a first audit recently, with the audited key count.
385 /// Bounded like the drainer's other per-peer maps.
386 recent: LruCache<PeerId, RecentFirstAudit>,
387}
388
389impl FirstAuditLimiter {
390 fn new(now: Instant) -> Self {
391 Self {
392 tokens: config::FIRST_AUDIT_BUDGET_BURST,
393 last_refill: now,
394 recent: LruCache::new(
395 NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
396 ),
397 }
398 }
399
400 /// Whether the per-peer re-audit window admits a nomination for `peer`
401 /// carrying `key_count` at `now`. Read-only (`peek`), so it is safe to
402 /// call at ENQUEUE time — suppressed nominations never occupy pending
403 /// slots — without disturbing LRU recency.
404 fn window_allows(&self, peer: &PeerId, key_count: u32, now: Instant) -> bool {
405 self.recent.peek(peer).map_or(true, |prev| {
406 now.saturating_duration_since(prev.launched_at)
407 >= config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL
408 || first_audit_count_jump(prev.key_count, key_count)
409 })
410 }
411
412 /// Refill the token bucket for the time elapsed up to `now`.
413 fn refill(&mut self, now: Instant) {
414 if self.tokens >= config::FIRST_AUDIT_BUDGET_BURST {
415 // Full bucket accrues nothing; keep the anchor current so the
416 // next consumption starts its interval from here.
417 self.last_refill = now;
418 return;
419 }
420 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
421 let elapsed = now.saturating_duration_since(self.last_refill);
422 let earned = elapsed.as_nanos() / interval.as_nanos().max(1);
423 if earned == 0 {
424 return;
425 }
426 let capacity_gap = u128::from(config::FIRST_AUDIT_BUDGET_BURST - self.tokens);
427 if earned >= capacity_gap {
428 self.tokens = config::FIRST_AUDIT_BUDGET_BURST;
429 self.last_refill = now;
430 } else {
431 // earned < capacity_gap <= u32::MAX, so both casts are lossless.
432 self.tokens = self
433 .tokens
434 .saturating_add(u32::try_from(earned).unwrap_or(u32::MAX));
435 let advance = interval.saturating_mul(u32::try_from(earned).unwrap_or(u32::MAX));
436 self.last_refill = self.last_refill.checked_add(advance).unwrap_or(now);
437 }
438 }
439
440 /// Decide whether a pending pin may launch now. Consumes NOTHING: the
441 /// caller runs the remaining (per-peer cooldown) gate and calls
442 /// [`Self::commit_launch`] only for a launch that actually happens, so a
443 /// deferral elsewhere never burns budget or stamps the window.
444 fn assess(
445 &mut self,
446 peer: &PeerId,
447 key_count: u32,
448 now: Instant,
449 inflight: u64,
450 ) -> LimiterVerdict {
451 if !self.window_allows(peer, key_count, now) {
452 return LimiterVerdict::WindowDeduped;
453 }
454 self.refill(now);
455 if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.tokens == 0 {
456 return LimiterVerdict::RateDeferred;
457 }
458 LimiterVerdict::Admit
459 }
460
461 /// Consume one launch token for a RESERVATION (ADR-0004 Amendment 2 E′).
462 /// Does NOT stamp the per-peer window: the durable `recent` stamp happens
463 /// only at [`Self::promote`], after the authoritative post-jitter
464 /// answerability check, so a reservation that is later cancelled leaves no
465 /// suppression behind.
466 fn reserve_token(&mut self) {
467 self.tokens = self.tokens.saturating_sub(1);
468 }
469
470 /// Return a token consumed by a reservation that was cancelled before it
471 /// launched (answerability lapsed or a concurrent gossip audit won the
472 /// cooldown). Capped at the burst so a spurious double-refund cannot exceed
473 /// the bucket.
474 fn refund_token(&mut self) {
475 self.tokens = (self.tokens + 1).min(config::FIRST_AUDIT_BUDGET_BURST);
476 }
477
478 /// Stamp the per-peer re-audit window for a launch that is ACTUALLY firing
479 /// (promotion). Separated from token consumption so suppression is only
480 /// ever recorded for a real send.
481 fn promote(&mut self, peer: PeerId, key_count: u32, now: Instant) {
482 self.recent.put(
483 peer,
484 RecentFirstAudit {
485 launched_at: now,
486 key_count,
487 },
488 );
489 }
490
491 /// Test convenience: the pre-E′ atomic "a launch happened" — consume a token
492 /// and stamp the window in one call. Production splits these across
493 /// reservation and promotion; the limiter's own budget/window unit tests do
494 /// not model the jitter reservation and use this shorthand.
495 #[cfg(test)]
496 fn commit_launch(&mut self, peer: PeerId, key_count: u32, now: Instant) {
497 self.reserve_token();
498 self.promote(peer, key_count, now);
499 }
500}
501
502/// ADR-0004 Amendment 2 (E′ B-prefilter): whether a monetized pin is answerable
503/// across the ENTIRE launch-jitter window ending at
504/// `now + FIRST_AUDIT_LAUNCH_JITTER_MAX + slack`, so committing scheduling state
505/// for it cannot later require aborting an out-of-window challenge. The
506/// too-future bound is enforced at `now` (a jitter delay only ages a pin
507/// forward, never toward the future); the too-old bound is enforced at the
508/// latest possible send time. This is a conservative admission prefilter; the
509/// authoritative answerability check still runs at promotion against the real
510/// send-time wall clock, so A1 (no false conviction) holds regardless of how
511/// jitter and the answerability margin are sized. `checked_add` overflow fails
512/// closed (skip the pin).
513fn quote_answerable_through_nominal_jitter(quote_ts: SystemTime, now: SystemTime) -> bool {
514 let Some(latest_send) = now
515 .checked_add(config::FIRST_AUDIT_LAUNCH_JITTER_MAX)
516 .and_then(|t| t.checked_add(FIRST_AUDIT_SEND_LATENCY_SLACK))
517 else {
518 return false;
519 };
520 quote_within_audit_window(quote_ts, now) && quote_within_audit_window(quote_ts, latest_send)
521}
522
523/// Open the single first-audit reservation from `pending` if none is
524/// outstanding: samples the launch jitter, snapshots the shared cooldown
525/// read-only, and delegates to [`FirstAuditScheduler::try_reserve`]. One
526/// shared implementation for both drainer call sites — the per-wake launch
527/// phase and the pre-overflow opportunity inside the ingress batch — so the
528/// two cannot drift.
529async fn open_first_audit_reservation(
530 scheduler: &mut FirstAuditScheduler,
531 cooldown: &RwLock<HashMap<PeerId, Instant>>,
532 observability: &Arc<FirstAuditObservability>,
533) {
534 if scheduler.has_reservation() {
535 return;
536 }
537 let jitter = Duration::from_millis(rand::thread_rng().gen_range(
538 0..=u64::try_from(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_millis()).unwrap_or(u64::MAX),
539 ));
540 let inflight = observability.inflight.load(Ordering::Relaxed);
541 let reserved = {
542 let cooldown = cooldown.read().await;
543 scheduler.try_reserve(Instant::now(), inflight, jitter, &cooldown, observability)
544 };
545 if reserved {
546 if let Some(peer) = scheduler.reserved_peer() {
547 debug!(
548 "First-audit scheduler: audit_trigger=first_monetized outcome=reserved peer={peer} pending={}",
549 scheduler.pending_len()
550 );
551 }
552 }
553}
554
555/// A far-future `Instant` used to effectively DISABLE the promotion-timer
556/// select arm when no reservation is outstanding. The drainer still wakes at
557/// least every [`config::FIRST_AUDIT_RETRY_INTERVAL`] via its tick, so this only
558/// needs to be comfortably past the next tick.
559fn first_audit_far_future() -> Instant {
560 Instant::now()
561 .checked_add(Duration::from_secs(3600))
562 .unwrap_or_else(Instant::now)
563}
564
565/// ADR-0004 Amendment 2 (E′): one outstanding first-audit reservation. Holds
566/// its in-flight slot and launch token from schedule time until the jitter
567/// timer fires; the durable suppression (`recent` + `first_audited`) is stamped
568/// only if the authoritative post-jitter answerability + cooldown checks pass at
569/// promotion, so a cancelled reservation leaves NO suppression behind.
570struct FirstAuditReservation {
571 event: MonetizedPinEvent,
572 ready_at: Instant,
573 inflight: FirstAuditInflightSlot,
574}
575
576/// ADR-0004 Amendment 2 (E′): the drainer-owned first-audit scheduler. Owns the
577/// pending queue, the dedup set, the launch limiter, the alternating lane, and
578/// the single outstanding reservation. All mutation is single-threaded in the
579/// drainer task; the only asynchrony is the spawned audit I/O (which just holds
580/// the moved-in in-flight slot). Kept as a struct so the reserve/promote/cancel
581/// state machine is unit-testable with injected clocks.
582struct FirstAuditScheduler {
583 /// Pins already given a first audit (dedup). A pin enters only at PROMOTION
584 /// (a real send), never at reservation, so a cancelled reservation can be
585 /// re-nominated.
586 first_audited: LruCache<[u8; 32], ()>,
587 /// Highest-count-per-peer pending nominations not yet launched. Capped at
588 /// [`FIRST_AUDIT_PENDING_CAP`] (what the token budget can launch within
589 /// one effective answerability window); at capacity a uniformly RANDOM
590 /// incumbent is displaced and counted as `capacity_evicted`, so eviction
591 /// of a specific entry can never be forced deterministically. One further
592 /// entry may be held in `reserved` outside this queue — a deliberate
593 /// one-entry guard slot, so total schedulable occupancy is at most
594 /// `cap + 1`; the summary line reports both (`pending`/`reserved`).
595 pending: LruCache<PeerId, MonetizedPinEvent>,
596 /// Token bucket + per-peer re-audit window.
597 limiter: FirstAuditLimiter,
598 /// The single outstanding reservation (E′ serializes reservations so the
599 /// per-launch lane alternation is preserved and at most one jitter timer is
600 /// live).
601 reserved: Option<FirstAuditReservation>,
602 /// Alternating launch lane, flipped on every PROMOTION (real launch).
603 oldest_first_lane: bool,
604 /// The local node's own peer ID. A verified payment's quote list includes
605 /// the node's own quote, so the verifier emits a monetized-pin event for
606 /// the local peer on every payment it verifies. The node cannot
607 /// network-audit itself (there is no dialable address for the local peer,
608 /// so the challenge fails instantly and is miscounted as a timeout), while
609 /// any other payee that verifies the same payment schedules its own first
610 /// audit of this node's pin — a self-dial adds no coverage either way.
611 /// Such an event is dropped at ingress: never queued, and hence never
612 /// launched nor marked first-audited.
613 self_peer: PeerId,
614 /// RNG for random-victim displacement (ADR-0004 Amendment 4). Owned by the
615 /// scheduler so tests can seed it and reproduce eviction sequences exactly;
616 /// production seeds from OS entropy at construction.
617 rng: StdRng,
618}
619
620impl FirstAuditScheduler {
621 fn new(now: Instant, self_peer: PeerId) -> Self {
622 let dedup_cap = NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN);
623 let pending_cap = NonZeroUsize::new(FIRST_AUDIT_PENDING_CAP).unwrap_or(NonZeroUsize::MIN);
624 Self {
625 first_audited: LruCache::new(dedup_cap),
626 pending: LruCache::new(pending_cap),
627 limiter: FirstAuditLimiter::new(now),
628 reserved: None,
629 oldest_first_lane: false,
630 self_peer,
631 rng: StdRng::from_entropy(),
632 }
633 }
634
635 /// Observability getter: used by the scheduler summary log and unit tests,
636 /// both absent from a release `--no-default-features` build, so it is dead
637 /// only in that configuration.
638 #[cfg_attr(not(feature = "logging"), allow(dead_code))]
639 fn pending_len(&self) -> usize {
640 self.pending.len()
641 }
642
643 /// Observability getter (see [`Self::pending_len`]).
644 #[cfg_attr(not(feature = "logging"), allow(dead_code))]
645 fn tokens(&self) -> u32 {
646 self.limiter.tokens
647 }
648
649 /// Observability getter (see [`Self::pending_len`]). Milliseconds since the
650 /// signed quote timestamp of the oldest pin still awaiting a first audit:
651 /// how close the longest-waiting pending pin is to aging out of the
652 /// answerability window. A value climbing toward the window means pending
653 /// work is expiring unaudited instead of launching; a small, steady value
654 /// means the queue is draining promptly. Returns `0` when `pending` is empty
655 /// and saturates to `0` for a future-dated quote (clock skew), never panics.
656 #[cfg_attr(not(feature = "logging"), allow(dead_code))]
657 fn oldest_pending_quote_age_ms(&self, now: SystemTime) -> u64 {
658 self.pending
659 .iter()
660 .map(|(_, e)| e.quote_ts)
661 .min()
662 .and_then(|oldest| now.duration_since(oldest).ok())
663 .map_or(0, |age| u64::try_from(age.as_millis()).unwrap_or(u64::MAX))
664 }
665
666 /// Drop every pending nomination that has aged past the answerability
667 /// horizon. `try_reserve` collects expired entries only while it can scan —
668 /// under token starvation it returns at the budget gate first — so without
669 /// a periodic sweep dead entries squat the capped pending queue (displacing
670 /// at capacity) and inflate the `pending`/`oldest_pending_quote_age_ms`
671 /// telemetry. Each removal is accounted as `outside_answerability_window`,
672 /// exactly like a scan-time expiry. Returns how many entries were dropped;
673 /// survivor recency is untouched.
674 fn sweep_expired(&mut self, wall_now: SystemTime, obs: &Arc<FirstAuditObservability>) -> usize {
675 let expired: Vec<PeerId> = self
676 .pending
677 .iter()
678 .filter(|(_, event)| !quote_answerable_through_nominal_jitter(event.quote_ts, wall_now))
679 .map(|(peer, _)| *peer)
680 .collect();
681 for peer in &expired {
682 self.pending.pop(peer);
683 }
684 if !expired.is_empty() {
685 obs.outside_answerability_window.fetch_add(
686 u64::try_from(expired.len()).unwrap_or(u64::MAX),
687 Ordering::Relaxed,
688 );
689 }
690 expired.len()
691 }
692
693 fn has_reservation(&self) -> bool {
694 self.reserved.is_some()
695 }
696
697 /// Whether admitting `event` would displace a DIFFERENT peer's pending
698 /// entry: the queue is at capacity and `event.peer` has no incumbent to
699 /// coalesce into. The drainer checks this before enqueueing so pending
700 /// work gets a reservation opportunity BEFORE destructive overflow
701 /// (ADR-0004 Amendment 4) — a successful reservation moves one entry out
702 /// of `pending`, freeing the slot without any eviction.
703 fn would_displace(&self, event: &MonetizedPinEvent) -> bool {
704 self.pending.len() >= self.pending.cap().get() && self.pending.peek(&event.peer).is_none()
705 }
706
707 /// When the outstanding reservation becomes eligible for promotion.
708 fn reserved_ready_at(&self) -> Option<Instant> {
709 self.reserved.as_ref().map(|r| r.ready_at)
710 }
711
712 /// The peer of the outstanding reservation, if any.
713 fn reserved_peer(&self) -> Option<PeerId> {
714 self.reserved.as_ref().map(|r| r.event.peer)
715 }
716
717 /// Admit a monetized nomination into `pending`. Dropped at ingress if it
718 /// targets the local peer (see [`Self::self_peer`]); dropped as a duplicate
719 /// if already first-audited; the window screen is bypassed for the currently
720 /// reserved peer (so a successor is retained across the reservation, never
721 /// window-dropped); otherwise window-screened. Coalescing is
722 /// highest-count-per-peer (newest on a tie) — a lower-count successor never
723 /// displaces a higher-count pending pin. An incumbent that has aged past
724 /// the answerability horizon is dropped (and accounted as an expiry) before
725 /// coalescing, so a dead pin never vetoes a live nomination. Admission for
726 /// a NEW peer at capacity displaces a uniformly RANDOM incumbent (see
727 /// [`FIRST_AUDIT_PENDING_CAP`] and [`coalesce_first_audit_event`]):
728 /// displacement is accounted as `capacity_evicted` and stamps no
729 /// suppression, so a displaced peer's next nomination is judged like any
730 /// newcomer. The drainer additionally offers a reservation opportunity
731 /// via [`Self::would_displace`] before calling this on an overflowing
732 /// arrival.
733 fn enqueue(&mut self, event: MonetizedPinEvent, obs: &Arc<FirstAuditObservability>) {
734 if event.peer == self.self_peer {
735 obs.self_target_skipped.fetch_add(1, Ordering::Relaxed);
736 return;
737 }
738 if self.first_audited.contains(&event.pin) {
739 obs.duplicates.fetch_add(1, Ordering::Relaxed);
740 return;
741 }
742 let reserved_peer = self.reserved_peer();
743 let is_reserved_peer = reserved_peer == Some(event.peer);
744 if !is_reserved_peer
745 && !self
746 .limiter
747 .window_allows(&event.peer, event.key_count, Instant::now())
748 {
749 obs.window_deduped.fetch_add(1, Ordering::Relaxed);
750 return;
751 }
752 // A pending incumbent past the answerability horizon can never launch,
753 // yet its (possibly higher) key count would still win the coalesce
754 // against a live incoming — e.g. a fresh post-prune lower-count pin —
755 // and under token starvation no reserve scan runs to collect it. Drop
756 // it first so the incoming is judged on its own merits.
757 let stale_incumbent = self.pending.peek(&event.peer).is_some_and(|existing| {
758 !quote_answerable_through_nominal_jitter(existing.quote_ts, SystemTime::now())
759 });
760 if stale_incumbent {
761 self.pending.pop(&event.peer);
762 obs.outside_answerability_window
763 .fetch_add(1, Ordering::Relaxed);
764 }
765 // Ordinary enqueue: the incoming arrived last, so it wins an equal-count
766 // tie.
767 match coalesce_first_audit_event(&mut self.pending, event, true, &mut self.rng) {
768 FirstAuditQueueOutcome::Queued => {
769 obs.queued.fetch_add(1, Ordering::Relaxed);
770 }
771 FirstAuditQueueOutcome::Coalesced | FirstAuditQueueOutcome::RetainedOnTie => {
772 obs.coalesced.fetch_add(1, Ordering::Relaxed);
773 }
774 FirstAuditQueueOutcome::SuppressedLower => {
775 obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
776 }
777 FirstAuditQueueOutcome::CapacityEvicted { .. } => {
778 obs.queued.fetch_add(1, Ordering::Relaxed);
779 obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
780 }
781 }
782 }
783
784 /// Attempt to create the single reservation from `pending` (E′ reserve).
785 /// Scans in the current lane order and reserves the FIRST eligible pin:
786 /// consumes one token, acquires one in-flight slot, and sets `ready_at =
787 /// mono_now + jitter`. Does NOT stamp `recent`/`first_audited` and does NOT
788 /// flip the lane — those happen only at promotion. Returns whether a
789 /// reservation was made. `cooldown` is a read-only snapshot (the
790 /// authoritative check-and-stamp is at promotion).
791 fn try_reserve(
792 &mut self,
793 mono_now: Instant,
794 inflight: u64,
795 jitter: Duration,
796 cooldown: &HashMap<PeerId, Instant>,
797 obs: &Arc<FirstAuditObservability>,
798 ) -> bool {
799 if self.reserved.is_some() || self.pending.is_empty() {
800 return false;
801 }
802 self.limiter.refill(mono_now);
803 if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.limiter.tokens == 0 {
804 obs.rate_deferred_attempts.fetch_add(1, Ordering::Relaxed);
805 return false;
806 }
807 // MRU->LRU order; reverse for the oldest-first lane so the preferred
808 // end is at the front.
809 let mut ordered: Vec<(usize, PeerId, MonetizedPinEvent)> = self
810 .pending
811 .iter()
812 .enumerate()
813 .map(|(i, (p, e))| (i, *p, *e))
814 .collect();
815 self.pending.clear();
816 if self.oldest_first_lane {
817 ordered.reverse();
818 }
819 let mut chosen: Option<MonetizedPinEvent> = None;
820 let mut kept: Vec<(usize, PeerId, MonetizedPinEvent)> = Vec::new();
821 for (idx, peer, event) in ordered {
822 if chosen.is_some() {
823 kept.push((idx, peer, event));
824 continue;
825 }
826 if self.first_audited.contains(&event.pin) {
827 obs.duplicates.fetch_add(1, Ordering::Relaxed);
828 continue; // drop: already audited
829 }
830 if !quote_answerable_through_nominal_jitter(event.quote_ts, SystemTime::now()) {
831 obs.outside_answerability_window
832 .fetch_add(1, Ordering::Relaxed);
833 continue; // drop: cannot stay answerable through the jitter
834 }
835 // Window + budget + inflight. Tokens do not decrease during the
836 // scan (reserve happens after the loop) and `inflight` is fixed, so
837 // after the upfront budget gate `assess` never returns RateDeferred
838 // here; a defensive RateDeferred keeps the pin.
839 match self
840 .limiter
841 .assess(&peer, event.key_count, mono_now, inflight)
842 {
843 LimiterVerdict::WindowDeduped => {
844 obs.window_deduped.fetch_add(1, Ordering::Relaxed);
845 continue; // drop: recently first-audited, no count jump
846 }
847 LimiterVerdict::RateDeferred => {
848 kept.push((idx, peer, event));
849 continue; // keep (defensive; unreachable after upfront gate)
850 }
851 LimiterVerdict::Admit => {}
852 }
853 if !cooldown_would_allow(cooldown, &peer, mono_now) {
854 obs.cooldown_deferred_attempts
855 .fetch_add(1, Ordering::Relaxed);
856 kept.push((idx, peer, event));
857 continue; // keep: on shared cooldown, retry later
858 }
859 chosen = Some(event);
860 }
861 // Restore relative recency (oldest re-put first -> newest stays MRU).
862 kept.sort_unstable_by_key(|(idx, _, _)| std::cmp::Reverse(*idx));
863 for (_, peer, event) in kept {
864 self.pending.put(peer, event);
865 }
866 let Some(event) = chosen else {
867 return false;
868 };
869 self.limiter.reserve_token();
870 let inflight_slot = FirstAuditInflightSlot::acquire(obs);
871 let ready_at = mono_now.checked_add(jitter).unwrap_or(mono_now);
872 self.reserved = Some(FirstAuditReservation {
873 event,
874 ready_at,
875 inflight: inflight_slot,
876 });
877 true
878 }
879
880 /// Take the outstanding reservation if its jitter has elapsed at `mono_now`.
881 fn take_due_reservation(&mut self, mono_now: Instant) -> Option<FirstAuditReservation> {
882 if self
883 .reserved
884 .as_ref()
885 .is_some_and(|r| mono_now >= r.ready_at)
886 {
887 self.reserved.take()
888 } else {
889 None
890 }
891 }
892
893 /// Authoritative promotion of a due reservation (E′). The caller holds the
894 /// shared cooldown write lock and passes the real send-time `wall_now` and
895 /// `mono_now`. Returns `Some((event, slot))` to spawn the audit on a real
896 /// launch, or `None` when the launch was cancelled (answerability lapsed
897 /// during jitter) or requeued (a concurrent gossip audit won the cooldown).
898 /// On both `None` paths the token is refunded, the in-flight slot released,
899 /// and NO suppression is recorded.
900 ///
901 /// Known operational residual: suppression is stamped here, at promotion,
902 /// while the wire challenge is sent by the detached task the caller spawns
903 /// with the returned event. A task-start or encoding failure between the
904 /// two therefore leaves a stamped-but-unsent window. No remote input can
905 /// force that failure (it requires local task-spawn/alloc failure), so it
906 /// is accepted rather than closed; closing it would require stamping from
907 /// inside the spawned task and re-introduce the cancel-leaves-suppression
908 /// race this design exists to prevent.
909 fn resolve(
910 &mut self,
911 reservation: FirstAuditReservation,
912 wall_now: SystemTime,
913 mono_now: Instant,
914 cooldown: &mut HashMap<PeerId, Instant>,
915 obs: &Arc<FirstAuditObservability>,
916 ) -> Option<(MonetizedPinEvent, FirstAuditInflightSlot)> {
917 let FirstAuditReservation {
918 event, inflight, ..
919 } = reservation;
920 // Authoritative answerability at the REAL send time.
921 if !quote_within_audit_window(event.quote_ts, wall_now) {
922 self.limiter.refund_token();
923 obs.outside_answerability_window
924 .fetch_add(1, Ordering::Relaxed);
925 drop(inflight);
926 return None; // cancelled; nothing stamped, nothing to roll back
927 }
928 // Authoritative shared-cooldown check-and-stamp. Losing this race to a
929 // concurrent gossip audit requeues the reserved event through the SAME
930 // security-aware coalescing: the reserved event is OLDER than any
931 // same-peer successor (`incoming_is_newer = false`), so a higher-count
932 // reserved event still wins over a lower-count successor (the inflated
933 // pin must be audited), while an equal/higher successor is preserved.
934 if !cooldown_allows_audit(cooldown, &event.peer, mono_now) {
935 self.limiter.refund_token();
936 obs.cooldown_deferred_attempts
937 .fetch_add(1, Ordering::Relaxed);
938 drop(inflight);
939 // Account for the requeue outcome (the nomination itself was already
940 // counted at ingress, so `queued` is not re-incremented): a capacity
941 // eviction of a DIFFERENT peer and a suppressed reserved event are
942 // both observable per the ADR funnel.
943 match coalesce_first_audit_event(&mut self.pending, event, false, &mut self.rng) {
944 FirstAuditQueueOutcome::CapacityEvicted { .. } => {
945 obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
946 }
947 FirstAuditQueueOutcome::SuppressedLower => {
948 obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
949 }
950 FirstAuditQueueOutcome::Queued
951 | FirstAuditQueueOutcome::Coalesced
952 | FirstAuditQueueOutcome::RetainedOnTie => {}
953 }
954 return None;
955 }
956 // Promote: stamp durable suppression, flip the lane, count the launch.
957 self.limiter.promote(event.peer, event.key_count, mono_now);
958 self.first_audited.put(event.pin, ());
959 self.oldest_first_lane = !self.oldest_first_lane;
960 obs.launched.fetch_add(1, Ordering::Relaxed);
961 Some((event, inflight))
962 }
963}
964
965// ---------------------------------------------------------------------------
966// Constants
967// ---------------------------------------------------------------------------
968
969/// Prefix used by saorsa-core's request-response mechanism.
970const RR_PREFIX: &str = "/rr/";
971
972/// Bounded handoff from the P2P broadcast receiver to serial non-audit
973/// replication processing.
974///
975/// The receiver fast-paths digest `AuditChallenge`s immediately and queues
976/// bulk/non-audit messages here. If this fills, the message is **dropped** —
977/// `start_message_handler` must never block on a full queue, because a stalled
978/// receiver laps the P2P broadcast ring and silently loses messages it never
979/// observed. Every serial-lane class has protocol recovery, so a drop costs a
980/// retry rather than the message.
981///
982/// This bounds a message COUNT, but a queued item is an owned decoded message
983/// of up to [`config::MAX_REPLICATION_MESSAGE_SIZE`], so the resident worst
984/// case is 64 × 10 MiB = 640 MiB. That ceiling is acknowledged, not designed
985/// for: the lane carries small requests and challenges alongside
986/// `FreshReplicationOffer`, its one multi-MiB class, so no single count is
987/// right for both. Responses never reach here — `replication_payload_from_event`
988/// filters them out and their requesters correlate them. ADR-0005 decision 12
989/// records the trade and why byte accounting is the correct eventual fix.
990const INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY: usize = 64;
991
992/// Maximum fresh-replication offers processed concurrently, away from the
993/// serial non-audit loop.
994///
995/// Fresh offers can perform an on-chain payment verification and a 4 MiB LMDB
996/// write. Four workers keep that latency off the responder dispatch path while
997/// keeping concurrent EVM/storage pressure small and predictable.
998const FRESH_OFFER_WORKER_LIMIT: usize = 4;
999
1000/// Maximum fresh offers admitted at once, counting both those running on a
1001/// worker and those queued for one.
1002///
1003/// An admitted offer holds its payload until it completes, so this bounds
1004/// memory rather than latency: at 4 MiB each, sixteen is a 64 MiB ceiling.
1005/// Offers past the bound are refused rather than queued or handled inline —
1006/// handling one on the message loop stalls every other non-audit message behind
1007/// a payment verification and a multi-MiB write. A refusal is not free: the
1008/// sender does not read it, so it resurfaces as a missing key at the delayed
1009/// possession check (5-15 min, ADR-0003) and is charged to this node at audit
1010/// severity. Only neighbor sync (10-20 min) actually refills the gap, so the
1011/// bound is sized to make refusal rare rather than cheap.
1012const FRESH_OFFER_MAX_OUTSTANDING: usize = 16;
1013
1014/// Distinct payment proofs queued for one fresh-offer key.
1015///
1016/// Duplicate offers for a key are routine rather than adversarial: a client PUT
1017/// is confirmed by `CLOSE_GROUP_MAJORITY` nodes, and *each* of them fans the
1018/// chunk out to the close group, so a receiver sees the same key from about that
1019/// many senders. They differ only in their proof — the bytes are provably
1020/// identical, since `fresh_offer_structural_rejection` has confirmed
1021/// `key == BLAKE3(data)` before any of them is queued.
1022///
1023/// Sizing the queue to the number of legitimate senders is what lets a failing
1024/// proof fall through to the next one instead of costing the node the record.
1025///
1026/// This is a **lifetime budget per entry**, not a queue depth: it counts proofs
1027/// admitted, and a proof the handler has popped has spent its slot rather than
1028/// returned it. That distinction is what bounds the work an attacker can buy —
1029/// at most this many on-chain verifications per key, after which the entry
1030/// refuses everyone until it closes. Gating on the queue's instantaneous length
1031/// instead would let a stream of distinct sources refill each popped slot and
1032/// run unbounded sequential verifications while holding one of the four worker
1033/// slots. One attempt per source additionally means a single peer can only ever
1034/// consume one of these.
1035const MAX_FRESH_OFFER_ATTEMPTS_PER_KEY: usize = crate::ant_protocol::CLOSE_GROUP_MAJORITY;
1036
1037/// Fresh-offer slots kept reachable by sources that hold none.
1038///
1039/// The property worth guaranteeing is that one peer cannot *starve* others, not
1040/// that any peer is held to a small quota. Expressing the bound as a reserve
1041/// rather than a quota is what keeps those two apart.
1042const FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES: usize = 4;
1043
1044/// Maximum fresh offers admitted from one source peer.
1045///
1046/// Without a per-source bound, one peer can hold every slot in the global pool
1047/// and every honest offer arriving in that window is refused — and because a
1048/// refusal is later read as absence by the sender's delayed possession check,
1049/// those refusals land as audit-severity trust penalties on the *refuser*.
1050/// That makes an unbounded global pool a targeted eviction primitive.
1051///
1052/// The bound is deliberately far looser than the other responder classes'
1053/// (fetch 2, verification 1, neighbor sync 1), because the traffic pattern is
1054/// the opposite shape. Those are request/response: a requester needs only a
1055/// couple in flight, so a small quota costs it nothing. Fresh offers are a
1056/// one-way bulk fan-out, and in the ordinary case a node's offers come almost
1057/// entirely from ONE peer — whichever node took the client's PUT. A quota sized
1058/// for request/response traffic therefore binds on completely legitimate
1059/// uploads: at 2, an ordinary 48-chunk upload had offers refused (see
1060/// `tests/e2e/fresh_offer_capacity.rs`), every one of them attributed to this
1061/// ceiling and none to the global pool.
1062///
1063/// Sizing it as "the pool minus a reserve" keeps the anti-starvation guarantee
1064/// exact — [`FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES`] slots always remain for a
1065/// peer holding none — while leaving a single legitimate fan-out unthrottled.
1066// The cast is from a compile-time constant difference of two small literals
1067// (16 - 4), so truncation is impossible; deriving the share keeps the reserve
1068// relationship visible in the code rather than only in a test.
1069#[allow(clippy::cast_possible_truncation)]
1070const FRESH_OFFER_MAX_OUTSTANDING_PER_PEER: u32 =
1071 (FRESH_OFFER_MAX_OUTSTANDING - FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES) as u32;
1072
1073/// Maximum paid-list notifications served concurrently.
1074///
1075/// A `PaidNotify` runs the same on-chain proof verification as a fresh offer
1076/// but stores only paid-list metadata, so it needs no chunk-write headroom.
1077/// Two workers keep cross-peer progress without multiplying concurrent EVM
1078/// and DHT lookup pressure.
1079const PAID_NOTIFY_WORKER_LIMIT: usize = 2;
1080
1081/// Maximum paid-list notifications admitted across workers and their waiters.
1082///
1083/// Sized as a **memory** ceiling, not a fairness device, because `PaidNotify`
1084/// is one-way: the protocol defines no response and the sender never retries,
1085/// so a refused notify is information permanently lost to this node until a
1086/// later verification cycle happens to re-derive the key's paid status from a
1087/// paid-list quorum. A tight admission bound therefore does not shed load, it
1088/// discards durable state — which is why the class's real protection is
1089/// [`PAID_NOTIFY_WORKER_LIMIT`], bounding the concurrent EVM and DHT work that
1090/// is actually expensive, rather than this queue depth.
1091///
1092/// A client PUT fans one notify per key out to the whole paid close group, so
1093/// a single upload legitimately arrives as a burst of tens. At the 512 KiB
1094/// `MAX_PAYMENT_PROOF_SIZE_BYTES` worst case, sixty-four outstanding is a
1095/// 32 MiB ceiling — half the fresh-offer admission ceiling, for messages that
1096/// carry no chunk payload.
1097const PAID_NOTIFY_MAX_OUTSTANDING: usize = 64;
1098
1099/// Maximum admitted paid-list notifications from one source peer.
1100///
1101/// A quarter of the pool. One peer legitimately supplies a whole upload's
1102/// worth of notifies, so this must comfortably exceed a typical file's chunk
1103/// count in flight; it exists to stop a single source evicting every other
1104/// peer's durable paid-list evidence, not to ration ordinary traffic.
1105const PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER: u32 = 16;
1106
1107/// Maximum fetch responses served concurrently.
1108///
1109/// Each successful response can upload a 4 MiB chunk. Matching
1110/// [`MAX_CONCURRENT_REPLICATION_SENDS`] keeps fetch serving to about 12 MiB of
1111/// simultaneous chunk data, which avoids saturating typical home upload links.
1112const FETCH_RESPONDER_WORKER_LIMIT: usize = 3;
1113
1114/// Maximum fetch requests admitted across workers and their bounded waiters.
1115///
1116/// Four worker waves absorb short bursts without retaining chunk bytes—the
1117/// request contains only a key—while the dequeue deadline sheds work before a
1118/// sustained flood can keep the node serving requests whose callers timed out.
1119const FETCH_RESPONDER_MAX_OUTSTANDING: usize = FETCH_RESPONDER_WORKER_LIMIT * 4;
1120
1121/// Maximum admitted fetch requests from one source peer.
1122///
1123/// Two requests let one peer pipeline useful reads while leaving at least one
1124/// of the three workers available to other peers under a single-source flood.
1125const FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 2;
1126
1127/// Maximum verification batches served concurrently.
1128///
1129/// LMDB point lookups are fast, but a batch can contain 8,192 of them. Two
1130/// workers isolate that synchronous work from message dispatch without turning
1131/// large batches into an I/O fan-out throughput contest.
1132const VERIFICATION_RESPONDER_WORKER_LIMIT: usize = 2;
1133
1134/// Maximum verification batches admitted across workers and bounded waiters.
1135///
1136/// Four worker waves absorb ordinary cross-peer bursts while the dequeue
1137/// deadline prevents queued batches from consuming lookup capacity after their
1138/// requesters have stopped waiting.
1139const VERIFICATION_RESPONDER_MAX_OUTSTANDING: usize = VERIFICATION_RESPONDER_WORKER_LIMIT * 4;
1140
1141/// Maximum admitted verification batches from one source peer.
1142///
1143/// Senders already aggregate a peer's keys into one batch. One outstanding
1144/// batch therefore preserves useful work while reserving the other worker and
1145/// the bounded queue for different peers.
1146const VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1147
1148/// Maximum neighbor-sync requests served concurrently across source peers.
1149///
1150/// Building a response scans local keys and performs DHT lookups, so two
1151/// workers allow cross-peer progress without multiplying that expensive scan
1152/// into broad network and storage contention.
1153const NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT: usize = 2;
1154
1155/// Maximum neighbor-sync requests admitted across workers and bounded waiters.
1156///
1157/// Four worker waves cover ordinary cadence overlap while keeping retained sync
1158/// payloads bounded; expired waiters are shed before any key scan begins.
1159const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING: usize = NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT * 4;
1160
1161/// Maximum admitted neighbor-sync requests from one source peer.
1162///
1163/// Sync history must be updated before repair proofs for the same peer. A
1164/// single slot preserves that ordering while independent peers remain parallel.
1165const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1166
1167/// Match an inbound topic against the replication protocol ids, in both the bare
1168/// gossip form and the `/rr/<id>` request-response form.
1169///
1170/// Returns the matched core or [`SUBTREE_AUDIT_PROTOCOL_ID`] id and whether it
1171/// was the RR form. The matched id is carried into the handler so it can enforce
1172/// that subtree messages only arrive on the subtree id.
1173fn match_replication_protocol(topic: &str) -> Option<(&'static str, bool)> {
1174 for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
1175 if topic == id {
1176 return Some((id, false));
1177 }
1178 if let Some(rest) = topic.strip_prefix(RR_PREFIX) {
1179 if rest == id {
1180 return Some((id, true));
1181 }
1182 }
1183 }
1184 None
1185}
1186
1187/// Whether a decoded body belongs on the protocol id it arrived on:
1188/// subtree-audit bodies on [`SUBTREE_AUDIT_PROTOCOL_ID`] and every other body,
1189/// including digest audits, on [`REPLICATION_PROTOCOL_ID`].
1190///
1191/// The receive guard drops any mismatch (a cross-version or misrouted message);
1192/// sharing this one predicate between the guard and its regression test means a
1193/// change to the rule cannot pass the test unnoticed.
1194fn body_matches_protocol(body: &ReplicationMessageBody, protocol: &str) -> bool {
1195 protocol == response_protocol_for(body)
1196}
1197
1198/// The protocol id a body belongs on — the single source of truth for BOTH
1199/// directions: the receive guard ([`body_matches_protocol`]) and the outbound
1200/// response selector in `send_replication_response_checked`.
1201///
1202/// Sharing one function makes the subtree/core isolation symmetric.
1203fn response_protocol_for(body: &ReplicationMessageBody) -> &'static str {
1204 if body.is_subtree_audit() {
1205 SUBTREE_AUDIT_PROTOCOL_ID
1206 } else {
1207 REPLICATION_PROTOCOL_ID
1208 }
1209}
1210
1211fn fresh_offer_payment_context() -> VerificationContext {
1212 VerificationContext::FreshReplication
1213}
1214
1215fn paid_notify_payment_context() -> VerificationContext {
1216 VerificationContext::PaidListAdmission
1217}
1218
1219/// Boxed future type for in-flight fetch tasks.
1220type FetchFuture = Pin<Box<dyn Future<Output = (XorName, Option<FetchOutcome>)> + Send>>;
1221
1222/// Fresh-offer keys currently being handled, each with the proofs still to try.
1223///
1224/// Concurrent duplicates are routine: a client PUT is confirmed by
1225/// `CLOSE_GROUP_MAJORITY` nodes and each of them fans the chunk out, so one key
1226/// commonly arrives from several senders at once. Collapsing them onto one
1227/// handler is what keeps a burst of PUTs from costing a permit, a worker slot,
1228/// and an on-chain verification per copy.
1229///
1230/// What they collapse *onto* is the load-bearing part. Keeping only the key and
1231/// refusing every later offer outright made the first arrival the only arrival:
1232/// if its proof failed, the record was lost even though a valid proof for the
1233/// same bytes was queued behind it, and the resulting absence was charged to
1234/// this node by the delayed possession check. So the entry holds the bytes once
1235/// and queues each sender's proof, and the handler works down that queue. A
1236/// later offer therefore costs a proof, not a payload — sound only because
1237/// `fresh_offer_structural_rejection` has confirmed `key == BLAKE3(data)` for
1238/// every one of them before it is queued, which is what makes their bytes
1239/// provably identical.
1240///
1241/// Entries are exact keys rather than hash shards. A node only receives offers
1242/// for keys it is close to, so the accepted key set clusters tightly around its
1243/// own ID — any index derived from the key would land nearly every offer on one
1244/// shard and serialize unrelated keys behind each other. Exact keys keep them
1245/// independent, and the map stays bounded by [`FRESH_OFFER_MAX_OUTSTANDING`],
1246/// each entry by [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`].
1247///
1248/// The critical section is a map insert, pop, or remove and is never held across
1249/// an await, so this is a blocking mutex rather than an async one.
1250type FreshOfferInFlight = Arc<Mutex<HashMap<XorName, FreshOfferEntry>>>;
1251
1252/// One sender's unverified claim to have paid for a key already in flight.
1253///
1254/// Carries no payload: the bytes live once in [`FreshOfferEntryGuard`], and the
1255/// content-address check ran before this attempt was queued.
1256struct FreshOfferAttempt {
1257 source: PeerId,
1258 proof_of_payment: Vec<u8>,
1259 request_id: u64,
1260 rr_message_id: Option<String>,
1261}
1262
1263/// Proofs still to try for one in-flight key, and who supplied them.
1264///
1265/// Deliberately holds neither the bytes nor an arrival time: both belong to the
1266/// handler that owns the key, and live once in [`FreshOfferEntryGuard`].
1267struct FreshOfferEntry {
1268 /// Untried proofs in arrival order. The handler holds the current one.
1269 pending: VecDeque<FreshOfferAttempt>,
1270 /// Sources already represented, so one peer cannot fill the queue alone.
1271 sources: HashSet<PeerId>,
1272 /// Proofs admitted over this entry's whole life, **never decremented**.
1273 ///
1274 /// The budget has to be spent by admissions rather than held by the queue.
1275 /// The handler pops a proof before verifying it, so gating on
1276 /// `pending.len()` would let a fresh source refill the slot that pop just
1277 /// freed, and a stream of distinct sources could then run unbounded
1278 /// sequential payment verifications while holding one of only four worker
1279 /// slots. Counting admissions makes the cap a lifetime budget instead.
1280 admitted: usize,
1281}
1282
1283/// How an arriving fresh offer joined the work already in flight for its key.
1284enum FreshOfferAdmission {
1285 /// Opened the entry. This offer's handler owns the key and drives every
1286 /// queued proof, including proofs that arrive later.
1287 Opened(Box<FreshOfferEntryGuard>),
1288 /// Merged into an entry another offer opened; its handler reaches this proof
1289 /// if the ones ahead of it fail.
1290 Joined,
1291 /// The entry already holds [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`] proofs.
1292 Full,
1293 /// This source already has a proof queued for this key.
1294 DuplicateSource,
1295}
1296
1297// Gated on `logging` like `SerialQueueDropReason::as_str`: the only caller is a
1298// `debug!`, which compiles to nothing without the feature.
1299#[cfg(feature = "logging")]
1300impl FreshOfferAdmission {
1301 /// Why the offer added nothing to the work already queued for its key.
1302 ///
1303 /// Local logging only — the wire reason stays uniform so a probing peer
1304 /// cannot tell a full queue from a repeat of its own proof.
1305 const fn surplus_reason(&self) -> &'static str {
1306 match self {
1307 Self::DuplicateSource => "this source already has a proof queued",
1308 Self::Full => "the key already holds its full complement of proofs",
1309 Self::Opened(_) | Self::Joined => "not surplus",
1310 }
1311 }
1312}
1313
1314/// RAII ownership of one in-flight fresh-offer key.
1315///
1316/// Clears the entry on drop, so an early return, an error, or a panic cannot
1317/// strand a key as permanently in flight. Also owns the single copy of the
1318/// offered bytes that every queued proof is tried against.
1319struct FreshOfferEntryGuard {
1320 in_flight: FreshOfferInFlight,
1321 key: XorName,
1322 /// The bytes every attempt for this key shares, held exactly once.
1323 data: Vec<u8>,
1324 /// Arrival of the offer that opened the entry.
1325 received_at: Instant,
1326 /// Cleared once the entry has been removed, so `drop` cannot delete an entry
1327 /// a *later* offer has since opened for the same key.
1328 holds_entry: bool,
1329}
1330
1331impl FreshOfferEntryGuard {
1332 /// Open an entry for this offer's key, or queue its proof behind the entry
1333 /// already open.
1334 ///
1335 /// Takes the offer by value: on `Opened` its bytes move into the guard, and
1336 /// on every other outcome they are dropped here rather than held for the
1337 /// lifetime of the entry.
1338 fn admit(
1339 in_flight: &FreshOfferInFlight,
1340 offer: protocol::FreshReplicationOffer,
1341 source: PeerId,
1342 request_id: u64,
1343 rr_message_id: Option<String>,
1344 received_at: Instant,
1345 ) -> FreshOfferAdmission {
1346 let key = offer.key;
1347 let attempt = FreshOfferAttempt {
1348 source,
1349 proof_of_payment: offer.proof_of_payment,
1350 request_id,
1351 rr_message_id,
1352 };
1353
1354 let mut in_flight_map = in_flight.lock();
1355 if let Some(entry) = in_flight_map.get_mut(&key) {
1356 if entry.sources.contains(&source) {
1357 return FreshOfferAdmission::DuplicateSource;
1358 }
1359 // Lifetime budget, not queue depth: a proof the handler has already
1360 // popped has spent its slot, not returned it.
1361 if entry.admitted >= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
1362 return FreshOfferAdmission::Full;
1363 }
1364 entry.admitted = entry.admitted.saturating_add(1);
1365 entry.sources.insert(source);
1366 entry.pending.push_back(attempt);
1367 return FreshOfferAdmission::Joined;
1368 }
1369
1370 let mut sources = HashSet::new();
1371 sources.insert(source);
1372 let mut pending = VecDeque::new();
1373 pending.push_back(attempt);
1374 in_flight_map.insert(
1375 key,
1376 FreshOfferEntry {
1377 pending,
1378 sources,
1379 admitted: 1,
1380 },
1381 );
1382 drop(in_flight_map);
1383 FreshOfferAdmission::Opened(Box::new(Self {
1384 in_flight: Arc::clone(in_flight),
1385 key,
1386 data: offer.data,
1387 received_at,
1388 holds_entry: true,
1389 }))
1390 }
1391
1392 /// The bytes every proof for this key is tried against.
1393 fn data(&self) -> &[u8] {
1394 &self.data
1395 }
1396
1397 /// When the first offer for this key arrived.
1398 fn received_at(&self) -> Instant {
1399 self.received_at
1400 }
1401
1402 /// Take the next untried proof, releasing the key when none remain.
1403 ///
1404 /// Popping and releasing happen under one lock so a proof arriving exactly
1405 /// as the queue empties is never silently discarded: it either lands in this
1406 /// entry and is returned here, or finds no entry and opens its own.
1407 fn next_attempt(&mut self) -> Option<FreshOfferAttempt> {
1408 let mut in_flight = self.in_flight.lock();
1409 let Some(entry) = in_flight.get_mut(&self.key) else {
1410 self.holds_entry = false;
1411 return None;
1412 };
1413 if let Some(attempt) = entry.pending.pop_front() {
1414 return Some(attempt);
1415 }
1416 in_flight.remove(&self.key);
1417 self.holds_entry = false;
1418 None
1419 }
1420
1421 /// Release the key and return the proofs that were never tried, so their
1422 /// senders can be told the outcome the key reached without them.
1423 fn release(&mut self) -> Vec<FreshOfferAttempt> {
1424 let mut in_flight = self.in_flight.lock();
1425 self.holds_entry = false;
1426 in_flight
1427 .remove(&self.key)
1428 .map(|entry| entry.pending.into_iter().collect())
1429 .unwrap_or_default()
1430 }
1431}
1432
1433impl Drop for FreshOfferEntryGuard {
1434 fn drop(&mut self) {
1435 if self.holds_entry {
1436 self.in_flight.lock().remove(&self.key);
1437 }
1438 }
1439}
1440
1441/// Shared dependencies for one verification worker cycle.
1442struct VerificationCycleContext<'a> {
1443 p2p_node: &'a Arc<P2PNode>,
1444 paid_list: &'a Arc<PaidList>,
1445 storage: &'a Arc<LmdbStorage>,
1446 queues: &'a Arc<RwLock<ReplicationQueues>>,
1447 config: &'a ReplicationConfig,
1448 bootstrap_state: &'a Arc<RwLock<BootstrapState>>,
1449 is_bootstrapping: &'a Arc<RwLock<bool>>,
1450 bootstrap_complete_notify: &'a Arc<Notify>,
1451 /// v12 §6 holder-eligibility inputs. The verifier downgrades a
1452 /// peer's Present claim to Unresolved unless they're a credited
1453 /// holder of the key (i.e. they recently passed a commitment-bound
1454 /// audit on it under their currently-credited commitment hash).
1455 last_commitment_by_peer: &'a Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1456 ever_capable_peers: &'a Arc<RwLock<HashSet<PeerId>>>,
1457 recent_provers: &'a Arc<RwLock<RecentProvers>>,
1458}
1459
1460/// Fetch worker polling interval in milliseconds.
1461const FETCH_WORKER_POLL_MS: u64 = 100;
1462
1463/// Verification worker polling interval in milliseconds.
1464const VERIFICATION_WORKER_POLL_MS: u64 = 250;
1465
1466/// Verification cycle duration that is worth surfacing at info level.
1467const VERIFICATION_CYCLE_SLOW_LOG_MS: u128 = 500;
1468
1469/// Standard trust event weight for per-operation success/failure signals.
1470///
1471/// Used for individual replication fetch outcomes, integrity check failures,
1472/// and bootstrap claim abuse. Distinct from `AUDIT_FAILURE_TRUST_WEIGHT` which
1473/// is reserved for confirmed audit failures.
1474const REPLICATION_TRUST_WEIGHT: f64 = 1.0;
1475/// Bound trust updates from one verification cycle. A malicious peer can
1476/// advertise thousands of bad singleton keys at once; a few independent
1477/// contradictions are enough for the trust engine without flooding it.
1478const MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE: usize = 3;
1479
1480/// Bootstrap drain check interval in seconds.
1481const BOOTSTRAP_DRAIN_CHECK_SECS: u64 = 5;
1482
1483/// Grace period `shutdown()` waits for each long-lived background task to
1484/// observe the cancellation token and terminate before aborting it.
1485///
1486/// Detached tasks are drained without a timeout because storage-capable work
1487/// may be awaiting a `spawn_blocking` LMDB operation, which continues running
1488/// if its async waiter is dropped.
1489const SHUTDOWN_TASK_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
1490
1491/// How often the responder rebuilds + rotates its storage commitment.
1492///
1493/// Each rebuild scans LMDB to compute leaf hashes; for ~10k keys this is
1494/// sub-100ms (BLAKE3 + tree build). Retention is gossip-anchored, NOT
1495/// rotation-anchored: the responder stays answerable for the current
1496/// commitment plus every root it recently gossiped that is still in-window
1497/// (~2 in steady state), each kept for `GOSSIP_ANSWERABILITY_TTL` (3 h) after
1498/// its last emission (see `commitment_state`). So the rotation cadence does
1499/// not by itself bound answerability — a gossiped commitment stays
1500/// answerable across rotations until its gossip TTL lapses.
1501///
1502/// Default: 1 hour, aligned with the worst-case neighbor-sync cooldown
1503/// (`NEIGHBOR_SYNC_COOLDOWN_SECS = 3600`). Because the gossip TTL (3 h)
1504/// comfortably exceeds the gap between our rotation and the next gossip
1505/// arrival at a remote peer, this prevents the "unknown commitment hash" ->
1506/// Idle audit-skip pattern from being the common case.
1507///
1508/// Why not faster: the v12 pin is bound to a specific point-in-time
1509/// commitment, so rotation isn't security-critical for pin freshness —
1510/// only for keeping the committed key set current as the responder
1511/// writes new keys. 1 hour is plenty for that, and slow enough that
1512/// honest auditors mostly hit `current` or `previous` rather than the
1513/// "rotated past" case.
1514const COMMITMENT_ROTATION_INTERVAL_SECS: u64 = 3600;
1515
1516/// How often the responder retention snapshot is flushed to disk (ADR-0004 A1).
1517/// Short relative to the answerability TTL (3 h) so a gossip-stamp refresh is
1518/// durable well before it could matter to a restart, while the write-on-change
1519/// guard keeps idle nodes from needless disk writes.
1520const RETENTION_PERSIST_INTERVAL_SECS: u64 = 30;
1521
1522/// Cadence of the `replication traffic summary (cumulative)` INFO lines
1523/// (V2-623). A `const` so testnets can drop it to 60s; 300s is the production
1524/// default that keeps log volume negligible.
1525const TRAFFIC_SUMMARY_INTERVAL_SECS: u64 = 300;
1526
1527/// Cadence of the read-only bootstrap state snapshot used to separate drain
1528/// debt from cache and broader connectivity failures in fleet logs.
1529#[cfg(feature = "logging")]
1530const BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS: u64 = 60;
1531
1532/// Maximum tolerated auditor↔responder wall-clock skew for the first-audit
1533/// in-window screen (ADR-0004 A1 guardrail A). The screen accepts a monetized pin
1534/// for first audit only if its SIGNED `quote_ts` lands in
1535/// `[now - (GOSSIP_ANSWERABILITY_TTL - MONETIZED_AUDIT_SKEW_MARGIN), now + MONETIZED_AUDIT_SKEW_MARGIN]`
1536/// — fail-closed on BOTH ends: a quote dated too far in the future (a
1537/// badly-skewed or replayed quote) and one too old (the responder may have aged
1538/// the pin out) are both skipped, so — with grace removed — a stale/skewed quote
1539/// cannot frame an honest node. This assumes bounded clock skew (nodes NTP-synced
1540/// within this margin); a legit first audit fires moments after payment
1541/// (`quote_ts ≈ now`), far from either bound. The gossip-lottery path (which pins
1542/// the responder's OWN freshly-gossiped root) is the clock-skew-immune backstop.
1543/// 30 min dwarfs any realistic honest skew while leaving a wide audit window.
1544const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_secs(30 * 60);
1545
1546/// ADR-0004 A1 (guardrail A): whether a monetized pin's SIGNED `quote_ts` lands
1547/// inside the answerability window relative to `now`, so first-auditing it cannot
1548/// false-convict once grace is removed. Fail-closed on BOTH ends (see
1549/// [`MONETIZED_AUDIT_SKEW_MARGIN`]): a quote more than the skew margin in the
1550/// future, or older than `GOSSIP_ANSWERABILITY_TTL - margin`, is out of window.
1551/// All comparisons use `duration_since` (no `Duration` overflow).
1552fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
1553 let too_future = quote_ts
1554 .duration_since(now)
1555 .is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
1556 let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
1557 let too_old = now
1558 .duration_since(quote_ts)
1559 .is_ok_and(|age| age >= audit_cutoff);
1560 !(too_future || too_old)
1561}
1562
1563/// Minimum interval between commitment signature verifications for a
1564/// single peer (v10/v12 §2 step 3 + §11 `DoS`).
1565///
1566/// A sybil that bypasses the routing-table gate (e.g. by transient
1567/// bucket pollution) could otherwise force one ML-DSA-65 verify (~1 ms)
1568/// per gossip message. This rate limit caps the verify-per-peer rate
1569/// at 1/min, which is comfortably above the legitimate gossip cadence
1570/// (the 10-20 min neighbor-sync round on each peer).
1571const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_secs(60);
1572
1573/// Hard cap on the size of `last_commitment_by_peer`.
1574///
1575/// Bounds the per-process memory cost of the auditor's per-peer
1576/// commitment cache. Each entry holds a `StorageCommitment`
1577/// (~5 KiB: 1952-byte pubkey + 3293-byte signature + small fields).
1578/// At 4096 entries the cache is ~20 MiB, which comfortably covers a
1579/// realistic close-group neighborhood. When the cap is hit, one
1580/// arbitrary existing entry is evicted on insert (`HashMap` iteration
1581/// order is unspecified; we do not track insertion order). The
1582/// `PeerRemoved` handler proactively drops entries as the DHT
1583/// detects departures, and `ingest_peer_commitment` only admits
1584/// commitments from peers currently in the routing table — together
1585/// the cap is the third line of defence against sybil/churn flooding.
1586const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
1587
1588/// ADR-0004 Amendment 4: admission cap for the first-audit pending queue,
1589/// sized to the launch budget instead of the commitment cache.
1590///
1591/// The token bucket can launch at most one audit per
1592/// [`config::FIRST_AUDIT_LAUNCH_INTERVAL`] (plus the
1593/// [`config::FIRST_AUDIT_BUDGET_BURST`] allowance), and a pending pin stays
1594/// launchable for at most the effective answerability window
1595/// ([`GOSSIP_ANSWERABILITY_TTL`] − [`MONETIZED_AUDIT_SKEW_MARGIN`]). Any
1596/// occupancy beyond `window / interval + burst` is work that cannot launch
1597/// before it expires, so admitting it only builds an aging backlog whose
1598/// telemetry measures the backlog instead of schedulable work.
1599///
1600/// At capacity, admission displaces a uniformly RANDOM incumbent (counted as
1601/// `capacity_evicted`), so under overload `pending` degrades to a budget-sized
1602/// rolling sample in which no arrival order lets an attacker deterministically
1603/// flush a chosen target; a fresh pin always enters the sample with an
1604/// unpredictable chance of near-immediate audit, whereas refusing at the door
1605/// would let a sustained payment flood guarantee that every later pin is never
1606/// admitted. See [`coalesce_first_audit_event`] for the displacement rule and
1607/// ADR-0004 Amendment 4 for the eviction-cost math.
1608///
1609/// Derivation uses the STRICT reserve-time horizon: a launch at quote age `a`
1610/// is usable only if the quote stays answerable through `a` plus the maximum
1611/// launch jitter and send slack, so the last usable refill is the largest
1612/// `k` with `k * interval < cutoff - jitter_max - slack`. The unit test
1613/// simulates the shipped predicate instant-by-instant and must agree.
1614#[allow(clippy::cast_possible_truncation)] // bounded by TTL-secs/interval-secs + burst (~31)
1615const FIRST_AUDIT_PENDING_CAP: usize = {
1616 let strict_horizon_secs = GOSSIP_ANSWERABILITY_TTL
1617 .as_secs()
1618 .saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN.as_secs())
1619 .saturating_sub(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_secs())
1620 .saturating_sub(FIRST_AUDIT_SEND_LATENCY_SLACK.as_secs());
1621 // Strictly-inside count: a refill landing exactly ON the horizon is dead
1622 // (`age >= cutoff` rejects), hence the `- 1`. Compile-time division-by-zero
1623 // if the launch interval is ever zeroed: a zero interval makes the budget
1624 // (and this cap) meaningless.
1625 let refills =
1626 strict_horizon_secs.saturating_sub(1) / config::FIRST_AUDIT_LAUNCH_INTERVAL.as_secs();
1627 (refills + config::FIRST_AUDIT_BUDGET_BURST as u64) as usize
1628};
1629
1630// Compile-time guardrails: the cap must be a usable `LruCache` capacity and
1631// strictly tighter than the commitment-cache bound it replaced.
1632const _: () = {
1633 assert!(FIRST_AUDIT_PENDING_CAP >= 1);
1634 assert!(FIRST_AUDIT_PENDING_CAP < MAX_LAST_COMMITMENT_BY_PEER);
1635};
1636
1637/// Cap on the sticky `ever_capable_peers` set. Bounds memory so a
1638/// long-running bootstrap node cannot have the set grow without limit
1639/// from peer-id churn. Sized at 4x `MAX_LAST_COMMITMENT_BY_PEER` so
1640/// the set comfortably outlives normal LRU churn but still caps the
1641/// blast radius of identity-rotation attacks. Once full we refuse new
1642/// inserts (no eviction) — keeps the historic set stable; new v12
1643/// peers above the cap are treated as legacy on rejoin, which matches
1644/// the behaviour before this set existed, not a security regression.
1645const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
1646
1647// ---------------------------------------------------------------------------
1648// ReplicationEngine
1649// ---------------------------------------------------------------------------
1650
1651/// The replication engine manages all replication background tasks and state.
1652pub struct ReplicationEngine {
1653 /// Replication configuration (shared across spawned tasks).
1654 config: Arc<ReplicationConfig>,
1655 /// P2P networking node.
1656 p2p_node: Arc<P2PNode>,
1657 /// Local chunk storage.
1658 storage: Arc<LmdbStorage>,
1659 /// Persistent paid-for-list.
1660 paid_list: Arc<PaidList>,
1661 /// Payment verifier for `PoP` validation.
1662 payment_verifier: Arc<PaymentVerifier>,
1663 /// Replication pipeline queues.
1664 queues: Arc<RwLock<ReplicationQueues>>,
1665 /// Neighbor sync cycle state.
1666 sync_state: Arc<RwLock<NeighborSyncState>>,
1667 /// Per-peer sync history (for `RepairOpportunity`).
1668 ///
1669 /// This map grows with peer churn and is intentionally unbounded: entries
1670 /// are lightweight (`PeerSyncRecord` is two fields) and peer IDs are
1671 /// naturally bounded by the routing table's k-bucket capacity.
1672 sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
1673 /// Per-peer cooldown for gossip-triggered subtree audits (ADR-0002).
1674 ///
1675 /// Records when each peer was last audited so a burst of gossiped
1676 /// commitment changes cannot spawn back-to-back audits of the same peer.
1677 /// Bounded by routing-table membership and cleaned on `PeerRemoved`.
1678 audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
1679 /// Gossip-private lottery attempt window (one roll per peer per window,
1680 /// win or lose). Kept separate from `audit_on_gossip_cooldown` so a losing
1681 /// ticket never stamps the shared map and thus never defers a monetized
1682 /// first audit. Bounded like its sibling and cleaned on `PeerRemoved`.
1683 gossip_lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1684 /// Completed local neighbor-sync cycle epoch for proof maturity.
1685 sync_cycle_epoch: Arc<RwLock<u64>>,
1686 /// Per-key repair proof tracking for audit eligibility.
1687 repair_proofs: Arc<RwLock<RepairProofs>>,
1688 /// Bootstrap state tracking.
1689 bootstrap_state: Arc<RwLock<BootstrapState>>,
1690 /// Whether this node is currently bootstrapping.
1691 is_bootstrapping: Arc<RwLock<bool>>,
1692 /// Trigger for early neighbor sync (signalled on topology changes).
1693 sync_trigger: Arc<Notify>,
1694 /// Notified when `is_bootstrapping` transitions from `true` to `false`.
1695 bootstrap_complete_notify: Arc<Notify>,
1696 /// Node identity (for signing storage commitments).
1697 ///
1698 /// Phase 3 of the v12 storage-bound audit design. The responder
1699 /// uses this to sign its periodically-built `StorageCommitment`.
1700 identity: Arc<NodeIdentity>,
1701 /// Responder-side commitment state (two-slot atomic rotation).
1702 ///
1703 /// Periodically rebuilt from the live LMDB key set; gossiped on
1704 /// outbound `NeighborSyncRequest`/`Response`; consulted by the
1705 /// commitment-bound audit handler.
1706 commitment_state: Arc<ResponderCommitmentState>,
1707 /// Path to the persisted responder retention snapshot
1708 /// (`{root_dir}/commitment_retention.bin`): reloaded on startup so an honest
1709 /// node's answerability survives restart (ADR-0004 A1), which is what makes
1710 /// removing audit grace safe (an unanswerable in-window pin is then provable
1711 /// misbehaviour, not an honest crash-restart).
1712 retention_path: PathBuf,
1713 /// Auditor-side per-peer commitment record (last known commitment +
1714 /// sticky `commitment_capable` flag).
1715 ///
1716 /// Populated whenever an inbound gossip carries a verified
1717 /// commitment from the sender. Used by `audit_tick` to snapshot
1718 /// `expected_commitment_hash` into outbound challenges, and by
1719 /// holder-eligibility (§6) to decide whether a peer's `recent_provers`
1720 /// proof should be honoured. The sticky `commitment_capable` flag
1721 /// flips true on first successful ingest and never reverts (§2
1722 /// step 5).
1723 last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1724 /// Sticky set of peer IDs we have EVER seen carrying a v12
1725 /// commitment, independent of whether their commitment bytes are
1726 /// still in `last_commitment_by_peer`. The §6 holder-eligibility
1727 /// closure consults this set to keep treating churned-out
1728 /// previously-v12 peers as v12-capable (rather than degrading them
1729 /// to "legacy" credit-unconditionally) when they re-appear on the
1730 /// network before their next gossip arrives. Bounded growth: even
1731 /// at one million peers seen over the node's lifetime, the set is
1732 /// 32 MB.
1733 ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
1734 /// Auditor-side holder-eligibility cache (v12 §6).
1735 ///
1736 /// Recorded on successful commitment-bound audit; read by future
1737 /// quorum / paid-list eligibility checks (phase-3 stretch).
1738 recent_provers: Arc<RwLock<RecentProvers>>,
1739 /// Per-peer last sig-verify attempt timestamp for the §2 step 3 /
1740 /// §11 `DoS` rate limit. Bumped on EVERY verify attempt (success or
1741 /// failure) so a peer we've never successfully verified can't burn
1742 /// CPU on a flood of structurally-plausible-but-invalid gossips.
1743 /// Lives separately from `last_commitment_by_peer` because that
1744 /// map's records only exist after a successful verify.
1745 sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1746 /// Limits concurrent outbound replication sends to prevent bandwidth
1747 /// saturation on home broadband connections.
1748 send_semaphore: Arc<Semaphore>,
1749 /// Bounds concurrent IN-FLIGHT LIGHT audit-responder tasks (responsible-chunk
1750 /// audits + subtree slice round 2). The heavy subtree round 1 has its own
1751 /// tighter pool ([`SubtreeRound1Limiter`]). Those are spawned off the serial
1752 /// message loop so disk
1753 /// reads don't block replication; the semaphore restores a global
1754 /// backpressure ceiling so the node can't fan out unbounded `get_raw` reads
1755 /// / multi-MiB byte serves.
1756 audit_responder_semaphore: Arc<Semaphore>,
1757 /// Per-source in-flight audit-responder counts, capped at
1758 /// [`MAX_AUDIT_RESPONSES_PER_PEER`]. The GLOBAL semaphore alone is not
1759 /// flood-fair: one peer spamming challenges could occupy every slot and
1760 /// starve honest auditors, whose dropped challenges then convert to
1761 /// audit timeouts against HONEST peers (codex-r2 A). This
1762 /// per-peer cap guarantees no single source can hold more than its share,
1763 /// so a flood self-throttles without denying service to everyone else.
1764 audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1765 /// Windowed per-origin capacity and processing-time telemetry for every
1766 /// request sharing the audit responder pool.
1767 audit_responder_metrics: Arc<AuditResponderMetrics>,
1768 /// Shared auditor-side limiter for outbound digest `AuditChallenge`s.
1769 ///
1770 /// Responsible-chunk audits, prune confirmations, and possession checks
1771 /// all use this before sending so local bursts wait instead of breaching
1772 /// the responder's deployed per-source admission cap.
1773 audit_challenge_coordinator: Arc<AuditChallengeCoordinator>,
1774 /// Worker permits for bandwidth-bound fetch responses.
1775 fetch_responder_worker_semaphore: Arc<Semaphore>,
1776 /// Admission permits bounding fetch workers and queued waiters together.
1777 fetch_responder_admission_semaphore: Arc<Semaphore>,
1778 /// Per-source fetch responder counts for flood-fair admission.
1779 fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1780 /// Worker permits for lookup-heavy verification batches.
1781 verification_responder_worker_semaphore: Arc<Semaphore>,
1782 /// Admission permits bounding verification workers and queued waiters.
1783 verification_responder_admission_semaphore: Arc<Semaphore>,
1784 /// Per-source verification responder counts for flood-fair admission.
1785 verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1786 /// Worker permits for expensive inbound neighbor-sync requests.
1787 neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
1788 /// Admission permits bounding sync workers and queued waiters together.
1789 neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
1790 /// Per-source sync responder counts; capped at one to preserve ordering.
1791 neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1792 /// Bounded worker permits for expensive fresh-offer handling.
1793 fresh_offer_worker_semaphore: Arc<Semaphore>,
1794 /// Admission permits bounding offers running on a worker or queued for one.
1795 fresh_offer_admission_semaphore: Arc<Semaphore>,
1796 /// Per-source fresh-offer counts, so one sender cannot hold the whole pool
1797 /// and turn honest senders' refusals into trust penalties on this node.
1798 fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1799 /// Keys claimed by an in-flight fresh-offer handler, so concurrent
1800 /// duplicates collapse onto one verification and one write.
1801 fresh_offer_in_flight: FreshOfferInFlight,
1802 /// Bounded worker permits for paid-list notification proof verification.
1803 paid_notify_worker_semaphore: Arc<Semaphore>,
1804 /// Admission permits bounding notifies on a worker or queued for one.
1805 paid_notify_admission_semaphore: Arc<Semaphore>,
1806 /// Per-source paid-notify counts for flood-fair admission.
1807 paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1808 /// Resource controls for the HEAVY subtree-audit round 1: its own
1809 /// tight admission pool (so a burst of full-subtree hashing can't starve the
1810 /// light audits), a per-peer rate cooldown, and single-use round-1 → round-2
1811 /// sessions binding a slice challenge to a matching round 1.
1812 subtree_round1: SubtreeRound1Limiter,
1813 /// Receiver for fresh-write events from the chunk PUT handler.
1814 ///
1815 /// When present, `start()` spawns a drainer task that calls
1816 /// `replicate_fresh` for each event.
1817 fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
1818 /// Sender for delayed possession-check events (ADR-0003). The fresh-write
1819 /// drainer pushes the responsible close-group peers here after each fresh
1820 /// replication; the possession-check scheduler drains the paired receiver.
1821 possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
1822 /// Receiver paired with `possession_check_tx`; taken by the scheduler task.
1823 possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
1824 /// ADR-0004: sender the payment verifier clones to surface monetized pins
1825 /// for a deterministic first audit. The matching receiver is drained by
1826 /// `start_first_audit_drainer`. BOUNDED (Amendment 2): the producer
1827 /// `try_send`s and drops on a full queue, so ingress memory is capped just
1828 /// like launches; a dropped nomination is penalty-free — the peer's
1829 /// gossiped commitments stay lottery-covered and its next settled payment
1830 /// re-nominates the paid pin.
1831 monetized_pin_tx: mpsc::Sender<MonetizedPinEvent>,
1832 /// ADR-0004: receiver half of the monetized-pin channel, taken by
1833 /// `start_first_audit_drainer`.
1834 monetized_pin_rx: Option<mpsc::Receiver<MonetizedPinEvent>>,
1835 /// Counters shared with the first-audit drainer task, so the scheduler's
1836 /// decisions (queued / launched / self-target skipped / outcome) stay
1837 /// observable from the engine after the drainer takes the receiver.
1838 first_audit_observability: Arc<FirstAuditObservability>,
1839 /// Shutdown token.
1840 shutdown: CancellationToken,
1841 /// Background task handles.
1842 task_handles: Vec<JoinHandle<()>>,
1843 /// Tracks detached, short-lived work spawned by background producers.
1844 ///
1845 /// Fresh-offer and bounded responder workers, audit launches, per-fetch
1846 /// tasks, and delayed possession checks may retain storage or P2P state
1847 /// after their producer exits, so shutdown drains them before those
1848 /// resources may be reopened.
1849 detached_task_tracker: TaskTracker,
1850}
1851
1852impl ReplicationEngine {
1853 /// Create a new replication engine.
1854 ///
1855 /// # Errors
1856 ///
1857 /// Returns an error if the `PaidList` LMDB environment cannot be opened
1858 /// or if the configuration fails validation.
1859 #[allow(clippy::too_many_arguments)]
1860 pub async fn new(
1861 config: ReplicationConfig,
1862 p2p_node: Arc<P2PNode>,
1863 storage: Arc<LmdbStorage>,
1864 payment_verifier: Arc<PaymentVerifier>,
1865 identity: Arc<NodeIdentity>,
1866 root_dir: &Path,
1867 fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
1868 shutdown: CancellationToken,
1869 ) -> Result<Self> {
1870 config.validate().map_err(Error::Config)?;
1871
1872 let paid_list = Arc::new(
1873 PaidList::new(root_dir)
1874 .await
1875 .map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
1876 );
1877
1878 let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
1879 let config = Arc::new(config);
1880 let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
1881
1882 // ADR-0004: monetized-pin channel (verifier -> first-audit drainer).
1883 // Bounded (Amendment 2): every stage of the first-audit pipeline is
1884 // now capacity-limited — ingress queue here, pending set (LRU), and
1885 // launch rate (token bucket).
1886 let (monetized_pin_tx, monetized_pin_rx) =
1887 mpsc::channel(config::FIRST_AUDIT_INGRESS_CAPACITY);
1888
1889 let engine = Self {
1890 config: Arc::clone(&config),
1891 p2p_node,
1892 storage,
1893 paid_list,
1894 payment_verifier,
1895 queues: Arc::new(RwLock::new(ReplicationQueues::new())),
1896 sync_state: Arc::new(RwLock::new(initial_neighbors)),
1897 sync_history: Arc::new(RwLock::new(HashMap::new())),
1898 audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
1899 gossip_lottery_attempts: Arc::new(RwLock::new(HashMap::new())),
1900 sync_cycle_epoch: Arc::new(RwLock::new(0)),
1901 repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
1902 bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
1903 is_bootstrapping: Arc::new(RwLock::new(true)),
1904 sync_trigger: Arc::new(Notify::new()),
1905 bootstrap_complete_notify: Arc::new(Notify::new()),
1906 identity,
1907 commitment_state: Arc::new(ResponderCommitmentState::new()),
1908 retention_path: root_dir.join("commitment_retention.bin"),
1909 last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
1910 ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
1911 recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
1912 sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
1913 send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
1914 audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
1915 audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1916 audit_responder_metrics: Arc::new(AuditResponderMetrics::default()),
1917 audit_challenge_coordinator: Arc::new(AuditChallengeCoordinator::new()),
1918 fetch_responder_worker_semaphore: Arc::new(Semaphore::new(
1919 FETCH_RESPONDER_WORKER_LIMIT,
1920 )),
1921 fetch_responder_admission_semaphore: Arc::new(Semaphore::new(
1922 FETCH_RESPONDER_MAX_OUTSTANDING,
1923 )),
1924 fetch_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1925 verification_responder_worker_semaphore: Arc::new(Semaphore::new(
1926 VERIFICATION_RESPONDER_WORKER_LIMIT,
1927 )),
1928 verification_responder_admission_semaphore: Arc::new(Semaphore::new(
1929 VERIFICATION_RESPONDER_MAX_OUTSTANDING,
1930 )),
1931 verification_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1932 neighbor_sync_responder_worker_semaphore: Arc::new(Semaphore::new(
1933 NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT,
1934 )),
1935 neighbor_sync_responder_admission_semaphore: Arc::new(Semaphore::new(
1936 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
1937 )),
1938 neighbor_sync_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1939 fresh_offer_worker_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_WORKER_LIMIT)),
1940 fresh_offer_admission_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING)),
1941 fresh_offer_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1942 fresh_offer_in_flight: Arc::new(Mutex::new(HashMap::new())),
1943 paid_notify_worker_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_WORKER_LIMIT)),
1944 paid_notify_admission_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING)),
1945 paid_notify_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1946 subtree_round1: SubtreeRound1Limiter::new(
1947 config.subtree_round1_responder_cooldown,
1948 config.subtree_round1_max_concurrent,
1949 ),
1950 fresh_write_rx: Some(fresh_write_rx),
1951 possession_check_tx,
1952 possession_check_rx: Some(possession_check_rx),
1953 monetized_pin_tx,
1954 monetized_pin_rx: Some(monetized_pin_rx),
1955 first_audit_observability: Arc::new(FirstAuditObservability::default()),
1956 shutdown,
1957 task_handles: Vec::new(),
1958 detached_task_tracker: TaskTracker::new(),
1959 };
1960 // ADR-0004 A1: reload persisted responder retention BEFORE any task
1961 // spawns, so an honest restarted node is answerable for its pre-restart
1962 // pins from the first audit it serves, and the persist loop never races
1963 // an empty snapshot over the good on-disk file.
1964 load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
1965 Ok(engine)
1966 }
1967
1968 /// ADR-0004: a sender the payment verifier uses to surface monetized pins
1969 /// (commitments that backed a payment) for a first audit. Cloneable; the
1970 /// engine drains the matching receiver. Bounded: senders must `try_send`
1971 /// and treat a full queue as a benign drop (Amendment 2 best-effort).
1972 #[must_use]
1973 pub fn monetized_pin_sender(&self) -> mpsc::Sender<MonetizedPinEvent> {
1974 self.monetized_pin_tx.clone()
1975 }
1976
1977 /// Get a reference to the `PaidList`.
1978 #[must_use]
1979 pub fn paid_list(&self) -> &Arc<PaidList> {
1980 &self.paid_list
1981 }
1982
1983 /// Get a reference to the responder's commitment state. Used by audit
1984 /// handlers to look up commitments by hash; used by the rotation tick
1985 /// to install fresh ones.
1986 #[must_use]
1987 pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
1988 &self.commitment_state
1989 }
1990
1991 /// Get a reference to the auditor's last-commitment-by-peer table.
1992 #[must_use]
1993 pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
1994 &self.last_commitment_by_peer
1995 }
1996
1997 /// Get a reference to the holder-eligibility cache. Phase-3 stretch:
1998 /// will be read by quorum / paid-list eligibility checks.
1999 #[must_use]
2000 pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
2001 &self.recent_provers
2002 }
2003
2004 /// Test-only: rebuild + rotate this node's storage commitment now over its
2005 /// current key set (normally on a 1h timer). Lets a test commit to chunks it
2006 /// just stored without waiting for the rotation cadence.
2007 ///
2008 /// # Errors
2009 ///
2010 /// Propagates any error from reading the local key set or building/signing
2011 /// the commitment.
2012 #[cfg(any(test, feature = "test-utils"))]
2013 pub async fn rebuild_commitment_now(&self) -> Result<()> {
2014 rebuild_and_rotate_commitment(
2015 &self.storage,
2016 &self.identity,
2017 &self.commitment_state,
2018 &self.p2p_node,
2019 &self.config,
2020 )
2021 .await
2022 }
2023
2024 /// Test-only: directly seed this node's cached commitment for `peer`,
2025 /// simulating "we received `peer`'s gossiped commitment" without depending
2026 /// on neighbor-sync propagation timing. Lets a two-node audit test pin the
2027 /// peer's commitment deterministically.
2028 #[cfg(any(feature = "test-utils", test))]
2029 pub async fn inject_peer_commitment_for_test(
2030 &self,
2031 peer: &PeerId,
2032 commitment: StorageCommitment,
2033 ) {
2034 let now = Instant::now();
2035 self.last_commitment_by_peer
2036 .write()
2037 .await
2038 .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
2039 self.ever_capable_peers.write().await.insert(*peer);
2040 }
2041
2042 /// Test-only: isolate a monetized first audit of `peer` from live gossip
2043 /// audits. Suppresses new gossip lottery attempts for the current cooldown
2044 /// window and clears any shared cooldown stamped by an earlier gossip
2045 /// launch. The locks follow the production gossip-audit lock order.
2046 #[cfg(any(test, feature = "test-utils"))]
2047 pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
2048 let now = Instant::now();
2049 let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
2050 let mut launched = self.audit_on_gossip_cooldown.write().await;
2051 lottery_attempts.insert(*peer, now);
2052 launched.remove(peer);
2053 }
2054
2055 /// Test-only: run ONE subtree audit against `peer` right now, pinned to the
2056 /// commitment this node has cached for it (from gossip), over the live wire.
2057 /// Returns the audit outcome so tests can assert honest-pass / adversary-fail
2058 /// in a real two-node setting without waiting for the gossip cadence.
2059 ///
2060 /// Returns `AuditTickResult::Idle` if we have no cached commitment for the
2061 /// peer yet (gossip hasn't reached us). Gated to test builds.
2062 #[cfg(any(test, feature = "test-utils"))]
2063 pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
2064 let target = {
2065 let map = self.last_commitment_by_peer.read().await;
2066 map.get(peer)
2067 .and_then(PeerCommitmentRecord::last_commitment)
2068 .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
2069 };
2070 let Some((pin, key_count)) = target else {
2071 return audit::AuditTickResult::Idle;
2072 };
2073 let credit = storage_commitment_audit::AuditCredit {
2074 recent_provers: &self.recent_provers,
2075 };
2076 storage_commitment_audit::run_subtree_audit(
2077 &self.p2p_node,
2078 &self.config,
2079 peer,
2080 pin,
2081 key_count,
2082 Some(&credit),
2083 )
2084 .await
2085 }
2086
2087 /// Test-only: snapshot the first-audit scheduler's counters. Lets e2e
2088 /// tests assert what the live drainer decided for an injected
2089 /// [`MonetizedPinEvent`] (dropped as self-target vs queued and launched).
2090 #[cfg(any(test, feature = "test-utils"))]
2091 #[must_use]
2092 pub fn first_audit_stats(&self) -> FirstAuditStats {
2093 let o = &self.first_audit_observability;
2094 FirstAuditStats {
2095 received: o.received.load(Ordering::Relaxed),
2096 queued: o.queued.load(Ordering::Relaxed),
2097 self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
2098 launched: o.launched.load(Ordering::Relaxed),
2099 passed: o.passed.load(Ordering::Relaxed),
2100 timed_out: o.timed_out.load(Ordering::Relaxed),
2101 failed: o.failed.load(Ordering::Relaxed),
2102 }
2103 }
2104
2105 /// Test-only: run the possession check immediately for `key` against
2106 /// `peers`, bypassing the scheduler's randomised 5-15 minute settle delay.
2107 ///
2108 /// Penalises any peer that does not hold `key` at `AuditChallenge`
2109 /// severity (ADR-0003). Lets e2e tests assert the detection+penalty path
2110 /// deterministically without waiting for the scheduled check.
2111 #[cfg(any(test, feature = "test-utils"))]
2112 pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
2113 possession::run_possession_check(
2114 key,
2115 peers,
2116 &self.p2p_node,
2117 &self.storage,
2118 &self.config,
2119 &self.sync_state,
2120 &self.audit_challenge_coordinator,
2121 &self.shutdown,
2122 )
2123 .await;
2124 }
2125
2126 /// Test-only: place `key` directly into the fetch queue as though a
2127 /// verification cycle had just promoted it, with `sources` as its
2128 /// verified holders. Returns whether the key was enqueued.
2129 ///
2130 /// Bypasses admission, verification, and the promotion-time
2131 /// responsibility pre-filter, modelling a promotion decision that has
2132 /// since gone stale (topology churn between promotion and download).
2133 /// The only guard left standing is the per-attempt recheck inside
2134 /// `execute_single_fetch` — exactly the gate e2e tests use this seam to
2135 /// exercise.
2136 #[cfg(any(test, feature = "test-utils"))]
2137 pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
2138 let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
2139 self.queues
2140 .write()
2141 .await
2142 .enqueue_fetch(key, distance, sources)
2143 }
2144
2145 /// Test-only: whether `key` is still tracked in any fetch-pipeline stage
2146 /// (pending verification, fetch queue, or in-flight fetch).
2147 #[cfg(any(test, feature = "test-utils"))]
2148 pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
2149 self.queues.read().await.contains_key(key)
2150 }
2151
2152 /// Test-only: place `key` into pending verification as though `hinter` had
2153 /// just advertised it with a replica hint. Returns whether it was admitted.
2154 ///
2155 /// Enters the pipeline one stage earlier than
2156 /// [`Self::enqueue_fetch_for_test`], so what the verification cycle itself
2157 /// decides about the key is observable.
2158 #[cfg(any(test, feature = "test-utils"))]
2159 pub async fn enqueue_pending_verify_for_test(&self, key: XorName, hinter: PeerId) -> bool {
2160 let now = Instant::now();
2161 let entry = VerificationEntry {
2162 state: VerificationState::PendingVerify,
2163 verified_sources: Vec::new(),
2164 tried_sources: HashSet::new(),
2165 created_at: now,
2166 next_verify_at: now,
2167 hint_sources: HashSet::from([hinter]),
2168 replica_hint_sources: HashSet::from([hinter]),
2169 unresolved_retries: 0,
2170 no_holder_reported: false,
2171 };
2172 self.queues
2173 .write()
2174 .await
2175 .add_pending_verify(key, entry)
2176 .admitted()
2177 }
2178
2179 /// Test-only: how far ahead `key`'s next verification round is scheduled,
2180 /// or `None` when the key is not pending verification.
2181 #[cfg(any(test, feature = "test-utils"))]
2182 pub async fn pending_verify_delay_for_test(&self, key: &XorName) -> Option<Duration> {
2183 self.queues.read().await.get_pending(key).map(|entry| {
2184 entry
2185 .next_verify_at
2186 .saturating_duration_since(Instant::now())
2187 })
2188 }
2189
2190 /// Start all background tasks.
2191 ///
2192 /// `dht_events` must be subscribed **before** `P2PNode::start()` so that
2193 /// the `BootstrapComplete` event emitted during DHT bootstrap is not
2194 /// missed by the bootstrap-sync gate.
2195 pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
2196 if !self.task_handles.is_empty() {
2197 error!("ReplicationEngine::start() called while already running — ignoring");
2198 return;
2199 }
2200 info!("Starting replication engine");
2201
2202 self.start_message_handler();
2203 self.start_neighbor_sync_loop();
2204 self.start_self_lookup_loop();
2205 // Audit #2 (responsible-chunk): periodic tick auditing peers for the
2206 // chunks they SHOULD store (responsibility + prior hint).
2207 self.start_audit_loop();
2208 // Audit #1 (storage-commitment) is gossip-triggered in the message
2209 // handler when a peer's commitment is ingested, not on a periodic tick.
2210 self.start_commitment_rotation_loop();
2211 self.start_retention_persist_loop();
2212 self.start_fetch_worker();
2213 self.start_verification_worker();
2214 self.start_bootstrap_sync(dht_events);
2215 self.start_fresh_write_drainer();
2216 self.start_possession_check_scheduler();
2217 // ADR-0004: deterministic first audit of commitments that backed a
2218 // payment (surfaced by the verifier cross-check).
2219 self.start_first_audit_drainer();
2220 // V2-623: periodic cumulative per-variant traffic accounting.
2221 self.start_traffic_summary_loop();
2222 // V2-884: read-only bootstrap state for cache/drain/connectivity triage.
2223 #[cfg(feature = "logging")]
2224 self.start_bootstrap_state_snapshot_loop();
2225 #[cfg(feature = "logging")]
2226 self.start_audit_responder_summary_loop();
2227
2228 info!(
2229 "Replication engine started with {} background tasks",
2230 self.task_handles.len()
2231 );
2232 }
2233
2234 /// Returns `true` if the node is still in the replication bootstrap phase.
2235 ///
2236 /// During bootstrap, audit challenges return `Bootstrapping` instead of
2237 /// digests, and neighbor sync responses carry `bootstrapping: true`.
2238 pub async fn is_bootstrapping(&self) -> bool {
2239 *self.is_bootstrapping.read().await
2240 }
2241
2242 /// Wait until the replication bootstrap phase completes.
2243 ///
2244 /// Returns immediately if bootstrap has already completed. Useful for
2245 /// readiness probes, health checks, and test harnesses that need the
2246 /// node to be fully operational before proceeding.
2247 ///
2248 /// Returns `true` if bootstrap completed within the timeout, `false`
2249 /// if the timeout elapsed first.
2250 pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
2251 // Register the notification future *before* checking the flag so that
2252 // a transition between the read and the await is not missed.
2253 let notified = self.bootstrap_complete_notify.notified();
2254 tokio::pin!(notified);
2255 notified.as_mut().enable();
2256
2257 if !*self.is_bootstrapping.read().await {
2258 return true;
2259 }
2260
2261 tokio::time::timeout(timeout, notified).await.is_ok()
2262 }
2263
2264 /// Cancel all background tasks and wait for them to terminate.
2265 ///
2266 /// This must be awaited before dropping the engine when the caller needs
2267 /// the `Arc<LmdbStorage>` references held by background tasks to be
2268 /// released (e.g. before reopening the same LMDB environment).
2269 ///
2270 /// When this returns, no engine-spawned task still holds
2271 /// `Arc<LmdbStorage>` or `Arc<PaidList>`, and no LMDB blocking operation
2272 /// (read or write, on either the chunk store or the paid-list
2273 /// environment) is still running. Engine tasks race their work against
2274 /// the shutdown token; a dropped future may leave a `spawn_blocking`
2275 /// LMDB transaction running detached, so this method additionally waits
2276 /// for both storage layers to go quiescent before returning.
2277 pub async fn shutdown(&mut self) {
2278 self.shutdown.cancel();
2279 for (i, mut handle) in self.task_handles.drain(..).enumerate() {
2280 match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
2281 Ok(Ok(())) => {}
2282 Ok(Err(e)) if e.is_cancelled() => {}
2283 Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
2284 Err(_) => {
2285 warn!(
2286 "Replication task {i} did not stop within {}s, aborting",
2287 SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
2288 );
2289 handle.abort();
2290 // `abort` only requests cancellation. Await the handle so
2291 // synchronous sections finish and the task drops every
2292 // storage/P2P clone before we claim producer quiescence.
2293 match handle.await {
2294 Ok(()) => {}
2295 Err(e) if e.is_cancelled() => {}
2296 Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
2297 }
2298 }
2299 }
2300 }
2301
2302 // Close the responder worker pools. Detached tasks still queued for a
2303 // worker take the `Err` arm of `acquire_owned()` and exit immediately
2304 // rather than waiting for a slot that will never free up — without
2305 // this, work admitted just before shutdown would queue behind the last
2306 // in-flight batch and hold the drain below open for its full duration.
2307 self.fresh_offer_worker_semaphore.close();
2308 self.paid_notify_worker_semaphore.close();
2309 self.fetch_responder_worker_semaphore.close();
2310 self.verification_responder_worker_semaphore.close();
2311 self.neighbor_sync_responder_worker_semaphore.close();
2312
2313 // All producers have stopped, so close and drain their detached work.
2314 // A started storage operation must run to completion: dropping an async
2315 // waiter does not cancel `spawn_blocking`, and would let shutdown return
2316 // while an LMDB transaction still owns the environment.
2317 //
2318 // Deliberately unbounded: the LMDB contract requires every worker to
2319 // release its `Arc<LmdbStorage>` before the caller may reopen the
2320 // environment, and a timeout here could return with one still held.
2321 // What makes that safe is that every detached task is now guaranteed to
2322 // finish — the pools above are closed, stale work is shed at dequeue,
2323 // and the one genuinely unbounded await (payment verification) races
2324 // `self.shutdown` via `verify_payment_until_shutdown`.
2325 self.detached_task_tracker.close();
2326 self.detached_task_tracker.wait().await;
2327
2328 // Every producer is gone, but a select! racing the shutdown token may
2329 // have dropped a future while it awaited an LMDB `spawn_blocking` op
2330 // (fetch `storage.put`, prune `storage.delete` /
2331 // `paid_list.remove_batch`, verification `paid_list.insert`). The
2332 // detached blocking closure owns a cloned `Env`; wait for both
2333 // environments to go quiescent — bounded by one in-flight transaction
2334 // per op — so the caller may reopen them.
2335 self.storage.wait_idle().await;
2336 self.paid_list.wait_idle().await;
2337 }
2338
2339 /// Trigger an early neighbor sync round.
2340 ///
2341 /// Useful after topology changes (new nodes joining, network heal after
2342 /// partition) when the caller wants replication to converge faster than
2343 /// the regular 10-20 minute cadence.
2344 pub fn trigger_neighbor_sync(&self) {
2345 self.sync_trigger.notify_one();
2346 }
2347
2348 /// Execute fresh replication for a newly stored record, then schedule the
2349 /// delayed possession check for the responsible close-group peers
2350 /// (ADR-0003). The production PUT path schedules via the fresh-write
2351 /// drainer; this direct entry point schedules here so callers (and tests)
2352 /// that drive replication directly still get the possession check.
2353 pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
2354 let peers = fresh::replicate_fresh(
2355 key,
2356 data,
2357 proof_of_payment,
2358 &self.p2p_node,
2359 &self.paid_list,
2360 &self.config,
2361 &self.send_semaphore,
2362 )
2363 .await;
2364 if !peers.is_empty() {
2365 let _ = self
2366 .possession_check_tx
2367 .send(possession::PossessionCheckEvent { key: *key, peers });
2368 }
2369 }
2370
2371 // =======================================================================
2372 // Background task launchers
2373 // =======================================================================
2374
2375 /// Spawn a task that drains the fresh-write channel and triggers
2376 /// replication for each newly-stored chunk.
2377 fn start_fresh_write_drainer(&mut self) {
2378 let Some(mut rx) = self.fresh_write_rx.take() else {
2379 return;
2380 };
2381 let p2p = Arc::clone(&self.p2p_node);
2382 let paid_list = Arc::clone(&self.paid_list);
2383 let config = Arc::clone(&self.config);
2384 let send_semaphore = Arc::clone(&self.send_semaphore);
2385 let possession_tx = self.possession_check_tx.clone();
2386 let shutdown = self.shutdown.clone();
2387
2388 let handle = tokio::spawn(async move {
2389 loop {
2390 tokio::select! {
2391 () = shutdown.cancelled() => break,
2392 event = rx.recv() => {
2393 let Some(event) = event else { break };
2394 let peers = fresh::replicate_fresh(
2395 &event.key,
2396 &event.data,
2397 &event.payment_proof,
2398 &p2p,
2399 &paid_list,
2400 &config,
2401 &send_semaphore,
2402 )
2403 .await;
2404 // Schedule the delayed possession check (ADR-0003) for
2405 // the responsible close-group peers. A closed receiver
2406 // (engine shutting down) is ignored.
2407 if !peers.is_empty() {
2408 let _ = possession_tx.send(possession::PossessionCheckEvent {
2409 key: event.key,
2410 peers,
2411 });
2412 }
2413 }
2414 }
2415 }
2416 debug!("Fresh-write drainer shut down");
2417 });
2418 self.task_handles.push(handle);
2419 }
2420
2421 /// Spawn the possession-check scheduler (ADR-0003).
2422 ///
2423 /// Drains scheduled possession-check events and, for each, waits a
2424 /// randomised 5-15 minute settle delay before probing every responsible
2425 /// peer for actual possession. A peer that fails to prove possession or does
2426 /// not answer is penalised at `AuditChallenge` severity.
2427 fn start_possession_check_scheduler(&mut self) {
2428 let Some(mut rx) = self.possession_check_rx.take() else {
2429 return;
2430 };
2431 let p2p = Arc::clone(&self.p2p_node);
2432 let storage = Arc::clone(&self.storage);
2433 let config = Arc::clone(&self.config);
2434 let sync_state = Arc::clone(&self.sync_state);
2435 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
2436 let shutdown = self.shutdown.clone();
2437 let detached_task_tracker = self.detached_task_tracker.clone();
2438
2439 let handle = tokio::spawn(async move {
2440 loop {
2441 tokio::select! {
2442 () = shutdown.cancelled() => break,
2443 event = rx.recv() => {
2444 let Some(event) = event else { break };
2445 // Spawn a per-chunk delayed check so the drain loop
2446 // keeps pace with the write rate. Each check sleeps the
2447 // randomised settle delay, then probes every peer.
2448 let p2p = Arc::clone(&p2p);
2449 let storage = Arc::clone(&storage);
2450 let config = Arc::clone(&config);
2451 let sync_state = Arc::clone(&sync_state);
2452 let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
2453 let shutdown = shutdown.clone();
2454 let delay_min = config.possession_check_delay_min;
2455 let delay_max = config.possession_check_delay_max;
2456 detached_task_tracker.spawn(async move {
2457 let delay = possession::random_delay(delay_min, delay_max);
2458 // Race shutdown against the whole settle-then-probe
2459 // sequence, not just the sleep. Once a check starts it
2460 // may park on the per-target audit coordinator, which
2461 // has no deadline of its own: with the settle delay
2462 // inside the branch BODY the select is already resolved,
2463 // so those waiters would drain only at the probe timeout
2464 // (roughly `queued / per-target-limit` probes deep) while
2465 // `detached_task_tracker.wait()` — deliberately unbounded
2466 // for the LMDB contract — held shutdown open.
2467 //
2468 // Dropping this future mid-probe is safe and is the same
2469 // shape the neighbor-sync round uses: a parked coordinator
2470 // acquire releases its counted reference via
2471 // `ReferenceGuard`, and a dropped LMDB `spawn_blocking` is
2472 // covered by the storage-quiescence wait in `shutdown`.
2473 tokio::select! {
2474 () = shutdown.cancelled() => {}
2475 () = async {
2476 tokio::time::sleep(delay).await;
2477 possession::run_possession_check(
2478 event.key,
2479 event.peers,
2480 &p2p,
2481 &storage,
2482 &config,
2483 &sync_state,
2484 &audit_challenge_coordinator,
2485 &shutdown,
2486 )
2487 .await;
2488 } => {}
2489 }
2490 });
2491 }
2492 }
2493 }
2494 debug!("Possession-check scheduler shut down");
2495 });
2496 self.task_handles.push(handle);
2497 }
2498
2499 /// ADR-0004: drain monetized pins surfaced by the verifier cross-check and
2500 /// run a **deterministic first audit** of each — the same `run_subtree_audit`
2501 /// as the gossip path, under the same per-peer cooldown and concurrency
2502 /// caps, but with the probability lottery BYPASSED (the lottery governs
2503 /// re-audits only). Deduped by pin via a bounded set so a pin gets one
2504 /// deterministic first audit; a peer minting fresh pins faster than the
2505 /// cooldown forfeits the older ones' coverage, never the newest's (the
2506 /// channel surfaces newest pins as they are monetized).
2507 #[allow(clippy::too_many_lines)]
2508 fn start_first_audit_drainer(&mut self) {
2509 let Some(mut rx) = self.monetized_pin_rx.take() else {
2510 return;
2511 };
2512 let gossip_audit = GossipAuditTrigger {
2513 p2p_node: Arc::clone(&self.p2p_node),
2514 config: Arc::clone(&self.config),
2515 recent_provers: Arc::clone(&self.recent_provers),
2516 sync_state: Arc::clone(&self.sync_state),
2517 cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2518 detached_task_tracker: self.detached_task_tracker.clone(),
2519 lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2520 };
2521 let shutdown = self.shutdown.clone();
2522 let observability = Arc::clone(&self.first_audit_observability);
2523 let self_peer = *self.p2p_node.peer_id();
2524
2525 let handle = tokio::spawn(async move {
2526 // ADR-0004 Amendment 2 (E'): the drainer-owned first-audit
2527 // scheduler. Payments only NOMINATE pins; the token bucket launches
2528 // them at a fixed per-node rate, and durable suppression is stamped
2529 // only at PROMOTION (after an authoritative post-jitter answerability
2530 // + cooldown check), so a cancelled reservation leaves nothing behind.
2531 let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
2532 // Periodic retry tick so budget/cooldown-deferred pins get retried
2533 // even when no new nomination arrives. `Skip` collapses a backlog.
2534 let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
2535 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2536 let mut last_summary = Instant::now();
2537 loop {
2538 // The reservation's jitter deadline is a wake source: if a
2539 // reservation is outstanding, sleep until it is due; otherwise
2540 // a far-future deadline effectively disables that arm and only
2541 // shutdown/rx/tick wake the loop. Recreated each iteration so a
2542 // newly reserved (earlier) deadline is honoured next turn.
2543 let promotion_due = scheduler
2544 .reserved_ready_at()
2545 .unwrap_or_else(first_audit_far_future);
2546 tokio::select! {
2547 () = shutdown.cancelled() => break,
2548 event = rx.recv() => match event {
2549 Some(e) => {
2550 observability.received.fetch_add(1, Ordering::Relaxed);
2551 // Pre-overflow reservation opportunity: before an
2552 // arrival may displace a DIFFERENT peer, let the
2553 // queue launch — a successful reservation frees the
2554 // slot without eviction. One reservation can be
2555 // outstanding at a time, so this consumes at most
2556 // one slot per jitter window; arrivals beyond it
2557 // fall through to random displacement (ADR-0004
2558 // Amendment 4).
2559 if scheduler.would_displace(&e) {
2560 open_first_audit_reservation(
2561 &mut scheduler,
2562 &gossip_audit.cooldown,
2563 &observability,
2564 )
2565 .await;
2566 }
2567 scheduler.enqueue(e, &observability);
2568 // Drain a bounded burst so a flood cannot starve the
2569 // launch phase.
2570 let mut drained = 1usize;
2571 while drained < config::FIRST_AUDIT_DRAIN_BATCH {
2572 match rx.try_recv() {
2573 Ok(e) => {
2574 observability.received.fetch_add(1, Ordering::Relaxed);
2575 if scheduler.would_displace(&e) {
2576 open_first_audit_reservation(
2577 &mut scheduler,
2578 &gossip_audit.cooldown,
2579 &observability,
2580 )
2581 .await;
2582 }
2583 scheduler.enqueue(e, &observability);
2584 drained += 1;
2585 }
2586 Err(_) => break,
2587 }
2588 }
2589 }
2590 None => break,
2591 },
2592 _ = tick.tick() => {}
2593 () = tokio::time::sleep_until(promotion_due.into()) => {}
2594 }
2595
2596 // 1) Promote a due reservation. Resolved after EVERY wake (not
2597 // only when the timer arm wins) so a continuously-ready `rx`
2598 // cannot indefinitely delay a due promotion. The authoritative
2599 // answerability + cooldown check-and-stamp happens here under
2600 // the shared cooldown write lock, immediately before the send.
2601 if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
2602 let promoted = {
2603 let mut cooldown = gossip_audit.cooldown.write().await;
2604 scheduler.resolve(
2605 reservation,
2606 SystemTime::now(),
2607 Instant::now(),
2608 &mut cooldown,
2609 &observability,
2610 )
2611 };
2612 if let Some((event, inflight_slot)) = promoted {
2613 debug!(
2614 "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
2615 event.peer, hex::encode(event.pin), event.key_count,
2616 observability.inflight.load(Ordering::Relaxed)
2617 );
2618 let trigger = gossip_audit.clone();
2619 let audit_observability = Arc::clone(&observability);
2620 // Track the launch so `shutdown()`'s detached drain
2621 // covers it. This task outlives the drainer loop that
2622 // spawned it — the loop breaks on the shutdown token
2623 // while the audit is still awaiting its response — so a
2624 // bare spawn would let an in-flight subtree audit keep
2625 // running, and keep its `Arc<P2PNode>`, past the point
2626 // `shutdown()` claims every engine task has stopped.
2627 let tracker = trigger.detached_task_tracker.clone();
2628 tracker.spawn(async move {
2629 // The jitter already elapsed as the reservation's
2630 // timer; the slot is held for the audit's duration
2631 // and released on drop (panic-safe).
2632 let inflight_slot = inflight_slot;
2633 let started = Instant::now();
2634 let credit = storage_commitment_audit::AuditCredit {
2635 recent_provers: &trigger.recent_provers,
2636 };
2637 let result = storage_commitment_audit::run_subtree_audit(
2638 &trigger.p2p_node,
2639 &trigger.config,
2640 &event.peer,
2641 event.pin,
2642 event.key_count,
2643 Some(&credit),
2644 )
2645 .await;
2646 let outcome = first_audit_terminal_outcome(&result);
2647 match outcome {
2648 FirstAuditTerminalOutcome::Passed => {
2649 audit_observability.passed.fetch_add(1, Ordering::Relaxed);
2650 }
2651 FirstAuditTerminalOutcome::Timeout => {
2652 audit_observability
2653 .timed_out
2654 .fetch_add(1, Ordering::Relaxed);
2655 }
2656 FirstAuditTerminalOutcome::Failed => {
2657 audit_observability.failed.fetch_add(1, Ordering::Relaxed);
2658 }
2659 FirstAuditTerminalOutcome::BootstrapClaim => {
2660 audit_observability
2661 .bootstrap_claims
2662 .fetch_add(1, Ordering::Relaxed);
2663 }
2664 FirstAuditTerminalOutcome::Idle => {
2665 audit_observability.idle.fetch_add(1, Ordering::Relaxed);
2666 }
2667 FirstAuditTerminalOutcome::InsufficientKeys => {
2668 audit_observability
2669 .insufficient_keys
2670 .fetch_add(1, Ordering::Relaxed);
2671 }
2672 }
2673 drop(inflight_slot);
2674 debug!(
2675 "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
2676 outcome.as_str(),
2677 event.peer, hex::encode(event.pin), event.key_count,
2678 started.elapsed().as_millis(),
2679 audit_observability.inflight.load(Ordering::Relaxed)
2680 );
2681 handle_subtree_audit_result(
2682 &result,
2683 &trigger.p2p_node,
2684 &trigger.sync_state,
2685 &trigger.recent_provers,
2686 &trigger.config,
2687 )
2688 .await;
2689 });
2690 }
2691 }
2692
2693 // 2) Open the single reservation from the pending queue if none
2694 // is outstanding (read-only cooldown snapshot; the
2695 // authoritative stamp is at promotion). Serializing
2696 // reservations preserves per-launch lane alternation and keeps
2697 // at most one jitter timer live.
2698 open_first_audit_reservation(
2699 &mut scheduler,
2700 &gossip_audit.cooldown,
2701 &observability,
2702 )
2703 .await;
2704
2705 if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
2706 // Token-independent hygiene: collect entries that aged past
2707 // the answerability horizon while the budget gate kept the
2708 // reserve scan from running, so the summary below reports
2709 // only live work.
2710 let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
2711 if swept > 0 {
2712 debug!(
2713 "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
2714 scheduler.pending_len()
2715 );
2716 }
2717 info!(
2718 "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={}",
2719 FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
2720 observability.received.load(Ordering::Relaxed),
2721 observability.queued.load(Ordering::Relaxed),
2722 observability.coalesced.load(Ordering::Relaxed),
2723 observability.suppressed_lower.load(Ordering::Relaxed),
2724 observability.duplicates.load(Ordering::Relaxed),
2725 observability.capacity_evicted.load(Ordering::Relaxed),
2726 observability.self_target_skipped.load(Ordering::Relaxed),
2727 observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
2728 observability.rate_deferred_attempts.load(Ordering::Relaxed),
2729 observability.window_deduped.load(Ordering::Relaxed),
2730 observability.launched.load(Ordering::Relaxed),
2731 observability.passed.load(Ordering::Relaxed),
2732 observability.timed_out.load(Ordering::Relaxed),
2733 observability.failed.load(Ordering::Relaxed),
2734 observability.bootstrap_claims.load(Ordering::Relaxed),
2735 observability.idle.load(Ordering::Relaxed),
2736 observability.insufficient_keys.load(Ordering::Relaxed),
2737 observability.outside_answerability_window.load(Ordering::Relaxed),
2738 scheduler.pending_len(),
2739 FIRST_AUDIT_PENDING_CAP,
2740 u8::from(scheduler.has_reservation()),
2741 scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
2742 observability.inflight.load(Ordering::Relaxed),
2743 scheduler.tokens(),
2744 );
2745 last_summary = Instant::now();
2746 }
2747 }
2748 debug!("First-audit drainer shut down");
2749 });
2750 self.task_handles.push(handle);
2751 }
2752
2753 #[allow(clippy::too_many_lines)]
2754 fn start_message_handler(&mut self) {
2755 let mut p2p_events = self.p2p_node.subscribe_events();
2756 let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
2757 let p2p = Arc::clone(&self.p2p_node);
2758 let storage = Arc::clone(&self.storage);
2759 let paid_list = Arc::clone(&self.paid_list);
2760 let payment_verifier = Arc::clone(&self.payment_verifier);
2761 let queues = Arc::clone(&self.queues);
2762 let config = Arc::clone(&self.config);
2763 let shutdown = self.shutdown.clone();
2764 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2765 let bootstrap_state = Arc::clone(&self.bootstrap_state);
2766 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
2767 let sync_history = Arc::clone(&self.sync_history);
2768 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2769 let repair_proofs = Arc::clone(&self.repair_proofs);
2770 let sync_trigger = Arc::clone(&self.sync_trigger);
2771 let my_commitment_state = Arc::clone(&self.commitment_state);
2772 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2773 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2774 let recent_provers = Arc::clone(&self.recent_provers);
2775 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
2776 let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
2777 let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
2778 let sync_state = Arc::clone(&self.sync_state);
2779 let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
2780 let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
2781 let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
2782 let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
2783 let fetch_responder_admission_semaphore =
2784 Arc::clone(&self.fetch_responder_admission_semaphore);
2785 let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
2786 let verification_responder_worker_semaphore =
2787 Arc::clone(&self.verification_responder_worker_semaphore);
2788 let verification_responder_admission_semaphore =
2789 Arc::clone(&self.verification_responder_admission_semaphore);
2790 let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
2791 let neighbor_sync_responder_worker_semaphore =
2792 Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
2793 let neighbor_sync_responder_admission_semaphore =
2794 Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
2795 let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
2796 let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
2797 let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
2798 let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
2799 let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
2800 let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
2801 let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
2802 let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
2803 let detached_task_tracker = self.detached_task_tracker.clone();
2804 let subtree_round1 = self.subtree_round1.clone();
2805
2806 // ADR-0002 gossip-audit trigger: bundled state so an ingested *changed*
2807 // commitment can spawn a probabilistic, cooldown-gated subtree audit.
2808 let gossip_audit = GossipAuditTrigger {
2809 p2p_node: Arc::clone(&p2p),
2810 config: Arc::clone(&config),
2811 recent_provers: Arc::clone(&recent_provers),
2812 sync_state: Arc::clone(&sync_state),
2813 cooldown: Arc::clone(&audit_on_gossip_cooldown),
2814 detached_task_tracker: detached_task_tracker.clone(),
2815 lottery_attempts: Arc::clone(&gossip_lottery_attempts),
2816 };
2817
2818 let handler_context = ReplicationMessageHandlerContext {
2819 p2p_node: Arc::clone(&p2p),
2820 storage,
2821 paid_list,
2822 payment_verifier,
2823 queues,
2824 config: Arc::clone(&config),
2825 is_bootstrapping,
2826 bootstrap_state,
2827 sync_history,
2828 sync_cycle_epoch,
2829 repair_proofs: Arc::clone(&repair_proofs),
2830 last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
2831 ever_capable_peers,
2832 sig_verify_attempts: Arc::clone(&sig_verify_attempts),
2833 my_commitment_state,
2834 gossip_audit,
2835 audit_responder_semaphore,
2836 audit_responder_inflight,
2837 audit_responder_metrics,
2838 subtree_round1,
2839 fetch_responder_worker_semaphore,
2840 fetch_responder_admission_semaphore,
2841 fetch_responder_inflight,
2842 verification_responder_worker_semaphore,
2843 verification_responder_admission_semaphore,
2844 verification_responder_inflight,
2845 neighbor_sync_responder_worker_semaphore,
2846 neighbor_sync_responder_admission_semaphore,
2847 neighbor_sync_responder_inflight,
2848 fresh_offer_worker_semaphore,
2849 fresh_offer_admission_semaphore,
2850 fresh_offer_responder_inflight,
2851 fresh_offer_in_flight,
2852 paid_notify_worker_semaphore,
2853 paid_notify_admission_semaphore,
2854 paid_notify_responder_inflight,
2855 shutdown: shutdown.clone(),
2856 detached_task_tracker,
2857 };
2858
2859 let (replication_tx, mut replication_rx) =
2860 mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
2861 let serial_context = handler_context.clone();
2862 let serial_shutdown = shutdown.clone();
2863 let serial_handle = tokio::spawn(async move {
2864 loop {
2865 tokio::select! {
2866 () = serial_shutdown.cancelled() => break,
2867 inbound = replication_rx.recv() => {
2868 let Some(inbound) = inbound else { break };
2869 let source = inbound.source;
2870 match handle_replication_message(
2871 &source,
2872 inbound.msg,
2873 &serial_context,
2874 inbound.received_at,
2875 inbound.rr_message_id.as_deref(),
2876 )
2877 .await
2878 {
2879 Ok(()) => {}
2880 Err(e) => {
2881 debug!("Replication message from {source} error: {e}");
2882 }
2883 }
2884 }
2885 }
2886 }
2887 debug!("Replication non-audit serial handler shut down");
2888 });
2889 self.task_handles.push(serial_handle);
2890
2891 let handle = tokio::spawn(async move {
2892 loop {
2893 tokio::select! {
2894 () = shutdown.cancelled() => break,
2895 event = p2p_events.recv() => {
2896 let event = match event {
2897 Ok(event) => event,
2898 Err(error) => match handle_replication_event_recv_error(&error) {
2899 ControlFlow::Continue(()) => continue,
2900 ControlFlow::Break(()) => break,
2901 },
2902 };
2903 let Some((source, payload, inbound_protocol, rr_message_id)) =
2904 replication_payload_from_event(event)
2905 else {
2906 continue;
2907 };
2908 let received_at = Instant::now();
2909 let msg = match ReplicationMessage::decode(&payload) {
2910 Ok(msg) => msg,
2911 Err(e) => {
2912 debug!("Replication message from {source} decode error: {e}");
2913 continue;
2914 }
2915 };
2916 if !body_matches_protocol(&msg.body, inbound_protocol) {
2917 debug!(
2918 "Dropping replication body (variant {}) on protocol \
2919 {inbound_protocol}: wrong id for its family \
2920 (cross-version or misrouted)",
2921 msg.body.variant_index()
2922 );
2923 continue;
2924 }
2925 if let Some(class) = audit_responder_class(&msg.body) {
2926 handler_context
2927 .audit_responder_metrics
2928 .record_received(source, class);
2929 }
2930 let inbound = InboundReplicationMessage {
2931 source,
2932 msg,
2933 rr_message_id,
2934 received_at,
2935 };
2936 if matches!(
2937 inbound.msg.body,
2938 ReplicationMessageBody::AuditChallenge(_)
2939 | ReplicationMessageBody::SubtreeAuditChallenge(_)
2940 | ReplicationMessageBody::SubtreeSliceChallenge(_)
2941 ) {
2942 let source = inbound.source;
2943 match handle_replication_message(
2944 &source,
2945 inbound.msg,
2946 &handler_context,
2947 inbound.received_at,
2948 inbound.rr_message_id.as_deref(),
2949 )
2950 .await
2951 {
2952 Ok(()) => {}
2953 Err(e) => {
2954 debug!("Replication message from {source} error: {e}");
2955 }
2956 }
2957 continue;
2958 }
2959 if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
2960 if dropped.audit_responder_class.is_some() {
2961 handler_context
2962 .audit_responder_metrics
2963 .record_serial_queue_drop(dropped.source);
2964 }
2965 // Every serial-lane class has protocol recovery: syncs rerun,
2966 // fetches retry, verification re-asks, and a dropped fresh
2967 // offer is refilled by neighbor sync (the possession check
2968 // penalises the absence but never re-offers). Responses are
2969 // covered by their requester's deadline/retry path. Never run
2970 // a bulk handler here: event receipt must remain non-blocking.
2971 warn!(
2972 message_class = dropped.message_class,
2973 source = %dropped.source,
2974 queue_depth = dropped.queue_depth,
2975 reason = dropped.reason.as_str(),
2976 "Replication serial-queue message dropped"
2977 );
2978 }
2979 }
2980 // Gap 4: Topology churn handling (Section 13).
2981 //
2982 // The DHT routing table emits KClosestPeersChanged when the
2983 // K-closest peer set actually changes, which is the precise
2984 // signal for triggering neighbor sync. This replaces the
2985 // previous approach of checking every PeerConnected /
2986 // PeerDisconnected event against the close group.
2987 dht_event = dht_events.recv() => {
2988 let dht_event = match dht_event {
2989 Ok(event) => event,
2990 Err(RecvError::Lagged(missed)) => {
2991 // Under heavy churn the broadcast buffer can overflow
2992 // and drop routing-table events — the moment
2993 // convergence matters most. A dropped
2994 // KClosestPeersChanged means its entrants were never
2995 // queued and its departures were never pruned, so
2996 // draining priority_order cannot recover either.
2997 // Resync from ground truth instead: snapshot the
2998 // current close-peer set, prune pending peers that
2999 // left it during the lost window (retain_sync_peers,
3000 // as the normal topology-change path does), and queue
3001 // every member. Dedup (queue_priority_peers) and
3002 // per-peer cooldown (select_next_sync_peer) drop peers
3003 // already queued or recently synced, so only genuine
3004 // entrants surface.
3005 warn!(
3006 "Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
3007 );
3008 let self_id = *p2p.peer_id();
3009 let neighbors = neighbor_sync::snapshot_close_neighbors(
3010 &p2p,
3011 &self_id,
3012 config.neighbor_sync_scope,
3013 )
3014 .await;
3015 let neighbor_set =
3016 neighbors.iter().copied().collect::<HashSet<_>>();
3017 let (requeued, sync_removals) = {
3018 let mut state = sync_state.write().await;
3019 let sync_removals =
3020 state.retain_sync_peers(&neighbor_set);
3021 let requeued = state.queue_priority_peers(neighbors);
3022 (requeued, sync_removals)
3023 };
3024 if sync_removals > 0 {
3025 debug!(
3026 "Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
3027 );
3028 }
3029 if requeued > 0 {
3030 debug!(
3031 "Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
3032 );
3033 sync_trigger.notify_one();
3034 }
3035 continue;
3036 }
3037 Err(RecvError::Closed) => {
3038 // A closed broadcast channel never yields again;
3039 // continuing would spin the select! loop forever.
3040 warn!(
3041 "DHT event stream closed on replication branch; stopping message handler"
3042 );
3043 break;
3044 }
3045 };
3046 match dht_event {
3047 DhtNetworkEvent::KClosestPeersChanged { old, new, .. } => {
3048 let old_peers = old
3049 .iter()
3050 .take(config.neighbor_sync_scope)
3051 .copied()
3052 .collect::<HashSet<_>>();
3053 let new_scoped = new
3054 .iter()
3055 .take(config.neighbor_sync_scope)
3056 .copied()
3057 .collect::<Vec<_>>();
3058 let new_peers =
3059 new_scoped.iter().copied().collect::<HashSet<_>>();
3060 let entrants = new_scoped
3061 .iter()
3062 .copied()
3063 .filter(|peer| !old_peers.contains(peer))
3064 .collect::<Vec<_>>();
3065 let entrant_count = entrants.len();
3066 let (priority_insertions, sync_removals) = {
3067 let mut state = sync_state.write().await;
3068 let sync_removals = state.retain_sync_peers(&new_peers);
3069 let priority_insertions = state.queue_priority_peers(entrants);
3070 (priority_insertions, sync_removals)
3071 };
3072 if priority_insertions > 0 {
3073 debug!(
3074 "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
3075 );
3076 } else {
3077 debug!(
3078 "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
3079 );
3080 }
3081 sync_trigger.notify_one();
3082 }
3083 DhtNetworkEvent::PeerRemoved { peer_id } => {
3084 sync_state.write().await.remove_peer(&peer_id);
3085 repair_proofs.write().await.remove_peer(&peer_id);
3086 update_bootstrap_after_peer_removed(
3087 &peer_id,
3088 &handler_context.bootstrap_state,
3089 &handler_context.queues,
3090 &handler_context.is_bootstrapping,
3091 &bootstrap_complete_notify,
3092 )
3093 .await;
3094 // v12: drop the commitment bytes and the
3095 // recent-prover credit so a churn / sybil
3096 // attacker cannot leave behind one
3097 // StorageCommitment per identity in
3098 // `last_commitment_by_peer`. Also drop the
3099 // sig-verify rate-limit timestamp.
3100 last_commitment_by_peer.write().await.remove(&peer_id);
3101 recent_provers.write().await.forget_peer(&peer_id);
3102 sig_verify_attempts.write().await.remove(&peer_id);
3103 // Same for the gossip-audit cooldown (ADR-0002)
3104 // and the lottery-attempt window.
3105 audit_on_gossip_cooldown.write().await.remove(&peer_id);
3106 gossip_lottery_attempts.write().await.remove(&peer_id);
3107 // The sticky `commitment_capable` flag is
3108 // preserved orthogonally via
3109 // `ever_capable_peers` — even after this
3110 // removal, a re-joining peer continues to
3111 // be treated as v12-capable rather than
3112 // legacy (§3 shield).
3113 }
3114 _ => {}
3115 }
3116 }
3117 }
3118 }
3119 debug!("Replication message handler shut down");
3120 });
3121 self.task_handles.push(handle);
3122 }
3123
3124 fn start_neighbor_sync_loop(&mut self) {
3125 let p2p = Arc::clone(&self.p2p_node);
3126 let storage = Arc::clone(&self.storage);
3127 let paid_list = Arc::clone(&self.paid_list);
3128 let queues = Arc::clone(&self.queues);
3129 let config = Arc::clone(&self.config);
3130 let shutdown = self.shutdown.clone();
3131 let sync_state = Arc::clone(&self.sync_state);
3132 let sync_history = Arc::clone(&self.sync_history);
3133 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3134 let repair_proofs = Arc::clone(&self.repair_proofs);
3135 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3136 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3137 let sync_trigger = Arc::clone(&self.sync_trigger);
3138 let commitment_state = Arc::clone(&self.commitment_state);
3139 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3140 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3141 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3142 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3143 let detached_task_tracker = self.detached_task_tracker.clone();
3144 // ADR-0002: a peer's commitment also arrives on the sync RESPONSE path
3145 // (we initiated, they piggybacked theirs). Carry a gossip-audit trigger
3146 // here too so a peer that only ever answers — never initiates sync —
3147 // is still audited; otherwise it could fully evade auditing.
3148 let gossip_audit = GossipAuditTrigger {
3149 p2p_node: Arc::clone(&p2p),
3150 config: Arc::clone(&config),
3151 recent_provers: Arc::clone(&self.recent_provers),
3152 sync_state: Arc::clone(&sync_state),
3153 cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
3154 detached_task_tracker,
3155 lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
3156 };
3157
3158 let handle = tokio::spawn(async move {
3159 loop {
3160 // Park for the periodic tick or an explicit trigger ONLY when no
3161 // priority (topology-change) peers are queued. `sync_trigger` is a
3162 // coalescing `Notify`, so a churn burst that queues many entrants
3163 // produces a single wakeup; parking after draining one batch would
3164 // leave the rest waiting up to a full periodic tick. `priority_order`
3165 // is the durable record of pending work, so drain it back-to-back —
3166 // each round removes the peers it selects (`select_next_sync_peer`),
3167 // so the drain terminates once the queue empties.
3168 if !sync_state.read().await.has_priority_peers() {
3169 let interval = config.random_neighbor_sync_interval();
3170 tokio::select! {
3171 () = shutdown.cancelled() => break,
3172 () = tokio::time::sleep(interval) => {}
3173 () = sync_trigger.notified() => {
3174 debug!("Neighbor sync triggered by topology change");
3175 }
3176 }
3177 }
3178 // Wrap the sync round in a select so shutdown cancels
3179 // in-progress network operations rather than waiting for
3180 // the full round to complete.
3181 tokio::select! {
3182 () = shutdown.cancelled() => break,
3183 () = run_neighbor_sync_round(
3184 &p2p,
3185 &storage,
3186 &paid_list,
3187 &queues,
3188 &config,
3189 &sync_state,
3190 &sync_history,
3191 &sync_cycle_epoch,
3192 &repair_proofs,
3193 &is_bootstrapping,
3194 &bootstrap_state,
3195 &commitment_state,
3196 &last_commitment_by_peer,
3197 &ever_capable_peers,
3198 &sig_verify_attempts,
3199 &audit_challenge_coordinator,
3200 &gossip_audit,
3201 ) => {}
3202 }
3203 }
3204 debug!("Neighbor sync loop shut down");
3205 });
3206 self.task_handles.push(handle);
3207 }
3208
3209 fn start_self_lookup_loop(&mut self) {
3210 let p2p = Arc::clone(&self.p2p_node);
3211 let config = Arc::clone(&self.config);
3212 let shutdown = self.shutdown.clone();
3213
3214 let handle = tokio::spawn(async move {
3215 loop {
3216 let interval = config.random_self_lookup_interval();
3217 tokio::select! {
3218 () = shutdown.cancelled() => break,
3219 () = tokio::time::sleep(interval) => {
3220 if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
3221 debug!("Self-lookup failed: {e}");
3222 }
3223 }
3224 }
3225 }
3226 debug!("Self-lookup loop shut down");
3227 });
3228 self.task_handles.push(handle);
3229 }
3230
3231 /// Periodic responsible-chunk audit loop (audit #2): every
3232 /// [`ReplicationConfig::random_audit_tick_interval`] (~10-20 min), audit one
3233 /// eligible close peer for the chunks it *should* be storing (by
3234 /// responsibility and prior repair hint), independent of the gossip-triggered
3235 /// storage-commitment audit. Waits for bootstrap to drain, then runs one tick
3236 /// immediately and periodically thereafter.
3237 fn start_audit_loop(&mut self) {
3238 let p2p = Arc::clone(&self.p2p_node);
3239 let storage = Arc::clone(&self.storage);
3240 let config = Arc::clone(&self.config);
3241 let shutdown = self.shutdown.clone();
3242 let sync_history = Arc::clone(&self.sync_history);
3243 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3244 let repair_proofs = Arc::clone(&self.repair_proofs);
3245 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3246 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3247 let sync_state = Arc::clone(&self.sync_state);
3248 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3249
3250 let handle = tokio::spawn(async move {
3251 // Invariant 19: wait for bootstrap to drain before starting audits.
3252 loop {
3253 tokio::select! {
3254 () = shutdown.cancelled() => return,
3255 () = tokio::time::sleep(
3256 std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
3257 ) => {
3258 if bootstrap_state.read().await.is_drained() {
3259 break;
3260 }
3261 }
3262 }
3263 }
3264
3265 // Run one audit tick immediately after bootstrap drain.
3266 {
3267 let bootstrapping = *is_bootstrapping.read().await;
3268 let result = {
3269 let history = sync_history.read().await;
3270 let current_sync_epoch = *sync_cycle_epoch.read().await;
3271 audit::audit_tick_with_repair_proofs(
3272 &p2p,
3273 &storage,
3274 &config,
3275 &history,
3276 &repair_proofs,
3277 &audit_challenge_coordinator,
3278 current_sync_epoch,
3279 bootstrapping,
3280 )
3281 .await
3282 };
3283 handle_audit_result(&result, &p2p, &sync_state, &config).await;
3284 }
3285
3286 // Then run periodically.
3287 loop {
3288 let interval = config.random_audit_tick_interval();
3289 tokio::select! {
3290 () = shutdown.cancelled() => break,
3291 () = tokio::time::sleep(interval) => {
3292 let bootstrapping = *is_bootstrapping.read().await;
3293 let result = {
3294 let history = sync_history.read().await;
3295 let current_sync_epoch = *sync_cycle_epoch.read().await;
3296 audit::audit_tick_with_repair_proofs(
3297 &p2p,
3298 &storage,
3299 &config,
3300 &history,
3301 &repair_proofs,
3302 &audit_challenge_coordinator,
3303 current_sync_epoch,
3304 bootstrapping,
3305 )
3306 .await
3307 };
3308 handle_audit_result(&result, &p2p, &sync_state, &config).await;
3309 }
3310 }
3311 }
3312 debug!("Audit loop shut down");
3313 });
3314 self.task_handles.push(handle);
3315 }
3316
3317 /// Periodically rebuild + sign + rotate the responder's storage
3318 /// commitment.
3319 ///
3320 /// Phase 3 of the v12 storage-bound audit. Once per
3321 /// [`COMMITMENT_ROTATION_INTERVAL_SECS`], the responder reads the
3322 /// current LMDB key set, builds a Merkle tree (for content-addressed
3323 /// chunks `bytes_hash == key`, so no chunk re-read is needed), signs
3324 /// the root with the node's `MlDsaSecretKey`, and rotates the result
3325 /// into `commitment_state`. Old `previous` slot is dropped by the
3326 /// rotate (per `ResponderCommitmentState::rotate`).
3327 ///
3328 /// Skips if the key set is empty (no commitment to make) — the
3329 /// auditor side falls back to the legacy plain-digest path for
3330 /// peers that have never gossiped a commitment.
3331 fn start_commitment_rotation_loop(&mut self) {
3332 let storage = Arc::clone(&self.storage);
3333 let identity = Arc::clone(&self.identity);
3334 let commitment_state = Arc::clone(&self.commitment_state);
3335 let shutdown = self.shutdown.clone();
3336 let p2p = Arc::clone(&self.p2p_node);
3337 let config = Arc::clone(&self.config);
3338 let sync_trigger = Arc::clone(&self.sync_trigger);
3339 let recent_provers = Arc::clone(&self.recent_provers);
3340
3341 let handle = tokio::spawn(async move {
3342 // Build the first commitment immediately on startup so a
3343 // restarted node can answer commitment-bound audits right
3344 // away — otherwise current() stays None for a full rotation
3345 // interval and audits silently fall back to legacy.
3346 //
3347 // After the first build, trigger an immediate neighbor-sync
3348 // round so the new commitment gossips out within seconds.
3349 // Without this, after a restart remote auditors keep pinning
3350 // the pre-restart (rotated-away) hash until their normal
3351 // sync cadence elapses — up to 1 h in the worst case,
3352 // during which time commitment-bound audits hit "unknown
3353 // commitment hash" -> Idle no-ops.
3354 // ML-DSA signatures are randomized so we cannot reproduce
3355 // the pre-restart hash; the only honest path to recovery
3356 // is fast re-gossip.
3357 // ADR-0004 A1: retention was reloaded in `new()` (before any task
3358 // spawned), so this initial rebuild no-ops when the key set is
3359 // unchanged — preserving the reloaded current pin; otherwise the
3360 // reloaded roots stay answerable as retained slots until their gossip
3361 // TTL lapses. Persistence is handled by the retention-persist loop.
3362 if let Err(e) =
3363 rebuild_and_rotate_commitment(&storage, &identity, &commitment_state, &p2p, &config)
3364 .await
3365 {
3366 warn!("Initial commitment build failed: {e}");
3367 } else {
3368 sync_trigger.notify_one();
3369 }
3370 loop {
3371 tokio::select! {
3372 () = shutdown.cancelled() => break,
3373 () = tokio::time::sleep(
3374 std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
3375 ) => {
3376 if let Err(e) = rebuild_and_rotate_commitment(
3377 &storage,
3378 &identity,
3379 &commitment_state,
3380 &p2p,
3381 &config,
3382 ).await {
3383 warn!("Commitment rotation failed: {e}");
3384 }
3385 // Piggyback a sweep of expired recent_provers
3386 // entries on the rotation tick (same cadence,
3387 // 1 h). is_credited_holder already honours the
3388 // TTL on read, but the sweep reclaims memory
3389 // for entries we'll never re-read.
3390 let dropped = recent_provers.write().await.sweep_expired(
3391 std::time::Instant::now()
3392 );
3393 if dropped > 0 {
3394 debug!("recent_provers: swept {dropped} expired entries");
3395 }
3396 }
3397 }
3398 }
3399 debug!("Commitment rotation loop shut down");
3400 });
3401 self.task_handles.push(handle);
3402 }
3403
3404 /// ADR-0004 A1: periodically flush the responder retention snapshot to disk
3405 /// (write-on-change) so answerability — including gossip-stamp refreshes and
3406 /// rotations — survives a restart. Flushes once immediately, then every
3407 /// `RETENTION_PERSIST_INTERVAL_SECS`, and once more on shutdown.
3408 fn start_retention_persist_loop(&mut self) {
3409 let commitment_state = Arc::clone(&self.commitment_state);
3410 let retention_path = self.retention_path.clone();
3411 let shutdown = self.shutdown.clone();
3412 let handle = tokio::spawn(async move {
3413 let mut last: Option<Vec<u8>> = None;
3414 persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
3415 loop {
3416 tokio::select! {
3417 () = shutdown.cancelled() => {
3418 persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3419 .await;
3420 break;
3421 }
3422 () = tokio::time::sleep(std::time::Duration::from_secs(
3423 RETENTION_PERSIST_INTERVAL_SECS,
3424 )) => {
3425 persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3426 .await;
3427 }
3428 }
3429 }
3430 debug!("Commitment retention persist loop shut down");
3431 });
3432 self.task_handles.push(handle);
3433 }
3434
3435 /// Periodically emit the cumulative replication traffic summaries: the
3436 /// per-variant line (V2-623) and the per-peer top-10 served-bytes line
3437 /// (V2-684). Both read process-global counter tables maintained by the
3438 /// encode/decode and serve choke points in [`protocol`]; needs no engine
3439 /// state.
3440 fn start_traffic_summary_loop(&mut self) {
3441 let shutdown = self.shutdown.clone();
3442 let handle = tokio::spawn(async move {
3443 loop {
3444 tokio::select! {
3445 () = shutdown.cancelled() => break,
3446 () = tokio::time::sleep(std::time::Duration::from_secs(
3447 TRAFFIC_SUMMARY_INTERVAL_SECS,
3448 )) => {
3449 protocol::log_traffic_summary();
3450 protocol::log_served_peers_summary();
3451 protocol::log_audit_outcome_summary();
3452 audit_metrics::log_responder_admission_summary();
3453 }
3454 }
3455 }
3456 debug!("Replication traffic summary loop shut down");
3457 });
3458 self.task_handles.push(handle);
3459 }
3460
3461 /// Periodically expose the state that gates bootstrap completion and prune
3462 /// admission. The state counts are copied before reading `is_bootstrapping`
3463 /// so this diagnostic path never nests async locks.
3464 #[cfg(feature = "logging")]
3465 fn start_bootstrap_state_snapshot_loop(&mut self) {
3466 let shutdown = self.shutdown.clone();
3467 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3468 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3469 let started_at = Instant::now();
3470 let handle = tokio::spawn(async move {
3471 loop {
3472 tokio::select! {
3473 () = shutdown.cancelled() => break,
3474 () = tokio::time::sleep(Duration::from_secs(
3475 BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS,
3476 )) => {
3477 let (
3478 drained,
3479 pending_peer_requests,
3480 pending_keys,
3481 capacity_rejected_sources,
3482 ) = {
3483 let state = bootstrap_state.read().await;
3484 (
3485 state.drained,
3486 state.pending_peer_requests,
3487 state.pending_keys.len(),
3488 state.capacity_rejected_sources.len(),
3489 )
3490 };
3491 let bootstrapping = *is_bootstrapping.read().await;
3492 let snapshot_state = if drained && !bootstrapping {
3493 "healthy"
3494 } else if drained {
3495 "drained_waiting_for_bootstrap_flag"
3496 } else {
3497 "pending"
3498 };
3499 info!(
3500 drained,
3501 pending_peer_requests,
3502 pending_keys,
3503 capacity_rejected_sources,
3504 is_bootstrapping = bootstrapping,
3505 snapshot_state,
3506 uptime_secs = started_at.elapsed().as_secs(),
3507 "Replication bootstrap state snapshot"
3508 );
3509 if drained && !bootstrapping {
3510 info!(
3511 "Replication bootstrap diagnostics reached healthy state; stopping periodic snapshots"
3512 );
3513 break;
3514 }
3515 }
3516 }
3517 }
3518 debug!("Bootstrap state snapshot loop shut down");
3519 });
3520 self.task_handles.push(handle);
3521 }
3522
3523 /// Periodically rank remote peers using the shared audit responder pool and
3524 /// report handler-only versus end-to-end latency. Windowed values make a
3525 /// burst visible even after a long-running node has accumulated traffic.
3526 #[cfg(feature = "logging")]
3527 fn start_audit_responder_summary_loop(&mut self) {
3528 let shutdown = self.shutdown.clone();
3529 let metrics = Arc::clone(&self.audit_responder_metrics);
3530 let semaphore = Arc::clone(&self.audit_responder_semaphore);
3531 let handle = tokio::spawn(async move {
3532 let mut window_started = Instant::now();
3533 loop {
3534 tokio::select! {
3535 () = shutdown.cancelled() => {
3536 log_audit_responder_summary(
3537 &metrics,
3538 &semaphore,
3539 window_started.elapsed(),
3540 );
3541 break;
3542 }
3543 () = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
3544 log_audit_responder_summary(
3545 &metrics,
3546 &semaphore,
3547 window_started.elapsed(),
3548 );
3549 window_started = Instant::now();
3550 }
3551 }
3552 }
3553 debug!("Audit responder summary loop shut down");
3554 });
3555 self.task_handles.push(handle);
3556 }
3557
3558 #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
3559 fn start_fetch_worker(&mut self) {
3560 let p2p = Arc::clone(&self.p2p_node);
3561 let storage = Arc::clone(&self.storage);
3562 let queues = Arc::clone(&self.queues);
3563 let config = Arc::clone(&self.config);
3564 let shutdown = self.shutdown.clone();
3565 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3566 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3567 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3568 let detached_task_tracker = self.detached_task_tracker.clone();
3569 let concurrency = max_parallel_fetch();
3570
3571 info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
3572
3573 let handle = tokio::spawn(async move {
3574 // Each in-flight future yields (key, Option<FetchOutcome>) so we
3575 // always recover the key — even if the inner task panics.
3576 let mut in_flight = FuturesUnordered::<FetchFuture>::new();
3577
3578 loop {
3579 // Fill up to `concurrency` slots from the queue.
3580 {
3581 let mut q = queues.write().await;
3582 while in_flight.len() < concurrency {
3583 let Some(candidate) = q.dequeue_fetch() else {
3584 break;
3585 };
3586 let fetch_key = candidate.key;
3587 let Some(&source) = candidate.sources.first() else {
3588 warn!(
3589 "Fetch candidate {} has no sources; requeueing for verification",
3590 hex::encode(fetch_key)
3591 );
3592 let _ = q.requeue_candidate_for_verification(
3593 candidate,
3594 config.verification_request_timeout,
3595 );
3596 continue;
3597 };
3598 q.start_dequeued_fetch(candidate, source);
3599
3600 let p2p = Arc::clone(&p2p);
3601 let storage = Arc::clone(&storage);
3602 let config = Arc::clone(&config);
3603 let token = shutdown.clone();
3604 let tracker = detached_task_tracker.clone();
3605 in_flight.push(Box::pin(async move {
3606 // Tracked so shutdown() still awaits the task if
3607 // this awaiter is dropped (e.g. the worker is
3608 // aborted): it holds Arc<LmdbStorage> and must
3609 // not outlive the engine.
3610 let handle = tracker.spawn(async move {
3611 // Cancel-aware: abort when the engine shuts down.
3612 tokio::select! {
3613 () = token.cancelled() => FetchOutcome {
3614 key: fetch_key,
3615 result: FetchResult::SourceFailed,
3616 },
3617 outcome = execute_single_fetch(
3618 p2p, storage, config, fetch_key, source,
3619 ) => outcome,
3620 }
3621 });
3622 match handle.await {
3623 Ok(outcome) => (outcome.key, Some(outcome)),
3624 Err(e) => {
3625 error!(
3626 "Fetch task for {} panicked: {e}",
3627 hex::encode(fetch_key)
3628 );
3629 (fetch_key, None)
3630 }
3631 }
3632 }));
3633 }
3634 } // release queues write lock
3635
3636 if in_flight.is_empty() {
3637 // No work — wait for new items or shutdown.
3638 tokio::select! {
3639 () = shutdown.cancelled() => break,
3640 () = tokio::time::sleep(
3641 std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
3642 ) => continue,
3643 }
3644 }
3645
3646 // Wait for the next fetch to complete and process the result.
3647 tokio::select! {
3648 () = shutdown.cancelled() => break,
3649 Some((key, maybe_outcome)) = in_flight.next() => {
3650 let mut q = queues.write().await;
3651 let terminal = if let Some(outcome) = maybe_outcome {
3652 match apply_fetch_result(
3653 &mut q,
3654 &key,
3655 &outcome.result,
3656 config.verification_request_timeout,
3657 ) {
3658 FetchFollowUp::Terminal => true,
3659 FetchFollowUp::RequeuedForVerification => false,
3660 FetchFollowUp::RetryFrom(next_peer) => {
3661 // Spawn a new fetch task for the next source.
3662 let p2p = Arc::clone(&p2p);
3663 let storage = Arc::clone(&storage);
3664 let config = Arc::clone(&config);
3665 let token = shutdown.clone();
3666 let tracker = detached_task_tracker.clone();
3667 let fetch_key = key;
3668 in_flight.push(Box::pin(async move {
3669 // Tracked for the same reason as the
3670 // initial fetch spawn above.
3671 let handle = tracker.spawn(async move {
3672 tokio::select! {
3673 () = token.cancelled() => FetchOutcome {
3674 key: fetch_key,
3675 result: FetchResult::SourceFailed,
3676 },
3677 outcome = execute_single_fetch(
3678 p2p, storage, config, fetch_key, next_peer,
3679 ) => outcome,
3680 }
3681 });
3682 match handle.await {
3683 Ok(outcome) => (outcome.key, Some(outcome)),
3684 Err(e) => {
3685 error!(
3686 "Fetch task for {} panicked: {e}",
3687 hex::encode(fetch_key)
3688 );
3689 (fetch_key, None)
3690 }
3691 }
3692 }));
3693 false
3694 }
3695 }
3696 } else {
3697 // Task panicked — retry verification when this was
3698 // a verified repair, otherwise reclaim the slot.
3699 !q.requeue_fetch_for_verification(
3700 &key,
3701 config.verification_request_timeout,
3702 )
3703 };
3704
3705 // Shrink bootstrap pending set on terminal exit.
3706 if terminal {
3707 drop(q); // release queues lock before acquiring bootstrap_state
3708 if !bootstrap_state.read().await.is_drained() {
3709 bootstrap_state.write().await.remove_key(&key);
3710 let q = queues.read().await;
3711 if bootstrap::check_bootstrap_drained(
3712 &bootstrap_state,
3713 &q,
3714 )
3715 .await
3716 {
3717 complete_bootstrap(
3718 &is_bootstrapping,
3719 &bootstrap_complete_notify,
3720 ).await;
3721 }
3722 }
3723 }
3724 }
3725 }
3726 }
3727
3728 // Cancel and drain remaining in-flight fetches on shutdown.
3729 // The CancellationToken is already cancelled by this point, so
3730 // spawned tasks will see cancellation via their select! branches.
3731 while in_flight.next().await.is_some() {}
3732 debug!("Fetch worker shut down");
3733 });
3734 self.task_handles.push(handle);
3735 }
3736
3737 fn start_verification_worker(&mut self) {
3738 let p2p = Arc::clone(&self.p2p_node);
3739 let storage = Arc::clone(&self.storage);
3740 let queues = Arc::clone(&self.queues);
3741 let paid_list = Arc::clone(&self.paid_list);
3742 let config = Arc::clone(&self.config);
3743 let shutdown = self.shutdown.clone();
3744 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3745 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3746 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3747 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3748 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3749 let recent_provers = Arc::clone(&self.recent_provers);
3750
3751 let handle = tokio::spawn(async move {
3752 loop {
3753 tokio::select! {
3754 () = shutdown.cancelled() => break,
3755 () = tokio::time::sleep(
3756 std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
3757 ) => {
3758 let ctx = VerificationCycleContext {
3759 p2p_node: &p2p,
3760 paid_list: &paid_list,
3761 storage: &storage,
3762 queues: &queues,
3763 config: &config,
3764 bootstrap_state: &bootstrap_state,
3765 is_bootstrapping: &is_bootstrapping,
3766 bootstrap_complete_notify: &bootstrap_complete_notify,
3767 last_commitment_by_peer: &last_commitment_by_peer,
3768 ever_capable_peers: &ever_capable_peers,
3769 recent_provers: &recent_provers,
3770 };
3771 run_verification_cycle(ctx).await;
3772 }
3773 }
3774 }
3775 debug!("Verification worker shut down");
3776 });
3777 self.task_handles.push(handle);
3778 }
3779
3780 /// Gap 3: Run a one-shot bootstrap sync on startup.
3781 ///
3782 /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
3783 /// (indicating the routing table is populated) before snapshotting
3784 /// close neighbors. Falls back after a timeout so bootstrap nodes
3785 /// (which have no peers and therefore never receive the event) still
3786 /// proceed.
3787 ///
3788 /// After the gate, finds close neighbors, syncs with each in
3789 /// round-robin batches, admits returned hints into the verification
3790 /// pipeline, and tracks discovered keys for bootstrap drain detection.
3791 #[allow(clippy::too_many_lines)]
3792 fn start_bootstrap_sync(
3793 &mut self,
3794 dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
3795 ) {
3796 let p2p = Arc::clone(&self.p2p_node);
3797 let storage = Arc::clone(&self.storage);
3798 let paid_list = Arc::clone(&self.paid_list);
3799 let queues = Arc::clone(&self.queues);
3800 let config = Arc::clone(&self.config);
3801 let shutdown = self.shutdown.clone();
3802 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3803 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3804 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3805 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3806 let repair_proofs = Arc::clone(&self.repair_proofs);
3807 let my_commitment_state = Arc::clone(&self.commitment_state);
3808 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3809 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3810 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3811
3812 let handle = tokio::spawn(async move {
3813 // Wait for DHT bootstrap to complete before snapshotting
3814 // neighbors. The routing table is empty until saorsa-core
3815 // finishes its FIND_NODE rounds and bucket refreshes.
3816 let gate = bootstrap::wait_for_bootstrap_complete(
3817 dht_events,
3818 config.bootstrap_complete_timeout_secs,
3819 &shutdown,
3820 )
3821 .await;
3822
3823 if gate == bootstrap::BootstrapGateResult::Shutdown {
3824 return;
3825 }
3826
3827 let self_id = *p2p.peer_id();
3828 let neighbors =
3829 neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
3830 .await;
3831
3832 if neighbors.is_empty() {
3833 info!("Bootstrap sync: no close neighbors found, marking drained");
3834 bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
3835 complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3836 return;
3837 }
3838
3839 let neighbor_count = neighbors.len();
3840 info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
3841
3842 // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
3843 for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
3844 if shutdown.is_cancelled() {
3845 break;
3846 }
3847
3848 let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
3849 batch,
3850 &storage,
3851 &paid_list,
3852 &p2p,
3853 config.close_group_size,
3854 config.paid_list_close_group_size,
3855 )
3856 .await;
3857
3858 // Keep the batch outstanding until every response has been
3859 // admitted and bootstrap accounting is updated. The verification
3860 // worker uses this counter as a batch barrier, so it cannot race
3861 // the source aggregation below.
3862 bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
3863 let bootstrapping = *is_bootstrapping.read().await;
3864
3865 let sync_futures = batch.iter().map(|peer| {
3866 let peer = *peer;
3867 let hints = hints_by_peer.remove(&peer).unwrap_or_default();
3868 // Atomically snapshot + mark-gossiped for each emitted
3869 // bootstrap request so we remain answerable for it.
3870 let commitment = my_commitment_state
3871 .current_for_gossip()
3872 .map(|binding| binding.commitment().clone());
3873 let p2p = &p2p;
3874 let config = &config;
3875 async move {
3876 let outcome = neighbor_sync::sync_with_peer_with_hints(
3877 &peer,
3878 p2p,
3879 config,
3880 bootstrapping,
3881 hints,
3882 commitment,
3883 )
3884 .await;
3885 (peer, outcome)
3886 }
3887 });
3888 let completed = join_all(sync_futures).await;
3889
3890 // Process response metadata before exposing any of this batch's
3891 // hints to verification.
3892 for (peer, outcome) in &completed {
3893 if let Some(outcome) = outcome {
3894 // Ingest the peer's piggybacked commitment from the
3895 // response (same verification as the request path).
3896 // Bootstrap is the FIRST gossip we receive from most
3897 // peers, so this populates last_commitment_by_peer.
3898 //
3899 // We intentionally do NOT trigger a gossip-audit here:
3900 // during bootstrap this node may itself still be
3901 // bootstrapping (audits are gated on that), and the
3902 // close-group/RT view is not yet stable. The peer is
3903 // audited on the first STEADY-STATE neighbor-sync round
3904 // after bootstrap drains (request + response paths both
3905 // trigger), which is within one sync cycle — so caching
3906 // the commitment here is sufficient and there is no
3907 // coverage gap (ADR-0002).
3908 ingest_peer_commitment(
3909 peer,
3910 outcome.response.commitment.as_ref(),
3911 &p2p,
3912 &last_commitment_by_peer,
3913 &ever_capable_peers,
3914 &sig_verify_attempts,
3915 )
3916 .await; // sig_verify_attempts in scope from line ~1080
3917
3918 if !outcome.response.bootstrapping {
3919 record_sent_replica_hints(
3920 peer,
3921 &outcome.sent_replica_hints,
3922 &repair_proofs,
3923 &sync_cycle_epoch,
3924 )
3925 .await;
3926 }
3927 }
3928 }
3929
3930 let pending_keys: HashSet<XorName> = {
3931 let q = queues.read().await;
3932 q.pending_keys().into_iter().collect()
3933 };
3934 let admission_futures = completed.iter().map(|(_, outcome)| async {
3935 match outcome {
3936 Some(outcome) if !outcome.response.bootstrapping => Some(
3937 admission::admit_hints(
3938 &self_id,
3939 &outcome.response.replica_hints,
3940 &outcome.response.paid_hints,
3941 &p2p,
3942 &config,
3943 &storage,
3944 &paid_list,
3945 &pending_keys,
3946 )
3947 .await,
3948 ),
3949 _ => None,
3950 }
3951 });
3952 let admitted = join_all(admission_futures).await;
3953
3954 // Queue every peer's admitted hints under one write lock. Once
3955 // released, source-count ordering sees the complete batch.
3956 let (batch_outcomes, batch_discovered) = {
3957 let mut q = queues.write().await;
3958 let outcomes = completed
3959 .iter()
3960 .zip(admitted)
3961 .filter_map(|((peer, _), admitted)| {
3962 admitted.map(|admitted| {
3963 (
3964 *peer,
3965 queue_admitted_hints(peer, admitted, &storage, &mut q),
3966 )
3967 })
3968 })
3969 .collect::<Vec<_>>();
3970 let live_discovered = outcomes
3971 .iter()
3972 .flat_map(|(_, outcome)| outcome.discovered.iter().copied())
3973 .filter(|key| q.contains_key(key))
3974 .collect::<HashSet<_>>();
3975 (outcomes, live_discovered)
3976 };
3977
3978 publish_bootstrap_admission_outcomes(
3979 &bootstrap_state,
3980 &batch_outcomes,
3981 &batch_discovered,
3982 )
3983 .await;
3984
3985 bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
3986 }
3987
3988 // Check drain condition.
3989 {
3990 let q = queues.read().await;
3991 if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
3992 complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3993 }
3994 }
3995
3996 info!("Bootstrap sync completed");
3997 });
3998 self.task_handles.push(handle);
3999 }
4000}
4001
4002// ===========================================================================
4003// Free functions for background tasks
4004// ===========================================================================
4005
4006#[cfg(feature = "logging")]
4007fn log_audit_responder_summary(
4008 metrics: &AuditResponderMetrics,
4009 semaphore: &Semaphore,
4010 window: Duration,
4011) {
4012 let snapshot = metrics.take_snapshot();
4013 if snapshot.origins.is_empty() {
4014 return;
4015 }
4016
4017 let total = snapshot.total;
4018 let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4019 total.received_by_class;
4020 let global_inflight =
4021 MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
4022 info!(
4023 target: "ant_node::replication::audit_responder",
4024 window_ms = window.as_millis(),
4025 source_count = snapshot.origins.len(),
4026 received = total.received(),
4027 digest_received,
4028 subtree_received,
4029 byte_received,
4030 commitment_pin_received,
4031 admitted = total.admitted,
4032 global_pool_drops = total.global_pool_drops,
4033 per_peer_cap_drops = total.per_peer_cap_drops,
4034 serial_queue_drops = total.serial_queue_drops,
4035 completed = total.completed,
4036 send_failures = total.send_failures,
4037 processing_avg_ms = total.processing_avg_ms(),
4038 processing_max_ms = total.processing_max_ms,
4039 total_avg_ms = total.total_avg_ms(),
4040 total_max_ms = total.total_max_ms,
4041 global_inflight,
4042 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4043 peak_global_inflight = total.peak_global_inflight,
4044 "Audit responder summary"
4045 );
4046
4047 for (index, origin) in snapshot
4048 .origins
4049 .iter()
4050 .take(config::AUDIT_RESPONDER_TOP_ORIGINS)
4051 .enumerate()
4052 {
4053 let Some(source) = origin.source else {
4054 continue;
4055 };
4056 let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4057 origin.received_by_class;
4058 info!(
4059 target: "ant_node::replication::audit_responder",
4060 rank = index + 1,
4061 source = %source,
4062 received = origin.received(),
4063 digest_received,
4064 subtree_received,
4065 byte_received,
4066 commitment_pin_received,
4067 admitted = origin.admitted,
4068 global_pool_drops = origin.global_pool_drops,
4069 per_peer_cap_drops = origin.per_peer_cap_drops,
4070 serial_queue_drops = origin.serial_queue_drops,
4071 completed = origin.completed,
4072 send_failures = origin.send_failures,
4073 processing_avg_ms = origin.processing_avg_ms(),
4074 processing_max_ms = origin.processing_max_ms,
4075 total_avg_ms = origin.total_avg_ms(),
4076 total_max_ms = origin.total_max_ms,
4077 peak_global_inflight = origin.peak_global_inflight,
4078 peak_peer_inflight = origin.peak_peer_inflight,
4079 "Audit responder top origin"
4080 );
4081 }
4082}
4083
4084/// Which ceiling rejected an audit-responder admission attempt.
4085///
4086/// Stable, machine-readable so a production log-scrape can bucket drops by
4087/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
4088/// single opaque "capacity reached" line; this splits the two distinct causes
4089/// so the next such investigation can tell a global-pool exhaustion (the whole
4090/// node is saturated) from a per-peer cap hit (one source is self-throttling)
4091/// without re-instrumenting.
4092///
4093/// This branch runs a SINGLE shared audit-responder pool for all challenge
4094/// kinds (responsible / subtree / byte), so there is no separate slow/fast
4095/// pool to distinguish here — the `kind=` log field already separates the
4096/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
4097/// dedicated slow pool is later split out, add its variants here.
4098#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4099enum ResponderRejectReason {
4100 /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
4101 /// free; the per-peer cap was not the binding constraint.
4102 GlobalPoolFull,
4103 /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
4104 /// share, so the global permit was never attempted.
4105 PerPeerCapFull,
4106}
4107
4108impl ResponderRejectReason {
4109 /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
4110 /// frozen — production log tooling greps for them.
4111 fn as_str(self) -> &'static str {
4112 match self {
4113 Self::GlobalPoolFull => "global_pool_full",
4114 Self::PerPeerCapFull => "per_peer_cap_full",
4115 }
4116 }
4117}
4118
4119impl From<ResponderRejectReason> for AuditResponderDropReason {
4120 fn from(reason: ResponderRejectReason) -> Self {
4121 match reason {
4122 ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
4123 ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
4124 }
4125 }
4126}
4127
4128impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
4129 fn from(reason: ResponderRejectReason) -> Self {
4130 match reason {
4131 ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
4132 ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
4133 }
4134 }
4135}
4136
4137/// Cumulative fresh-offer admission refusals in this process.
4138///
4139/// **Expected value in healthy operation is zero.** A node that refuses a
4140/// legitimate fresh offer does not merely shed load: the sender transmits
4141/// offers one-way and never reads the refusal, so the chunk's absence
4142/// resurfaces at the sender's delayed possession check and is charged to the
4143/// refusing node at audit severity (ADR-0003). Reaching this ceiling therefore
4144/// means the node is either under-provisioned for its offered load or its
4145/// admission share is mis-sized — and is accruing unearned trust damage either
4146/// way. Operators should alarm on any sustained non-zero rate.
4147///
4148/// Process-global rather than per-engine, which is exactly right in production
4149/// (one node per process) and adequate in multi-node test harnesses, where the
4150/// useful assertion is that *no* node in the fleet refused.
4151#[must_use]
4152pub fn fresh_offer_admission_refusals() -> u64 {
4153 audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
4154}
4155
4156/// Cumulative paid-list notification admission refusals in this process.
4157///
4158/// As with [`fresh_offer_admission_refusals`], zero is the expected value.
4159/// `PaidNotify` is one-way with no retry, so a refusal discards durable
4160/// paid-list evidence outright rather than pushing work back onto a requester.
4161#[must_use]
4162pub fn paid_notify_admission_refusals() -> u64 {
4163 audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
4164}
4165
4166/// Fresh-offer refusals caused by the class-wide pool being exhausted.
4167///
4168/// Split from [`fresh_offer_refusals_per_peer_share`] because the two indict
4169/// different things: this one says the node was saturated across all sources
4170/// and is genuinely under-provisioned for its offered load.
4171#[must_use]
4172pub fn fresh_offer_refusals_global_pool() -> u64 {
4173 audit_metrics::responder_admission_drops_by_ceiling(
4174 ReplicationResponderClass::FreshOffer,
4175 ResponderAdmissionCeiling::GlobalPool,
4176 )
4177}
4178
4179/// Fresh-offer refusals caused by one source exhausting its per-peer share.
4180///
4181/// For fresh offers this usually indicts the *share's size* rather than the
4182/// sender: the legitimate traffic pattern is bulk from a single peer — the one
4183/// node handling a client's PUT and fanning it out — so a share sized for
4184/// request/response traffic will refuse ordinary uploads.
4185#[must_use]
4186pub fn fresh_offer_refusals_per_peer_share() -> u64 {
4187 audit_metrics::responder_admission_drops_by_ceiling(
4188 ReplicationResponderClass::FreshOffer,
4189 ResponderAdmissionCeiling::PerPeerShare,
4190 )
4191}
4192
4193/// Why an audit-responder admission attempt failed, with the decision-time
4194/// capacity counters that let a drop be logged with full context.
4195///
4196/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
4197/// decision was made (the two ceilings are read under different locks, so they
4198/// are not a single atomic view), but they are exact enough to tell a saturated
4199/// node from a single self-throttling flooder.
4200#[derive(Debug, Clone, Copy)]
4201struct ResponderAdmissionFailure {
4202 reason: ResponderRejectReason,
4203 /// Global permits in use across the whole engine at decision time.
4204 global_inflight: usize,
4205 /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
4206 global_limit: usize,
4207 /// In-flight audit responders already held for `source` at decision time.
4208 peer_inflight: u32,
4209 /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
4210 peer_limit: u32,
4211}
4212
4213impl fmt::Display for ResponderAdmissionFailure {
4214 /// Renders the stable `reason=... global_inflight=... global_limit=...
4215 /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
4216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4217 write!(
4218 f,
4219 "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
4220 self.reason.as_str(),
4221 self.global_inflight,
4222 self.global_limit,
4223 self.peer_inflight,
4224 self.peer_limit,
4225 )
4226 }
4227}
4228
4229/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
4230/// on drop, decrements the PER-PEER in-flight count. Moving this into the
4231/// spawned task ties both bounds to the task's exact lifetime — no manual
4232/// decrement to forget on an early return or panic.
4233struct ResponderGuard {
4234 _permit: tokio::sync::OwnedSemaphorePermit,
4235 _peer_slot: PeerResponderSlot,
4236 global_inflight: usize,
4237 peer_inflight: u32,
4238}
4239
4240type AuditResponderGuard = ResponderGuard;
4241type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
4242
4243/// Provisional or admitted per-peer responder slot.
4244///
4245/// The slot is claimed before the global permit is attempted. Keeping that
4246/// claim under RAII means cancellation while rolling a failed admission back
4247/// cannot strand a peer at its cap. Once admission succeeds this guard moves
4248/// into [`ResponderGuard`] and remains held for the worker's exact lifetime.
4249struct PeerResponderSlot {
4250 inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4251 peer: PeerId,
4252}
4253
4254#[derive(Clone)]
4255struct ReplicationMessageHandlerContext {
4256 p2p_node: Arc<P2PNode>,
4257 storage: Arc<LmdbStorage>,
4258 paid_list: Arc<PaidList>,
4259 payment_verifier: Arc<PaymentVerifier>,
4260 queues: Arc<RwLock<ReplicationQueues>>,
4261 config: Arc<ReplicationConfig>,
4262 is_bootstrapping: Arc<RwLock<bool>>,
4263 bootstrap_state: Arc<RwLock<BootstrapState>>,
4264 sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4265 sync_cycle_epoch: Arc<RwLock<u64>>,
4266 repair_proofs: Arc<RwLock<RepairProofs>>,
4267 last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4268 ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
4269 sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
4270 my_commitment_state: Arc<ResponderCommitmentState>,
4271 gossip_audit: GossipAuditTrigger,
4272 audit_responder_semaphore: Arc<Semaphore>,
4273 audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4274 audit_responder_metrics: Arc<AuditResponderMetrics>,
4275 subtree_round1: SubtreeRound1Limiter,
4276 fetch_responder_worker_semaphore: Arc<Semaphore>,
4277 fetch_responder_admission_semaphore: Arc<Semaphore>,
4278 fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4279 verification_responder_worker_semaphore: Arc<Semaphore>,
4280 verification_responder_admission_semaphore: Arc<Semaphore>,
4281 verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4282 neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
4283 neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
4284 neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4285 fresh_offer_worker_semaphore: Arc<Semaphore>,
4286 fresh_offer_admission_semaphore: Arc<Semaphore>,
4287 fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4288 fresh_offer_in_flight: FreshOfferInFlight,
4289 paid_notify_worker_semaphore: Arc<Semaphore>,
4290 paid_notify_admission_semaphore: Arc<Semaphore>,
4291 paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4292 /// The engine's shutdown token, for detached responder work.
4293 ///
4294 /// Workers on [`Self::detached_task_tracker`] race this around their
4295 /// *network* phase only — never around an LMDB `spawn_blocking` await,
4296 /// where dropping the awaiter would detach a live transaction. This is
4297 /// what lets `shutdown()` keep its unbounded `tracker.wait()` and still
4298 /// terminate: the wait stays safe because it is now guaranteed finite.
4299 shutdown: CancellationToken,
4300 /// Shared tracker for detached work so `shutdown()` can await release of
4301 /// storage and P2P resources after all producer tasks have stopped.
4302 detached_task_tracker: TaskTracker,
4303}
4304
4305struct InboundReplicationMessage {
4306 source: PeerId,
4307 msg: ReplicationMessage,
4308 rr_message_id: Option<String>,
4309 received_at: Instant,
4310}
4311
4312#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4313enum SerialQueueDropReason {
4314 Full,
4315 Closed,
4316}
4317
4318#[cfg(feature = "logging")]
4319impl SerialQueueDropReason {
4320 const fn as_str(self) -> &'static str {
4321 match self {
4322 Self::Full => "full",
4323 Self::Closed => "closed",
4324 }
4325 }
4326}
4327
4328#[derive(Debug, Clone, Copy)]
4329#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
4330struct SerialQueueDrop {
4331 source: PeerId,
4332 message_class: &'static str,
4333 audit_responder_class: Option<AuditResponderClass>,
4334 queue_depth: usize,
4335 reason: SerialQueueDropReason,
4336}
4337
4338fn try_enqueue_serial_message(
4339 sender: &mpsc::Sender<InboundReplicationMessage>,
4340 inbound: InboundReplicationMessage,
4341) -> std::result::Result<(), SerialQueueDrop> {
4342 let source = inbound.source;
4343 let message_class = replication_message_class(&inbound.msg.body);
4344 let audit_responder_class = audit_responder_class(&inbound.msg.body);
4345 let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
4346 sender.try_send(inbound).map_err(|error| {
4347 let (reason, dropped) = match error {
4348 mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
4349 mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
4350 };
4351 audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
4352 SerialQueueDrop {
4353 source,
4354 message_class,
4355 audit_responder_class,
4356 queue_depth,
4357 reason,
4358 }
4359 })
4360}
4361
4362const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
4363 match body {
4364 ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
4365 ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
4366 ReplicationMessageBody::PaidNotify(_) => "paid_notify",
4367 ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
4368 ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
4369 ReplicationMessageBody::VerificationRequest(_) => "verification_request",
4370 ReplicationMessageBody::VerificationResponse(_) => "verification_response",
4371 ReplicationMessageBody::FetchRequest(_) => "fetch_request",
4372 ReplicationMessageBody::FetchResponse(_) => "fetch_response",
4373 ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
4374 ReplicationMessageBody::AuditResponse(_) => "audit_response",
4375 ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
4376 ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
4377 ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
4378 ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
4379 ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
4380 ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
4381 }
4382}
4383
4384const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
4385 match body {
4386 ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
4387 ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
4388 ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
4389 ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
4390 _ => None,
4391 }
4392}
4393
4394impl AuditResponderClass {
4395 const fn per_peer_limit(self) -> u32 {
4396 match self {
4397 Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
4398 Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
4399 }
4400 }
4401}
4402
4403fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
4404 match error {
4405 RecvError::Lagged(missed) => {
4406 audit_metrics::record_replication_event_lagged(*missed);
4407 warn!(
4408 "Missed {missed} P2P events on replication branch (broadcast lag); \
4409 replication messages may have been dropped before dispatch"
4410 );
4411 ControlFlow::Continue(())
4412 }
4413 RecvError::Closed => {
4414 // A closed broadcast channel never yields again, so the branch
4415 // would otherwise be immediately ready on every select! iteration.
4416 warn!("P2P event stream closed on replication branch; stopping message handler");
4417 ControlFlow::Break(())
4418 }
4419 }
4420}
4421
4422fn replication_payload_from_event(
4423 event: P2PEvent,
4424) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
4425 let P2PEvent::Message {
4426 topic,
4427 source: Some(source),
4428 data,
4429 ..
4430 } = event
4431 else {
4432 return None;
4433 };
4434
4435 let (matched_id, is_rr) = match_replication_protocol(&topic)?;
4436 if !is_rr {
4437 return Some((source, data, matched_id, None));
4438 }
4439 if is_rr {
4440 return P2PNode::parse_request_envelope(&data)
4441 .filter(|(_, is_resp, _)| !is_resp)
4442 .map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
4443 }
4444 None
4445}
4446
4447impl Drop for PeerResponderSlot {
4448 fn drop(&mut self) {
4449 // Decrement (and prune to keep the map bounded) without blocking the
4450 // async runtime: a short lock on a tiny map.
4451 //
4452 // Fast path: if the (uncontended, tiny) lock is free, decrement inline
4453 // with no spawn. Otherwise defer to a task — but only if a runtime is
4454 // actually current, so `Drop` during shutdown (no runtime) can never
4455 // panic. A missed decrement at shutdown is harmless: the whole map is
4456 // being dropped with the engine.
4457 let peer = self.peer;
4458 if let Ok(mut map) = self.inflight.try_write() {
4459 if let Some(n) = map.get_mut(&peer) {
4460 *n = n.saturating_sub(1);
4461 if *n == 0 {
4462 map.remove(&peer);
4463 }
4464 }
4465 return;
4466 }
4467 if let Ok(handle) = tokio::runtime::Handle::try_current() {
4468 let inflight = Arc::clone(&self.inflight);
4469 handle.spawn(async move {
4470 let mut map = inflight.write().await;
4471 if let Some(n) = map.get_mut(&peer) {
4472 *n = n.saturating_sub(1);
4473 if *n == 0 {
4474 map.remove(&peer);
4475 }
4476 }
4477 });
4478 }
4479 }
4480}
4481
4482/// Try to admit one bounded responder task for `source`: claim a per-peer slot
4483/// and then a global permit. The limits are parameters so independent responder
4484/// classes can reuse the same flood-fair admission and cancellation semantics.
4485async fn admit_bounded_responder(
4486 semaphore: &Arc<Semaphore>,
4487 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4488 source: &PeerId,
4489 global_limit: usize,
4490 peer_limit: u32,
4491) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
4492 let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
4493
4494 let admitted_peer_inflight = {
4495 let mut map = inflight.write().await;
4496 let entry = map.entry(*source).or_insert(0);
4497 if *entry >= peer_limit {
4498 let peer_inflight = *entry;
4499 drop(map);
4500 return Err(ResponderAdmissionFailure {
4501 reason: ResponderRejectReason::PerPeerCapFull,
4502 global_inflight: global_inflight(semaphore),
4503 global_limit,
4504 peer_inflight,
4505 peer_limit,
4506 });
4507 }
4508 *entry += 1;
4509 *entry
4510 };
4511
4512 let peer_slot = PeerResponderSlot {
4513 inflight: Arc::clone(inflight),
4514 peer: *source,
4515 };
4516 let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
4517 return Err(ResponderAdmissionFailure {
4518 reason: ResponderRejectReason::GlobalPoolFull,
4519 global_inflight: global_inflight(semaphore),
4520 global_limit,
4521 peer_inflight: admitted_peer_inflight.saturating_sub(1),
4522 peer_limit,
4523 });
4524 };
4525
4526 Ok(ResponderGuard {
4527 _permit: permit,
4528 _peer_slot: peer_slot,
4529 global_inflight: global_inflight(semaphore),
4530 peer_inflight: admitted_peer_inflight,
4531 })
4532}
4533
4534/// A live round-1 → round-2 subtree-audit session: proof of a matching round 1.
4535struct SubtreeSession {
4536 commitment_hash: [u8; 32],
4537 nonce: [u8; 32],
4538 inserted: Instant,
4539}
4540
4541/// Responder-wide token bucket over the chunk bytes round-1 proof building may
4542/// read and hash, refilled continuously at
4543/// [`SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC`] up to
4544/// [`SUBTREE_ROUND1_WORK_BURST_BYTES`].
4545///
4546/// Deliberately keyed by nothing. The per-peer cooldown limits how often one
4547/// identity may ask, so it is refilled by acquiring more identities; this is
4548/// charged for work done regardless of who asked, so it is not.
4549///
4550/// Charged after the fact, with the bytes the proof actually covered: the cost
4551/// of a request is not known until the pinned commitment has been resolved and
4552/// its subtree selected, both of which happen inside the handler. Admission
4553/// therefore asks only whether the balance is positive, and a proof that costs
4554/// more than is left drives the balance NEGATIVE rather than stopping at zero.
4555/// Carrying the debt is what makes the bound real: without it a maximal proof
4556/// would cost the same as a trivial one, since either way the next request only
4557/// has to wait for the balance to climb back above zero. With it, sustained
4558/// throughput settles at refill ÷ cost-per-proof, so expensive proofs are
4559/// admitted proportionally less often.
4560struct Round1WorkBudget {
4561 /// Signed, so an over-large proof leaves debt to work off.
4562 balance: i64,
4563 last_refill: Instant,
4564}
4565
4566impl Round1WorkBudget {
4567 /// Deepest debt carried, so one huge proof cannot lock out honest audits
4568 /// for longer than the burst takes to refill.
4569 const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
4570 /// Nanoseconds per second, for the sub-second part of a refill.
4571 const NANOS_PER_SEC: i64 = 1_000_000_000;
4572
4573 fn new() -> Self {
4574 Self {
4575 balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
4576 last_refill: Instant::now(),
4577 }
4578 }
4579
4580 /// Add the tokens accrued since the last touch, capped at the burst size.
4581 fn refill(&mut self, now: Instant) {
4582 let elapsed = now.saturating_duration_since(self.last_refill);
4583 self.last_refill = now;
4584 let whole_secs = i64::try_from(elapsed.as_secs())
4585 .unwrap_or(i64::MAX)
4586 .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
4587 let sub_sec = i64::from(elapsed.subsec_nanos())
4588 .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
4589 / Self::NANOS_PER_SEC;
4590 self.balance = self
4591 .balance
4592 .saturating_add(whole_secs.saturating_add(sub_sec))
4593 .min(SUBTREE_ROUND1_WORK_BURST_BYTES);
4594 }
4595
4596 /// Whether budget remains for a new round-1 proof.
4597 fn has_budget(&mut self, now: Instant) -> bool {
4598 self.refill(now);
4599 self.balance > 0
4600 }
4601
4602 /// Charge `bytes` of completed proof work, carrying debt down to
4603 /// [`Self::MAX_DEBT`].
4604 fn charge(&mut self, bytes: i64, now: Instant) {
4605 self.refill(now);
4606 self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
4607 }
4608}
4609
4610/// Resource controls for the HEAVY subtree-audit round 1: a tight
4611/// admission pool separate from the light responsible/slice audits, a per-peer
4612/// rate cooldown, and single-use round-1 → round-2 sessions so a round-2 slice
4613/// challenge is only served after a matching round 1.
4614///
4615/// It also holds the responder-wide [`Round1WorkBudget`], the only one of those
4616/// bounds not keyed by peer identity, and so the only one that bounds sustained
4617/// work rather than concurrency or per-identity frequency.
4618#[derive(Clone)]
4619struct SubtreeRound1Limiter {
4620 semaphore: Arc<Semaphore>,
4621 /// Global ceiling on concurrent round-1 proofs (config-driven;
4622 /// [`MAX_CONCURRENT_SUBTREE_ROUND1`] in production). Held alongside the
4623 /// semaphore because the per-peer admission helper needs the same number.
4624 max_concurrent: usize,
4625 inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4626 cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4627 /// Per-peer minimum spacing between served round-1 proofs (config-driven;
4628 /// [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`] in production, near-zero in tests).
4629 cooldown_interval: Duration,
4630 sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
4631 /// Identity-independent ceiling on sustained round-1 work.
4632 work: Arc<RwLock<Round1WorkBudget>>,
4633}
4634
4635impl SubtreeRound1Limiter {
4636 /// `max_concurrent` of 0 would wedge the responder into refusing every
4637 /// round-1 proof, which reads on the auditor side as a silent whole-fleet
4638 /// audit outage. Clamp to at least one so a mis-set config degrades to slow
4639 /// rather than to off.
4640 fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
4641 let max_concurrent = max_concurrent.max(1);
4642 Self {
4643 semaphore: Arc::new(Semaphore::new(max_concurrent)),
4644 max_concurrent,
4645 inflight: Arc::new(RwLock::new(HashMap::new())),
4646 cooldown: Arc::new(RwLock::new(HashMap::new())),
4647 cooldown_interval,
4648 sessions: Arc::new(RwLock::new(HashMap::new())),
4649 work: Arc::new(RwLock::new(Round1WorkBudget::new())),
4650 }
4651 }
4652
4653 /// Charge completed round-1 proof work against the responder-wide budget.
4654 async fn charge_work(&self, content_bytes: i64) {
4655 self.work
4656 .write()
4657 .await
4658 .charge(content_bytes, Instant::now());
4659 }
4660
4661 /// Admit one heavy round-1 proof for `source`: take a concurrency permit
4662 /// FIRST (so a full pool never wastes the peer's cooldown allowance), then
4663 /// the responder-wide work budget, then the per-peer rate cooldown. `None`
4664 /// drops the challenge (the remote auditor applies its own graced-timeout
4665 /// policy).
4666 async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
4667 let guard = admit_bounded_responder(
4668 &self.semaphore,
4669 &self.inflight,
4670 source,
4671 self.max_concurrent,
4672 MAX_SUBTREE_ROUND1_PER_PEER,
4673 )
4674 .await
4675 .ok()?;
4676 // Checked before the per-peer cooldown is stamped, so a peer refused for
4677 // want of budget is not also charged its next allowance.
4678 if !self.work.write().await.has_budget(Instant::now()) {
4679 return None; // guard drops here, releasing the permit + slot
4680 }
4681 let now = Instant::now();
4682 let mut cooldown = self.cooldown.write().await;
4683 if let Some(&last) = cooldown.get(source) {
4684 if now.duration_since(last) < self.cooldown_interval {
4685 return None; // guard drops here, releasing the permit + slot
4686 }
4687 }
4688 // Evict lapsed entries (their cooldown has expired, so they no longer
4689 // limit) and cap capacity, so peer-id churn can't grow this map unbounded.
4690 cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
4691 if cooldown.len() >= MAX_SUBTREE_SESSIONS {
4692 if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
4693 cooldown.remove(&oldest);
4694 }
4695 }
4696 cooldown.insert(*source, now);
4697 Some(guard)
4698 }
4699
4700 /// Record a single-use session once a round-1 proof is built and about to be
4701 /// sent, so the matching round 2 is admitted exactly once.
4702 async fn open_session(
4703 &self,
4704 source: PeerId,
4705 challenge_id: u64,
4706 commitment_hash: [u8; 32],
4707 nonce: [u8; 32],
4708 ) {
4709 let now = Instant::now();
4710 let mut sessions = self.sessions.write().await;
4711 sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
4712 if sessions.len() >= MAX_SUBTREE_SESSIONS {
4713 if let Some(oldest) = sessions
4714 .iter()
4715 .min_by_key(|(_, e)| e.inserted)
4716 .map(|(k, _)| *k)
4717 {
4718 sessions.remove(&oldest);
4719 }
4720 }
4721 sessions.insert(
4722 (source, challenge_id),
4723 SubtreeSession {
4724 commitment_hash,
4725 nonce,
4726 inserted: now,
4727 },
4728 );
4729 }
4730
4731 /// Atomically consume the round-2 session for this exchange. `true` iff a
4732 /// live session matching `(source, challenge_id, commitment_hash, nonce)`
4733 /// existed (and is now removed); a miss silently drops round 2 to the graced
4734 /// timeout lane (sessions are ephemeral and can be lost across a restart).
4735 async fn consume_session(
4736 &self,
4737 source: &PeerId,
4738 challenge_id: u64,
4739 commitment_hash: &[u8; 32],
4740 nonce: &[u8; 32],
4741 ) -> bool {
4742 let mut sessions = self.sessions.write().await;
4743 let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
4744 Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
4745 && &e.commitment_hash == commitment_hash
4746 && &e.nonce == nonce
4747 });
4748 if matches {
4749 sessions.remove(&(*source, challenge_id));
4750 }
4751 matches
4752 }
4753}
4754
4755/// Outcome of admitting a round-2 slice challenge.
4756enum SliceAdmission {
4757 /// Admitted: the guard holds the global permit and the per-peer slot, and
4758 /// the single-use round-1 session has been consumed.
4759 Admitted(AuditResponderGuard),
4760 /// Refused at a responder ceiling. The round-1 session is left INTACT.
4761 Capacity(AuditResponderAdmissionFailure),
4762 /// No live round-1 session matched this challenge.
4763 NoSession,
4764}
4765
4766/// Admit a round-2 slice challenge: take the responder permit BEFORE consuming
4767/// the single-use round-1 session.
4768///
4769/// The order is the point: a single-use token must not be spent on work that is
4770/// then refused. Consuming first and testing admission second leaves the session
4771/// destroyed by a purely local capacity drop, so the refusal is not recoverable
4772/// even in principle.
4773///
4774/// Scope of the benefit today, stated honestly: `request_slice_proof` issues one
4775/// `send_request` and maps any failure straight to `SliceRound::Timeout`, so the
4776/// auditor does not currently re-send round 2 within an audit. The preserved
4777/// session is therefore not yet *recovering* an audit — it keeps a refusal
4778/// truthful (temporary means temporary) and keeps the invariant available for a
4779/// retry, rather than baking "capacity drop is permanent" into the state
4780/// machine. If an application-level retry is ruled out for good, this ordering
4781/// still costs nothing over the alternative.
4782///
4783/// Cost of the ordering: the permit and per-peer slot are held across the
4784/// session probe, which is one in-memory map lookup and no chunk work. The
4785/// per-peer cap still bounds a peer sending unsessioned challenges to the same
4786/// share it could already occupy with well-formed ones, so the admission
4787/// surface is unchanged.
4788async fn admit_slice_challenge(
4789 semaphore: &Arc<Semaphore>,
4790 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4791 round1: &SubtreeRound1Limiter,
4792 source: &PeerId,
4793 challenge: &protocol::SubtreeSliceChallenge,
4794) -> SliceAdmission {
4795 let guard =
4796 match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
4797 Ok(guard) => guard,
4798 Err(failure) => return SliceAdmission::Capacity(failure),
4799 };
4800 if !round1
4801 .consume_session(
4802 source,
4803 challenge.challenge_id,
4804 &challenge.expected_commitment_hash,
4805 &challenge.nonce,
4806 )
4807 .await
4808 {
4809 // Release the permit and per-peer slot before the caller replies: no
4810 // chunk work follows, so holding them would shrink the pool for nothing.
4811 drop(guard);
4812 return SliceAdmission::NoSession;
4813 }
4814 SliceAdmission::Admitted(guard)
4815}
4816
4817/// Try to admit one audit-responder task for `source`: take a global permit AND
4818/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
4819/// its decision-time counters (caller drops the challenge, leaving the remote
4820/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
4821/// so one flooder can neither exhaust the global pool's effect on others nor
4822/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
4823/// log exactly WHY the drop happened rather than a single opaque "capacity
4824/// reached".
4825async fn admit_audit_responder(
4826 semaphore: &Arc<Semaphore>,
4827 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4828 source: &PeerId,
4829 class: AuditResponderClass,
4830) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
4831 let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
4832 let peer_limit = class.per_peer_limit();
4833 admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
4834}
4835
4836/// Handle an incoming replication protocol message.
4837///
4838/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
4839/// request-response path and the response must be sent via `send_response`
4840/// so saorsa-core can route it back to the waiting `send_request` caller.
4841#[allow(clippy::too_many_lines)]
4842async fn handle_replication_message(
4843 source: &PeerId,
4844 msg: ReplicationMessage,
4845 ctx: &ReplicationMessageHandlerContext,
4846 received_at: Instant,
4847 rr_message_id: Option<&str>,
4848) -> Result<()> {
4849 match msg.body {
4850 ReplicationMessageBody::FreshReplicationOffer(offer) => {
4851 dispatch_fresh_offer(
4852 *source,
4853 offer,
4854 ctx,
4855 msg.request_id,
4856 received_at,
4857 rr_message_id,
4858 )
4859 .await
4860 }
4861 ReplicationMessageBody::PaidNotify(notify) => {
4862 dispatch_paid_notify(*source, notify, ctx, received_at).await
4863 }
4864 ReplicationMessageBody::NeighborSyncRequest(request) => {
4865 let bootstrapping = *ctx.is_bootstrapping.read().await;
4866 // Phase-3 storage-bound audit: store the sender's
4867 // commitment for use as `expected_commitment_hash` in
4868 // future audits. Verify signature before storing so a peer
4869 // cannot inject a forged commitment for someone else.
4870 if let Some(target) = ingest_peer_commitment(
4871 source,
4872 request.commitment.as_ref(),
4873 &ctx.p2p_node,
4874 &ctx.last_commitment_by_peer,
4875 &ctx.ever_capable_peers,
4876 &ctx.sig_verify_attempts,
4877 )
4878 .await
4879 {
4880 maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
4881 }
4882 dispatch_neighbor_sync_request(
4883 *source,
4884 request,
4885 ctx,
4886 bootstrapping,
4887 // Atomically snapshot + mark-gossiped: emitted in the sync
4888 // response, so we must stay answerable for it (ADR-0002).
4889 ctx.my_commitment_state
4890 .current_for_gossip()
4891 .map(|b| b.commitment().clone()),
4892 msg.request_id,
4893 received_at,
4894 rr_message_id,
4895 )
4896 .await
4897 }
4898 ReplicationMessageBody::VerificationRequest(request) => {
4899 dispatch_verification_request(
4900 *source,
4901 request,
4902 ctx,
4903 msg.request_id,
4904 received_at,
4905 rr_message_id,
4906 )
4907 .await
4908 }
4909 ReplicationMessageBody::FetchRequest(request) => {
4910 dispatch_fetch_request(
4911 *source,
4912 request,
4913 ctx,
4914 msg.request_id,
4915 received_at,
4916 rr_message_id,
4917 )
4918 .await
4919 }
4920 ReplicationMessageBody::AuditChallenge(challenge) => {
4921 // Responsible-chunk audit (audit #2) responder: answer with per-key
4922 // possession digests. This same handler also answers the
4923 // prune-confirmation audit, which sends the same `AuditChallenge`
4924 // wire message.
4925 //
4926 // Answering digests the stored bytes of every challenged key, so —
4927 // like the subtree/byte audits below — run it on a detached task off
4928 // this serial message loop. Handling it inline lets one challenge
4929 // block all other replication traffic until its digests complete
4930 // (head-of-line blocking). The same flood-fair admission applies: a
4931 // global ceiling AND a per-peer cap, dropping the challenge if either
4932 // is hit. A dropped challenge reads as a penalised timeout to the
4933 // auditor, so the caps must remain high enough for honest audit load;
4934 // the per-peer share still prevents one flooder from starving others.
4935 let class = AuditResponderClass::Digest;
4936 let guard = match admit_audit_responder(
4937 &ctx.audit_responder_semaphore,
4938 &ctx.audit_responder_inflight,
4939 source,
4940 class,
4941 )
4942 .await
4943 {
4944 Ok(guard) => guard,
4945 Err(failure) => {
4946 protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
4947 audit_metrics::record_admission_drop(class);
4948 ctx.audit_responder_metrics
4949 .record_drop(*source, failure.reason.into());
4950 warn!(
4951 target: "ant_node::replication::audit_responder",
4952 event = "admission_dropped",
4953 kind = "responsible",
4954 responder_class = class.as_str(),
4955 source = %source,
4956 challenge_id = challenge.challenge_id,
4957 key_count = challenge.keys.len(),
4958 request_response = rr_message_id.is_some(),
4959 dispatch_ms = received_at.elapsed().as_millis(),
4960 reason = failure.reason.as_str(),
4961 global_inflight = failure.global_inflight,
4962 global_limit = failure.global_limit,
4963 peer_inflight = failure.peer_inflight,
4964 peer_limit = failure.peer_limit,
4965 "Audit responder admission dropped"
4966 );
4967 return Ok(());
4968 }
4969 };
4970 let admission_global_inflight = guard.global_inflight;
4971 let admission_peer_inflight = guard.peer_inflight;
4972 ctx.audit_responder_metrics.record_admitted(
4973 *source,
4974 admission_global_inflight,
4975 admission_peer_inflight,
4976 );
4977 info!(
4978 target: "ant_node::replication::audit_responder",
4979 event = "admitted",
4980 kind = "responsible",
4981 responder_class = class.as_str(),
4982 source = %source,
4983 challenge_id = challenge.challenge_id,
4984 key_count = challenge.keys.len(),
4985 request_response = rr_message_id.is_some(),
4986 dispatch_ms = received_at.elapsed().as_millis(),
4987 global_inflight = admission_global_inflight,
4988 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4989 peer_inflight = admission_peer_inflight,
4990 peer_limit = class.per_peer_limit(),
4991 "Audit responder request admitted"
4992 );
4993 let bootstrapping = *ctx.is_bootstrapping.read().await;
4994 let dispatch_latency = received_at.elapsed();
4995 audit_metrics::record_digest_dispatch_latency(dispatch_latency);
4996 debug!(
4997 audit_type = "digest_responder",
4998 dispatch_latency_ms = dispatch_latency.as_millis(),
4999 source = %source,
5000 "Audit challenge dispatch latency measured"
5001 );
5002 let storage = Arc::clone(&ctx.storage);
5003 let p2p_node = Arc::clone(&ctx.p2p_node);
5004 let source = *source;
5005 let request_id = msg.request_id;
5006 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5007 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5008 ctx.detached_task_tracker.spawn(async move {
5009 let _guard = guard; // global permit + per-peer slot, held until done
5010 let worker_started = Instant::now();
5011 match handle_audit_challenge_msg(
5012 &source,
5013 &challenge,
5014 &storage,
5015 &p2p_node,
5016 bootstrapping,
5017 ReplyRoute {
5018 request_id,
5019 rr_message_id: rr_message_id.as_deref(),
5020 protocol: REPLICATION_PROTOCOL_ID,
5021 },
5022 )
5023 .await
5024 {
5025 Ok(completion) => log_audit_responder_completion(
5026 &responder_metrics,
5027 source,
5028 class,
5029 "responsible",
5030 challenge.challenge_id,
5031 challenge.keys.len(),
5032 completion.response_kind,
5033 completion.sent,
5034 received_at,
5035 worker_started,
5036 completion.processing,
5037 completion.response_send,
5038 ),
5039 Err(e) => debug!("Audit challenge from {source} error: {e}"),
5040 }
5041 });
5042 Ok(())
5043 }
5044 ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
5045 // Gossip-triggered storage-bound subtree audit (ADR-0002). The
5046 // responder rebuilds the WHOLE nonce-selected subtree, reading every
5047 // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
5048 // detached task so this serial message loop is never blocked on disk
5049 // I/O — otherwise one audit stalls all replication traffic (§5).
5050 //
5051 // A bounded, flood-fair admission restores backpressure (codex#1 +
5052 // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
5053 // we drop this challenge. Subtree auditors grace timeout
5054 // non-responses, so capacity drops throttle flooders without turning
5055 // into trust penalties (and one source cannot starve other peers,
5056 // since its share is capped per-peer).
5057 let class = AuditResponderClass::Subtree;
5058 info!(
5059 "Audit challenge received: kind=subtree source={source} request_response={}",
5060 rr_message_id.is_some(),
5061 );
5062 // Round 1 is the HEAVY path (rebuilds + hashes the whole sqrt-subtree),
5063 // so it uses its own tight admission pool + per-peer rate cooldown,
5064 // separate from the light responsible/slice audits, and a miss silently
5065 // drops (subtree auditors grace timeouts).
5066 let Some(guard) = ctx.subtree_round1.admit(source).await else {
5067 protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5068 warn!(
5069 target: "ant_node::replication::audit_responder",
5070 event = "admission_dropped",
5071 kind = "subtree",
5072 responder_class = class.as_str(),
5073 source = %source,
5074 challenge_id = challenge.challenge_id,
5075 request_response = rr_message_id.is_some(),
5076 dispatch_ms = received_at.elapsed().as_millis(),
5077 reason = "heavy_pool_cooldown_or_work_budget",
5078 "Audit responder admission dropped"
5079 );
5080 return Ok(());
5081 };
5082 let admission_global_inflight = guard.global_inflight;
5083 let admission_peer_inflight = guard.peer_inflight;
5084 ctx.audit_responder_metrics.record_admitted(
5085 *source,
5086 admission_global_inflight,
5087 admission_peer_inflight,
5088 );
5089 info!(
5090 target: "ant_node::replication::audit_responder",
5091 event = "admitted",
5092 kind = "subtree",
5093 responder_class = class.as_str(),
5094 source = %source,
5095 challenge_id = challenge.challenge_id,
5096 request_response = rr_message_id.is_some(),
5097 dispatch_ms = received_at.elapsed().as_millis(),
5098 global_inflight = admission_global_inflight,
5099 global_limit = ctx.subtree_round1.max_concurrent,
5100 peer_inflight = admission_peer_inflight,
5101 peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
5102 "Audit responder request admitted"
5103 );
5104 let bootstrapping = *ctx.is_bootstrapping.read().await;
5105 let storage = Arc::clone(&ctx.storage);
5106 let p2p_node = Arc::clone(&ctx.p2p_node);
5107 let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5108 let source = *source;
5109 let request_id = msg.request_id;
5110 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5111 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5112 let subtree_round1 = ctx.subtree_round1.clone();
5113 ctx.detached_task_tracker.spawn(async move {
5114 let _guard = guard; // global permit + per-peer slot, held until done
5115 let worker_started = Instant::now();
5116 let processing_started = Instant::now();
5117 let storage_commitment_audit::Round1Work {
5118 response,
5119 content_bytes,
5120 } = storage_commitment_audit::handle_subtree_challenge_measured(
5121 &challenge,
5122 &storage,
5123 p2p_node.peer_id(),
5124 bootstrapping,
5125 Some(&my_commitment_state),
5126 )
5127 .await;
5128 let processing = processing_started.elapsed();
5129 // Charge the work actually done, on EVERY outcome.
5130 //
5131 // This used to charge only the `Proof` arm, reasoning that the
5132 // rejecting paths either read nothing or reflected this node's
5133 // own broken storage. The second half of that was wrong: a
5134 // retained commitment containing one unreadable key still costs
5135 // a full run of reads and keyed-BLAKE3 passes over every leaf
5136 // before it, and then rejects. An attacker who finds such a
5137 // commitment could replay subtrees over it indefinitely for
5138 // free. The per-peer cooldown does not catch that either, since
5139 // it is escapable by rotating identity — the responder-wide
5140 // budget is the only bound that applies, so it has to see the
5141 // work. A zero charge is a no-op, so the untouched paths are
5142 // unaffected.
5143 subtree_round1.charge_work(content_bytes).await;
5144 // A round-1 proof authorizes exactly one matching round 2: open a
5145 // single-use session so a slice challenge cannot be served without
5146 // a live round-1 exchange.
5147 if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
5148 {
5149 subtree_round1
5150 .open_session(
5151 source,
5152 challenge.challenge_id,
5153 challenge.expected_commitment_hash,
5154 challenge.nonce,
5155 )
5156 .await;
5157 }
5158 let response_kind = subtree_audit_response_kind(&response);
5159 let work_items = subtree_audit_response_work_items(&response);
5160 let response_send_started = Instant::now();
5161 let sent = send_replication_response_checked(
5162 &source,
5163 &p2p_node,
5164 request_id,
5165 ReplicationMessageBody::SubtreeAuditResponse(response),
5166 rr_message_id.as_deref(),
5167 None,
5168 )
5169 .await;
5170 let response_send = response_send_started.elapsed();
5171 log_audit_responder_completion(
5172 &responder_metrics,
5173 source,
5174 class,
5175 "subtree",
5176 challenge.challenge_id,
5177 work_items,
5178 response_kind,
5179 sent,
5180 received_at,
5181 worker_started,
5182 processing,
5183 response_send,
5184 );
5185 });
5186 Ok(())
5187 }
5188 ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
5189 // Round 2 of the storage audit (ADR-0002 / V2-685): open one 1 KiB
5190 // block of each auditor-selected spot-check key with a Bao verified
5191 // slice + nonced block-tree opening. Reads chunk bytes from disk to
5192 // build the proofs, so it runs off the serial loop under the light
5193 // audit pool's global and per-peer ceilings.
5194 let class = AuditResponderClass::Byte;
5195 info!(
5196 "Audit challenge received: kind=slice source={source} request_response={}",
5197 rr_message_id.is_some(),
5198 );
5199 let guard = match admit_slice_challenge(
5200 &ctx.audit_responder_semaphore,
5201 &ctx.audit_responder_inflight,
5202 &ctx.subtree_round1,
5203 source,
5204 &challenge,
5205 )
5206 .await
5207 {
5208 SliceAdmission::Admitted(guard) => guard,
5209 SliceAdmission::Capacity(failure) => {
5210 protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5211 audit_metrics::record_admission_drop(class);
5212 ctx.audit_responder_metrics
5213 .record_drop(*source, failure.reason.into());
5214 warn!(
5215 target: "ant_node::replication::audit_responder",
5216 event = "admission_dropped",
5217 kind = "byte",
5218 responder_class = class.as_str(),
5219 source = %source,
5220 challenge_id = challenge.challenge_id,
5221 key_count = challenge.openings.len(),
5222 request_response = rr_message_id.is_some(),
5223 dispatch_ms = received_at.elapsed().as_millis(),
5224 reason = failure.reason.as_str(),
5225 global_inflight = failure.global_inflight,
5226 global_limit = failure.global_limit,
5227 peer_inflight = failure.peer_inflight,
5228 peer_limit = failure.peer_limit,
5229 "Audit responder admission dropped"
5230 );
5231 return Ok(());
5232 }
5233 // No live round-1 session: reply with a cheap `Transient` rejection
5234 // rather than dropping silently. Sessions are ephemeral (an honest
5235 // responder that restarts between rounds loses its session), and an
5236 // unanswered `send_request` would make saorsa-core record a
5237 // transport trust failure against that honest responder — an
5238 // ongoing effect, not just a rollout-window one. A `Transient`
5239 // reply routes the auditor to the graced timeout lane (no trust
5240 // penalty; the responder re-earns pinned credit on the next audit)
5241 // and does no chunk work, so it is not a DoS lever.
5242 SliceAdmission::NoSession => {
5243 protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5244 debug!(
5245 "Slice challenge without a live round-1 session source={source} \
5246 challenge_id={} → Transient reject",
5247 challenge.challenge_id
5248 );
5249 send_replication_response_checked(
5250 source,
5251 &ctx.p2p_node,
5252 msg.request_id,
5253 ReplicationMessageBody::SubtreeSliceResponse(
5254 protocol::SubtreeSliceResponse::Rejected {
5255 challenge_id: challenge.challenge_id,
5256 kind: protocol::RejectKind::Transient,
5257 reason: "no live round-1 session".to_string(),
5258 },
5259 ),
5260 rr_message_id,
5261 None,
5262 )
5263 .await;
5264 return Ok(());
5265 }
5266 };
5267 let admission_global_inflight = guard.global_inflight;
5268 let admission_peer_inflight = guard.peer_inflight;
5269 ctx.audit_responder_metrics.record_admitted(
5270 *source,
5271 admission_global_inflight,
5272 admission_peer_inflight,
5273 );
5274 info!(
5275 target: "ant_node::replication::audit_responder",
5276 event = "admitted",
5277 kind = "byte",
5278 responder_class = class.as_str(),
5279 source = %source,
5280 challenge_id = challenge.challenge_id,
5281 key_count = challenge.openings.len(),
5282 request_response = rr_message_id.is_some(),
5283 dispatch_ms = received_at.elapsed().as_millis(),
5284 global_inflight = admission_global_inflight,
5285 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5286 peer_inflight = admission_peer_inflight,
5287 peer_limit = class.per_peer_limit(),
5288 "Audit responder request admitted"
5289 );
5290 let bootstrapping = *ctx.is_bootstrapping.read().await;
5291 let storage = Arc::clone(&ctx.storage);
5292 let p2p_node = Arc::clone(&ctx.p2p_node);
5293 let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5294 let source = *source;
5295 let request_id = msg.request_id;
5296 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5297 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5298 ctx.detached_task_tracker.spawn(async move {
5299 let _guard = guard; // global permit + per-peer slot, held until done
5300 let worker_started = Instant::now();
5301 let processing_started = Instant::now();
5302 let response = storage_commitment_audit::handle_subtree_slice_challenge(
5303 &challenge,
5304 &storage,
5305 p2p_node.peer_id(),
5306 bootstrapping,
5307 Some(&my_commitment_state),
5308 )
5309 .await;
5310 let processing = processing_started.elapsed();
5311 let response_kind = subtree_slice_response_kind(&response);
5312 let response_send_started = Instant::now();
5313 let sent = send_replication_response_checked(
5314 &source,
5315 &p2p_node,
5316 request_id,
5317 ReplicationMessageBody::SubtreeSliceResponse(response),
5318 rr_message_id.as_deref(),
5319 None,
5320 )
5321 .await;
5322 let response_send = response_send_started.elapsed();
5323 log_audit_responder_completion(
5324 &responder_metrics,
5325 source,
5326 class,
5327 "byte",
5328 challenge.challenge_id,
5329 challenge.openings.len(),
5330 response_kind,
5331 sent,
5332 received_at,
5333 worker_started,
5334 processing,
5335 response_send,
5336 );
5337 });
5338 Ok(())
5339 }
5340 ReplicationMessageBody::GetCommitmentByPin(ref request) => {
5341 // ADR-0004: answer a commitment-by-pin fetch from the retained set
5342 // only. `lookup_by_hash` is an allocation-light read over the
5343 // bounded slot set; it returns the live current commitment or any
5344 // still-answerable recently-gossiped/quoted one. A miss is reported
5345 // as `NotRetained` (graced, never confirmed) rather than an error,
5346 // so an aged-out pin can never brand an honest node.
5347 //
5348 // Reuse the audit-responder admission guard (global ceiling + per-peer
5349 // cap) so a flood of fetches cannot drive unbounded commitment
5350 // clone/encode/send work; over-limit is dropped, which the fetching
5351 // peer graces exactly like a missed audit response.
5352 let class = AuditResponderClass::CommitmentPin;
5353 let guard = match admit_audit_responder(
5354 &ctx.audit_responder_semaphore,
5355 &ctx.audit_responder_inflight,
5356 source,
5357 class,
5358 )
5359 .await
5360 {
5361 Ok(guard) => guard,
5362 Err(failure) => {
5363 audit_metrics::record_admission_drop(class);
5364 ctx.audit_responder_metrics
5365 .record_drop(*source, failure.reason.into());
5366 warn!(
5367 target: "ant_node::replication::audit_responder",
5368 event = "admission_dropped",
5369 kind = "commitment_pin",
5370 responder_class = class.as_str(),
5371 source = %source,
5372 challenge_id = msg.request_id,
5373 request_response = rr_message_id.is_some(),
5374 dispatch_ms = received_at.elapsed().as_millis(),
5375 reason = failure.reason.as_str(),
5376 global_inflight = failure.global_inflight,
5377 global_limit = failure.global_limit,
5378 peer_inflight = failure.peer_inflight,
5379 peer_limit = failure.peer_limit,
5380 "Audit responder admission dropped"
5381 );
5382 return Ok(());
5383 }
5384 };
5385 ctx.audit_responder_metrics.record_admitted(
5386 *source,
5387 guard.global_inflight,
5388 guard.peer_inflight,
5389 );
5390 info!(
5391 target: "ant_node::replication::audit_responder",
5392 event = "admitted",
5393 kind = "commitment_pin",
5394 responder_class = class.as_str(),
5395 source = %source,
5396 challenge_id = msg.request_id,
5397 request_response = rr_message_id.is_some(),
5398 dispatch_ms = received_at.elapsed().as_millis(),
5399 global_inflight = guard.global_inflight,
5400 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5401 peer_inflight = guard.peer_inflight,
5402 peer_limit = class.per_peer_limit(),
5403 "Audit responder request admitted"
5404 );
5405 let worker_started = Instant::now();
5406 let processing_started = Instant::now();
5407 let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
5408 protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
5409 |built| protocol::GetCommitmentByPinResponse::Found {
5410 commitment: built.commitment().clone(),
5411 },
5412 );
5413 let processing = processing_started.elapsed();
5414 let response_kind = commitment_pin_response_kind(&response);
5415 let response_send_started = Instant::now();
5416 let sent = send_replication_response_checked(
5417 source,
5418 &ctx.p2p_node,
5419 msg.request_id,
5420 ReplicationMessageBody::GetCommitmentByPinResponse(response),
5421 rr_message_id,
5422 None,
5423 )
5424 .await;
5425 let response_send = response_send_started.elapsed();
5426 log_audit_responder_completion(
5427 &ctx.audit_responder_metrics,
5428 *source,
5429 class,
5430 "commitment_pin",
5431 msg.request_id,
5432 1,
5433 response_kind,
5434 sent,
5435 received_at,
5436 worker_started,
5437 processing,
5438 response_send,
5439 );
5440 drop(guard);
5441 Ok(())
5442 }
5443 // Response messages are handled by their respective request initiators.
5444 ReplicationMessageBody::FreshReplicationResponse(_)
5445 | ReplicationMessageBody::NeighborSyncResponse(_)
5446 | ReplicationMessageBody::VerificationResponse(_)
5447 | ReplicationMessageBody::FetchResponse(_)
5448 | ReplicationMessageBody::AuditResponse(_)
5449 | ReplicationMessageBody::SubtreeAuditResponse(_)
5450 | ReplicationMessageBody::SubtreeSliceResponse(_)
5451 | ReplicationMessageBody::GetCommitmentByPinResponse(_) => Ok(()),
5452 }
5453}
5454
5455// ---------------------------------------------------------------------------
5456// Per-message-type handlers
5457// ---------------------------------------------------------------------------
5458
5459/// Verify a payment proof, yielding early if the engine is shutting down.
5460///
5461/// Returns `None` when shutdown won the race, meaning no verdict was reached
5462/// and the caller must abandon the message without storing or penalising.
5463///
5464/// Payment verification is pure network I/O — an EVM round trip and, on the
5465/// merkle path, an iterative Kademlia lookup bounded only by the verifier's
5466/// own `CLOSENESS_LOOKUP_TIMEOUT`. Racing it against the shutdown token is
5467/// what keeps `ReplicationEngine::shutdown()`'s deliberately unbounded
5468/// `detached_task_tracker.wait()` finite: the wait may block only on work that
5469/// is guaranteed to end.
5470///
5471/// Deliberately NOT applied to `storage.put`: that awaits `spawn_blocking`, so
5472/// dropping its awaiter would detach a live LMDB transaction and break the
5473/// very contract the unbounded wait exists to uphold.
5474async fn verify_payment_until_shutdown(
5475 payment_verifier: &Arc<PaymentVerifier>,
5476 key: &XorName,
5477 proof_of_payment: &[u8],
5478 context: VerificationContext,
5479 shutdown: &CancellationToken,
5480) -> Option<Result<crate::payment::PaymentStatus>> {
5481 tokio::select! {
5482 () = shutdown.cancelled() => None,
5483 result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
5484 Some(result)
5485 }
5486 }
5487}
5488
5489/// A fresh offer rejected on payload shape alone.
5490struct FreshOfferRejection {
5491 /// Wire-visible reason returned to the sender.
5492 reason: String,
5493 /// Whether the sender is charged for it. Reserved for offers no honest
5494 /// node would construct, so an ordinary capacity refusal stays free.
5495 penalise: bool,
5496}
5497
5498/// Reject a fresh offer on payload shape, or return `None` to admit it.
5499///
5500/// Pure and non-blocking by construction: these are the checks answerable from
5501/// the payload alone, run on the serial message loop *before* the in-flight
5502/// claim and the admission permit, so a malformed offer can neither lock an
5503/// honest offer out of its key nor occupy one of the scarce
5504/// [`FRESH_OFFER_MAX_OUTSTANDING`] slots for the duration of a payment
5505/// verification. Anything needing I/O — routing lookups, capacity checks, proof
5506/// verification — stays on the worker.
5507///
5508/// The content-address hash is deliberately included despite costing real CPU
5509/// on the loop: it is what makes the entry below *earned* rather than merely
5510/// asserted. Its cost is self-limiting — BLAKE3 runs at GB/s while offers
5511/// arrive at link speed, so a flooder can never make this loop hash faster than
5512/// it can deliver the bytes, and delivering them already cost it more than the
5513/// hash costs us. The receive path has in any case already deserialised the
5514/// same buffer.
5515///
5516/// Every rejection here is penalised. These are the conditions no honest sender
5517/// can produce — an absent, undersized, oversized, or non-matching payload — as
5518/// distinct from a capacity refusal, which is this node's own state and stays
5519/// free. Payment *outcomes* are deliberately not judged here or anywhere: a
5520/// proof that fails to verify may simply have been read against a lagging chain
5521/// view, and penalising that would charge honest senders in correlated bursts.
5522fn fresh_offer_structural_rejection(
5523 key: &XorName,
5524 data: &[u8],
5525 proof_of_payment: &[u8],
5526) -> Option<FreshOfferRejection> {
5527 // Rule 5: reject if PoP is missing. An honest sender always attaches one,
5528 // and an absent proof is the cheapest possible slot-filler, so this is the
5529 // first thing checked.
5530 if proof_of_payment.is_empty() {
5531 return Some(FreshOfferRejection {
5532 reason: "Missing proof of payment".to_string(),
5533 penalise: true,
5534 });
5535 }
5536
5537 // Bound the proof before it can be queued. The verifier applies the same
5538 // limits, but only once the offer reaches a worker — too late here, because
5539 // an entry retains a proof per queued sender, and a proof is capped on the
5540 // wire only by MAX_REPLICATION_MESSAGE_SIZE. Without this an offer carrying
5541 // a byte of data and a 10 MiB "proof" would be admitted, and
5542 // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY of them per key across
5543 // FRESH_OFFER_MAX_OUTSTANDING keys would dwarf the payload ceiling the
5544 // admission bound exists to enforce.
5545 if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
5546 return Some(FreshOfferRejection {
5547 reason: format!(
5548 "Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
5549 proof_of_payment.len(),
5550 ),
5551 penalise: true,
5552 });
5553 }
5554 if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
5555 return Some(FreshOfferRejection {
5556 reason: format!(
5557 "Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
5558 proof_of_payment.len(),
5559 ),
5560 penalise: true,
5561 });
5562 }
5563
5564 // Enforce chunk size invariant: the normal PUT path rejects data larger
5565 // than MAX_CHUNK_SIZE; the replication receive path must do the same to
5566 // prevent peers from pushing oversized records through replication.
5567 if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
5568 return Some(FreshOfferRejection {
5569 reason: format!(
5570 "Data size {} exceeds maximum chunk size {}",
5571 data.len(),
5572 crate::ant_protocol::MAX_CHUNK_SIZE,
5573 ),
5574 penalise: true,
5575 });
5576 }
5577
5578 // Mirror the normal PUT path: the advertised key must be the content
5579 // address of the supplied bytes. Ordered last so an oversized payload is
5580 // refused without being hashed.
5581 //
5582 // This is the check that makes the entry safe to open, and safe for later
5583 // offers to be folded into. Until it passes, the sender has only *asserted*
5584 // an association between the key and the bytes. Opening an entry on an
5585 // assertion would let any peer that knows a key — every recipient of its
5586 // `PaidNotify`, not just the close group — seize it with junk; folding a
5587 // later offer into an entry on an assertion would be worse still, since the
5588 // handler tries each queued proof against the *opener's* bytes and would be
5589 // storing bytes nobody offered for that proof.
5590 let computed_key = crate::client::compute_address(data);
5591 if computed_key != *key {
5592 return Some(FreshOfferRejection {
5593 reason: format!(
5594 "Content address mismatch: expected {}, computed {}",
5595 hex::encode(key),
5596 hex::encode(computed_key),
5597 ),
5598 penalise: true,
5599 });
5600 }
5601
5602 None
5603}
5604
5605/// Tell `source` its offer for `key` was not taken.
5606///
5607/// Note the sender does not currently read this: `fresh::replicate_fresh` uses
5608/// one-way `send_message`, so the refusal is observed only as a later absence by
5609/// the delayed possession check. Recorded in ADR-0005 as a known gap.
5610async fn refuse_fresh_offer(
5611 source: &PeerId,
5612 key: XorName,
5613 reason: String,
5614 ctx: &ReplicationMessageHandlerContext,
5615 request_id: u64,
5616 rr_message_id: Option<&str>,
5617) {
5618 send_replication_response(
5619 source,
5620 &ctx.p2p_node,
5621 request_id,
5622 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5623 key,
5624 reason,
5625 }),
5626 rr_message_id,
5627 )
5628 .await;
5629}
5630
5631/// Refuse an offer that failed [`fresh_offer_structural_rejection`], charging
5632/// the sender when the defect is one no honest node could produce.
5633///
5634/// Kept apart from the capacity refusal in `dispatch_fresh_offer` because the
5635/// two say opposite things: this is the sender's fault, that one is ours.
5636async fn refuse_malformed_fresh_offer(
5637 source: &PeerId,
5638 key: XorName,
5639 rejection: FreshOfferRejection,
5640 ctx: &ReplicationMessageHandlerContext,
5641 request_id: u64,
5642 rr_message_id: Option<&str>,
5643) {
5644 if rejection.penalise {
5645 warn!(
5646 "Rejecting fresh offer for key {} from {source}: {}",
5647 hex::encode(key),
5648 rejection.reason
5649 );
5650 ctx.p2p_node
5651 .report_trust_event(
5652 source,
5653 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5654 )
5655 .await;
5656 } else {
5657 debug!(
5658 "Fresh offer for {} from {source} refused before admission: {}",
5659 hex::encode(key),
5660 rejection.reason
5661 );
5662 }
5663 refuse_fresh_offer(
5664 source,
5665 key,
5666 rejection.reason,
5667 ctx,
5668 request_id,
5669 rr_message_id,
5670 )
5671 .await;
5672}
5673
5674/// Tell senders whose proofs joined an entry that was torn down before a handler
5675/// ever ran for it.
5676///
5677/// Only reachable in the window between opening an entry and failing to take an
5678/// admission permit. Their proofs are answered rather than dropped with the
5679/// entry, so the refusal count reflects what actually happened.
5680async fn refuse_stranded_fresh_offers(
5681 key: XorName,
5682 stranded: Vec<FreshOfferAttempt>,
5683 ctx: &ReplicationMessageHandlerContext,
5684) {
5685 for attempt in stranded {
5686 refuse_fresh_offer(
5687 &attempt.source,
5688 key,
5689 "Receiver at fresh-offer capacity".to_string(),
5690 ctx,
5691 attempt.request_id,
5692 attempt.rr_message_id.as_deref(),
5693 )
5694 .await;
5695 }
5696}
5697
5698/// Admit a fresh offer for handling on a worker, or refuse it.
5699///
5700/// This runs on the serial non-audit message loop, so it must stay cheap: every
5701/// path here is a set insert, a permit try, or a small response send. The offer
5702/// itself — an on-chain payment verification and a multi-MiB LMDB write — always
5703/// runs on a tracked worker task, never inline, because stalling this loop backs
5704/// up the inbound queue and ultimately drops replication messages wholesale.
5705///
5706/// Admission is bounded **per source** as well as globally
5707/// ([`FRESH_OFFER_MAX_OUTSTANDING_PER_PEER`]). Without that share one peer can
5708/// hold every slot, and since a refusal is later read as absence by the
5709/// sender's delayed possession check, the resulting refusals land as
5710/// audit-severity penalties on this node rather than on the flooder.
5711///
5712/// The structurally-invalid checks run **before** the entry is opened and before
5713/// the permit is taken, so junk can neither seize a key nor occupy a slot for
5714/// the duration of a payment verification.
5715///
5716/// Only the offer that *opens* an entry costs a permit and a worker. Later
5717/// offers for the same key contribute their proof and are answered by whatever
5718/// the opener's handler concludes, which is what keeps the routine
5719/// `CLOSE_GROUP_MAJORITY`-way duplication of a client PUT down to one permit and
5720/// one verification per key.
5721async fn dispatch_fresh_offer(
5722 source: PeerId,
5723 offer: protocol::FreshReplicationOffer,
5724 ctx: &ReplicationMessageHandlerContext,
5725 request_id: u64,
5726 received_at: Instant,
5727 rr_message_id: Option<&str>,
5728) -> Result<()> {
5729 if let Some(rejection) =
5730 fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
5731 {
5732 refuse_malformed_fresh_offer(
5733 &source,
5734 offer.key,
5735 rejection,
5736 ctx,
5737 request_id,
5738 rr_message_id,
5739 )
5740 .await;
5741 return Ok(());
5742 }
5743
5744 // Join the work already in flight for this key before taking an admission
5745 // permit, so the duplicates a single client PUT produces cost one permit
5746 // between them rather than one each.
5747 //
5748 // Reaching this point means `fresh_offer_structural_rejection` has confirmed
5749 // `key == BLAKE3(data)`, so this offer's bytes are provably identical to any
5750 // already held for the key. That is what lets its payload be dropped here
5751 // and only its proof retained: the handler will try that proof against the
5752 // bytes it already has.
5753 let key = offer.key;
5754 let admission_outcome = FreshOfferEntryGuard::admit(
5755 &ctx.fresh_offer_in_flight,
5756 offer,
5757 source,
5758 request_id,
5759 rr_message_id.map(ToOwned::to_owned),
5760 received_at,
5761 );
5762 let mut entry = match admission_outcome {
5763 FreshOfferAdmission::Opened(entry) => entry,
5764 FreshOfferAdmission::Joined => {
5765 // No response yet: this proof has not been judged. The handler that
5766 // owns the key answers every queued sender once it settles.
5767 debug!(
5768 "Fresh offer for {} from {source} queued behind the handler already \
5769 holding the key",
5770 hex::encode(key)
5771 );
5772 return Ok(());
5773 }
5774 // Surplus, not suspect: the proofs already queued are enough to place
5775 // the record, so neither case is charged as misbehaviour.
5776 surplus => {
5777 debug!(
5778 "Fresh offer for {} from {source} refused: {}",
5779 hex::encode(key),
5780 surplus.surplus_reason()
5781 );
5782 refuse_fresh_offer(
5783 &source,
5784 key,
5785 "Duplicate offer already in flight".to_string(),
5786 ctx,
5787 request_id,
5788 rr_message_id,
5789 )
5790 .await;
5791 return Ok(());
5792 }
5793 };
5794
5795 let admission = match admit_bounded_responder(
5796 &ctx.fresh_offer_admission_semaphore,
5797 &ctx.fresh_offer_responder_inflight,
5798 &source,
5799 FRESH_OFFER_MAX_OUTSTANDING,
5800 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
5801 )
5802 .await
5803 {
5804 Ok(guard) => guard,
5805 Err(failure) => {
5806 audit_metrics::record_responder_admission_drop(
5807 ReplicationResponderClass::FreshOffer,
5808 failure.reason.into(),
5809 );
5810 // WARN, not DEBUG: a healthy node should never refuse a legitimate
5811 // fresh offer. The sender does not read this refusal, so it
5812 // resurfaces as a missing key at the delayed possession check and
5813 // is charged to US at audit severity. Log the binding ceiling
5814 // locally; the wire reason stays generic so a probing peer cannot
5815 // map out this node's live occupancy.
5816 warn!(
5817 responder_class = "fresh_offer",
5818 source = %source,
5819 key = %hex::encode(key),
5820 penalty_suspended = config::close_group_storage_penalty_suspended(),
5821 "Fresh offer refused at admission; the resulting absence is recorded \
5822 against this node, and penalised unless the release withholds it: \
5823 {failure}"
5824 );
5825 // Release the key explicitly rather than on drop, so the next offer
5826 // opens a fresh entry rather than queueing behind a handler that was
5827 // never spawned — and so any proof that joined in the window between
5828 // opening the entry and failing here is answered rather than
5829 // discarded with it.
5830 let stranded = entry.release();
5831 refuse_fresh_offer(
5832 &source,
5833 key,
5834 "Receiver at fresh-offer capacity".to_string(),
5835 ctx,
5836 request_id,
5837 rr_message_id,
5838 )
5839 .await;
5840 refuse_stranded_fresh_offers(key, stranded, ctx).await;
5841 return Ok(());
5842 }
5843 };
5844
5845 let ctx = ctx.clone();
5846 // Track the worker so `ReplicationEngine::shutdown()` can await it: it holds
5847 // an `Arc<LmdbStorage>` while writing, and the shutdown contract requires
5848 // those references be released before the caller reopens the environment.
5849 ctx.detached_task_tracker
5850 .clone()
5851 .spawn(run_fresh_offer_worker(key, entry, ctx, admission));
5852 Ok(())
5853}
5854
5855/// Body of one tracked fresh-offer worker: drive one key to a verdict.
5856///
5857/// Split out so `dispatch_fresh_offer` stays a readable admission decision.
5858/// A started handler is never cancelled: `storage.put()` awaits
5859/// `spawn_blocking`, and dropping that awaiter would detach the live LMDB
5860/// transaction. Shutdown responsiveness comes from the closed worker semaphore
5861/// and from `handle_fresh_offer` racing the token around payment verification.
5862///
5863/// Works down the key's queued proofs rather than judging the key on the first
5864/// one. A proof that fails to establish payment disqualifies its *sender*, not
5865/// the record: the bytes are content-addressed and identical across every offer,
5866/// so the next sender's proof is tried against the copy already in hand — no
5867/// second payload, no second permit, no refetch. Only when a failure is about
5868/// the key itself (not responsible, no capacity, shutting down) does rotating
5869/// become pointless, because every remaining proof would meet the same wall.
5870async fn run_fresh_offer_worker(
5871 key: XorName,
5872 mut entry: Box<FreshOfferEntryGuard>,
5873 ctx: ReplicationMessageHandlerContext,
5874 admission: ResponderGuard,
5875) {
5876 // The admission permit is released on completion, freeing the payload's
5877 // memory budget and the opening source's per-peer share. The entry releases
5878 // the key itself, either as the queue empties or on drop.
5879 let _admission = admission;
5880 let received_at = entry.received_at();
5881 // Wait for a worker slot here rather than in the caller. The worker bound
5882 // caps concurrent EVM and storage pressure; making the message loop wait on
5883 // it is what put that pressure back on the loop.
5884 //
5885 // The semaphore is closed by `shutdown()`, so this arm is the prompt exit
5886 // path for offers still queued behind a worker when the engine stops — not
5887 // dead code.
5888 let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
5889 .acquire_owned()
5890 .await
5891 else {
5892 debug!(
5893 "Fresh offer for {} dropped: worker pool shut down",
5894 hex::encode(key)
5895 );
5896 return;
5897 };
5898 // Fresh offers are fire-and-forget (`send_message`), so there is no
5899 // requester deadline to honour and a late store is still genuinely useful.
5900 // The threshold is the point past which the offer has already cost us what
5901 // it was going to cost: the possession check (ADR-0003) has run by then and
5902 // charged the absence to this node, and it does not re-offer the key —
5903 // repair comes later from neighbor sync. Shedding here trades a copy that
5904 // would have arrived after the penalty for the multi-MiB payload it is
5905 // holding, and keeps a backlog from outliving its own admission bound.
5906 //
5907 // Note this is a memory-pressure decision, not a redundancy one: the copy
5908 // is late, not useless, so on a node with headroom finishing it would still
5909 // beat waiting for neighbor sync.
5910 if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
5911 debug!(
5912 responder_class = "fresh_offer",
5913 key = %hex::encode(key),
5914 request_age_ms = received_at.elapsed().as_millis(),
5915 "Superseded fresh offer shed at dequeue"
5916 );
5917 return;
5918 }
5919
5920 let mut verdict = FreshOfferOutcome::Abandoned;
5921 while let Some(attempt) = entry.next_attempt() {
5922 match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
5923 Ok(outcome) => {
5924 verdict = outcome;
5925 match outcome {
5926 // Settled: the record is down and every remaining sender
5927 // wanted exactly that. Abandoned: the key cannot be placed
5928 // by anyone right now, so the proofs behind this one would
5929 // fail identically. Either way there is nothing left to try.
5930 FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
5931 // This sender's claim to have paid did not hold up. Say so
5932 // to that sender alone and try the next proof.
5933 FreshOfferOutcome::ProofRejected => {}
5934 }
5935 }
5936 Err(e) => {
5937 debug!(
5938 "Fresh replication offer for {} from {} error: {e}",
5939 hex::encode(key),
5940 attempt.source
5941 );
5942 verdict = FreshOfferOutcome::Abandoned;
5943 break;
5944 }
5945 }
5946 }
5947
5948 // Answer the senders whose proofs were never reached. A stored record is
5949 // what they were asking for, so it is an acceptance even though their own
5950 // proof went untested.
5951 let unreached = entry.release();
5952 if unreached.is_empty() {
5953 return;
5954 }
5955 let response = match verdict {
5956 FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
5957 FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
5958 FreshReplicationResponse::Rejected {
5959 key,
5960 reason: "Record could not be stored from any offered proof".to_string(),
5961 }
5962 }
5963 };
5964 for attempt in unreached {
5965 send_replication_response(
5966 &attempt.source,
5967 &ctx.p2p_node,
5968 attempt.request_id,
5969 ReplicationMessageBody::FreshReplicationResponse(response.clone()),
5970 attempt.rr_message_id.as_deref(),
5971 )
5972 .await;
5973 }
5974}
5975
5976/// What one proof concluded, and whether another proof for the same key is worth
5977/// trying.
5978///
5979/// The distinction the worker acts on is *what the failure was about*. A
5980/// rejected proof is a statement about its sender; anything else is a statement
5981/// about the key or this node, which no other sender's proof can change.
5982#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5983enum FreshOfferOutcome {
5984 /// The record is stored. The key is done.
5985 Settled,
5986 /// This proof did not establish payment. A different sender's proof for the
5987 /// same bytes may still succeed.
5988 ProofRejected,
5989 /// Nothing about this key can succeed right now — not responsible, no disk,
5990 /// shutting down, or a write that failed. Rotating repeats the failure.
5991 Abandoned,
5992}
5993
5994// A linear sequence of protocol steps — structural recheck, responsibility,
5995// capacity, payment, write — each with its own refusal response. Splitting it
5996// would scatter one decision across several functions.
5997#[allow(clippy::too_many_lines)]
5998async fn handle_fresh_offer(
5999 key: &XorName,
6000 data: &[u8],
6001 attempt: &FreshOfferAttempt,
6002 ctx: &ReplicationMessageHandlerContext,
6003) -> Result<FreshOfferOutcome> {
6004 let source = &attempt.source;
6005 let request_id = attempt.request_id;
6006 let rr_message_id = attempt.rr_message_id.as_deref();
6007 let p2p_node = &ctx.p2p_node;
6008 let config = &ctx.config;
6009 let self_id = *p2p_node.peer_id();
6010
6011 // Defence in depth: `dispatch_fresh_offer` already applied these — missing
6012 // proof, bad proof size, oversized payload, content-address mismatch —
6013 // before opening the entry or taking an admission permit, so nothing
6014 // reaching a worker should trip them. Kept so the handler is correct in
6015 // isolation. Note this re-checks the *pairing* actually being used: these
6016 // bytes against this attempt's proof.
6017 if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
6018 {
6019 if rejection.penalise {
6020 warn!(
6021 "Rejecting fresh offer for key {}: {}",
6022 hex::encode(key),
6023 rejection.reason
6024 );
6025 p2p_node
6026 .report_trust_event(
6027 source,
6028 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
6029 )
6030 .await;
6031 }
6032 send_replication_response(
6033 source,
6034 p2p_node,
6035 request_id,
6036 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6037 key: *key,
6038 reason: rejection.reason,
6039 }),
6040 rr_message_id,
6041 )
6042 .await;
6043 // Structurally invalid is a fact about this attempt, not the key.
6044 return Ok(FreshOfferOutcome::ProofRejected);
6045 }
6046
6047 // Rule 7: check storage admission. Fresh chunk receivers accept across the
6048 // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
6049 // the same width client PUTs use), not just the close group plus a small
6050 // margin (ADR-0003). During full-node shunning a healthy replica's routing
6051 // table may still list closer full nodes it hasn't evicted yet, ranking it
6052 // outside the narrow window in its own view; the wider accept window absorbs
6053 // that transient skew so the chunk still lands. Retention (pruning) stays at
6054 // `storage_admission_width`, so steady-state replication is unchanged.
6055 if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
6056 {
6057 send_replication_response(
6058 source,
6059 p2p_node,
6060 request_id,
6061 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6062 key: *key,
6063 reason: "Not in storage-admission range for this key".to_string(),
6064 }),
6065 rr_message_id,
6066 )
6067 .await;
6068 // About the key and this node's place in the routing table, not about
6069 // the sender: every queued proof would be refused identically.
6070 return Ok(FreshOfferOutcome::Abandoned);
6071 }
6072
6073 // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
6074 // never store this record, so reject it before the expensive payment
6075 // verification (EVM on-chain query / merkle pool work) rather than verifying
6076 // and only then failing at `storage.put` below. Reuses the cached capacity
6077 // check (passing results only, so freed space is detected promptly), and the
6078 // store path keeps its own check as defence-in-depth.
6079 if let Err(e) = ctx.storage.check_capacity() {
6080 info!(
6081 target: "ant_node::storage::disk_precheck",
6082 key = %hex::encode(key),
6083 "Rejecting fresh replication offer before payment verification: {e}"
6084 );
6085 send_replication_response(
6086 source,
6087 p2p_node,
6088 request_id,
6089 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6090 key: *key,
6091 reason: e.to_string(),
6092 }),
6093 rr_message_id,
6094 )
6095 .await;
6096 // A full disk is this node's condition, not the sender's.
6097 return Ok(FreshOfferOutcome::Abandoned);
6098 }
6099
6100 // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
6101 // part of the immediate write fan-out: this receiver is about to store the
6102 // record as if the client had PUT it here directly. Storage admission
6103 // was checked above before proof work. FreshReplication verification is
6104 // identical to ClientPut — store-strength cache semantics, paid-quote
6105 // issuer K-closeness checks for single-node proofs, merkle candidate
6106 // closeness for merkle proofs, and the same price-floor policy — the
6107 // distinct context only labels price-floor telemetry.
6108 let Some(verification) = verify_payment_until_shutdown(
6109 &ctx.payment_verifier,
6110 key,
6111 &attempt.proof_of_payment,
6112 fresh_offer_payment_context(),
6113 &ctx.shutdown,
6114 )
6115 .await
6116 else {
6117 debug!(
6118 "Fresh offer for {} from {source} abandoned: engine shutting down \
6119 during payment verification",
6120 hex::encode(key)
6121 );
6122 return Ok(FreshOfferOutcome::Abandoned);
6123 };
6124 match verification {
6125 Ok(status) if status.can_store() => {
6126 debug!("PoP validated for fresh offer key {}", hex::encode(key));
6127 }
6128 // The chain has no record of this payment. That is a statement about
6129 // *this sender's* proof, so the key rotates to the next one rather than
6130 // being written off — the whole point of queueing them.
6131 //
6132 // Deliberately unpenalised. `PaymentRequired` means "no payment found",
6133 // not "definitively unpaid", so a lagging or reorganising chain view
6134 // renders honest senders indistinguishable from forgers, and penalising
6135 // would land on the entire close group at once. The structural checks in
6136 // `fresh_offer_structural_rejection` are where misbehaviour is charged,
6137 // because those cannot be produced by an honest sender at all.
6138 Ok(_) => {
6139 debug!(
6140 "Fresh offer for {} from {source}: no payment found for this proof",
6141 hex::encode(key)
6142 );
6143 send_replication_response(
6144 source,
6145 p2p_node,
6146 request_id,
6147 ReplicationMessageBody::FreshReplicationResponse(
6148 FreshReplicationResponse::Rejected {
6149 key: *key,
6150 reason: "Payment verification failed: payment required".to_string(),
6151 },
6152 ),
6153 rr_message_id,
6154 )
6155 .await;
6156 return Ok(FreshOfferOutcome::ProofRejected);
6157 }
6158 // A verification *error* is usually ours — an unreachable or failing EVM
6159 // endpoint — so it is neither penalised nor treated as this sender's
6160 // fault. Another proof still gets its turn, since the next call may well
6161 // succeed against a recovered endpoint.
6162 Err(e) => {
6163 warn!("PoP verification error for key {}: {e}", hex::encode(key));
6164 send_replication_response(
6165 source,
6166 p2p_node,
6167 request_id,
6168 ReplicationMessageBody::FreshReplicationResponse(
6169 FreshReplicationResponse::Rejected {
6170 key: *key,
6171 reason: format!("Payment verification error: {e}"),
6172 },
6173 ),
6174 rr_message_id,
6175 )
6176 .await;
6177 return Ok(FreshOfferOutcome::ProofRejected);
6178 }
6179 }
6180
6181 // Rule 6: add to PaidForList.
6182 if let Err(e) = ctx.paid_list.insert(key).await {
6183 warn!("Failed to add key to PaidForList: {e}");
6184 }
6185
6186 // Store the record.
6187 match ctx.storage.put(key, data).await {
6188 Ok(_) => {
6189 send_replication_response(
6190 source,
6191 p2p_node,
6192 request_id,
6193 ReplicationMessageBody::FreshReplicationResponse(
6194 FreshReplicationResponse::Accepted { key: *key },
6195 ),
6196 rr_message_id,
6197 )
6198 .await;
6199 Ok(FreshOfferOutcome::Settled)
6200 }
6201 Err(e) => {
6202 send_replication_response(
6203 source,
6204 p2p_node,
6205 request_id,
6206 ReplicationMessageBody::FreshReplicationResponse(
6207 FreshReplicationResponse::Rejected {
6208 key: *key,
6209 reason: e.to_string(),
6210 },
6211 ),
6212 rr_message_id,
6213 )
6214 .await;
6215 // The payment was good and the write still failed, so this is local
6216 // storage trouble that another proof cannot get around.
6217 Ok(FreshOfferOutcome::Abandoned)
6218 }
6219 }
6220}
6221
6222/// Admit a paid-list notification for handling on a worker, or drop it.
6223///
6224/// `PaidNotify` used to be handled inline on the serial non-audit loop, which
6225/// meant one message could park every other non-audit message behind a full
6226/// payment verification. That verification is not a bounded local computation:
6227/// on the merkle path it performs an iterative Kademlia lookup capped only by
6228/// the verifier's `CLOSENESS_LOOKUP_TIMEOUT`, so a single notify could stall
6229/// the loop for minutes while the bounded inbound queue behind it overflowed
6230/// and dropped unrelated replication traffic wholesale.
6231///
6232/// It now follows the same detached-responder pattern as neighbor sync and
6233/// verification (ADR-0005 decision 2): bounded globally and per source, shed
6234/// when stale, and run on a tracked worker.
6235///
6236/// `PaidNotify` is one-way — the protocol defines no response variant — so a
6237/// refused notify is simply dropped. The sender's own paid-list convergence
6238/// (periodic neighbor sync and the verification cycle's paid-list quorum) is
6239/// the recovery path, exactly as for a notify lost in transit.
6240async fn dispatch_paid_notify(
6241 source: PeerId,
6242 notify: protocol::PaidNotify,
6243 ctx: &ReplicationMessageHandlerContext,
6244 received_at: Instant,
6245) -> Result<()> {
6246 let admission = match admit_bounded_responder(
6247 &ctx.paid_notify_admission_semaphore,
6248 &ctx.paid_notify_responder_inflight,
6249 &source,
6250 PAID_NOTIFY_MAX_OUTSTANDING,
6251 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
6252 )
6253 .await
6254 {
6255 Ok(guard) => guard,
6256 Err(failure) => {
6257 audit_metrics::record_responder_admission_drop(
6258 ReplicationResponderClass::PaidNotify,
6259 failure.reason.into(),
6260 );
6261 // WARN for the same reason as fresh offers: PaidNotify is one-way,
6262 // so a refusal discards durable paid-list evidence outright rather
6263 // than pushing work back onto a requester.
6264 warn!(
6265 responder_class = "paid_notify",
6266 source = %source,
6267 key = %hex::encode(notify.key),
6268 "Paid notify dropped at admission — paid-list evidence lost until a verification cycle re-derives it: {failure}"
6269 );
6270 return Ok(());
6271 }
6272 };
6273
6274 let ctx = ctx.clone();
6275 let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
6276 // Deliberately NOT the verification request deadline used by the
6277 // request/response responders. Nobody is waiting on a notify, and shedding
6278 // one discards durable paid-list evidence rather than a reply a requester
6279 // has already given up on. The threshold is instead the point at which the
6280 // pull path would have learned the same fact anyway: one slow-cadence
6281 // neighbor-sync interval, after which the verification cycle's paid-list
6282 // quorum makes this notify genuinely redundant.
6283 let queue_max_age = ctx.config.neighbor_sync_interval_max;
6284 ctx.detached_task_tracker.clone().spawn(async move {
6285 let _admission = admission;
6286 // Closed by `shutdown()`, so this is the prompt exit path for notifies
6287 // still queued behind a worker when the engine stops.
6288 let Ok(_worker) = worker_semaphore.acquire_owned().await else {
6289 debug!("Paid notify from {source} dropped: worker pool shut down");
6290 return;
6291 };
6292 if request_is_stale(received_at, queue_max_age) {
6293 debug!(
6294 responder_class = "paid_notify",
6295 source = %source,
6296 request_age_ms = received_at.elapsed().as_millis(),
6297 "Redundant paid notify shed at dequeue"
6298 );
6299 return;
6300 }
6301 if let Err(e) = handle_paid_notify(
6302 &source,
6303 ¬ify,
6304 &ctx.paid_list,
6305 &ctx.payment_verifier,
6306 &ctx.p2p_node,
6307 &ctx.config,
6308 &ctx.shutdown,
6309 )
6310 .await
6311 {
6312 debug!("Paid notify from {source} error: {e}");
6313 }
6314 });
6315
6316 Ok(())
6317}
6318
6319async fn handle_paid_notify(
6320 _source: &PeerId,
6321 notify: &protocol::PaidNotify,
6322 paid_list: &Arc<PaidList>,
6323 payment_verifier: &Arc<PaymentVerifier>,
6324 p2p_node: &Arc<P2PNode>,
6325 config: &ReplicationConfig,
6326 shutdown: &CancellationToken,
6327) -> Result<()> {
6328 let self_id = *p2p_node.peer_id();
6329
6330 // Rule 3: validate PoP presence before adding.
6331 if notify.proof_of_payment.is_empty() {
6332 return Ok(());
6333 }
6334
6335 // Check if we're in PaidCloseGroup for this key.
6336 if !admission::is_in_paid_close_group(
6337 &self_id,
6338 ¬ify.key,
6339 p2p_node,
6340 config.paid_list_close_group_size,
6341 )
6342 .await
6343 {
6344 return Ok(());
6345 }
6346
6347 // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
6348 // paid-list metadata, so local paid-list close-group membership was checked
6349 // above before proof work. The verifier then runs the same payment proof
6350 // checks as ClientPut while writing a paid-list-strength cache entry.
6351 let Some(verification) = verify_payment_until_shutdown(
6352 payment_verifier,
6353 ¬ify.key,
6354 ¬ify.proof_of_payment,
6355 paid_notify_payment_context(),
6356 shutdown,
6357 )
6358 .await
6359 else {
6360 debug!(
6361 "Paid notify for {} abandoned: engine shutting down during payment \
6362 verification",
6363 hex::encode(notify.key)
6364 );
6365 return Ok(());
6366 };
6367 match verification {
6368 Ok(status) if status.can_store() => {
6369 debug!(
6370 "PoP validated for paid notify key {}",
6371 hex::encode(notify.key)
6372 );
6373 }
6374 Ok(_) => {
6375 warn!(
6376 "Paid notify rejected: payment required for key {}",
6377 hex::encode(notify.key)
6378 );
6379 return Ok(());
6380 }
6381 Err(e) => {
6382 warn!(
6383 "PoP verification error for paid notify key {}: {e}",
6384 hex::encode(notify.key)
6385 );
6386 return Ok(());
6387 }
6388 }
6389
6390 if let Err(e) = paid_list.insert(¬ify.key).await {
6391 warn!("Failed to add paid notify key to PaidForList: {e}");
6392 }
6393
6394 Ok(())
6395}
6396
6397#[allow(clippy::too_many_arguments)]
6398async fn dispatch_neighbor_sync_request(
6399 source: PeerId,
6400 request: protocol::NeighborSyncRequest,
6401 ctx: &ReplicationMessageHandlerContext,
6402 is_bootstrapping: bool,
6403 my_commitment: Option<StorageCommitment>,
6404 request_id: u64,
6405 received_at: Instant,
6406 rr_message_id: Option<&str>,
6407) -> Result<()> {
6408 let guard = match admit_bounded_responder(
6409 &ctx.neighbor_sync_responder_admission_semaphore,
6410 &ctx.neighbor_sync_responder_inflight,
6411 &source,
6412 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
6413 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6414 )
6415 .await
6416 {
6417 Ok(guard) => guard,
6418 Err(failure) => {
6419 audit_metrics::record_responder_admission_drop(
6420 ReplicationResponderClass::NeighborSync,
6421 failure.reason.into(),
6422 );
6423 warn!(
6424 responder_class = "neighbor_sync",
6425 source = %source,
6426 "Neighbor-sync response dropped at admission: {failure}"
6427 );
6428 return Ok(());
6429 }
6430 };
6431
6432 let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
6433 let p2p_node = Arc::clone(&ctx.p2p_node);
6434 let storage = Arc::clone(&ctx.storage);
6435 let paid_list = Arc::clone(&ctx.paid_list);
6436 let queues = Arc::clone(&ctx.queues);
6437 let config = Arc::clone(&ctx.config);
6438 let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
6439 let sync_history = Arc::clone(&ctx.sync_history);
6440 let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
6441 let repair_proofs = Arc::clone(&ctx.repair_proofs);
6442 let request_timeout = ctx.config.verification_request_timeout;
6443 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6444 ctx.detached_task_tracker.spawn(async move {
6445 let _guard = guard;
6446 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6447 debug!(
6448 responder_class = "neighbor_sync",
6449 source = %source,
6450 "Neighbor-sync responder worker pool closed before dequeue"
6451 );
6452 return;
6453 };
6454 if request_is_stale(received_at, request_timeout) {
6455 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
6456 debug!(
6457 responder_class = "neighbor_sync",
6458 source = %source,
6459 request_age_ms = received_at.elapsed().as_millis(),
6460 "Stale neighbor-sync request shed at dequeue"
6461 );
6462 return;
6463 }
6464 if let Err(e) = handle_neighbor_sync_request(
6465 &source,
6466 &request,
6467 &p2p_node,
6468 &storage,
6469 &paid_list,
6470 &queues,
6471 &config,
6472 is_bootstrapping,
6473 &bootstrap_state,
6474 &sync_history,
6475 &sync_cycle_epoch,
6476 &repair_proofs,
6477 my_commitment,
6478 request_id,
6479 rr_message_id.as_deref(),
6480 )
6481 .await
6482 {
6483 debug!(source = %source, "Neighbor-sync request handling failed: {e}");
6484 }
6485 });
6486
6487 Ok(())
6488}
6489
6490#[allow(clippy::too_many_arguments)]
6491async fn handle_neighbor_sync_request(
6492 source: &PeerId,
6493 request: &protocol::NeighborSyncRequest,
6494 p2p_node: &Arc<P2PNode>,
6495 storage: &Arc<LmdbStorage>,
6496 paid_list: &Arc<PaidList>,
6497 queues: &Arc<RwLock<ReplicationQueues>>,
6498 config: &ReplicationConfig,
6499 is_bootstrapping: bool,
6500 bootstrap_state: &Arc<RwLock<BootstrapState>>,
6501 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
6502 sync_cycle_epoch: &Arc<RwLock<u64>>,
6503 repair_proofs: &Arc<RwLock<RepairProofs>>,
6504 my_commitment: Option<StorageCommitment>,
6505 request_id: u64,
6506 rr_message_id: Option<&str>,
6507) -> Result<()> {
6508 let self_id = *p2p_node.peer_id();
6509
6510 // No per-request hint count limit: the wire message size limit
6511 // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
6512 // challenges, sync hints don't drive expensive computation — they just
6513 // enter the verification queue. A per-request limit here would break
6514 // bootstrap replication for newly-joined nodes with 0 stored chunks.
6515
6516 // Build response (outbound hints).
6517 let (response, sent_replica_hints, sender_in_rt) =
6518 neighbor_sync::handle_sync_request_with_proofs(
6519 source,
6520 request,
6521 p2p_node,
6522 storage,
6523 paid_list,
6524 config,
6525 is_bootstrapping,
6526 my_commitment.clone(),
6527 )
6528 .await;
6529
6530 // Send response.
6531 let response_sent = send_replication_response_checked(
6532 source,
6533 p2p_node,
6534 request_id,
6535 ReplicationMessageBody::NeighborSyncResponse(response),
6536 rr_message_id,
6537 None,
6538 )
6539 .await;
6540
6541 // Process inbound hints only if sender is in LocalRT (Rule 4-6).
6542 if !sender_in_rt {
6543 return Ok(());
6544 }
6545
6546 // Update sync history for this peer before recording repair proofs so a
6547 // same-tick audit cannot combine a fresh key proof with stale peer maturity.
6548 {
6549 let mut history = sync_history.write().await;
6550 let record = history.entry(*source).or_insert(PeerSyncRecord {
6551 last_sync: None,
6552 cycles_since_sync: 0,
6553 });
6554 record.last_sync = Some(Instant::now());
6555 record.cycles_since_sync = 0;
6556 }
6557
6558 if response_sent && !request.bootstrapping {
6559 record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
6560 .await;
6561 }
6562
6563 // Admit inbound hints and queue for verification.
6564 let outcome = admit_and_queue_hints(
6565 &self_id,
6566 source,
6567 &request.replica_hints,
6568 &request.paid_hints,
6569 p2p_node,
6570 config,
6571 storage,
6572 paid_list,
6573 queues,
6574 )
6575 .await;
6576
6577 // Track discovered keys for bootstrap drain detection so that hints
6578 // admitted via inbound sync requests are not missed. Capacity-rejected
6579 // hints keep this source on the "not yet drained" list until its next
6580 // sync re-admits them; a clean cycle clears the source.
6581 if is_bootstrapping {
6582 let live_discovered = outcome.discovered.clone();
6583 let outcomes = [(*source, outcome)];
6584 publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
6585 }
6586
6587 Ok(())
6588}
6589
6590/// Test-only record of who *sent* a verification request covering a watched key.
6591///
6592/// The capacity gate's entire effect is a request that is never sent, and a
6593/// request that was not sent leaves no production counter anywhere — not on the
6594/// sender, whose traffic counters are process-global and so cannot separate one
6595/// node of a single-process testnet from another, and not on the responder,
6596/// which simply never hears from it. Recording who asked is what lets a test
6597/// tell "held the key back" apart from "probed the close group, was refused at
6598/// the dial, and then held the key back", which are otherwise identical from the
6599/// queue's point of view.
6600///
6601/// Arming replaces the previous watch, so the outer map holds exactly the keys
6602/// the current test named, and each inner map holds at most one entry per node
6603/// in the process. Nothing is recorded until a test arms it, and the armed path
6604/// costs one read lock on the sending side.
6605///
6606/// Counting is per key because a node that cannot write legitimately keeps
6607/// sending verification requests for keys it has not yet authorized — that is
6608/// `PaidForList` convergence, which the gate leaves alone — so a per-peer total
6609/// would assert something untrue.
6610///
6611/// It counts *send attempts*, deliberately, recorded immediately before the wire
6612/// call. A responder sheds requests at admission and as stale, so a
6613/// receiver-side count would report zero for probes that were really sent, and
6614/// an assertion that this node asked nobody would pass on the strength of the
6615/// receiver dropping the question. It is not proof of delivery: a send that
6616/// fails immediately, with no route or during shutdown, is still counted.
6617///
6618/// `OnceLock` rather than `LazyLock`, which needs a newer Rust than this crate's
6619/// MSRV.
6620#[cfg(any(test, feature = "test-utils"))]
6621type VerificationWatch = HashMap<XorName, HashMap<PeerId, usize>>;
6622
6623#[cfg(any(test, feature = "test-utils"))]
6624static VERIFICATION_WATCH: std::sync::OnceLock<std::sync::RwLock<VerificationWatch>> =
6625 std::sync::OnceLock::new();
6626
6627#[cfg(any(test, feature = "test-utils"))]
6628fn verification_watch() -> &'static std::sync::RwLock<VerificationWatch> {
6629 VERIFICATION_WATCH.get_or_init(|| std::sync::RwLock::new(HashMap::new()))
6630}
6631
6632/// Test-only: start counting verification requests for `keys`, from zero.
6633///
6634/// Replaces any previous watch rather than adding to it, so the map is bounded
6635/// by the keys of the test that armed it last and nothing accumulates across a
6636/// process running many tests.
6637#[cfg(any(test, feature = "test-utils"))]
6638pub fn watch_verification_requests_for_test(keys: &[XorName]) {
6639 if let Ok(mut watch) = verification_watch().write() {
6640 watch.clear();
6641 for key in keys {
6642 watch.insert(*key, HashMap::new());
6643 }
6644 }
6645}
6646
6647/// Record that `requester` sent a verification request covering `keys`, for
6648/// whichever of them are watched. A poisoned lock is ignored rather than
6649/// propagated: this is observation for tests and must never change behaviour.
6650#[cfg(any(test, feature = "test-utils"))]
6651pub(crate) fn record_verification_request_sent(requester: &PeerId, keys: &[XorName]) {
6652 // Fast path under a read lock: with nothing watched — every production
6653 // build, and every test that did not ask — this is all the sender pays.
6654 match verification_watch().read() {
6655 Ok(watch) if watch.is_empty() => return,
6656 Ok(watch) if !keys.iter().any(|key| watch.contains_key(key)) => return,
6657 Ok(_) => {}
6658 Err(_) => return,
6659 }
6660 if let Ok(mut watch) = verification_watch().write() {
6661 for key in keys {
6662 if let Some(by_peer) = watch.get_mut(key) {
6663 *by_peer.entry(*requester).or_insert(0) += 1;
6664 }
6665 }
6666 }
6667}
6668
6669/// Test-only: how many times `requester` has asked this process about `key`.
6670/// Zero unless the key was registered with `watch_verification_requests_for_test`.
6671#[cfg(any(test, feature = "test-utils"))]
6672#[must_use]
6673pub fn verification_requests_for_key_from_for_test(requester: &PeerId, key: &XorName) -> usize {
6674 verification_watch().read().map_or(0, |watch| {
6675 watch
6676 .get(key)
6677 .and_then(|by_peer| by_peer.get(requester))
6678 .copied()
6679 .unwrap_or(0)
6680 })
6681}
6682
6683async fn handle_verification_request(
6684 source: &PeerId,
6685 request: &protocol::VerificationRequest,
6686 storage: &Arc<LmdbStorage>,
6687 paid_list: &Arc<PaidList>,
6688 p2p_node: &Arc<P2PNode>,
6689 request_id: u64,
6690 rr_message_id: Option<&str>,
6691) -> Result<()> {
6692 #[derive(Clone, Copy)]
6693 enum CachedPaidLookup {
6694 NotChecked,
6695 Checked(Option<bool>),
6696 }
6697
6698 #[derive(Clone, Copy)]
6699 struct CachedVerificationLookup {
6700 present: Option<bool>,
6701 paid: CachedPaidLookup,
6702 }
6703
6704 if verification_request_exceeds_limit(request.keys.len()) {
6705 warn!(
6706 "Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
6707 request.keys.len(),
6708 );
6709 send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6710 return Ok(());
6711 }
6712
6713 let requested_keys = request.keys.as_slice();
6714
6715 if request.paid_list_check_indices.len() > request.keys.len() {
6716 warn!(
6717 "Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
6718 request.paid_list_check_indices.len(),
6719 request.keys.len(),
6720 );
6721 send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6722 return Ok(());
6723 }
6724
6725 let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
6726 let paid_check_set: HashSet<u32> = request
6727 .paid_list_check_indices
6728 .iter()
6729 .copied()
6730 .filter(|&idx| {
6731 if idx >= keys_len {
6732 warn!(
6733 "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
6734 requested_keys.len(),
6735 );
6736 false
6737 } else {
6738 true
6739 }
6740 })
6741 .collect();
6742
6743 let mut results = Vec::with_capacity(requested_keys.len());
6744 let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
6745 for (i, key) in requested_keys.iter().enumerate() {
6746 let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
6747 let cached = lookup_cache.entry(*key).or_insert_with(|| {
6748 let present = match storage.exists(key) {
6749 Ok(present) => Some(present),
6750 Err(e) => {
6751 warn!(
6752 "Verification request from {source}: failed to check storage for {}: {e}",
6753 hex::encode(key)
6754 );
6755 None
6756 }
6757 };
6758 CachedVerificationLookup {
6759 present,
6760 paid: CachedPaidLookup::NotChecked,
6761 }
6762 });
6763
6764 if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
6765 cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
6766 Ok(paid) => Some(paid),
6767 Err(e) => {
6768 warn!(
6769 "Verification request from {source}: failed to check paid-list for {}: {e}",
6770 hex::encode(key)
6771 );
6772 None
6773 }
6774 });
6775 }
6776
6777 let paid = if needs_paid {
6778 match cached.paid {
6779 CachedPaidLookup::Checked(paid) => paid,
6780 CachedPaidLookup::NotChecked => None,
6781 }
6782 } else {
6783 None
6784 };
6785
6786 if cached.present.is_none() && paid.is_none() {
6787 continue;
6788 }
6789
6790 results.push(protocol::KeyVerificationResult {
6791 key: *key,
6792 present: cached.present.unwrap_or(false),
6793 paid,
6794 });
6795 }
6796
6797 send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
6798
6799 Ok(())
6800}
6801
6802async fn dispatch_verification_request(
6803 source: PeerId,
6804 request: protocol::VerificationRequest,
6805 ctx: &ReplicationMessageHandlerContext,
6806 request_id: u64,
6807 received_at: Instant,
6808 rr_message_id: Option<&str>,
6809) -> Result<()> {
6810 let guard = match admit_bounded_responder(
6811 &ctx.verification_responder_admission_semaphore,
6812 &ctx.verification_responder_inflight,
6813 &source,
6814 VERIFICATION_RESPONDER_MAX_OUTSTANDING,
6815 VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6816 )
6817 .await
6818 {
6819 Ok(guard) => guard,
6820 Err(failure) => {
6821 audit_metrics::record_responder_admission_drop(
6822 ReplicationResponderClass::Verification,
6823 failure.reason.into(),
6824 );
6825 warn!(
6826 responder_class = "verification",
6827 source = %source,
6828 "Verification response dropped at admission: {failure}"
6829 );
6830 return Ok(());
6831 }
6832 };
6833
6834 let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
6835 let storage = Arc::clone(&ctx.storage);
6836 let paid_list = Arc::clone(&ctx.paid_list);
6837 let p2p_node = Arc::clone(&ctx.p2p_node);
6838 let request_timeout = ctx.config.verification_request_timeout;
6839 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6840 ctx.detached_task_tracker.spawn(async move {
6841 let _guard = guard;
6842 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6843 debug!(
6844 responder_class = "verification",
6845 source = %source,
6846 "Verification responder worker pool closed before dequeue"
6847 );
6848 return;
6849 };
6850 if request_is_stale(received_at, request_timeout) {
6851 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
6852 debug!(
6853 responder_class = "verification",
6854 source = %source,
6855 request_age_ms = received_at.elapsed().as_millis(),
6856 "Stale verification request shed at dequeue"
6857 );
6858 return;
6859 }
6860 if let Err(e) = handle_verification_request(
6861 &source,
6862 &request,
6863 &storage,
6864 &paid_list,
6865 &p2p_node,
6866 request_id,
6867 rr_message_id.as_deref(),
6868 )
6869 .await
6870 {
6871 debug!(source = %source, "Verification request handling failed: {e}");
6872 }
6873 });
6874
6875 Ok(())
6876}
6877
6878const fn verification_request_exceeds_limit(key_count: usize) -> bool {
6879 key_count > MAX_INCOMING_VERIFICATION_KEYS
6880}
6881
6882async fn send_verification_results(
6883 source: &PeerId,
6884 p2p_node: &Arc<P2PNode>,
6885 request_id: u64,
6886 results: Vec<protocol::KeyVerificationResult>,
6887 rr_message_id: Option<&str>,
6888) {
6889 send_replication_response(
6890 source,
6891 p2p_node,
6892 request_id,
6893 ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
6894 rr_message_id,
6895 )
6896 .await;
6897}
6898
6899async fn dispatch_fetch_request(
6900 source: PeerId,
6901 request: protocol::FetchRequest,
6902 ctx: &ReplicationMessageHandlerContext,
6903 request_id: u64,
6904 received_at: Instant,
6905 rr_message_id: Option<&str>,
6906) -> Result<()> {
6907 let guard = match admit_bounded_responder(
6908 &ctx.fetch_responder_admission_semaphore,
6909 &ctx.fetch_responder_inflight,
6910 &source,
6911 FETCH_RESPONDER_MAX_OUTSTANDING,
6912 FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6913 )
6914 .await
6915 {
6916 Ok(guard) => guard,
6917 Err(failure) => {
6918 audit_metrics::record_responder_admission_drop(
6919 ReplicationResponderClass::Fetch,
6920 failure.reason.into(),
6921 );
6922 warn!(
6923 responder_class = "fetch",
6924 source = %source,
6925 "Fetch response dropped at admission: {failure}"
6926 );
6927 return Ok(());
6928 }
6929 };
6930
6931 let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
6932 let storage = Arc::clone(&ctx.storage);
6933 let p2p_node = Arc::clone(&ctx.p2p_node);
6934 let request_timeout = ctx.config.fetch_request_timeout;
6935 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6936 ctx.detached_task_tracker.spawn(async move {
6937 let _guard = guard;
6938 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6939 debug!(
6940 responder_class = "fetch",
6941 source = %source,
6942 "Fetch responder worker pool closed before dequeue"
6943 );
6944 return;
6945 };
6946 if request_is_stale(received_at, request_timeout) {
6947 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
6948 debug!(
6949 responder_class = "fetch",
6950 source = %source,
6951 request_age_ms = received_at.elapsed().as_millis(),
6952 "Stale fetch request shed at dequeue"
6953 );
6954 return;
6955 }
6956 if let Err(e) = handle_fetch_request(
6957 &source,
6958 &request,
6959 &storage,
6960 &p2p_node,
6961 request_id,
6962 rr_message_id.as_deref(),
6963 )
6964 .await
6965 {
6966 debug!(source = %source, "Fetch request handling failed: {e}");
6967 }
6968 });
6969
6970 Ok(())
6971}
6972
6973fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
6974 received_at.elapsed() >= timeout
6975}
6976
6977/// How a fetch responder's answer is charged against its reputation.
6978#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6979enum FetchFault {
6980 /// The peer does not hold a chunk it was expected to hold.
6981 ///
6982 /// This is the lane the release withholds, because a node part-way through moving
6983 /// off the legacy store answers exactly this way about chunks it has legitimately
6984 /// given up.
6985 UnheldChunk,
6986 /// The peer's own storage failed, or served bytes that no longer hash to their
6987 /// address.
6988 ///
6989 /// Never withheld. `FetchResponse::Error` has one producer, and it is the responder's
6990 /// storage read returning an error: an I/O fault, an exhausted descriptor table, or a
6991 /// failed integrity check. A peer that merely does not hold the chunk answers
6992 /// `NotFound` instead, so nothing about the migration produces this.
6993 ResponderFault,
6994}
6995
6996/// Classify a fetch response that did not carry the chunk.
6997///
6998/// `Success` yields `None`. Every other answer is a fault of one kind or the other, and
6999/// which kind decides whether this release charges for it.
7000fn fetch_fault_for(response: &protocol::FetchResponse) -> Option<FetchFault> {
7001 match response {
7002 protocol::FetchResponse::Success { .. } => None,
7003 protocol::FetchResponse::NotFound { .. } => Some(FetchFault::UnheldChunk),
7004 protocol::FetchResponse::Error { .. } => Some(FetchFault::ResponderFault),
7005 }
7006}
7007
7008/// Charge a fetch fault to the responder.
7009///
7010/// The only place the two kinds are treated differently. An unheld chunk goes through the
7011/// release switch, which is currently withholding it; a responder fault is charged
7012/// directly and is not affected by the switch at all.
7013async fn charge_fetch_fault(
7014 p2p_node: &Arc<P2PNode>,
7015 source: &PeerId,
7016 fault: FetchFault,
7017 lane: &'static str,
7018) {
7019 match fault {
7020 FetchFault::UnheldChunk => {
7021 config::penalise_unheld_close_group_chunk(
7022 p2p_node,
7023 source,
7024 lane,
7025 REPLICATION_TRUST_WEIGHT,
7026 )
7027 .await;
7028 }
7029 FetchFault::ResponderFault => {
7030 p2p_node
7031 .report_trust_event(
7032 source,
7033 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7034 )
7035 .await;
7036 }
7037 }
7038}
7039
7040/// Turn the responder's storage read into the answer it sends back.
7041///
7042/// The whole distinction the fetch lanes rest on is made here. A key this node does not
7043/// hold reads as `Ok(None)` and is answered `NotFound`. A read that fails, from an I/O
7044/// fault, an exhausted descriptor table, or a failed integrity check, is answered `Error`.
7045/// Nothing about a node giving chunks up produces the second.
7046fn fetch_response_for(key: XorName, read: Result<Option<Vec<u8>>>) -> protocol::FetchResponse {
7047 match read {
7048 Ok(Some(data)) => protocol::FetchResponse::Success { key, data },
7049 Ok(None) => protocol::FetchResponse::NotFound { key },
7050 Err(e) => protocol::FetchResponse::Error {
7051 key,
7052 reason: format!("{e}"),
7053 },
7054 }
7055}
7056
7057async fn handle_fetch_request(
7058 source: &PeerId,
7059 request: &protocol::FetchRequest,
7060 storage: &Arc<LmdbStorage>,
7061 p2p_node: &Arc<P2PNode>,
7062 request_id: u64,
7063 rr_message_id: Option<&str>,
7064) -> Result<()> {
7065 let response = fetch_response_for(request.key, storage.get(&request.key).await);
7066
7067 send_replication_response(
7068 source,
7069 p2p_node,
7070 request_id,
7071 ReplicationMessageBody::FetchResponse(response),
7072 rr_message_id,
7073 )
7074 .await;
7075
7076 Ok(())
7077}
7078
7079/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
7080/// the prune-confirmation audit, which reuses the same wire message): reply with
7081/// per-key possession digests.
7082struct AuditResponderCompletion {
7083 response_kind: &'static str,
7084 sent: bool,
7085 processing: Duration,
7086 response_send: Duration,
7087}
7088
7089async fn handle_audit_challenge_msg(
7090 source: &PeerId,
7091 challenge: &protocol::AuditChallenge,
7092 storage: &Arc<LmdbStorage>,
7093 p2p_node: &Arc<P2PNode>,
7094 is_bootstrapping: bool,
7095 reply: ReplyRoute<'_>,
7096) -> Result<AuditResponderCompletion> {
7097 #[allow(clippy::cast_possible_truncation)]
7098 let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
7099 info!(
7100 "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
7101 challenge.keys.len(),
7102 is_bootstrapping,
7103 reply.rr_message_id.is_some(),
7104 );
7105
7106 let processing_started = Instant::now();
7107 let response = audit::handle_audit_challenge(
7108 challenge,
7109 storage,
7110 p2p_node.peer_id(),
7111 is_bootstrapping,
7112 stored_chunks,
7113 )
7114 .await;
7115 let processing = processing_started.elapsed();
7116 let response_kind = audit_response_kind(&response);
7117
7118 let response_send_started = Instant::now();
7119 let sent = send_replication_response_checked(
7120 source,
7121 p2p_node,
7122 reply.request_id,
7123 ReplicationMessageBody::AuditResponse(response),
7124 reply.rr_message_id,
7125 Some(reply.protocol),
7126 )
7127 .await;
7128 let response_send = response_send_started.elapsed();
7129
7130 Ok(AuditResponderCompletion {
7131 response_kind,
7132 sent,
7133 processing,
7134 response_send,
7135 })
7136}
7137
7138#[allow(clippy::too_many_arguments)]
7139fn log_audit_responder_completion(
7140 metrics: &AuditResponderMetrics,
7141 source: PeerId,
7142 class: AuditResponderClass,
7143 kind: &'static str,
7144 challenge_id: u64,
7145 work_items: usize,
7146 response_kind: &'static str,
7147 sent: bool,
7148 received_at: Instant,
7149 worker_started: Instant,
7150 processing: Duration,
7151 response_send: Duration,
7152) {
7153 let dispatch = worker_started.saturating_duration_since(received_at);
7154 let total = received_at.elapsed();
7155 metrics.record_completed(source, processing, total, sent);
7156 if sent {
7157 info!(
7158 target: "ant_node::replication::audit_responder",
7159 event = "completed",
7160 kind,
7161 responder_class = class.as_str(),
7162 source = %source,
7163 challenge_id,
7164 work_items,
7165 response = response_kind,
7166 sent,
7167 dispatch_ms = dispatch.as_millis(),
7168 processing_ms = processing.as_millis(),
7169 response_send_ms = response_send.as_millis(),
7170 total_ms = total.as_millis(),
7171 "Audit responder request completed"
7172 );
7173 } else {
7174 warn!(
7175 target: "ant_node::replication::audit_responder",
7176 event = "completed",
7177 kind,
7178 responder_class = class.as_str(),
7179 source = %source,
7180 challenge_id,
7181 work_items,
7182 response = response_kind,
7183 sent,
7184 dispatch_ms = dispatch.as_millis(),
7185 processing_ms = processing.as_millis(),
7186 response_send_ms = response_send.as_millis(),
7187 total_ms = total.as_millis(),
7188 "Audit responder request completed without sending a reply"
7189 );
7190 }
7191}
7192
7193/// Where a reply goes and how it is addressed.
7194///
7195/// Grouped because the audit responder needs all three together and one of them
7196/// is not derivable from the body: during the rollout window a possession reply
7197/// may have to go out on the core id rather than its family's own (see
7198/// [`is_legacy_possession_challenge`]).
7199struct ReplyRoute<'a> {
7200 /// Correlates the reply with the challenge, at the replication layer.
7201 request_id: u64,
7202 /// Present when the challenge arrived over request-response, in which case
7203 /// the reply rides the same exchange back.
7204 rr_message_id: Option<&'a str>,
7205 /// The protocol id to answer on.
7206 protocol: &'static str,
7207}
7208
7209fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
7210 match response {
7211 protocol::AuditResponse::Digests { .. } => "digests",
7212 protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
7213 protocol::AuditResponse::Rejected { .. } => "rejected",
7214 }
7215}
7216
7217fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
7218 match response {
7219 protocol::SubtreeAuditResponse::Proof { .. } => "proof",
7220 protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
7221 protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
7222 }
7223}
7224
7225fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
7226 match response {
7227 protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
7228 protocol::SubtreeAuditResponse::Bootstrapping { .. }
7229 | protocol::SubtreeAuditResponse::Rejected { .. } => 0,
7230 }
7231}
7232
7233fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
7234 match response {
7235 protocol::SubtreeSliceResponse::Items { .. } => "items",
7236 protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
7237 protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
7238 }
7239}
7240
7241fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
7242 match response {
7243 protocol::GetCommitmentByPinResponse::Found { .. } => "found",
7244 protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
7245 }
7246}
7247
7248// ---------------------------------------------------------------------------
7249// Message sending helper
7250// ---------------------------------------------------------------------------
7251
7252/// Send a replication response message as a best-effort reply.
7253///
7254/// Encode and send failures are logged by the checked helper. Most response
7255/// paths do not need to branch on send success, so this wrapper keeps those
7256/// call sites explicit about their best-effort behavior.
7257async fn send_replication_response(
7258 peer: &PeerId,
7259 p2p_node: &Arc<P2PNode>,
7260 request_id: u64,
7261 body: ReplicationMessageBody,
7262 rr_message_id: Option<&str>,
7263) {
7264 let _ =
7265 send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
7266 .await;
7267}
7268
7269/// Send a replication response message and report whether it was accepted.
7270///
7271/// Returns `true` after the message is encoded and accepted by the P2P send
7272/// path. Returns `false` after logging an encode or send failure. Repair-proof
7273/// recording uses this to avoid trusting hints that were not actually sent.
7274///
7275/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
7276/// request-response path so saorsa-core can route it back to the caller's
7277/// `send_request` future. Otherwise it is sent as a plain message.
7278///
7279/// `protocol` overrides the id the body would route on by family. Exactly one
7280/// caller needs it: a possession challenge from a peer that predates the family
7281/// split has to be answered where it was asked (see
7282/// [`is_legacy_possession_challenge`]). Everything else passes `None` and gets
7283/// [`response_protocol_for`], which is what keeps send and receive symmetric.
7284async fn send_replication_response_checked(
7285 peer: &PeerId,
7286 p2p_node: &Arc<P2PNode>,
7287 request_id: u64,
7288 body: ReplicationMessageBody,
7289 rr_message_id: Option<&str>,
7290 protocol: Option<&'static str>,
7291) -> bool {
7292 let msg = ReplicationMessage { request_id, body };
7293 let encoded = match msg.encode() {
7294 Ok(data) => data,
7295 Err(e) => {
7296 warn!("Failed to encode replication response: {e}");
7297 return false;
7298 }
7299 };
7300 // V2-684: per-peer served-bytes attribution for the heavy serve paths.
7301 // `FetchResponse` carries ~99% of served bytes; `NeighborSyncResponse` is
7302 // included for completeness. Other response variants (verification/audit/
7303 // commitment) are intentionally excluded — the round-2 audit reply is now a
7304 // few-KB verified slice (V2-685), not a full-chunk transfer, so it is light.
7305 if matches!(
7306 msg.body,
7307 ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
7308 ) {
7309 protocol::record_served(peer, encoded.len());
7310 }
7311 let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
7312 let result = if let Some(msg_id) = rr_message_id {
7313 p2p_node
7314 .send_response(peer, protocol, msg_id, encoded)
7315 .await
7316 } else {
7317 p2p_node.send_message(peer, protocol, encoded, &[]).await
7318 };
7319 if let Err(e) = result {
7320 debug!("Failed to send replication response to {peer}: {e}");
7321 return false;
7322 }
7323 true
7324}
7325
7326async fn record_sent_replica_hints(
7327 peer: &PeerId,
7328 hints: &[neighbor_sync::SentReplicaHint],
7329 repair_proofs: &Arc<RwLock<RepairProofs>>,
7330 sync_cycle_epoch: &Arc<RwLock<u64>>,
7331) {
7332 if hints.is_empty() {
7333 return;
7334 }
7335
7336 let hinted_at_epoch = *sync_cycle_epoch.read().await;
7337 let mut proofs = repair_proofs.write().await;
7338 for hint in hints {
7339 if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
7340 debug!(
7341 "Recorded repair hint proof for peer {peer} and key {}",
7342 hex::encode(hint.key)
7343 );
7344 }
7345 }
7346}
7347
7348// ---------------------------------------------------------------------------
7349// Neighbor sync round
7350// ---------------------------------------------------------------------------
7351
7352/// Run one neighbor sync round.
7353#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
7354async fn run_neighbor_sync_round(
7355 p2p_node: &Arc<P2PNode>,
7356 storage: &Arc<LmdbStorage>,
7357 paid_list: &Arc<PaidList>,
7358 queues: &Arc<RwLock<ReplicationQueues>>,
7359 config: &ReplicationConfig,
7360 sync_state: &Arc<RwLock<NeighborSyncState>>,
7361 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7362 sync_cycle_epoch: &Arc<RwLock<u64>>,
7363 repair_proofs: &Arc<RwLock<RepairProofs>>,
7364 is_bootstrapping: &Arc<RwLock<bool>>,
7365 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7366 commitment_state: &Arc<ResponderCommitmentState>,
7367 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7368 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7369 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7370 audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
7371 gossip_audit: &GossipAuditTrigger,
7372) {
7373 let self_id = *p2p_node.peer_id();
7374 let bootstrapping = *is_bootstrapping.read().await;
7375
7376 // Check if cycle is complete; start new one if needed.
7377 // We check under a read lock, then release it before the expensive
7378 // prune pass and DHT snapshot so other tasks are not starved.
7379 let cycle_complete = sync_state.read().await.is_cycle_complete();
7380 if cycle_complete {
7381 // A completed local neighbor-sync cycle advances the epoch component
7382 // of repair-proof maturity. The per-key wall-clock minimum age is
7383 // checked when audits are selected.
7384 {
7385 let mut history = sync_history.write().await;
7386 for record in history.values_mut() {
7387 record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
7388 }
7389 }
7390 {
7391 let mut epoch = sync_cycle_epoch.write().await;
7392 *epoch = epoch.saturating_add(1);
7393 }
7394
7395 // Post-cycle pruning (Section 11) — runs without holding sync_state.
7396 // Prune candidacy is unconditional once the hysteresis elapses;
7397 // bootstrap state only defers the remote prune-confirmation audits
7398 // until bootstrap has drained.
7399 let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
7400 pruning::run_prune_pass_with_context(pruning::PrunePassContext {
7401 self_id: &self_id,
7402 storage,
7403 paid_list,
7404 p2p_node,
7405 config,
7406 sync_state,
7407 repair_proofs,
7408 allow_remote_prune_audits,
7409 commitment_state: Some(commitment_state),
7410 audit_challenge_coordinator,
7411 })
7412 .await;
7413
7414 // Take fresh close-neighbor snapshot (DHT query, no lock held).
7415 let neighbors =
7416 neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
7417 .await;
7418
7419 // Now re-acquire write lock and re-check before swapping cycle.
7420 let mut state = sync_state.write().await;
7421 if state.is_cycle_complete() {
7422 // Preserve cooldown and bootstrap-claim tracking across cycles.
7423 // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
7424 // would reset the abuse detection timer every cycle.
7425 let old_sync_times = std::mem::take(&mut state.last_sync_times);
7426 let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
7427 let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
7428 let old_prune_cursor = state.prune_cursor;
7429 *state = NeighborSyncState::new_cycle(neighbors);
7430 state.last_sync_times = old_sync_times;
7431 state.bootstrap_claims = old_bootstrap_claims;
7432 state.bootstrap_claim_history = old_bootstrap_claim_history;
7433 state.prune_cursor = old_prune_cursor;
7434 }
7435 }
7436
7437 // Select batch of peers.
7438 let batch = {
7439 let mut state = sync_state.write().await;
7440 neighbor_sync::select_sync_batch(
7441 &mut state,
7442 config.neighbor_sync_peer_count,
7443 config.neighbor_sync_cooldown,
7444 )
7445 };
7446
7447 if batch.is_empty() {
7448 return;
7449 }
7450
7451 debug!("Neighbor sync: syncing with {} peers", batch.len());
7452
7453 // Snapshot our current commitment once per round so all peers in
7454 // this batch see the same thing (gossip is the responder's attestation;
7455 // same value across the batch is fine and reduces RwLock churn). Atomically
7456 // snapshot + mark-gossiped so we stay answerable for exactly what we emit
7457 // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
7458 let my_commitment = commitment_state
7459 .current_for_gossip()
7460 .map(|b| b.commitment().clone());
7461
7462 let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
7463 &batch,
7464 storage,
7465 paid_list,
7466 p2p_node,
7467 config.close_group_size,
7468 config.paid_list_close_group_size,
7469 )
7470 .await;
7471
7472 // Sync with each peer in the batch.
7473 for peer in &batch {
7474 let hints = hints_by_peer.remove(peer).unwrap_or_default();
7475 let outcome = neighbor_sync::sync_with_peer_with_hints(
7476 peer,
7477 p2p_node,
7478 config,
7479 bootstrapping,
7480 hints,
7481 my_commitment.clone(),
7482 )
7483 .await;
7484
7485 if let Some(outcome) = outcome {
7486 handle_sync_response(
7487 &self_id,
7488 peer,
7489 &outcome.response,
7490 &outcome.sent_replica_hints,
7491 p2p_node,
7492 config,
7493 bootstrapping,
7494 bootstrap_state,
7495 storage,
7496 paid_list,
7497 queues,
7498 sync_state,
7499 sync_history,
7500 sync_cycle_epoch,
7501 repair_proofs,
7502 last_commitment_by_peer,
7503 ever_capable_peers,
7504 sig_verify_attempts,
7505 gossip_audit,
7506 )
7507 .await;
7508 } else {
7509 // Sync failed -- remove peer and try to fill slot.
7510 let replacement = {
7511 let mut state = sync_state.write().await;
7512 neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
7513 };
7514
7515 // Attempt sync with the replacement peer (if one was found).
7516 if let Some(replacement_peer) = replacement {
7517 let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
7518 std::slice::from_ref(&replacement_peer),
7519 storage,
7520 paid_list,
7521 p2p_node,
7522 config.close_group_size,
7523 config.paid_list_close_group_size,
7524 )
7525 .await;
7526 let hints = replacement_hints
7527 .remove(&replacement_peer)
7528 .unwrap_or_default();
7529 let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
7530 &replacement_peer,
7531 p2p_node,
7532 config,
7533 bootstrapping,
7534 hints,
7535 my_commitment.clone(),
7536 )
7537 .await;
7538
7539 if let Some(outcome) = replacement_outcome {
7540 handle_sync_response(
7541 &self_id,
7542 &replacement_peer,
7543 &outcome.response,
7544 &outcome.sent_replica_hints,
7545 p2p_node,
7546 config,
7547 bootstrapping,
7548 bootstrap_state,
7549 storage,
7550 paid_list,
7551 queues,
7552 sync_state,
7553 sync_history,
7554 sync_cycle_epoch,
7555 repair_proofs,
7556 last_commitment_by_peer,
7557 ever_capable_peers,
7558 sig_verify_attempts,
7559 gossip_audit,
7560 )
7561 .await;
7562 }
7563 }
7564 }
7565 }
7566}
7567
7568/// Process a successful neighbor sync response: record the sync, check for
7569/// bootstrap claim abuse, and admit inbound hints.
7570#[allow(clippy::too_many_arguments)]
7571async fn handle_sync_response(
7572 self_id: &PeerId,
7573 peer: &PeerId,
7574 resp: &NeighborSyncResponse,
7575 sent_replica_hints: &[neighbor_sync::SentReplicaHint],
7576 p2p_node: &Arc<P2PNode>,
7577 config: &ReplicationConfig,
7578 bootstrapping: bool,
7579 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7580 storage: &Arc<LmdbStorage>,
7581 paid_list: &Arc<PaidList>,
7582 queues: &Arc<RwLock<ReplicationQueues>>,
7583 sync_state: &Arc<RwLock<NeighborSyncState>>,
7584 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7585 sync_cycle_epoch: &Arc<RwLock<u64>>,
7586 repair_proofs: &Arc<RwLock<RepairProofs>>,
7587 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7588 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7589 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7590 gossip_audit: &GossipAuditTrigger,
7591) {
7592 // Ingest the peer's commitment if they piggybacked one on the response.
7593 // Same verification as the request path (peer-id binding + signature);
7594 // forged commitments are dropped at the edge. A *changed* commitment here
7595 // is a gossip-audit trigger just like on the request path — so a peer that
7596 // only ever answers sync (never initiates) is still audited (ADR-0002).
7597 if let Some(target) = ingest_peer_commitment(
7598 peer,
7599 resp.commitment.as_ref(),
7600 p2p_node,
7601 last_commitment_by_peer,
7602 ever_capable_peers,
7603 sig_verify_attempts,
7604 )
7605 .await
7606 {
7607 maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
7608 }
7609
7610 // Record successful sync.
7611 {
7612 let mut state = sync_state.write().await;
7613 neighbor_sync::record_successful_sync(&mut state, peer);
7614 }
7615 {
7616 let mut history = sync_history.write().await;
7617 let record = history.entry(*peer).or_insert(PeerSyncRecord {
7618 last_sync: None,
7619 cycles_since_sync: 0,
7620 });
7621 record.last_sync = Some(Instant::now());
7622 record.cycles_since_sync = 0;
7623 }
7624
7625 // Process inbound hints from response (skip if peer is bootstrapping).
7626 if resp.bootstrapping {
7627 // Gap 6: BootstrapClaimAbuse grace period enforcement.
7628 // Separate state mutation from network I/O to avoid holding the
7629 // write lock across report_trust_event.
7630 let should_report = {
7631 let now = Instant::now();
7632 let mut state = sync_state.write().await;
7633 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
7634 BootstrapClaimObservation::WithinGrace { .. } => false,
7635 BootstrapClaimObservation::PastGrace { first_seen } => {
7636 warn!(
7637 "Peer {peer} has been claiming bootstrap for {:?}, \
7638 exceeding grace period of {:?} — reporting abuse",
7639 now.duration_since(first_seen),
7640 config.bootstrap_claim_grace_period,
7641 );
7642 true
7643 }
7644 BootstrapClaimObservation::Repeated { first_seen } => {
7645 warn!(
7646 "Peer {peer} repeated bootstrap claim after previously stopping; \
7647 first claim was {:?} ago — reporting abuse",
7648 now.duration_since(first_seen),
7649 );
7650 true
7651 }
7652 }
7653 };
7654 if should_report {
7655 p2p_node
7656 .report_trust_event(
7657 peer,
7658 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7659 )
7660 .await;
7661 }
7662 } else {
7663 // Peer is not claiming bootstrap; clear active claim while retaining
7664 // history so the peer cannot start a second grace window later.
7665 {
7666 let mut state = sync_state.write().await;
7667 state.clear_active_bootstrap_claim(peer);
7668 }
7669 record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
7670 let outcome = admit_and_queue_hints(
7671 self_id,
7672 peer,
7673 &resp.replica_hints,
7674 &resp.paid_hints,
7675 p2p_node,
7676 config,
7677 storage,
7678 paid_list,
7679 queues,
7680 )
7681 .await;
7682
7683 // Track discovered keys for bootstrap drain detection so that hints
7684 // admitted via regular neighbor sync are not missed. Capacity-
7685 // rejected hints keep this source on the "not yet drained" list
7686 // until its next sync replays them; a clean cycle clears it.
7687 if bootstrapping {
7688 let live_discovered = outcome.discovered.clone();
7689 let outcomes = [(*peer, outcome)];
7690 publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
7691 .await;
7692 }
7693 }
7694}
7695
7696/// Admit hints and queue them for verification, returning newly-discovered keys.
7697///
7698/// Shared by neighbor-sync request handling, response handling, and bootstrap
7699/// sync so that admission + queueing logic lives in one place.
7700#[allow(clippy::too_many_arguments)]
7701/// Outcome of [`admit_and_queue_hints`].
7702///
7703/// `capacity_rejected_count` tracks incoming hints for which no fair slot was
7704/// available; that source is kept outstanding until it re-hints. `displaced`
7705/// tracks older borrowed hints reclaimed for another sender; only the key is
7706/// dropped from bootstrap tracking — the former owner's standing is untouched
7707/// (see [`publish_bootstrap_admission_outcomes`]).
7708struct AdmissionOutcome {
7709 discovered: HashSet<XorName>,
7710 capacity_rejected_count: usize,
7711 displaced: Vec<CapacityDisplacement>,
7712}
7713
7714/// Publish one atomic admission unit into bootstrap drain accounting.
7715///
7716/// Only sources that were themselves capacity-rejected are kept outstanding.
7717/// A fairness displacement forfeits the displaced *key* but never stamps its
7718/// former owner: reclaiming a borrowed slot is this node's own fairness
7719/// decision, so charging it to the victim would let a sustained flooder wedge
7720/// our bootstrap drain open through an unrelated honest peer. Clean sources
7721/// are cleared only after every outcome in the unit is known, so peer
7722/// iteration order cannot falsely clear a rejection recorded later in the same
7723/// bootstrap batch.
7724async fn publish_bootstrap_admission_outcomes(
7725 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7726 outcomes: &[(PeerId, AdmissionOutcome)],
7727 live_discovered: &HashSet<XorName>,
7728) {
7729 let mut rejected_sources = HashSet::new();
7730 let mut clean_sources = HashSet::new();
7731 let mut displaced_keys = HashSet::new();
7732
7733 for (source, outcome) in outcomes {
7734 if outcome.capacity_rejected_count > 0 {
7735 rejected_sources.insert(*source);
7736 } else {
7737 clean_sources.insert(*source);
7738 }
7739 // Only the *key* of a fairness displacement is forfeited here, never
7740 // its owner's standing. Reclaiming a borrowed slot is our own fairness
7741 // decision, not a failure by the peer that held it: stamping the victim
7742 // would let a sustained flooder block our bootstrap drain through an
7743 // unrelated honest peer that never overflowed us. The displaced key
7744 // falls to the same post-bootstrap neighbor-sync and audit/repair
7745 // recovery path that TTL expiry already relies on.
7746 for displacement in &outcome.displaced {
7747 displaced_keys.insert(displacement.key);
7748 }
7749 }
7750 clean_sources.retain(|source| !rejected_sources.contains(source));
7751
7752 let now = Instant::now();
7753 let mut state = bootstrap_state.write().await;
7754 for key in displaced_keys {
7755 state.remove_key(&key);
7756 }
7757 state.pending_keys.extend(live_discovered);
7758 for source in clean_sources {
7759 state.capacity_rejected_sources.remove(&source);
7760 }
7761 for source in rejected_sources {
7762 // First-seen: a source that keeps overflowing us must not keep its own
7763 // record fresh, or bootstrap never drains and auditing stays off.
7764 state.note_capacity_rejected(source, now);
7765 }
7766}
7767
7768#[allow(clippy::too_many_arguments)]
7769async fn admit_and_queue_hints(
7770 self_id: &PeerId,
7771 source_peer: &PeerId,
7772 replica_hints: &[XorName],
7773 paid_hints: &[XorName],
7774 p2p_node: &Arc<P2PNode>,
7775 config: &ReplicationConfig,
7776 storage: &Arc<LmdbStorage>,
7777 paid_list: &Arc<PaidList>,
7778 queues: &Arc<RwLock<ReplicationQueues>>,
7779) -> AdmissionOutcome {
7780 let pending_keys: HashSet<XorName> = {
7781 let q = queues.read().await;
7782 q.pending_keys().into_iter().collect()
7783 };
7784
7785 let admitted = admission::admit_hints(
7786 self_id,
7787 replica_hints,
7788 paid_hints,
7789 p2p_node,
7790 config,
7791 storage,
7792 paid_list,
7793 &pending_keys,
7794 )
7795 .await;
7796
7797 let mut q = queues.write().await;
7798 queue_admitted_hints(source_peer, admitted, storage, &mut q)
7799}
7800
7801fn queue_admitted_hints(
7802 source_peer: &PeerId,
7803 admitted: admission::AdmissionResult,
7804 storage: &LmdbStorage,
7805 q: &mut ReplicationQueues,
7806) -> AdmissionOutcome {
7807 let mut discovered = HashSet::new();
7808 let mut capacity_rejected_count: usize = 0;
7809 let mut displaced = Vec::new();
7810 let now = Instant::now();
7811
7812 for key in admitted.replica_keys {
7813 if !storage.exists(&key).unwrap_or(false) {
7814 let result = q.add_pending_verify(
7815 key,
7816 VerificationEntry {
7817 state: VerificationState::PendingVerify,
7818 verified_sources: Vec::new(),
7819 tried_sources: HashSet::new(),
7820 created_at: now,
7821 next_verify_at: now,
7822 hint_sources: HashSet::from([*source_peer]),
7823 // Non-empty: this peer claimed possession, so it is a
7824 // fetch-source candidate. Derives HintPipeline::Replica.
7825 replica_hint_sources: HashSet::from([*source_peer]),
7826 unresolved_retries: 0,
7827 no_holder_reported: false,
7828 },
7829 );
7830 match result {
7831 crate::replication::scheduling::AdmissionResult::Admitted => {
7832 discovered.insert(key);
7833 }
7834 crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7835 crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7836 capacity_rejected_count += 1;
7837 }
7838 }
7839 }
7840 }
7841
7842 for key in admitted.paid_only_keys {
7843 let result = q.add_pending_verify(
7844 key,
7845 VerificationEntry {
7846 state: VerificationState::PendingVerify,
7847 verified_sources: Vec::new(),
7848 tried_sources: HashSet::new(),
7849 created_at: now,
7850 next_verify_at: now,
7851 hint_sources: HashSet::from([*source_peer]),
7852 // Empty: a paid hint makes no possession claim, so this peer is
7853 // not a fetch source. Derives HintPipeline::PaidOnly.
7854 replica_hint_sources: HashSet::new(),
7855 unresolved_retries: 0,
7856 no_holder_reported: false,
7857 },
7858 );
7859 match result {
7860 crate::replication::scheduling::AdmissionResult::Admitted => {
7861 discovered.insert(key);
7862 }
7863 crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7864 crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7865 capacity_rejected_count += 1;
7866 }
7867 }
7868 }
7869
7870 if capacity_rejected_count > 0 {
7871 debug!(
7872 "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
7873 rejected at queue capacity; source will need to re-hint after pending_verify drains"
7874 );
7875 }
7876
7877 displaced.extend(q.take_capacity_displacements());
7878
7879 AdmissionOutcome {
7880 discovered,
7881 capacity_rejected_count,
7882 displaced,
7883 }
7884}
7885
7886// ---------------------------------------------------------------------------
7887// Verification cycle
7888// ---------------------------------------------------------------------------
7889
7890/// Run one verification cycle: process pending keys through quorum checks.
7891#[allow(clippy::too_many_lines)]
7892async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
7893 let cycle_started = Instant::now();
7894 let VerificationCycleContext {
7895 p2p_node,
7896 paid_list,
7897 storage,
7898 queues,
7899 config,
7900 bootstrap_state,
7901 is_bootstrapping,
7902 bootstrap_complete_notify,
7903 last_commitment_by_peer,
7904 ever_capable_peers,
7905 recent_provers,
7906 } = ctx;
7907
7908 // Self-heal the bootstrap drain before any early-return below: abandoned
7909 // capacity-rejection records must expire, and a drain condition that
7910 // became true without a triggering event must still be observed. Pending
7911 // peer requests legitimately block the drain check itself, but not this.
7912 expire_and_recheck_bootstrap_drain(
7913 bootstrap_state,
7914 queues,
7915 is_bootstrapping,
7916 bootstrap_complete_notify,
7917 config.capacity_rejected_max_age(),
7918 )
7919 .await;
7920
7921 // Bootstrap admits one concurrent neighbor batch as an atomic source
7922 // aggregation unit. Do not select newly queued keys until that batch's
7923 // hints and drain accounting have both been published.
7924 if bootstrap_state.read().await.pending_peer_requests > 0 {
7925 return;
7926 }
7927
7928 // Evict stale entries that have been pending too long (e.g. unreachable
7929 // verification targets during a network partition).
7930 let stale_pending_keys = {
7931 let mut q = queues.write().await;
7932 q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
7933 };
7934 if !stale_pending_keys.is_empty() {
7935 update_bootstrap_after_verification(
7936 &stale_pending_keys,
7937 bootstrap_state,
7938 queues,
7939 is_bootstrapping,
7940 bootstrap_complete_notify,
7941 )
7942 .await;
7943 }
7944
7945 let pending_keys = {
7946 let mut q = queues.write().await;
7947 // Re-check while holding the queue write lock used by fair selection.
7948 // This closes the race
7949 // where a bootstrap batch starts after the early check: the batch
7950 // cannot publish its hints under the queue write lock until this
7951 // selection either returns or declines to run.
7952 if bootstrap_state.read().await.pending_peer_requests > 0 {
7953 return;
7954 }
7955 q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
7956 };
7957
7958 if pending_keys.is_empty() {
7959 return;
7960 }
7961 let initial_pending_count = pending_keys.len();
7962
7963 // Capacity verdict for this cycle — the same pre-check the PUT handler and
7964 // the fresh-offer path already run (V2-411), read once and reused below.
7965 //
7966 // It gates only the two steps that exist to enable a fetch: the presence
7967 // probe that discovers holders, and the promotion that queues the download.
7968 // Everything a cycle does that does not need a local write still runs on a
7969 // full node — the local paid-list fast path, `PaidForList` convergence
7970 // through the quorum round, and the terminal checks that retire a key this
7971 // node already holds or is no longer admitted for. Gating earlier than this
7972 // would stop a full node learning which of its keys were paid for, and
7973 // would strand keys that should have retired, which keeps bootstrap drain
7974 // pending and audits disabled until stale eviction.
7975 // Only a *full* disk is a standing condition worth minutes of backoff. A
7976 // failed `statvfs` says nothing about available space and may have cleared
7977 // by the next cycle, so it is treated as writable here and left to the
7978 // pre-check at the dial, which queries again and may well permit the write.
7979 let write_blocked = storage.capacity_verdict() == CapacityVerdict::Full;
7980 // Counted per gate rather than combined. `local_paid_probe` below counts
7981 // probes actually sent, so it reads zero once the first gate fires; keeping
7982 // the two deferral counts apart is what lets an operator see which branch a
7983 // full node's keys are taking without adding a code path to find out.
7984 let mut capacity_deferred_probe = 0usize;
7985 let mut capacity_deferred_promote = 0usize;
7986
7987 let self_id = *p2p_node.peer_id();
7988
7989 // Step 1: Check local PaidForList for fast-path authorization (Section 9,
7990 // step 4). Paid-list membership settles *validity* — the key is known-paid,
7991 // so no quorum round is needed. It says nothing about whether we must hold
7992 // the bytes; that is decided below.
7993 let mut local_paid_keys = Vec::new();
7994 let mut keys_needing_network = Vec::new();
7995 let mut terminal_keys: Vec<XorName> = Vec::new();
7996 {
7997 let mut q = queues.write().await;
7998 for key in &pending_keys {
7999 if paid_list.contains(key).unwrap_or(false) {
8000 if q.set_pending_state(key, VerificationState::PaidListVerified) {
8001 local_paid_keys.push(*key);
8002 }
8003 } else {
8004 keys_needing_network.push(*key);
8005 }
8006 }
8007 }
8008
8009 // Storage responsibility is a live routing question, decided identically
8010 // for every known-paid key regardless of how the advertising peer labelled
8011 // its hint — a replica hint is a possession *claim* by the sender, never
8012 // permission for us to store. Held outside the queue lock: `is_responsible`
8013 // awaits into the DHT manager.
8014 let mut local_paid_presence_probe_keys = Vec::new();
8015 if !local_paid_keys.is_empty() {
8016 let mut terminal_paid = Vec::new();
8017 for key in local_paid_keys {
8018 if storage.exists(&key).unwrap_or(false) {
8019 terminal_paid.push(key);
8020 } else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
8021 // We carry storage responsibility and lack the bytes. The
8022 // presence probe below discovers holders to fetch from; it is
8023 // source discovery, not re-verification.
8024 local_paid_presence_probe_keys.push(key);
8025 } else {
8026 terminal_paid.push(key);
8027 }
8028 }
8029
8030 if !terminal_paid.is_empty() {
8031 let mut q = queues.write().await;
8032 for key in terminal_paid {
8033 q.remove_pending(&key);
8034 terminal_keys.push(key);
8035 }
8036 }
8037
8038 // Capacity gate, first of two. Everything above this point has already
8039 // run: authorization succeeded via the local `PaidForList` hit, and the
8040 // keys that should retire (already held, or no longer storage-admitted)
8041 // have retired. What is left is a probe whose only purpose is finding a
8042 // holder to download from, and this node cannot write what it would
8043 // download.
8044 if write_blocked && !local_paid_presence_probe_keys.is_empty() {
8045 let mut q = queues.write().await;
8046 for key in std::mem::take(&mut local_paid_presence_probe_keys) {
8047 if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8048 capacity_deferred_probe += 1;
8049 }
8050 }
8051 }
8052 }
8053
8054 let local_paid_probe_count = local_paid_presence_probe_keys.len();
8055 let keys_needing_network_count = keys_needing_network.len();
8056 // Keys this cycle put back because no peer claimed possession. Reported in
8057 // aggregate below; the per-key line is warned once per entry, not per retry.
8058 let mut no_holder_deferrals = 0usize;
8059
8060 // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
8061 // step 4, authorization succeeds immediately; run a presence-only probe
8062 // to find any holder we can fetch from.
8063 if !local_paid_presence_probe_keys.is_empty() {
8064 let targets = quorum::compute_presence_targets(
8065 &local_paid_presence_probe_keys,
8066 p2p_node,
8067 config,
8068 &self_id,
8069 )
8070 .await;
8071 let evidence = quorum::run_verification_round(
8072 &local_paid_presence_probe_keys,
8073 &targets,
8074 p2p_node,
8075 config,
8076 )
8077 .await;
8078
8079 let mut q = queues.write().await;
8080 for key in local_paid_presence_probe_keys {
8081 if storage.exists(&key).unwrap_or(false) {
8082 q.remove_pending(&key);
8083 terminal_keys.push(key);
8084 continue;
8085 }
8086 let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
8087 quorum::present_sources_for_key(&key, ev, &targets)
8088 });
8089 if let Some(entry) = q.get_pending(&key) {
8090 add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
8091 }
8092 if sources.is_empty() {
8093 no_holder_deferrals += 1;
8094 let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8095 let first_report = q.claim_no_holder_report(&key);
8096 report_unresolved_deferral("Locally paid key", &key, outcome, first_report);
8097 } else {
8098 // A holder answered, so whatever came before is not a run of
8099 // consecutive failures any more. Clear before promoting: if the
8100 // fetch queue is full the entry stays pending, and it must not
8101 // carry the old backoff.
8102 q.clear_unresolved(&key);
8103 let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8104 // Atomic remove+enqueue: if fetch_queue is at capacity, the
8105 // pending entry is preserved and retried next cycle (no
8106 // silent drop of verified replica-repair work).
8107 let _ = q.promote_pending_to_fetch(key, distance, sources);
8108 }
8109 }
8110 }
8111
8112 // Steps 2-5: Network verification (skipped if all keys resolved locally).
8113 if !keys_needing_network.is_empty() {
8114 // Step 2: Compute targets and run network verification round.
8115 let targets =
8116 quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
8117 .await;
8118
8119 let evidence =
8120 quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
8121
8122 // Step 3: Evaluate results — collect outcomes without holding the write
8123 // lock across paid-list I/O.
8124 //
8125 // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
8126 // table and recent_provers cache up front so the synchronous
8127 // evaluate_key_evidence_with_holder_check predicate can consult
8128 // them without awaiting. The predicate downgrades a Present
8129 // claim to Unresolved unless the peer is credited for that key.
8130 // Snapshot per-peer commitment data. We need two views:
8131 // - `commitment_by_peer_snapshot`: peers that currently have
8132 // a verified commitment record on file (used to look up
8133 // their current hash).
8134 // - `capable_peer_snapshot`: the sticky "ever v12-capable"
8135 // set. Sourced from a separate set rather than the
8136 // commitment map so eviction (PeerRemoved cleanup, sybil
8137 // cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
8138 // a previously-v12 peer to "legacy" credit-unconditionally.
8139 // Legacy / pre-v12 peers that have never sent a commitment
8140 // remain absent from the set and are credited via the
8141 // legacy path so mixed-version networks stay live.
8142 let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
8143 let map = last_commitment_by_peer.read().await;
8144 map.iter()
8145 // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
8146 // of every peer's ~5 KiB commitment.
8147 .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
8148 .collect()
8149 };
8150 let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
8151 // Take a full snapshot of recent_provers under the read lock,
8152 // then release. The cache is bounded (16/key × keys), so the
8153 // clone is cheap.
8154 let provers_snapshot = recent_provers.read().await.clone();
8155 // For the replica-fetch path, we need to know whether THIS
8156 // node already holds the key being verified. The v12 §6
8157 // holder-credit gate is meant to prevent uncredited Present
8158 // claims from contributing to paid-list / reward quorum for
8159 // keys we DO hold (and could audit ourselves). For keys we
8160 // are trying to FETCH (i.e. not in local storage), there is
8161 // no possible local audit credit, and gating the presence
8162 // quorum on credit would deadlock replica-repair in a
8163 // fully v12-capable close group.
8164 let mut locally_held: HashSet<XorName> = HashSet::new();
8165 for key in &keys_needing_network {
8166 if storage.exists(key).unwrap_or(false) {
8167 locally_held.insert(*key);
8168 }
8169 }
8170 let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
8171 if !locally_held.contains(key) {
8172 // Replica-fetch path: we don't hold this key, so we
8173 // cannot have collected audit credit for it. Trust
8174 // Present claims to drive fetch-source promotion;
8175 // chunk-PUT payment_verifier is the security backstop
8176 // when the bytes actually arrive.
8177 return true;
8178 }
8179 if !capable_peer_snapshot.contains(peer) {
8180 // Pre-v12 / legacy peer that has never gossiped a
8181 // commitment. The v12 §6 holder-eligibility check
8182 // doesn't apply: their Present evidence comes through
8183 // the legacy path and we credit it unconditionally
8184 // so a mixed-version network stays live during
8185 // transition.
8186 return true;
8187 }
8188 let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
8189 // Peer is commitment_capable (sticky) but currently
8190 // has no live commitment record on file (e.g. their
8191 // last gossip was evicted from the LRU cache, or it
8192 // failed verification). Withhold credit until they
8193 // re-prove storage under a fresh commitment.
8194 return false;
8195 };
8196 provers_snapshot.is_credited_holder(key, peer, hash)
8197 };
8198
8199 let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
8200 {
8201 let q = queues.read().await;
8202 for key in &keys_needing_network {
8203 let Some(ev) = evidence.get(key) else {
8204 continue;
8205 };
8206 if q.get_pending(key).is_none() {
8207 continue;
8208 }
8209 let outcome = quorum::evaluate_key_evidence_with_holder_check(
8210 key,
8211 ev,
8212 &targets,
8213 config,
8214 holder_credit,
8215 );
8216 evaluated.push((*key, outcome));
8217 }
8218 } // read lock released
8219
8220 // Step 4: Insert verified keys into PaidForList (no lock held).
8221 let mut paid_insert_keys: Vec<XorName> = Vec::new();
8222 for (key, outcome) in &evaluated {
8223 if matches!(
8224 outcome,
8225 KeyVerificationOutcome::QuorumVerified { .. }
8226 | KeyVerificationOutcome::PaidListVerified { .. }
8227 ) {
8228 paid_insert_keys.push(*key);
8229 }
8230 }
8231 for key in &paid_insert_keys {
8232 if let Err(e) = paid_list.insert(key).await {
8233 warn!("Failed to add verified key to PaidForList: {e}");
8234 }
8235 }
8236
8237 // Verification established validity; the paid-list insert above records
8238 // it. Downloading the bytes is a separate duty, owed only by the
8239 // storage-admission group, asked on the same terms for every verified
8240 // key — the advertising peer's replica/paid labelling is a claim about
8241 // itself and carries no authority over what we store. This check is a
8242 // cheap pre-filter that keeps never-responsible keys out of the fetch
8243 // queue entirely; the authoritative gate is the per-attempt recheck in
8244 // `execute_single_fetch`, because a key can wait in the nearest-first
8245 // fetch queue long enough for this promotion-time answer to go stale.
8246 let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
8247 for (key, outcome) in &evaluated {
8248 if matches!(
8249 outcome,
8250 KeyVerificationOutcome::QuorumVerified { .. }
8251 | KeyVerificationOutcome::PaidListVerified { .. }
8252 ) && !storage.exists(key).unwrap_or(false)
8253 && is_storage_admitted(&self_id, key, p2p_node, config).await
8254 {
8255 fetch_allowed_keys.insert(*key);
8256 }
8257 }
8258
8259 // Step 5: Update queues with the evaluated outcomes.
8260 let mut bad_singleton_hints: HashMap<(PeerId, SingletonHintFault), usize> = HashMap::new();
8261 let mut q = queues.write().await;
8262 for (key, outcome) in evaluated {
8263 let replica_hint_sources = q
8264 .get_pending(&key)
8265 .map(|entry| entry.replica_hint_sources.clone())
8266 .unwrap_or_default();
8267 if let Some(ev) = evidence.get(&key) {
8268 if let Some(source) =
8269 punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
8270 {
8271 *bad_singleton_hints.entry(source).or_insert(0) += 1;
8272 }
8273 }
8274 match outcome {
8275 KeyVerificationOutcome::QuorumVerified { sources }
8276 | KeyVerificationOutcome::PaidListVerified { sources } => {
8277 let mut fetch_sources = sources;
8278 add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
8279 let fetch_eligible = fetch_allowed_keys.contains(&key);
8280 if fetch_eligible && write_blocked {
8281 // Capacity gate, second of two, and deliberately after
8282 // Step 4: the key is now recorded in `PaidForList` and
8283 // its verification stands. Only the download is held,
8284 // because `execute_single_fetch` would refuse it and
8285 // hand the key straight back here.
8286 if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8287 capacity_deferred_promote += 1;
8288 }
8289 } else if fetch_eligible && !fetch_sources.is_empty() {
8290 // A holder answered; see the matching clear on the
8291 // local-paid path.
8292 q.clear_unresolved(&key);
8293 let distance =
8294 crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8295 // Atomic remove+enqueue: on fetch_queue capacity miss
8296 // the pending entry is preserved so this verified key
8297 // is retried on the next cycle (no silent drop).
8298 let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
8299 // Not terminal — either moved to fetch queue, or
8300 // retained as pending until queue drains.
8301 } else if fetch_eligible && fetch_sources.is_empty() {
8302 no_holder_deferrals += 1;
8303 let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8304 let first_report = q.claim_no_holder_report(&key);
8305 report_unresolved_deferral(
8306 "Verified storage-admitted key",
8307 &key,
8308 outcome,
8309 first_report,
8310 );
8311 } else {
8312 q.remove_pending(&key);
8313 terminal_keys.push(key);
8314 }
8315 }
8316 KeyVerificationOutcome::QuorumFailed => {
8317 q.remove_pending(&key);
8318 terminal_keys.push(key);
8319 }
8320 KeyVerificationOutcome::QuorumInconclusive => {
8321 q.set_pending_state(&key, VerificationState::QuorumInconclusive);
8322 // Backed off like any other unresolved round, but it does
8323 // NOT claim the no-holder report: nothing yet says this key
8324 // has no holder, so the first round that does say so must
8325 // still be the one that warns.
8326 let _ = q.defer_unresolved(&key, config.verification_request_timeout);
8327 }
8328 }
8329 }
8330 drop(q);
8331
8332 for ((peer, fault), bad_hint_count) in bad_singleton_hints {
8333 let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
8334 warn!(
8335 "Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
8336 sole-source replica hints ({fault:?}); \
8337 reporting {reports} bounded trust failure(s)"
8338 );
8339 for _ in 0..reports {
8340 match fault {
8341 // A claim about a key that does not exist. Punishable whatever the
8342 // sender's disk is doing.
8343 SingletonHintFault::RejectedByCloseGroup => {
8344 p2p_node
8345 .report_trust_event(
8346 &peer,
8347 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8348 )
8349 .await;
8350 }
8351 // "I advertised it and no longer have it." That is the one statement a
8352 // node short of disk cannot avoid making while it moves its chunks, so
8353 // it goes through the release switch.
8354 SingletonHintFault::DeniedPossession => {
8355 config::penalise_unheld_close_group_chunk(
8356 p2p_node,
8357 &peer,
8358 "replica_hint_denied_possession",
8359 REPLICATION_TRUST_WEIGHT,
8360 )
8361 .await;
8362 }
8363 }
8364 }
8365 }
8366 }
8367
8368 // Step 6: Remove terminal keys from bootstrap pending set and re-check
8369 // the drain condition.
8370 update_bootstrap_after_verification(
8371 &terminal_keys,
8372 bootstrap_state,
8373 queues,
8374 is_bootstrapping,
8375 bootstrap_complete_notify,
8376 )
8377 .await;
8378
8379 let (pending_after, fetch_after, in_flight_after) = {
8380 let q = queues.read().await;
8381 (
8382 q.pending_count(),
8383 q.fetch_queue_count(),
8384 q.in_flight_count(),
8385 )
8386 };
8387 let terminal_key_count = terminal_keys.len();
8388 let elapsed_ms = cycle_started.elapsed().as_millis();
8389
8390 if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
8391 info!(
8392 target: "ant_node::replication::verification",
8393 "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}",
8394 );
8395 } else {
8396 debug!(
8397 target: "ant_node::replication::verification",
8398 "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}",
8399 );
8400 }
8401}
8402
8403/// Report a verification round that left a key without a usable holder.
8404///
8405/// Warns once per entry — the first failure is news, and by the hundredth the
8406/// node is re-asking peers it has already exhausted. Later failures stay at
8407/// `debug`, and the per-cycle count is carried in the cycle summary so the
8408/// scale of a backlog is still visible without a line per key per retry.
8409///
8410/// `first_report` comes from `claim_no_holder_report`, not from the attempt
8411/// number: a round may advance the count without producing a no-holder result,
8412/// and such a round must not consume the warning.
8413///
8414/// Eviction at `PENDING_VERIFY_MAX_AGE` drops the entry, and a round that finds
8415/// a holder clears it, so a later relapse warns again: "once per episode", not
8416/// "once ever".
8417fn report_unresolved_deferral(
8418 what: &str,
8419 key: &XorName,
8420 outcome: Option<DeferralOutcome>,
8421 first_report: bool,
8422) {
8423 let Some(outcome) = outcome else {
8424 // The entry left `pending_verify` under the same lock; nothing deferred.
8425 return;
8426 };
8427 if first_report {
8428 warn!(
8429 "{what} {} has no responding holders yet; deferring retry",
8430 hex::encode(key)
8431 );
8432 } else {
8433 debug!(
8434 "{what} {} still has no responding holders after {} attempts; \
8435 retrying in {}s",
8436 hex::encode(key),
8437 outcome.attempt,
8438 outcome.retry_after.as_secs()
8439 );
8440 }
8441}
8442
8443/// Add peers that claimed possession as fallback fetch sources.
8444///
8445/// Paid-only advertisers make no possession claim and are absent from
8446/// `replica_hint_sources` by construction, so they are never added.
8447fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
8448 for source in replica_hint_sources {
8449 if !sources.contains(source) {
8450 sources.push(*source);
8451 }
8452 }
8453}
8454
8455/// Why a sole-source replica hint is punishable.
8456///
8457/// The two cases look alike and are not. A hint the close group rejects outright is a
8458/// claim about a key that does not exist, which is a bad hint however the sender's disk is
8459/// doing. A sender that advertised a key and then answers `Absent` for it is making a
8460/// statement about its own storage, and that is the one thing a node short of disk cannot
8461/// avoid saying while it moves its chunks out of a store that will not give the space back.
8462#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8463enum SingletonHintFault {
8464 /// The close group says the key does not exist.
8465 RejectedByCloseGroup,
8466 /// The sender advertised the key and then denied holding it.
8467 DeniedPossession,
8468}
8469
8470/// Return the sole replica advertiser when either the close group definitively
8471/// rejects the key or the advertiser explicitly denies possessing it, and say which.
8472/// Paid-only advertisements, corroborated replica hints, and inconclusive
8473/// rounds without that direct contradiction are deliberately non-penalizing.
8474fn punishable_singleton_replica_hint_source(
8475 replica_hint_sources: &HashSet<PeerId>,
8476 outcome: &KeyVerificationOutcome,
8477 evidence: &crate::replication::types::KeyVerificationEvidence,
8478) -> Option<(PeerId, SingletonHintFault)> {
8479 // A paid-only advertiser leaves this set empty, so the sole-source lane is
8480 // reserved for peers that actually claimed possession.
8481 if replica_hint_sources.len() != 1 {
8482 return None;
8483 }
8484 let source = *replica_hint_sources.iter().next()?;
8485 if matches!(outcome, KeyVerificationOutcome::QuorumFailed) {
8486 return Some((source, SingletonHintFault::RejectedByCloseGroup));
8487 }
8488 if evidence.presence.get(&source) == Some(&PresenceEvidence::Absent) {
8489 return Some((source, SingletonHintFault::DeniedPossession));
8490 }
8491 None
8492}
8493
8494/// Post-verification bootstrap bookkeeping: remove terminal keys from the
8495/// bootstrap pending set and transition out of bootstrapping when drained.
8496async fn update_bootstrap_after_verification(
8497 terminal_keys: &[XorName],
8498 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8499 queues: &Arc<RwLock<ReplicationQueues>>,
8500 is_bootstrapping: &Arc<RwLock<bool>>,
8501 bootstrap_complete_notify: &Arc<Notify>,
8502) {
8503 if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
8504 return;
8505 }
8506 {
8507 let mut bs = bootstrap_state.write().await;
8508 for key in terminal_keys {
8509 bs.remove_key(key);
8510 }
8511 }
8512 let q = queues.read().await;
8513 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8514 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8515 }
8516}
8517
8518/// Retire bootstrap work owed by a peer that permanently left the routing
8519/// table, then immediately re-check drain so this removal can complete
8520/// bootstrap without waiting for an unrelated pipeline event.
8521async fn update_bootstrap_after_peer_removed(
8522 peer: &PeerId,
8523 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8524 queues: &Arc<RwLock<ReplicationQueues>>,
8525 is_bootstrapping: &Arc<RwLock<bool>>,
8526 bootstrap_complete_notify: &Arc<Notify>,
8527) {
8528 let orphaned_keys = queues.write().await.remove_hint_source(peer);
8529 let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
8530
8531 if !orphaned_keys.is_empty() {
8532 let mut state = bootstrap_state.write().await;
8533 for key in &orphaned_keys {
8534 state.remove_key(key);
8535 }
8536 }
8537
8538 if orphaned_keys.is_empty() && !cleared_rejection {
8539 return;
8540 }
8541 let q = queues.read().await;
8542 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8543 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8544 }
8545}
8546
8547/// Periodic bootstrap-drain self-healing, run on every verification worker
8548/// tick until bootstrap drains.
8549///
8550/// Two liveness gaps make this necessary. A `PeerRemoved` that races the
8551/// recording of a capacity rejection leaves an entry no future event can
8552/// clear — `max_age` expiry is its only exit. And a clean-cycle
8553/// `clear_capacity_rejected` never triggers its own drain re-check, so on a
8554/// quiet node the drain condition can become true with nothing left to
8555/// observe it. Expiry must run even while `pending_peer_requests` blocks the
8556/// drain itself, so this is invoked before `run_verification_cycle`'s
8557/// early-returns.
8558async fn expire_and_recheck_bootstrap_drain(
8559 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8560 queues: &Arc<RwLock<ReplicationQueues>>,
8561 is_bootstrapping: &Arc<RwLock<bool>>,
8562 bootstrap_complete_notify: &Arc<Notify>,
8563 max_age: Duration,
8564) {
8565 if bootstrap_state.read().await.is_drained() {
8566 return;
8567 }
8568 bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
8569 let q = queues.read().await;
8570 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8571 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8572 }
8573}
8574
8575/// Set `is_bootstrapping` to `false` and wake all waiters.
8576async fn complete_bootstrap(
8577 is_bootstrapping: &Arc<RwLock<bool>>,
8578 bootstrap_complete_notify: &Arc<Notify>,
8579) {
8580 *is_bootstrapping.write().await = false;
8581 bootstrap_complete_notify.notify_waiters();
8582 info!("Replication bootstrap complete");
8583}
8584
8585// ---------------------------------------------------------------------------
8586// Fetch types and single-fetch executor
8587// ---------------------------------------------------------------------------
8588
8589/// Result classification for a single fetch attempt.
8590enum FetchResult {
8591 /// Data fetched, integrity-checked, and stored successfully.
8592 Stored,
8593 /// Content-address integrity check failed — do not retry.
8594 IntegrityFailed,
8595 /// Source failed (network error or non-success response) — retryable.
8596 SourceFailed,
8597 /// This node could not write the chunk locally: the capacity pre-check
8598 /// refused before the dial, or `put` failed after the bytes arrived.
8599 ///
8600 /// Distinct from [`Self::SourceFailed`] because nothing about the source
8601 /// is implicated, and because the remedy is the opposite one. A source
8602 /// failure should move on to the next holder; a local write failure must
8603 /// not — every remaining source would send the same chunk into the same
8604 /// full disk. The key returns to verification instead, so a later cycle
8605 /// retries it once local capacity allows. That is a retry path, not a
8606 /// liveness guarantee: `evict_stale` still expires the entry at
8607 /// `PENDING_VERIFY_MAX_AGE` measured from when it was first queued, after
8608 /// which re-acquisition depends on a fresh hint.
8609 LocalWriteFailed,
8610 /// This node already holds the key, so there is nothing to fetch —
8611 /// terminal, exactly like [`Self::Stored`], because the duty is already
8612 /// discharged.
8613 ///
8614 /// Responsibility is rechecked at download time; possession has to be too.
8615 /// The earlier gates already drop held keys out of the fetch pipeline —
8616 /// `queue_admitted_hints` skips them, and the promotion-time
8617 /// `fetch_allowed_keys` filter and the local-paid probe both terminate
8618 /// them. (`is_relevant` is not one of them: possession there makes a key
8619 /// *relevant*, which is what keeps us tracking it.) So a held key reaches
8620 /// the dial only when it arrived *after* promotion — a fresh-offer push, a
8621 /// client PUT, or another source landing first. The nearest-first fetch
8622 /// queue is deep enough for that window to be real.
8623 ///
8624 /// This check must also precede the capacity pre-check below, because
8625 /// `LmdbStorage::put` tests `exists` *before* it tests disk space: without
8626 /// it, a full node would decline a key it already holds, which `put` would
8627 /// have accepted as a duplicate.
8628 AlreadyHeld,
8629 /// Live routing state no longer places this node in the storage-admission
8630 /// group for the key — terminal, exactly like [`Self::Stored`]. The duty
8631 /// the fetch was serving has lapsed, so no alternate source is tried and
8632 /// no trust event is reported: the source did nothing wrong.
8633 NoLongerResponsible,
8634}
8635
8636/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
8637/// worker loop to update queue state.
8638struct FetchOutcome {
8639 key: XorName,
8640 result: FetchResult,
8641}
8642
8643/// What the fetch worker must do next for a key whose fetch attempt resolved.
8644#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8645enum FetchFollowUp {
8646 /// The key terminally left the fetch pipeline (its in-flight entry is
8647 /// removed and any verification retry-slot reservation released); the
8648 /// caller must run bootstrap accounting for it.
8649 Terminal,
8650 /// The key returned to `pending_verify` for a later verification round.
8651 RequeuedForVerification,
8652 /// Retry immediately from this next untried verified source.
8653 RetryFrom(PeerId),
8654}
8655
8656/// Apply a resolved [`FetchResult`] to the queues and report the follow-up.
8657///
8658/// Split out of the fetch-worker loop so the per-variant queue transitions
8659/// are unit-testable without a live network. The caller holds the queues
8660/// write lock. [`FetchResult::NoLongerResponsible`] deliberately shares
8661/// [`FetchResult::Stored`]'s terminal path: `complete_fetch` releases the
8662/// retry-slot reservation, and the caller's terminal handling shrinks the
8663/// bootstrap pending set — dropping the key without that accounting would
8664/// stall bootstrap drain forever.
8665///
8666/// The nursery `option_if_let_else` rewrite is impossible here: both
8667/// `map_or_else` closures would need `&mut *q` simultaneously.
8668#[allow(clippy::option_if_let_else)]
8669fn apply_fetch_result(
8670 q: &mut ReplicationQueues,
8671 key: &XorName,
8672 result: &FetchResult,
8673 verification_retry_after: Duration,
8674) -> FetchFollowUp {
8675 match result {
8676 FetchResult::Stored | FetchResult::NoLongerResponsible | FetchResult::AlreadyHeld => {
8677 q.complete_fetch(key);
8678 FetchFollowUp::Terminal
8679 }
8680 FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
8681 if let Some(next_peer) = q.retry_fetch(key) {
8682 FetchFollowUp::RetryFrom(next_peer)
8683 } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
8684 FetchFollowUp::RequeuedForVerification
8685 } else {
8686 FetchFollowUp::Terminal
8687 }
8688 }
8689 // No `retry_fetch`: the local write is what failed, so every other
8690 // source would be asked to send the same chunk into the same full
8691 // disk. Requeueing for verification is what keeps the key from being
8692 // stranded — it comes back once capacity allows — and the fallthrough
8693 // to `Terminal` when there is no retry metadata is what keeps
8694 // bootstrap drain accounting correct, exactly as for a source failure.
8695 //
8696 // The ordinary requeue delay, deliberately. A standing capacity block
8697 // does not need a longer one here: the key returns to pending, and the
8698 // gate at the head of the next cycle defers it for minutes. A separate
8699 // backoff on this path would duplicate that to save one 15 s round, on
8700 // a race the gate already makes rare.
8701 FetchResult::LocalWriteFailed => {
8702 if q.requeue_fetch_for_verification(key, verification_retry_after) {
8703 FetchFollowUp::RequeuedForVerification
8704 } else {
8705 FetchFollowUp::Terminal
8706 }
8707 }
8708 }
8709}
8710
8711/// Whether this node currently sits inside the storage-admission group for
8712/// `key`, per live local routing state.
8713///
8714/// This is the one question every storage decision in this module asks; see
8715/// [`admission::is_responsible`]. A purely local routing-table lookup — no
8716/// network I/O — but it awaits into the DHT manager, so callers must not
8717/// hold the queues lock across it.
8718async fn is_storage_admitted(
8719 self_id: &PeerId,
8720 key: &XorName,
8721 p2p_node: &Arc<P2PNode>,
8722 config: &ReplicationConfig,
8723) -> bool {
8724 admission::is_responsible(
8725 self_id,
8726 key,
8727 p2p_node,
8728 storage_admission_width(config.close_group_size),
8729 )
8730 .await
8731}
8732
8733#[allow(clippy::too_many_lines)]
8734/// Execute a single fetch request against `source` for `key`.
8735///
8736/// Handles encoding, network I/O, integrity checking, storage, and trust
8737/// event reporting. Returns a [`FetchOutcome`] so the caller can update
8738/// queue state without holding any locks during the network round-trip.
8739///
8740/// This is the authoritative storage-responsibility gate: each attempt —
8741/// including every per-source retry, which re-enters here — rechecks live
8742/// routing state before spending bandwidth, and once more before writing
8743/// bytes that arrived after a round-trip. The verification-time check that
8744/// promoted the key into the fetch queue is only a pre-filter; the queue is
8745/// nearest-first and deep, so a promotion decision can go stale under
8746/// topology churn before the key is ever dequeued.
8747async fn execute_single_fetch(
8748 p2p_node: Arc<P2PNode>,
8749 storage: Arc<LmdbStorage>,
8750 config: Arc<ReplicationConfig>,
8751 key: XorName,
8752 source: PeerId,
8753) -> FetchOutcome {
8754 let self_id = *p2p_node.peer_id();
8755 if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8756 debug!(
8757 "Skipping fetch for {}: no longer in the storage-admission group",
8758 hex::encode(key)
8759 );
8760 return FetchOutcome {
8761 key,
8762 result: FetchResult::NoLongerResponsible,
8763 };
8764 }
8765
8766 // Possession, then capacity — both before the dial, and in that order.
8767 //
8768 // `LmdbStorage::put` tests `exists` before it tests disk space, so a full
8769 // node still accepts a key it already holds. Checking possession first is
8770 // what keeps this pair of gates from declining work `put` would have
8771 // taken.
8772 if storage.exists(&key).unwrap_or(false) {
8773 debug!(
8774 "Skipping fetch for {}: already held locally",
8775 hex::encode(key)
8776 );
8777 return FetchOutcome {
8778 key,
8779 result: FetchResult::AlreadyHeld,
8780 };
8781 }
8782
8783 // Capacity is checked before the dial rather than after the bytes arrive.
8784 // `put` runs this same check on every write of a key it does not already
8785 // hold, so this reaches the same verdict `put` would reach *at this
8786 // instant*. It is not a guarantee about the later write: both answers can
8787 // change across the round trip. Space freed in between would have let a
8788 // post-download `put` succeed, so a refusal here can cost a fleeting
8789 // acquisition and one retry cycle of delay; space lost in between is why
8790 // the check inside `put` still has to stay.
8791 //
8792 // What it buys is that the refusal costs no bandwidth. Without it a
8793 // disk-full node pulls the whole chunk over the network first, and the
8794 // failure is then classified as the source's — no trust event, but the
8795 // worker walks to every remaining holder, and each re-uploads the same
8796 // chunk into the same full disk.
8797 if let Err(e) = storage.check_capacity() {
8798 debug!(
8799 "Skipping fetch for {}: local storage cannot accept a write: {e}",
8800 hex::encode(key)
8801 );
8802 return FetchOutcome {
8803 key,
8804 result: FetchResult::LocalWriteFailed,
8805 };
8806 }
8807
8808 let request = protocol::FetchRequest { key };
8809 let msg = ReplicationMessage {
8810 request_id: rand::thread_rng().gen::<u64>(),
8811 body: ReplicationMessageBody::FetchRequest(request),
8812 };
8813
8814 let encoded = match msg.encode() {
8815 Ok(data) => data,
8816 Err(e) => {
8817 warn!("Failed to encode fetch request: {e}");
8818 return FetchOutcome {
8819 key,
8820 result: FetchResult::SourceFailed,
8821 };
8822 }
8823 };
8824
8825 let result = p2p_node
8826 .send_request(
8827 &source,
8828 REPLICATION_PROTOCOL_ID,
8829 encoded,
8830 config.fetch_request_timeout,
8831 )
8832 .await;
8833
8834 match result {
8835 Ok(response) => {
8836 let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
8837 p2p_node
8838 .report_trust_event(
8839 &source,
8840 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8841 )
8842 .await;
8843 return FetchOutcome {
8844 key,
8845 result: FetchResult::SourceFailed,
8846 };
8847 };
8848
8849 match resp_msg.body {
8850 ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
8851 key: resp_key,
8852 data,
8853 }) => {
8854 // Validate the response key matches the requested key.
8855 // A malicious peer could serve valid data for a different
8856 // key, passing integrity checks while the requested key
8857 // is falsely marked as fetched.
8858 if resp_key != key {
8859 warn!(
8860 "Fetch response key mismatch: requested {}, got {}",
8861 hex::encode(key),
8862 hex::encode(resp_key)
8863 );
8864 p2p_node
8865 .report_trust_event(
8866 &source,
8867 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8868 )
8869 .await;
8870 return FetchOutcome {
8871 key,
8872 result: FetchResult::IntegrityFailed,
8873 };
8874 }
8875
8876 // Enforce chunk size invariant on fetched data.
8877 // Checked before the content-address hash to avoid
8878 // hashing up to 10 MiB of oversized junk data.
8879 if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
8880 warn!(
8881 "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
8882 hex::encode(resp_key),
8883 data.len(),
8884 crate::ant_protocol::MAX_CHUNK_SIZE,
8885 );
8886 p2p_node
8887 .report_trust_event(
8888 &source,
8889 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8890 )
8891 .await;
8892 return FetchOutcome {
8893 key,
8894 result: FetchResult::IntegrityFailed,
8895 };
8896 }
8897
8898 // Content-address integrity check.
8899 let computed = crate::client::compute_address(&data);
8900 if computed != resp_key {
8901 warn!(
8902 "Fetched record integrity check failed: expected {}, got {}",
8903 hex::encode(resp_key),
8904 hex::encode(computed)
8905 );
8906 p2p_node
8907 .report_trust_event(
8908 &source,
8909 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8910 )
8911 .await;
8912 return FetchOutcome {
8913 key,
8914 result: FetchResult::IntegrityFailed,
8915 };
8916 }
8917
8918 // Responsibility can lapse during the network round-trip.
8919 // The bandwidth is already spent; declining the write is
8920 // what still avoids the disk write and the later
8921 // fetch→store→prune churn. Edge flapping is dampened by
8922 // the margin `storage_admission_width` adds over
8923 // `close_group_size`.
8924 if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8925 debug!(
8926 "Fetched {} but responsibility lapsed in transit; not storing",
8927 hex::encode(key)
8928 );
8929 return FetchOutcome {
8930 key,
8931 result: FetchResult::NoLongerResponsible,
8932 };
8933 }
8934
8935 if let Err(e) = storage.put(&resp_key, &data).await {
8936 // The bytes arrived and passed the content-address
8937 // check, so the source did its job; the failure is
8938 // entirely local (disk-full, or an LMDB error). Any
8939 // valid source must serve identical content, so trying
8940 // the next one cannot cure a local error — it only
8941 // re-downloads the same chunk into the same store.
8942 warn!(
8943 "Failed to store fetched record {}: {e}",
8944 hex::encode(resp_key)
8945 );
8946 return FetchOutcome {
8947 key,
8948 result: FetchResult::LocalWriteFailed,
8949 };
8950 }
8951
8952 FetchOutcome {
8953 key,
8954 result: FetchResult::Stored,
8955 }
8956 }
8957 ReplicationMessageBody::FetchResponse(
8958 ref response @ (protocol::FetchResponse::NotFound { .. }
8959 | protocol::FetchResponse::Error { .. }),
8960 ) => {
8961 // This peer was selected as a fetch source because it recently
8962 // answered `Present` during verification, so either answer is
8963 // evidence of something. Which one decides what it is charged: a peer
8964 // that does not hold the chunk is the lane this release withholds, a
8965 // peer whose own read failed is not.
8966 if let protocol::FetchResponse::Error { reason, .. } = response {
8967 warn!(
8968 "Fetch: peer {source} returned error for {}: {reason}",
8969 hex::encode(key)
8970 );
8971 } else {
8972 warn!(
8973 "Fetch: verified source {source} returned NotFound for {}",
8974 hex::encode(key)
8975 );
8976 }
8977 if let Some(fault) = fetch_fault_for(response) {
8978 let lane = match fault {
8979 FetchFault::UnheldChunk => "fetch_not_found",
8980 FetchFault::ResponderFault => "fetch_error",
8981 };
8982 charge_fetch_fault(&p2p_node, &source, fault, lane).await;
8983 }
8984 FetchOutcome {
8985 key,
8986 result: FetchResult::SourceFailed,
8987 }
8988 }
8989 _ => {
8990 // Unexpected message type — treat as malformed.
8991 p2p_node
8992 .report_trust_event(
8993 &source,
8994 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8995 )
8996 .await;
8997 FetchOutcome {
8998 key,
8999 result: FetchResult::SourceFailed,
9000 }
9001 }
9002 }
9003 }
9004 Err(e) => {
9005 debug!("Fetch request to {source} failed: {e}");
9006 // No ApplicationFailure here — P2PNode::send_request() already
9007 // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
9008 FetchOutcome {
9009 key,
9010 result: FetchResult::SourceFailed,
9011 }
9012 }
9013 }
9014}
9015
9016// ---------------------------------------------------------------------------
9017// Audit result handler
9018// ---------------------------------------------------------------------------
9019
9020/// Format the first confirmed-failed key as a 16-hex-char label.
9021///
9022/// Pairs with `challenged_peer` to form a stable cross-host correlation
9023/// handle in the audit-failure log line, e.g.
9024///
9025/// ```text
9026/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
9027/// ```
9028///
9029/// Falls back to `"0x"` when the list is empty so the log line never
9030/// contains a misleading default.
9031fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
9032 confirmed_failed_keys.first().map_or_else(
9033 || "0x".to_string(),
9034 |k| format!("0x{}", hex::encode(&k[..8])),
9035 )
9036}
9037
9038/// Execute the side effects for a subtree storage-commitment audit failure.
9039///
9040/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
9041/// legitimately time out on slow or loaded honest peers, so it never touches the
9042/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
9043/// failures still penalise immediately and revoke holder credit.
9044async fn handle_subtree_failed_audit(
9045 challenged_peer: &PeerId,
9046 confirmed_failed_key_count: usize,
9047 reason: &AuditFailureReason,
9048 p2p_node: &Arc<P2PNode>,
9049 sync_state: &Arc<RwLock<NeighborSyncState>>,
9050 recent_provers: &Arc<RwLock<RecentProvers>>,
9051) {
9052 if matches!(reason, AuditFailureReason::Timeout) {
9053 debug!(
9054 "Audit timeout for {challenged_peer} fully graced \
9055 (subtree audit does not evict on timeout)"
9056 );
9057 return;
9058 }
9059
9060 // The caller already logged the rich failure line with reason + per-category
9061 // summary; avoid a redundant second error log here.
9062 let _ = confirmed_failed_key_count;
9063 {
9064 let mut state = sync_state.write().await;
9065 state.clear_active_bootstrap_claim(challenged_peer);
9066 }
9067 {
9068 let mut provers_guard = recent_provers.write().await;
9069 apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
9070 }
9071 // Deliberately NOT routed through the release switch. This is the commitment-bound
9072 // subtree audit: the peer published a signed claim to hold these keys and could not
9073 // answer for them. That contract is enforced in every release, including the one that
9074 // withholds the penalty for merely not holding a close-group chunk.
9075 p2p_node
9076 .report_trust_event(
9077 challenged_peer,
9078 TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
9079 )
9080 .await;
9081}
9082
9083/// Handle audit result: log findings and emit trust events.
9084async fn handle_subtree_audit_result(
9085 result: &AuditTickResult,
9086 p2p_node: &Arc<P2PNode>,
9087 sync_state: &Arc<RwLock<NeighborSyncState>>,
9088 recent_provers: &Arc<RwLock<RecentProvers>>,
9089 config: &ReplicationConfig,
9090) {
9091 match result {
9092 AuditTickResult::Passed {
9093 challenged_peer,
9094 keys_checked,
9095 } => {
9096 protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
9097 debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9098 // Peer responded normally — clear the active bootstrap claim while
9099 // retaining history so a later claim is treated as repeated abuse.
9100 {
9101 let mut state = sync_state.write().await;
9102 state.clear_active_bootstrap_claim(challenged_peer);
9103 }
9104 p2p_node
9105 .report_trust_event(
9106 challenged_peer,
9107 TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9108 )
9109 .await;
9110 }
9111 AuditTickResult::Failed {
9112 evidence,
9113 no_response_class,
9114 } => {
9115 if let FailureEvidence::AuditFailure {
9116 challenged_peer,
9117 confirmed_failed_keys,
9118 summary,
9119 reason,
9120 ..
9121 } = evidence
9122 {
9123 protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
9124 // Rich diagnostics (from main's audit-failure logging) + the
9125 // first-failed-key correlation handle.
9126 let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9127 let audit_failure_class = no_response_class.unwrap_or("confirmed");
9128 error!(
9129 "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}",
9130 audit_failure_class,
9131 confirmed_failed_keys.len(),
9132 summary.challenged_keys,
9133 summary.absent_keys,
9134 summary.digest_mismatch_keys,
9135 );
9136 // Route the side effects through the subtree-only failure path.
9137 // Responsible-chunk `AuditChallenge` handling intentionally uses
9138 // its own old immediate-penalty handler below.
9139 handle_subtree_failed_audit(
9140 challenged_peer,
9141 confirmed_failed_keys.len(),
9142 reason,
9143 p2p_node,
9144 sync_state,
9145 recent_provers,
9146 )
9147 .await;
9148 }
9149 }
9150 AuditTickResult::BootstrapClaim { peer } => {
9151 // Gap 6: BootstrapClaimAbuse grace period in audit path.
9152 // Separate state mutation from network I/O to avoid holding the
9153 // write lock across report_trust_event.
9154 let should_report = {
9155 let now = Instant::now();
9156 let mut state = sync_state.write().await;
9157 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9158 {
9159 BootstrapClaimObservation::WithinGrace { .. } => {
9160 debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9161 false
9162 }
9163 BootstrapClaimObservation::PastGrace { first_seen } => {
9164 warn!(
9165 "Audit: peer {peer} claiming bootstrap past grace period \
9166 ({:?} > {:?}), reporting abuse",
9167 now.duration_since(first_seen),
9168 config.bootstrap_claim_grace_period,
9169 );
9170 true
9171 }
9172 BootstrapClaimObservation::Repeated { first_seen } => {
9173 warn!(
9174 "Audit: peer {peer} repeated bootstrap claim after previously \
9175 stopping; first claim was {:?} ago, reporting abuse",
9176 now.duration_since(first_seen),
9177 );
9178 true
9179 }
9180 }
9181 };
9182 if should_report {
9183 p2p_node
9184 .report_trust_event(
9185 peer,
9186 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9187 )
9188 .await;
9189 }
9190 }
9191 AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9192 }
9193}
9194
9195/// Whether a confirmed audit failure with this reason clears the peer's active
9196/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
9197/// bootstrapping); every confirmed storage-integrity reason does.
9198///
9199/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
9200/// the bootstrap claim, matching the pre-ADR-0002 behaviour, while every failure
9201/// still reports the normal audit trust penalty.
9202fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
9203 !matches!(reason, AuditFailureReason::Timeout)
9204}
9205
9206/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
9207/// events and manage bootstrap-claim state.
9208///
9209/// This is intentionally separate from the subtree audit result handler. A
9210/// responsible-chunk `AuditChallenge` `Failed` result reports
9211/// `ApplicationFailure` immediately for every reason, including `Timeout`,
9212/// restoring the pre-ADR-0002 behaviour.
9213#[allow(clippy::too_many_lines)]
9214async fn handle_audit_result(
9215 result: &AuditTickResult,
9216 p2p_node: &Arc<P2PNode>,
9217 sync_state: &Arc<RwLock<NeighborSyncState>>,
9218 config: &ReplicationConfig,
9219) {
9220 match result {
9221 AuditTickResult::Passed {
9222 challenged_peer,
9223 keys_checked,
9224 } => {
9225 protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
9226 debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9227 {
9228 let mut state = sync_state.write().await;
9229 state.clear_active_bootstrap_claim(challenged_peer);
9230 }
9231 p2p_node
9232 .report_trust_event(
9233 challenged_peer,
9234 TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9235 )
9236 .await;
9237 }
9238 AuditTickResult::Failed {
9239 evidence,
9240 no_response_class,
9241 } => {
9242 if let FailureEvidence::AuditFailure {
9243 challenged_peer,
9244 confirmed_failed_keys,
9245 summary,
9246 reason,
9247 ..
9248 } = evidence
9249 {
9250 protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
9251 let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9252 let audit_failure_class = no_response_class.unwrap_or("confirmed");
9253 error!(
9254 "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}",
9255 audit_failure_class,
9256 confirmed_failed_keys.len(),
9257 summary.challenged_keys,
9258 summary.absent_keys,
9259 summary.digest_mismatch_keys,
9260 );
9261 if audit_failure_clears_bootstrap_claim(reason) {
9262 let mut state = sync_state.write().await;
9263 state.clear_active_bootstrap_claim(challenged_peer);
9264 } else {
9265 debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
9266 }
9267 config::penalise_unheld_close_group_chunk(
9268 p2p_node,
9269 challenged_peer,
9270 crate::replication::audit_metrics::AuditType::ResponsibleChunk.as_str(),
9271 config::AUDIT_FAILURE_TRUST_WEIGHT,
9272 )
9273 .await;
9274 }
9275 }
9276 AuditTickResult::BootstrapClaim { peer } => {
9277 let should_report = {
9278 let now = Instant::now();
9279 let mut state = sync_state.write().await;
9280 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9281 {
9282 BootstrapClaimObservation::WithinGrace { .. } => {
9283 debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9284 false
9285 }
9286 BootstrapClaimObservation::PastGrace { first_seen } => {
9287 warn!(
9288 "Audit: peer {peer} claiming bootstrap past grace period \
9289 ({:?} > {:?}), reporting abuse",
9290 now.duration_since(first_seen),
9291 config.bootstrap_claim_grace_period,
9292 );
9293 true
9294 }
9295 BootstrapClaimObservation::Repeated { first_seen } => {
9296 warn!(
9297 "Audit: peer {peer} repeated bootstrap claim after previously \
9298 stopping; first claim was {:?} ago, reporting abuse",
9299 now.duration_since(first_seen),
9300 );
9301 true
9302 }
9303 }
9304 };
9305 if should_report {
9306 p2p_node
9307 .report_trust_event(
9308 peer,
9309 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9310 )
9311 .await;
9312 }
9313 }
9314 AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9315 }
9316}
9317
9318/// Whether a confirmed audit failure with this reason should revoke the
9319/// peer's `recent_provers` holder credit immediately (v12 §6).
9320///
9321/// `true` for any reason where the peer actually answered (or admitted
9322/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
9323/// bytes for committed key"), `MalformedResponse` — these prove the
9324/// peer no longer holds what it committed to, so it must not keep
9325/// holder credit for the proof TTL. `false` for `Timeout`: a single
9326/// dropped packet must not strip an honest peer; the 40-min TTL is the
9327/// deliberate liveness cushion there.
9328fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
9329 !matches!(reason, AuditFailureReason::Timeout)
9330}
9331
9332/// Apply the holder-credit revocation decision for a confirmed audit
9333/// failure. Pure over `RecentProvers` so the handler wiring is unit-
9334/// testable without a live `P2PNode`: the production `Failed` arm of
9335/// `handle_subtree_audit_result` calls exactly this.
9336fn apply_audit_failure_credit_revocation(
9337 provers: &mut RecentProvers,
9338 challenged_peer: &PeerId,
9339 reason: &AuditFailureReason,
9340) {
9341 if audit_failure_revokes_holder_credit(reason) {
9342 provers.forget_peer(challenged_peer);
9343 }
9344}
9345
9346// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
9347
9348// ---------------------------------------------------------------------------
9349// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
9350// ---------------------------------------------------------------------------
9351
9352/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
9353/// message handler passes one value instead of a long argument list; all
9354/// fields are cheap `Arc` clones.
9355#[derive(Clone)]
9356struct GossipAuditTrigger {
9357 p2p_node: Arc<P2PNode>,
9358 config: Arc<ReplicationConfig>,
9359 recent_provers: Arc<RwLock<RecentProvers>>,
9360 sync_state: Arc<RwLock<NeighborSyncState>>,
9361 /// Shared "an audit actually launched" cooldown, consulted by BOTH the
9362 /// gossip-lottery path and the monetized first-audit scheduler. Stamped
9363 /// only when a real audit is about to be sent — never by a losing lottery
9364 /// ticket — so gossip traffic alone can never suppress a paid first audit.
9365 cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
9366 detached_task_tracker: TaskTracker,
9367 /// Gossip-private lottery attempt window: stamped on every roll (win or
9368 /// lose) so a gossip flood cannot re-roll the lottery within the window.
9369 /// The first-audit scheduler never reads this map.
9370 lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
9371}
9372
9373/// What a gossip ingest yields for the audit trigger: the commitment hash to
9374/// pin and the `key_count` needed to size the response deadline from the actual
9375/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
9376/// or not) so a stable-keyset node stays auditable — not just on its first
9377/// commitment.
9378#[derive(Debug, Clone, Copy)]
9379struct AuditTarget {
9380 pin_hash: [u8; 32],
9381 key_count: u32,
9382}
9383
9384/// ADR-0004: a commitment that backed a payment, surfaced by the payment
9385/// verifier's cross-check so it can receive a **deterministic first audit**.
9386///
9387/// Sent from the verifier to the replication engine's first-audit drainer. The
9388/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
9389/// audits of the same peer revert to the gossip lottery), orders most-recently-
9390/// monetized first, and runs the same `run_subtree_audit` under the same
9391/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
9392#[derive(Debug, Clone, Copy)]
9393pub struct MonetizedPinEvent {
9394 /// The peer whose commitment backed the payment.
9395 pub peer: PeerId,
9396 /// The pinned commitment hash.
9397 pub pin: [u8; 32],
9398 /// The committed key count (sizes the audit deadline).
9399 pub key_count: u32,
9400 /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
9401 /// pin whose quote is older than the answerability window (ADR-0004 A1
9402 /// guardrail A): with grace removed, challenging an aged-out pin would
9403 /// false-convict, so a stale client-forwarded quote must not trigger an audit.
9404 pub quote_ts: SystemTime,
9405}
9406
9407/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
9408/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
9409/// stamps `now`), `false` if it was audited within
9410/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
9411/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
9412/// without a live node: a burst of gossips from one peer yields at most one
9413/// `true` per cooldown window.
9414fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9415 let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9416 let known = match map.get(peer) {
9417 Some(&last) => {
9418 if now.saturating_duration_since(last) < cooldown {
9419 return false;
9420 }
9421 true
9422 }
9423 None => false,
9424 };
9425 // Bound the map under churn like its siblings (drop the oldest stamp) before
9426 // admitting a brand-new peer.
9427 if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
9428 if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9429 map.remove(&victim);
9430 }
9431 }
9432 map.insert(*peer, now);
9433 true
9434}
9435
9436/// Read-only companion to [`cooldown_allows_audit`]: whether `peer` is OUTSIDE
9437/// its cooldown at `now`, WITHOUT stamping. Used by the first-audit reserve gate
9438/// (ADR-0004 Amendment 2 E′) to avoid reserving a peer that a recent audit
9439/// already covered; the authoritative check-and-stamp still runs at promotion,
9440/// so this is only an optimization and never the security boundary.
9441fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9442 let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9443 map.get(peer).map_or(true, |&last| {
9444 now.saturating_duration_since(last) >= cooldown
9445 })
9446}
9447
9448/// The gossip-audit launch decision in ONE place so the ordering is shared
9449/// between production and its test (ADR-0002 "occasional surprise exams").
9450///
9451/// Order matters and is the security-relevant property. Gate 1 checks-and-stamps
9452/// the gossip-PRIVATE `attempts` window, win or lose: if the lottery were
9453/// sampled first, a gossip flood would re-roll it on every message until one
9454/// won, multiplying audits, so each peer gets at most one lottery roll per
9455/// window regardless of how often it gossips. Gate 3 checks-and-stamps the
9456/// SHARED `launched` cooldown — the map the monetized first-audit scheduler
9457/// also consults — only after a WIN, i.e. only when a real audit is about to be
9458/// sent. A losing ticket must never stamp `launched`: no challenge went on the
9459/// wire, so it must not defer a paid first audit (repeatable losses could
9460/// otherwise hold a monetized pin past its answerability window). Production
9461/// calls this with `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the
9462/// test calls it with a deterministic `lottery_wins`, so a reorder regression
9463/// here fails the test.
9464fn audit_launch_decision(
9465 attempts: &mut HashMap<PeerId, Instant>,
9466 launched: &mut HashMap<PeerId, Instant>,
9467 peer: &PeerId,
9468 now: Instant,
9469 lottery_wins: bool,
9470) -> bool {
9471 // Gate 1: lottery-attempt window check-and-stamp (consumes the attempt
9472 // window even on a loss; private to the gossip path).
9473 if !cooldown_allows_audit(attempts, peer, now) {
9474 return false;
9475 }
9476 // Gate 2: the probability lottery. A loss stops here and stamps nothing
9477 // shared.
9478 if !lottery_wins {
9479 return false;
9480 }
9481 // Gate 3: the shared actual-audit cooldown (a recent real audit from
9482 // either path still suppresses this launch), stamped only on launch.
9483 cooldown_allows_audit(launched, peer, now)
9484}
9485
9486/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
9487/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
9488/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
9489/// handling is never blocked on a network round-trip.
9490async fn maybe_trigger_gossip_audit(
9491 trigger: &GossipAuditTrigger,
9492 peer: &PeerId,
9493 target: AuditTarget,
9494) {
9495 // The launch decision (attempt-window, lottery, shared-cooldown ordering)
9496 // lives in the pure `audit_launch_decision` so the ordering is shared with
9497 // its test. Sample the lottery here, then let the helper apply the gates.
9498 let now = Instant::now();
9499 let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
9500 {
9501 // Lock order: attempts before the shared cooldown; this is the only
9502 // place both are held together.
9503 let mut attempts = trigger.lottery_attempts.write().await;
9504 let mut launched = trigger.cooldown.write().await;
9505 if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
9506 return;
9507 }
9508 }
9509
9510 let detached_task_tracker = trigger.detached_task_tracker.clone();
9511 let trigger = trigger.clone();
9512 let peer = *peer;
9513 detached_task_tracker.spawn(async move {
9514 let credit = storage_commitment_audit::AuditCredit {
9515 recent_provers: &trigger.recent_provers,
9516 };
9517 let result = storage_commitment_audit::run_subtree_audit_with_origin(
9518 &trigger.p2p_node,
9519 &trigger.config,
9520 &peer,
9521 target.pin_hash,
9522 target.key_count,
9523 Some(&credit),
9524 storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9525 )
9526 .await;
9527 handle_subtree_audit_result(
9528 &result,
9529 &trigger.p2p_node,
9530 &trigger.sync_state,
9531 &trigger.recent_provers,
9532 &trigger.config,
9533 )
9534 .await;
9535 });
9536}
9537
9538/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
9539///
9540/// Returns `true` if a signature verify is allowed now (and stamps the attempt
9541/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
9542/// of its last attempt. Holds one write lock across the decision so two
9543/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
9544/// caller's expensive verify so a slow/failed verify still rate-limits the next
9545/// message. Bounds the map under a flood of distinct peer ids.
9546async fn sig_verify_rate_limit_ok(
9547 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9548 source: &PeerId,
9549 now: Instant,
9550) -> bool {
9551 let mut attempts = sig_verify_attempts.write().await;
9552 if let Some(&last) = attempts.get(source) {
9553 if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9554 return false;
9555 }
9556 }
9557 if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9558 if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9559 attempts.remove(&victim);
9560 }
9561 }
9562 attempts.insert(*source, now);
9563 true
9564}
9565
9566/// Verify + store an inbound commitment from a gossip peer.
9567///
9568/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
9569/// the bootstrap-sync loop. Drops the commitment unless all five gates
9570/// pass:
9571/// 1. `source` is in our DHT routing table (sybil/churn cap).
9572/// 2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
9573/// binding to the authenticated transport peer).
9574/// 3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
9575/// (the embedded pubkey actually belongs to the claimed identity —
9576/// saorsa-core derives `PeerId = BLAKE3(pubkey)`).
9577/// 4. `verify_commitment_signature(commitment)` succeeds against the
9578/// embedded public key. The signed payload binds the pubkey, so an
9579/// adversary cannot swap the key while keeping the body.
9580/// 5. The cache has room or this is an update for an existing entry
9581/// (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
9582///
9583/// On all-pass, the commitment is stored as the auditor's per-peer
9584/// "last known commitment" for use as `expected_commitment_hash` in
9585/// future audits.
9586///
9587/// Failures (no commitment / mismatched peer id / bad signature) are
9588/// silent drops — gossip is best-effort and a malformed commitment from
9589/// one peer should not affect anything else.
9590///
9591/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
9592/// or not its root changed), so the caller can run a probabilistic,
9593/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
9594/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
9595/// being auditable, so it cannot pass one audit and then delete data while
9596/// re-gossiping the same root forever. The cooldown + probability bound the
9597/// audit frequency. Returns `None` only if the commitment was dropped (failed a
9598/// gate) or there is nothing to pin.
9599///
9600/// Handle a capable peer gossiping `None` (a commitment downgrade).
9601///
9602/// A capable peer that previously gossiped a commitment but now gossips `None`
9603/// is trying to drop off the audit path. Within the answerability window we keep
9604/// the cached commitment pinned AND return it as an audit target so this gossip
9605/// still schedules a subtree audit against the peer's last known commitment — if
9606/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
9607/// the trigger MUST fire here or the downgrade is never re-challenged).
9608///
9609/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
9610/// honours for its own retired commitment: once that elapses since we last
9611/// received the peer's commitment, an honest peer has legitimately retired that
9612/// root (its responder side `retire_current`s and lets it age out) and can no
9613/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
9614/// failure, so we then forget the cached commitment (keeping the sticky
9615/// `commitment_capable` bit) and stop pinning it.
9616async fn handle_commitment_downgrade(
9617 source: &PeerId,
9618 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9619) -> Option<AuditTarget> {
9620 let now = Instant::now();
9621 let cached = {
9622 let map = last_commitment_by_peer.read().await;
9623 map.get(source).and_then(|rec| {
9624 if !rec.commitment_capable {
9625 return None;
9626 }
9627 let last = rec.last_commitment()?;
9628 let pin = rec.commitment_hash()?;
9629 let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
9630 Some((pin, last.key_count, fresh))
9631 })
9632 };
9633 match cached {
9634 Some((pin, key_count, true)) => {
9635 warn!(
9636 "ingest_peer_commitment: commitment-capable peer {source} sent None \
9637 (downgrade attempt); auditing against its last cached commitment"
9638 );
9639 Some(AuditTarget {
9640 pin_hash: pin,
9641 key_count,
9642 })
9643 }
9644 Some((_, _, false)) => {
9645 // Cached commitment has aged past the answerability window — forget
9646 // it so we stop pinning a root the peer is no longer obliged to
9647 // answer. Keep `commitment_capable` (sticky). Re-check freshness
9648 // UNDER the write lock (compare-and-clear): a concurrent valid gossip
9649 // from this peer may have refreshed `received_at` in the gap between
9650 // our read and write locks; if so, leave its fresh commitment intact.
9651 if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
9652 let still_stale =
9653 now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
9654 if still_stale {
9655 rec.clear_commitment();
9656 debug!(
9657 "ingest_peer_commitment: capable peer {source} sent None and its cached \
9658 commitment aged past the answerability TTL; forgetting it"
9659 );
9660 }
9661 }
9662 None
9663 }
9664 None => None,
9665 }
9666}
9667
9668async fn ingest_peer_commitment(
9669 source: &PeerId,
9670 commitment: Option<&StorageCommitment>,
9671 p2p_node: &Arc<P2PNode>,
9672 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9673 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
9674 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9675) -> Option<AuditTarget> {
9676 let Some(c) = commitment else {
9677 return handle_commitment_downgrade(source, last_commitment_by_peer).await;
9678 };
9679 // RT-membership gate: only accept commitments from peers in our
9680 // routing table. Off-RT senders (sybils, drive-by relays) cannot
9681 // populate the cache, which closes the hole where a flood of
9682 // off-RT identities could fill the cap and evict honest
9683 // peers. The neighbor-sync request handler applies the same gate
9684 // before admitting inbound replication hints (see neighbor_sync.rs
9685 // `sender_in_rt`); we mirror that policy here for the commitment
9686 // piggyback.
9687 if !p2p_node.dht_manager().is_in_routing_table(source).await {
9688 debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
9689 return None;
9690 }
9691 // Peer-id binding: the commitment's claimed sender must match the
9692 // authenticated transport peer (`source`). Defeats relay/replay
9693 // and also pins which embedded public key we are about to verify
9694 // against — the verify itself trusts the embedded key, so the
9695 // peer-id binding is the link to a real identity.
9696 if &c.sender_peer_id != source.as_bytes() {
9697 warn!(
9698 "ingest_peer_commitment: sender_peer_id mismatch from {source} \
9699 (dropped, possible relay attempt)"
9700 );
9701 return None;
9702 }
9703 // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
9704 // BLAKE3(pubkey_bytes). Without this check, a responder could sign
9705 // with a throwaway key they own and lie about which identity it
9706 // belongs to (the embedded-key signature would verify trivially).
9707 let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
9708 if derived_peer_id != c.sender_peer_id {
9709 warn!(
9710 "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
9711 {source} (dropped, throwaway-key attack)"
9712 );
9713 return None;
9714 }
9715 // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
9716 // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
9717 // sybil/RT-membership-bypassing peer that flooded valid-looking
9718 // gossip would otherwise burn CPU on every message. The rate
9719 // limit is checked AFTER cheap structural gates (RT, peer-id
9720 // binding, pubkey-binding) and BEFORE the expensive sig verify.
9721 //
9722 // Tracked in `sig_verify_attempts` (separate from
9723 // last_commitment_by_peer) so EVERY attempt — successful or not —
9724 // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
9725 // would skip the cap for peers we've never successfully verified,
9726 // letting a flood of invalid-but-structurally-plausible gossips
9727 // burn CPU.
9728 let now = Instant::now();
9729 if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
9730 debug!(
9731 "ingest_peer_commitment: rate-limited sig verify from {source} \
9732 (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
9733 );
9734 return None;
9735 }
9736 // Signature verify, using the public key embedded in the commitment
9737 // itself. The pubkey is bound by the signature payload (see
9738 // commitment_signed_payload) so an adversary cannot keep the body
9739 // and swap the key to one they hold the secret for.
9740 if !crate::replication::commitment::verify_commitment_signature(c) {
9741 warn!(
9742 "ingest_peer_commitment: signature did not verify under embedded key for {source} \
9743 (dropped, forged commitment)"
9744 );
9745 return None;
9746 }
9747 // The new commitment's hash, used to store and to pin for the audit target.
9748 let new_hash = commitment_hash(c);
9749 let mut map = last_commitment_by_peer.write().await;
9750 // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
9751 // evict an arbitrary existing entry to make room. Updates for peers
9752 // already in the map are always accepted (they replace, not grow).
9753 if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
9754 // Drop one arbitrary entry. HashMap iter order is random which
9755 // is fine — over time PeerRemoved cleanup keeps the working set
9756 // anchored on the real RT membership; this cap only fires under
9757 // active flooding attempts.
9758 if let Some(victim) = map.keys().next().copied() {
9759 map.remove(&victim);
9760 warn!(
9761 "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
9762 evicted {victim} to admit {source}"
9763 );
9764 }
9765 }
9766 // Preserve sticky commitment_capable across updates — once true,
9767 // always true. New entries start with capable = true (we just
9768 // verified a valid commitment from this peer).
9769 map.entry(*source)
9770 .and_modify(|r| {
9771 // set_commitment refreshes the cached hash (§13) alongside the
9772 // commitment + received_at so they never drift.
9773 r.set_commitment(c.clone(), now);
9774 r.last_sig_verify_at = now;
9775 r.commitment_capable = true; // sticky-redundant but explicit
9776 })
9777 .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
9778 drop(map);
9779 // Record the sticky "ever v12-capable" bit in a set independent of
9780 // `last_commitment_by_peer` (whose entries can be evicted by
9781 // `PeerRemoved` and the sybil cap). This is what the §3 audit
9782 // shield and the §6 holder-eligibility closure consult to decide
9783 // whether the peer is expected to speak v12.
9784 //
9785 // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
9786 // identity-rotation attacks: once full, new entries are refused.
9787 // Refusal degrades over-cap peers to the behaviour before this set
9788 // existed (treated as legacy on rejoin), which is not a security
9789 // regression and preserves the historic set stable.
9790 {
9791 let mut set = ever_capable_peers.write().await;
9792 if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
9793 set.insert(*source);
9794 } else {
9795 warn!(
9796 "ingest_peer_commitment: ever_capable_peers at cap \
9797 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
9798 );
9799 }
9800 }
9801 // Return an audit target for EVERY valid stored commitment (changed or
9802 // not), so the caller's cooldown+probability-gated trigger keeps a
9803 // stable-keyset peer auditable over time (ADR-0002). Only a serialization
9804 // failure (new_hash == None, unreachable for a real commitment) yields None.
9805 new_hash.map(|pin_hash| AuditTarget {
9806 pin_hash,
9807 key_count: c.key_count,
9808 })
9809}
9810
9811// ---------------------------------------------------------------------------
9812// Storage-bound audit (v12) — responder commitment rotation
9813// ---------------------------------------------------------------------------
9814
9815/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
9816/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
9817/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
9818async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
9819 let bytes = match tokio::fs::read(path).await {
9820 Ok(b) => b,
9821 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
9822 debug!(
9823 "Commitment retention: no snapshot at {} (fresh start)",
9824 path.display()
9825 );
9826 return;
9827 }
9828 Err(e) => {
9829 warn!(
9830 "Commitment retention: failed to read {}: {e}",
9831 path.display()
9832 );
9833 return;
9834 }
9835 };
9836 if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
9837 state.restore(&persisted);
9838 info!(
9839 "Commitment retention: reloaded {} slot(s) from {}",
9840 state.retained_slot_count(),
9841 path.display()
9842 );
9843 } else {
9844 warn!(
9845 "Commitment retention: corrupt snapshot at {}; starting with empty retention",
9846 path.display()
9847 );
9848 }
9849}
9850
9851/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
9852/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
9853/// needless disk writes on idle nodes. On success updates `last` to the bytes
9854/// written; on a serialization/write error the existing on-disk snapshot is left
9855/// intact (never truncated).
9856async fn persist_retention_if_changed(
9857 state: &ResponderCommitmentState,
9858 path: &Path,
9859 last: &mut Option<Vec<u8>>,
9860) {
9861 let Some(bytes) = state.snapshot().to_bytes() else {
9862 warn!("Commitment retention: serialization failed; keeping previous snapshot");
9863 return;
9864 };
9865 if last.as_deref() == Some(bytes.as_slice()) {
9866 return;
9867 }
9868 if write_retention_atomic(path, bytes.clone()).await {
9869 *last = Some(bytes);
9870 }
9871}
9872
9873/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
9874/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
9875/// success. Only the retention-persist loop writes this path, so a fixed temp
9876/// name is safe.
9877async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
9878 let path = path.to_path_buf();
9879 let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
9880 let tmp = path.with_extension("tmp");
9881 std::fs::write(&tmp, &bytes)?;
9882 std::fs::File::open(&tmp)?.sync_all()?;
9883 std::fs::rename(&tmp, &path)?;
9884 // Fsync the directory so the rename (the durable-commit point) is not
9885 // lost on a crash right after it. An empty parent (relative filename)
9886 // means the current directory.
9887 let dir = path
9888 .parent()
9889 .filter(|p| !p.as_os_str().is_empty())
9890 .unwrap_or_else(|| Path::new("."));
9891 std::fs::File::open(dir)?.sync_all()?;
9892 Ok(())
9893 })
9894 .await;
9895 match res {
9896 Ok(Ok(())) => true,
9897 Ok(Err(e)) => {
9898 warn!("Commitment retention: persist failed: {e}");
9899 false
9900 }
9901 Err(e) => {
9902 warn!("Commitment retention: persist task join failed: {e}");
9903 false
9904 }
9905 }
9906}
9907
9908/// Read the current LMDB key set, build + sign a fresh
9909/// `StorageCommitment`, and rotate it into `state` as the new `current`.
9910/// The prior `current` is demoted to `previous`; the prior `previous` is
9911/// dropped (per `ResponderCommitmentState::rotate`).
9912///
9913/// For content-addressed chunks (Autonomi's chunk store), `address ==
9914/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
9915/// re-read each chunk's bytes to compute the leaf hash.
9916///
9917/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
9918/// rotate. The auditor side handles "no commitment for this peer" by
9919/// falling back to the legacy plain-digest audit path.
9920async fn rebuild_and_rotate_commitment(
9921 storage: &Arc<LmdbStorage>,
9922 identity: &Arc<NodeIdentity>,
9923 state: &Arc<ResponderCommitmentState>,
9924 p2p: &Arc<P2PNode>,
9925 config: &Arc<ReplicationConfig>,
9926) -> Result<()> {
9927 let stored_keys = storage
9928 .all_keys()
9929 .await
9930 .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
9931
9932 // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
9933 // everything currently on disk ("hold"). This is the half of the retention
9934 // contract that lets out-of-range chunks age out: a key that has left our
9935 // close group is excluded from the NEXT commitment, so once its last gossip
9936 // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
9937 // set, `ResponderCommitmentState::is_held` goes false,
9938 // and the pruner (which until then vetoes its deletion) reclaims it. Without
9939 // this filter the pruner's reprieve would keep re-committing stale keys
9940 // forever (the rebuild reads all_keys, so a retained-on-disk key would be
9941 // re-committed and re-gossiped every rotation — a permanent pin).
9942 let storage_empty = stored_keys.is_empty();
9943 let self_id = *p2p.peer_id();
9944 let mut keys = Vec::with_capacity(stored_keys.len());
9945 for k in stored_keys {
9946 if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
9947 keys.push(k);
9948 }
9949 }
9950
9951 if keys.is_empty() {
9952 if storage_empty {
9953 // Storage is genuinely empty — there is nothing to answer for, so
9954 // drop the previously advertised commitment immediately. Keeping it
9955 // would leave remote auditors pinning a hash we can never satisfy
9956 // again (the bytes are gone).
9957 if state.retained_slot_count() > 0 {
9958 debug!("Commitment rotation: storage empty, clearing retained slots");
9959 state.clear_all();
9960 }
9961 return Ok(());
9962 }
9963 // Bytes are still on disk but no key is currently in range. We must NOT
9964 // clear retention here: a peer may still be pinning a root we gossiped
9965 // moments ago and could demand its bytes in a round-2 challenge, which
9966 // we can still answer (the bytes are present). But we must STOP
9967 // advertising the stale commitment: retire it so `current()` returns
9968 // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
9969 // The retired slot then ages out by its gossip-answerability TTL while
9970 // remaining answerable for in-flight pins until then. Once it ages out,
9971 // `is_held` flips false and the pruner reclaims the now-uncommitted,
9972 // out-of-range chunks. (Calling `age_out` alone would leave `current()`
9973 // pointing at the stale root, which the gossip loop would keep
9974 // re-stamping — pinning its keys forever.)
9975 debug!(
9976 "Commitment rotation: no responsible keys to commit to; retiring current commitment \
9977 (stays answerable until its gossip TTL lapses, bytes still on disk)"
9978 );
9979 state.retire_current();
9980 return Ok(());
9981 }
9982
9983 // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
9984 // to more than the protocol limit; auditor would reject the
9985 // commitment otherwise).
9986 let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
9987 if keys.len() > cap {
9988 warn!(
9989 "Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
9990 truncating — investigate as this likely means a misconfiguration",
9991 keys.len(),
9992 cap
9993 );
9994 }
9995
9996 // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
9997 // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
9998 // full chunk re-read per rotation.
9999 //
10000 // Consequence to be precise about: because the leaf is `(key, key)`,
10001 // the Merkle root commits to the SET OF KEYS, not to the bytes. The
10002 // commitment therefore binds "which keys I claim to hold"; it does NOT
10003 // by itself prove byte possession. Byte possession is enforced by the
10004 // round-2 slice audit: a Bao verified slice decoded against the chunk
10005 // ADDRESS plus a keyed nonced block-tree opening under a fresh per-audit
10006 // nonce, so a responder that holds the key list but dropped the bytes
10007 // cannot answer. This is sound ONLY while keys are content addresses;
10008 // the round-1 verifier enforces `bytes_hash == key` on every audited leaf
10009 // (`evaluate_subtree_structure`), so a non-content-addressed
10010 // `(key, bytes_hash)` leaf is rejected rather than letting a byte-less node
10011 // earn credit for `key`. If this module is ever reused for
10012 // non-content-addressed records, that `(k, k)` shortcut AND the verifier
10013 // gate must be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
10014 let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
10015
10016 // No-op-rotation guard: compute just the Merkle root from `entries`
10017 // and compare against the currently-advertised commitment's root.
10018 // If they match, the key set is unchanged and a new rotation would
10019 // only swap a randomized ML-DSA signature for a fresh one — same
10020 // content, different commitment_hash. That invalidates every
10021 // outstanding `recent_provers` credit on this node across the
10022 // close group with no security benefit, breaking steady-state
10023 // quorum liveness on large nodes that can't re-audit every key
10024 // every rotation interval. Skip the rotation entirely when the
10025 // tree is unchanged.
10026 // Build the tree ONCE here (moving `entries`): it serves both the no-op
10027 // root check below and, if we proceed, the signed commitment via
10028 // `build_from_tree` (§11 — previously the tree was built here and AGAIN
10029 // inside `BuiltCommitment::build`).
10030 let candidate_tree = commitment::MerkleTree::build(entries)
10031 .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
10032 let candidate_root = candidate_tree.root();
10033 if let Some(current) = state.current() {
10034 if current.commitment().root == candidate_root {
10035 debug!(
10036 "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
10037 hex::encode(candidate_root)
10038 );
10039 // Even though we skip re-signing (to avoid invalidating holder
10040 // credit), retention must still advance on the wall clock: a
10041 // previously-gossiped commitment that holds a now-out-of-range key
10042 // must be able to age out of the answerability window even when the
10043 // committed key set is frozen here for many rotations. Without this,
10044 // the no-op guard would pin a stale slot — and its key — forever.
10045 state.age_out();
10046 return Ok(());
10047 }
10048 }
10049
10050 let sk_bytes = identity.secret_key_bytes().to_vec();
10051 let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
10052 .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
10053 let pk_bytes = identity.public_key().as_bytes().to_vec();
10054 let peer_id_bytes = *p2p.peer_id().as_bytes();
10055
10056 let built = commitment_state::BuiltCommitment::build_from_tree(
10057 candidate_tree,
10058 &peer_id_bytes,
10059 &sk,
10060 &pk_bytes,
10061 )
10062 .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
10063
10064 let hash = hex::encode(built.hash());
10065 let key_count = built.commitment().key_count;
10066 state.rotate(built);
10067 info!("Storage commitment rotated: hash={hash} key_count={key_count}");
10068 Ok(())
10069}
10070
10071#[cfg(test)]
10072#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
10073mod tests {
10074
10075 /// The two fetch failures mean different things and must be charged differently.
10076 ///
10077 /// `NotFound` is a peer saying it does not hold the chunk, which is what a node
10078 /// part-way through the migration says about chunks it has legitimately given up, so
10079 /// it is the lane this release withholds. `Error` has a single producer, the
10080 /// responder's own storage read failing, and that is never about the migration.
10081 #[test]
10082 fn a_missing_chunk_and_a_failed_read_are_different_faults() {
10083 let key = [7u8; 32];
10084 assert_eq!(
10085 fetch_fault_for(&protocol::FetchResponse::NotFound { key }),
10086 Some(FetchFault::UnheldChunk)
10087 );
10088 assert_eq!(
10089 fetch_fault_for(&protocol::FetchResponse::Error {
10090 key,
10091 reason: "read failed".to_string(),
10092 }),
10093 Some(FetchFault::ResponderFault)
10094 );
10095 assert_eq!(
10096 fetch_fault_for(&protocol::FetchResponse::Success {
10097 key,
10098 data: vec![1, 2, 3],
10099 }),
10100 None
10101 );
10102 }
10103
10104 /// The responder's answer says which fault it is, so the mapping from a storage read
10105 /// to a response is what the classification above rests on.
10106 ///
10107 /// A key the peer does not hold reads as `Ok(None)`. A read that fails, whether from
10108 /// an I/O fault or a failed integrity check, reads as `Err`. Nothing in the migration
10109 /// turns the first into the second.
10110 #[tokio::test]
10111 async fn a_missing_key_reads_as_a_plain_miss_and_a_failed_read_as_a_fault() {
10112 let dir = tempfile::tempdir().expect("temp dir");
10113 let storage = LmdbStorage::new(crate::storage::LmdbStorageConfig {
10114 root_dir: dir.path().to_path_buf(),
10115 verify_on_read: true,
10116 max_map_size: 0,
10117 disk_reserve: 0,
10118 })
10119 .await
10120 .expect("open store");
10121
10122 let absent = [9u8; 32];
10123 assert!(
10124 matches!(storage.get(&absent).await, Ok(None)),
10125 "a chunk this node does not hold must read as a plain miss, not a fault"
10126 );
10127
10128 // And the answer each read produces. A miss is `NotFound`, which is the withheld
10129 // lane; a failed read is `Error`, which is not.
10130 assert!(matches!(
10131 fetch_response_for(absent, Ok(None)),
10132 protocol::FetchResponse::NotFound { .. }
10133 ));
10134 assert!(matches!(
10135 fetch_response_for(absent, Ok(Some(vec![1, 2, 3]))),
10136 protocol::FetchResponse::Success { .. }
10137 ));
10138 assert!(matches!(
10139 fetch_response_for(
10140 absent,
10141 Err(crate::error::Error::Storage("read failed".into()))
10142 ),
10143 protocol::FetchResponse::Error { .. }
10144 ));
10145 }
10146 use super::*;
10147 use super::{
10148 apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
10149 audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
10150 config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
10151 first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
10152 quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
10153 FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
10154 FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
10155 FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
10156 };
10157 use crate::payment::VerificationContext;
10158 use crate::replication::audit::AuditTickResult;
10159 use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
10160 use crate::replication::recent_provers::RecentProvers;
10161 use crate::replication::types::{AuditFailureReason, FailureEvidence};
10162 use lru::LruCache;
10163 use saorsa_core::identity::PeerId;
10164 use std::collections::HashMap;
10165 use std::num::NonZeroUsize;
10166 use std::sync::atomic::Ordering;
10167 use std::sync::Arc;
10168 use std::time::Duration;
10169 use std::time::Instant;
10170 use std::time::SystemTime;
10171
10172 #[test]
10173 fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
10174 for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
10175 assert_eq!(match_replication_protocol(id), Some((id, false)));
10176 assert_eq!(
10177 match_replication_protocol(&format!("{RR_PREFIX}{id}")),
10178 Some((id, true))
10179 );
10180 }
10181 assert_eq!(
10182 match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
10183 None
10184 );
10185 assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
10186 assert_eq!(match_replication_protocol(RR_PREFIX), None);
10187 }
10188
10189 #[test]
10190 fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
10191 use crate::replication::protocol::{
10192 AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
10193 SubtreeSliceChallenge,
10194 };
10195
10196 let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
10197 challenge_id: 1,
10198 nonce: [0u8; 32],
10199 challenged_peer_id: [0u8; 32],
10200 expected_commitment_hash: [0u8; 32],
10201 openings: vec![],
10202 });
10203 let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
10204 challenge_id: 1,
10205 nonce: [0u8; 32],
10206 challenged_peer_id: [0u8; 32],
10207 keys: vec![[0u8; 32]],
10208 });
10209 let digest_response =
10210 ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
10211 let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
10212 key: [0u8; 32],
10213 data: vec![],
10214 proof_of_payment: vec![],
10215 });
10216
10217 assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
10218 assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
10219
10220 for body in [&digest_challenge, &digest_response, &core] {
10221 assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
10222 assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
10223 }
10224
10225 for body in [&subtree, &digest_challenge, &digest_response, &core] {
10226 assert!(body_matches_protocol(body, response_protocol_for(body)));
10227 }
10228 }
10229
10230 fn test_peer(b: u8) -> PeerId {
10231 let mut bytes = [0u8; 32];
10232 bytes[0] = b;
10233 PeerId::from_bytes(bytes)
10234 }
10235
10236 /// A structurally valid offer for `data`: real content address, a proof of
10237 /// the minimum accepted size, distinguished by `proof_marker` so a test can
10238 /// tell whose proof came back out of the queue.
10239 fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
10240 protocol::FreshReplicationOffer {
10241 key: crate::client::compute_address(&data),
10242 data,
10243 proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
10244 }
10245 }
10246
10247 fn admit_test_offer(
10248 in_flight: &FreshOfferInFlight,
10249 offer: protocol::FreshReplicationOffer,
10250 source: PeerId,
10251 ) -> FreshOfferAdmission {
10252 FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
10253 }
10254
10255 #[test]
10256 fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
10257 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10258 let data = vec![0x11u8; 64];
10259
10260 let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
10261 let FreshOfferAdmission::Opened(entry) = opened else {
10262 panic!("first offer for a key should open the entry")
10263 };
10264
10265 // A second sender contributes its proof instead of being turned away:
10266 // its bytes are provably the same, so only the proof is worth keeping.
10267 assert!(
10268 matches!(
10269 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
10270 FreshOfferAdmission::Joined
10271 ),
10272 "a duplicate from a new source should queue its proof"
10273 );
10274 // The same peer twice is not extra evidence, just extra work.
10275 assert!(
10276 matches!(
10277 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
10278 FreshOfferAdmission::DuplicateSource
10279 ),
10280 "one source should hold at most one queued proof per key"
10281 );
10282
10283 // An entry that outlived its handler would bar the key forever.
10284 drop(entry);
10285 assert!(
10286 matches!(
10287 admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
10288 FreshOfferAdmission::Opened(_)
10289 ),
10290 "a released key should be openable again"
10291 );
10292 }
10293
10294 #[test]
10295 fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
10296 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10297
10298 // A node only receives offers for keys close to its own ID, so accepted
10299 // keys share a long prefix. Any prefix-derived shard index would have
10300 // funnelled these two onto one lock and serialized them.
10301 let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
10302 assert!(
10303 matches!(
10304 admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
10305 FreshOfferAdmission::Opened(_)
10306 ),
10307 "distinct keys should never block each other"
10308 );
10309 }
10310
10311 /// The regression that motivated queueing proofs at all.
10312 ///
10313 /// A sender whose proof does not verify must cost the network its own
10314 /// attempt and nothing more. Refusing every later offer outright made the
10315 /// first arrival the only arrival, so one bad proof lost the record — and
10316 /// the delayed possession check then charged that absence to this node.
10317 #[test]
10318 fn a_failing_proof_hands_the_key_to_the_next_sender() {
10319 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10320 let data = vec![0x5Au8; 128];
10321 let forger = test_peer(0xF0);
10322 let genuine = test_peer(0x0F);
10323
10324 let FreshOfferAdmission::Opened(mut entry) =
10325 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
10326 else {
10327 panic!("the first offer should open the entry");
10328 };
10329 assert!(
10330 matches!(
10331 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
10332 FreshOfferAdmission::Joined
10333 ),
10334 "the genuine sender must not be turned away by the forger"
10335 );
10336
10337 let first = entry
10338 .next_attempt()
10339 .expect("the opener's proof comes first");
10340 assert_eq!(first.source, forger);
10341
10342 // Treat the forger's proof as failed: the next one is still reachable,
10343 // and it is tried against the bytes already held rather than a refetch.
10344 let second = entry
10345 .next_attempt()
10346 .expect("a failed proof must not consume the key");
10347 assert_eq!(second.source, genuine);
10348 assert_eq!(
10349 second.proof_of_payment,
10350 vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
10351 );
10352 assert_eq!(
10353 entry.data(),
10354 data.as_slice(),
10355 "every proof is tried against the one copy of the bytes"
10356 );
10357
10358 // Draining the queue releases the key rather than stranding it.
10359 assert!(entry.next_attempt().is_none());
10360 assert!(
10361 matches!(
10362 admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
10363 FreshOfferAdmission::Opened(_)
10364 ),
10365 "an exhausted entry should release its key"
10366 );
10367 }
10368
10369 /// The cap has to be a lifetime budget, not a queue depth.
10370 ///
10371 /// The handler pops a proof before verifying it, so gating admission on the
10372 /// *instantaneous* queue length lets a fresh source refill the slot that pop
10373 /// just freed. Each refill is another on-chain payment verification, run
10374 /// sequentially while the entry holds its admission permit and a worker
10375 /// slot, so a stream of distinct sources could keep one key's handler — and
10376 /// one of only four workers — busy indefinitely.
10377 #[test]
10378 fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
10379 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10380 let data = vec![0x3Du8; 32];
10381
10382 let FreshOfferAdmission::Opened(mut entry) =
10383 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
10384 else {
10385 panic!("the first offer should open the entry")
10386 };
10387
10388 // Drive pop-then-admit with a fresh source every time, exactly as a
10389 // sybil stream would. The budget must be spent by admissions, not
10390 // returned by pops.
10391 let mut admitted = 1;
10392 for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
10393 let _ = entry.next_attempt();
10394 if matches!(
10395 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
10396 FreshOfferAdmission::Joined
10397 ) {
10398 admitted += 1;
10399 }
10400 }
10401
10402 assert!(
10403 admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
10404 "a key accepted {admitted} proofs over its lifetime, but the budget is \
10405 {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
10406 );
10407 }
10408
10409 #[test]
10410 fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
10411 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10412 let data = vec![0x2Cu8; 32];
10413
10414 // The opener occupies the first slot, so the cap is reached after
10415 // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY distinct sources in total.
10416 let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
10417 for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
10418 let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
10419 assert!(
10420 matches!(
10421 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
10422 FreshOfferAdmission::Joined
10423 ),
10424 "sender {i} is within the legitimate close-group fan-out"
10425 );
10426 }
10427
10428 let surplus = test_peer(0xEE);
10429 assert!(
10430 matches!(
10431 admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
10432 FreshOfferAdmission::Full
10433 ),
10434 "past the cap a proof is surplus: enough are already queued to place the record"
10435 );
10436 }
10437
10438 #[test]
10439 fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
10440 assert!(!verification_request_exceeds_limit(
10441 config::MAX_VERIFICATION_KEYS_PER_CYCLE
10442 ));
10443 assert!(verification_request_exceeds_limit(
10444 config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
10445 ));
10446 }
10447
10448 // The heavy round-1 limiter enforces the per-peer rate cooldown
10449 // and single-use round-1 → round-2 sessions.
10450 #[tokio::test]
10451 async fn subtree_round1_limiter_cooldown_and_single_use_session() {
10452 let limiter = SubtreeRound1Limiter::new(
10453 Duration::from_secs(3600),
10454 config::MAX_CONCURRENT_SUBTREE_ROUND1,
10455 );
10456 let peer = test_peer(1);
10457
10458 // First round-1 is admitted; drop the guard so concurrency is free again.
10459 let guard = limiter.admit(&peer).await;
10460 assert!(guard.is_some(), "first round-1 admitted");
10461 drop(guard);
10462 // A second round-1 within the cooldown is dropped even though the heavy
10463 // pool now has a free slot — the rate cooldown, not concurrency, blocks it.
10464 assert!(
10465 limiter.admit(&peer).await.is_none(),
10466 "second round-1 within cooldown is rate-dropped"
10467 );
10468 // A different peer has its own cooldown.
10469 assert!(limiter.admit(&test_peer(2)).await.is_some());
10470
10471 // Session: opened by round 1, consumed exactly once by the matching round 2.
10472 let hash = [7u8; 32];
10473 let nonce = [9u8; 32];
10474 limiter.open_session(peer, 42, hash, nonce).await;
10475 // Wrong nonce / commitment does not match.
10476 assert!(!limiter.consume_session(&peer, 42, &hash, &[0u8; 32]).await);
10477 assert!(!limiter.consume_session(&peer, 42, &[0u8; 32], &nonce).await);
10478 // A round 2 with no prior round 1 (wrong challenge_id) misses.
10479 assert!(!limiter.consume_session(&peer, 99, &hash, &nonce).await);
10480 // The matching round 2 consumes it — and only once (single-use).
10481 assert!(limiter.consume_session(&peer, 42, &hash, &nonce).await);
10482 assert!(!limiter.consume_session(&peer, 42, &hash, &nonce).await);
10483 }
10484
10485 // The concurrency pool and the per-peer cooldown are both keyed by peer id,
10486 // so a party holding several identities refills its allowance by rotating
10487 // between them and can keep the heavy pool busy indefinitely. The work
10488 // budget is keyed by nothing: it is charged for bytes proved, whoever asked,
10489 // so a fresh identity is refused exactly like a repeat caller once it is
10490 // spent. That is the difference between bounding concurrency and bounding
10491 // sustained work.
10492 #[tokio::test]
10493 async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
10494 // Cooldown disabled so only the work budget can refuse anything.
10495 let limiter =
10496 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10497 assert!(
10498 limiter.admit(&test_peer(1)).await.is_some(),
10499 "a node starts with budget in hand so it can serve audits at once"
10500 );
10501
10502 // Serve enough proof work to run the balance into debt. Charging exactly
10503 // the burst would leave it at zero, which the next nanosecond of refill
10504 // lifts back above the line — the debt is the point.
10505 limiter
10506 .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
10507 .await;
10508
10509 for id in 2..8u8 {
10510 assert!(
10511 limiter.admit(&test_peer(id)).await.is_none(),
10512 "a never-seen peer must still be refused while the budget is spent"
10513 );
10514 }
10515 }
10516
10517 // The budget is a rate, not a quota: it comes back on its own, so an honest
10518 // auditor blocked by a flood is only delayed. Carrying the debt is what
10519 // prices an expensive proof above a cheap one — without it, a proof reading
10520 // a maximal subtree would cost no more of the next caller's wait than a
10521 // one-leaf proof.
10522 #[test]
10523 fn round1_work_budget_carries_debt_and_refills_over_time() {
10524 let now = Instant::now();
10525 let at = |secs: u64| {
10526 now.checked_add(Duration::from_secs(secs))
10527 .unwrap_or_else(Instant::now)
10528 };
10529 let mut budget = Round1WorkBudget {
10530 balance: 0,
10531 last_refill: now,
10532 };
10533 assert!(!budget.has_budget(now), "empty means empty");
10534
10535 // A proof costing four seconds' worth of refill leaves four seconds of
10536 // debt, so the wait scales with what was actually served.
10537 budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
10538 assert!(
10539 !budget.has_budget(at(3)),
10540 "still in debt three seconds after an over-large proof"
10541 );
10542 assert!(
10543 budget.has_budget(at(5)),
10544 "the debt is worked off at the refill rate"
10545 );
10546
10547 // Idle time does not bank unbounded credit for a later flood.
10548 budget.refill(at(24 * 60 * 60));
10549 assert_eq!(
10550 budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
10551 "refill is capped at the burst size"
10552 );
10553 }
10554
10555 // The heavy round-1 pool size is the tightest bound the responder applies and
10556 // the one least backed by fleet measurement, so it is read from config rather
10557 // than baked into the binary: a fleet that lands on the wrong number retunes
10558 // instead of waiting for a release. These pin that the configured value is
10559 // what actually gates admission, and that a 0 degrades to slow, not to off —
10560 // a wedged-shut responder would read on every auditor as a graced timeout,
10561 // i.e. a silent audit outage with nobody penalised and nothing in the logs.
10562 #[tokio::test]
10563 async fn round1_pool_size_comes_from_config() {
10564 // Cooldown disabled so only concurrency can refuse anything.
10565 let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
10566 let held = limiter.admit(&test_peer(1)).await;
10567 assert!(held.is_some(), "the single configured slot is admitted");
10568 assert!(
10569 limiter.admit(&test_peer(2)).await.is_none(),
10570 "a second concurrent round 1 is refused at a configured pool of 1, \
10571 proving admission follows config rather than the compiled-in default"
10572 );
10573 drop(held);
10574 assert!(
10575 limiter.admit(&test_peer(2)).await.is_some(),
10576 "the slot is reusable once the first proof completes"
10577 );
10578 }
10579
10580 #[tokio::test]
10581 async fn round1_pool_size_of_zero_is_clamped_to_one() {
10582 let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
10583 assert!(
10584 limiter.admit(&test_peer(1)).await.is_some(),
10585 "a mis-set pool of 0 must still serve audits, not silently refuse every one"
10586 );
10587 }
10588
10589 fn test_key(b: u8) -> crate::ant_protocol::XorName {
10590 let mut k = [0u8; 32];
10591 k[0] = b;
10592 k
10593 }
10594
10595 #[test]
10596 fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
10597 let source = test_peer(0x91);
10598 let corroborator = test_peer(0x92);
10599 let mut evidence = types::KeyVerificationEvidence {
10600 presence: HashMap::from([(source, PresenceEvidence::Absent)]),
10601 paid_list: HashMap::new(),
10602 };
10603 let failed = KeyVerificationOutcome::QuorumFailed;
10604
10605 assert_eq!(
10606 punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10607 Some((source, SingletonHintFault::RejectedByCloseGroup)),
10608 "a close-group rejection outranks the denial: the key does not exist, which is \
10609 a bad hint however the sender's own disk is doing"
10610 );
10611 assert_eq!(
10612 punishable_singleton_replica_hint_source(
10613 &HashSet::from([source, corroborator]),
10614 &failed,
10615 &evidence,
10616 ),
10617 None,
10618 "corroborated hints must not use the sole-source penalty lane"
10619 );
10620 assert_eq!(
10621 punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
10622 None,
10623 "paid-list advertisements do not claim possession, so they leave the \
10624 replica-hint source set empty and cannot be penalized"
10625 );
10626
10627 evidence
10628 .presence
10629 .insert(source, PresenceEvidence::Unresolved);
10630 assert_eq!(
10631 punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10632 Some((source, SingletonHintFault::RejectedByCloseGroup)),
10633 "definitive close-group rejection is punishable without direct contradiction"
10634 );
10635 assert_eq!(
10636 punishable_singleton_replica_hint_source(
10637 &HashSet::from([source]),
10638 &KeyVerificationOutcome::QuorumInconclusive,
10639 &evidence,
10640 ),
10641 None,
10642 "timeouts and inconclusive evidence are neutral"
10643 );
10644
10645 evidence.presence.insert(source, PresenceEvidence::Absent);
10646 assert_eq!(
10647 punishable_singleton_replica_hint_source(
10648 &HashSet::from([source]),
10649 &KeyVerificationOutcome::QuorumVerified {
10650 sources: vec![corroborator],
10651 },
10652 &evidence,
10653 ),
10654 Some((source, SingletonHintFault::DeniedPossession)),
10655 "an explicit denial is punishable regardless of the overall outcome, and is \
10656 classified separately because it is a statement about the sender's own \
10657 storage rather than about the key"
10658 );
10659 }
10660
10661 /// Build a round-2 slice challenge matching an open session. `openings` is
10662 /// empty: these tests exercise admission and session handling only, which
10663 /// run before any block is opened.
10664 fn slice_challenge(
10665 challenge_id: u64,
10666 commitment_hash: [u8; 32],
10667 nonce: [u8; 32],
10668 ) -> protocol::SubtreeSliceChallenge {
10669 protocol::SubtreeSliceChallenge {
10670 challenge_id,
10671 nonce,
10672 challenged_peer_id: [0u8; 32],
10673 expected_commitment_hash: commitment_hash,
10674 openings: Vec::new(),
10675 }
10676 }
10677
10678 // Regression (Copilot, PR #181): a round-2 slice challenge refused at the
10679 // responder caps MUST NOT burn the single-use round-1 session.
10680 //
10681 // The handler used to consume the session first and admit second, so a
10682 // transient local capacity drop permanently destroyed that audit exchange —
10683 // every retry hit the `no live round-1 session` path and got `Transient`,
10684 // even after load cleared. Turning momentary local load into a deterministic
10685 // round-2 miss costs the responder its whole-slice credit for that round.
10686 #[tokio::test]
10687 async fn capacity_refused_slice_challenge_preserves_round1_session() {
10688 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10689 let inflight = Arc::new(RwLock::new(HashMap::new()));
10690 let round1 =
10691 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10692 let peer = test_peer(0xB1);
10693 let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
10694 let challenge = slice_challenge(id, hash, nonce);
10695
10696 round1.open_session(peer, id, hash, nonce).await;
10697
10698 // Saturate this peer's share so the next admission must be refused.
10699 let mut hold = Vec::new();
10700 for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10701 match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
10702 .await
10703 {
10704 Ok(guard) => hold.push(guard),
10705 Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
10706 }
10707 }
10708
10709 let refused =
10710 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10711 assert!(
10712 matches!(refused, SliceAdmission::Capacity(_)),
10713 "a saturated peer share must refuse on capacity, not on session"
10714 );
10715
10716 // Load clears. The session must have survived the refusal.
10717 drop(hold);
10718 let retried =
10719 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10720 assert!(
10721 matches!(retried, SliceAdmission::Admitted(_)),
10722 "the round-1 session must survive a capacity refusal so the retry succeeds"
10723 );
10724
10725 // Still single-use: the successful admission consumed it exactly once.
10726 drop(retried);
10727 let replayed =
10728 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10729 assert!(
10730 matches!(replayed, SliceAdmission::NoSession),
10731 "a consumed session must not be replayable"
10732 );
10733 }
10734
10735 // The permit taken for the session probe is released when the probe misses,
10736 // so an unsessioned flood cannot pin the responder pool shut.
10737 #[tokio::test]
10738 async fn unsessioned_slice_challenge_releases_its_admission_slot() {
10739 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10740 let inflight = Arc::new(RwLock::new(HashMap::new()));
10741 let round1 =
10742 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10743 let peer = test_peer(0xB2);
10744 let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
10745
10746 // Far more unsessioned challenges than the per-peer cap would allow if
10747 // the slot leaked on the miss path.
10748 for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
10749 let outcome =
10750 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10751 assert!(
10752 matches!(outcome, SliceAdmission::NoSession),
10753 "no session was ever opened, so every attempt must miss"
10754 );
10755 }
10756
10757 assert_eq!(
10758 semaphore.available_permits(),
10759 MAX_CONCURRENT_AUDIT_RESPONSES,
10760 "every global permit must be returned"
10761 );
10762 assert!(
10763 inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
10764 "no per-peer slot may be left occupied"
10765 );
10766 }
10767
10768 #[test]
10769 fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
10770 assert!(!audit_failure_revokes_holder_credit(
10771 &AuditFailureReason::Timeout
10772 ));
10773 assert!(audit_failure_revokes_holder_credit(
10774 &AuditFailureReason::DigestMismatch
10775 ));
10776 }
10777
10778 #[tokio::test]
10779 async fn audit_responder_admission_reports_per_peer_cap_full() {
10780 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10781 let inflight = Arc::new(RwLock::new(HashMap::new()));
10782 let peer = test_peer(0xA1);
10783
10784 let mut guards = Vec::new();
10785 for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10786 match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
10787 .await
10788 {
10789 Ok(guard) => guards.push(guard),
10790 Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
10791 }
10792 }
10793
10794 let Err(err) =
10795 admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10796 else {
10797 panic!("admission should fail once per-peer cap is full");
10798 };
10799 assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
10800 assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
10801 assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10802 assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10803
10804 drop(guards);
10805 }
10806
10807 #[tokio::test]
10808 async fn audit_responder_admission_reports_global_pool_full() {
10809 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10810 let inflight = Arc::new(RwLock::new(HashMap::new()));
10811 let peer = test_peer(0xA2);
10812
10813 let mut held_global_permits = Vec::new();
10814 for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
10815 held_global_permits.push(
10816 Arc::clone(&semaphore)
10817 .try_acquire_owned()
10818 .expect("test should be able to exhaust the global pool"),
10819 );
10820 }
10821
10822 let Err(err) =
10823 admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10824 else {
10825 panic!("admission should fail once global pool is full");
10826 };
10827 assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
10828 assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
10829 assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10830 assert_eq!(err.peer_inflight, 0);
10831 assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10832
10833 drop(held_global_permits);
10834 }
10835
10836 #[tokio::test]
10837 async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
10838 let semaphore = Arc::new(Semaphore::new(1));
10839 let inflight = Arc::new(RwLock::new(HashMap::new()));
10840 let peer = test_peer(0xA3);
10841
10842 let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
10843 .await
10844 .expect("first responder should be admitted");
10845 assert_eq!(semaphore.available_permits(), 0);
10846 assert_eq!(inflight.read().await.get(&peer), Some(&1));
10847
10848 drop(guard);
10849 assert_eq!(semaphore.available_permits(), 1);
10850 assert!(!inflight.read().await.contains_key(&peer));
10851 }
10852
10853 #[tokio::test]
10854 async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
10855 let semaphore = Arc::new(Semaphore::new(1));
10856 let inflight = Arc::new(RwLock::new(HashMap::new()));
10857 let peer = test_peer(0xA4);
10858 let held_map = inflight.write().await;
10859
10860 let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
10861 assert!(
10862 tokio::time::timeout(Duration::from_millis(10), waiting)
10863 .await
10864 .is_err(),
10865 "admission should still be waiting for the peer map"
10866 );
10867
10868 drop(held_map);
10869 assert_eq!(semaphore.available_permits(), 1);
10870 assert!(!inflight.read().await.contains_key(&peer));
10871 }
10872
10873 #[test]
10874 fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
10875 let timeout = Duration::from_secs(1);
10876 let old_received_at = Instant::now()
10877 .checked_sub(timeout)
10878 .unwrap_or_else(Instant::now);
10879
10880 assert!(request_is_stale(old_received_at, timeout));
10881 assert!(!request_is_stale(Instant::now(), timeout));
10882 }
10883
10884 #[tokio::test]
10885 async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
10886 let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
10887 let inflight = Arc::new(RwLock::new(HashMap::new()));
10888 let first_peer = test_peer(0xB3);
10889 let second_peer = test_peer(0xB4);
10890
10891 let first_guard = admit_bounded_responder(
10892 &semaphore,
10893 &inflight,
10894 &first_peer,
10895 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10896 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10897 )
10898 .await
10899 .expect("first sync from a peer should be admitted");
10900 let duplicate = admit_bounded_responder(
10901 &semaphore,
10902 &inflight,
10903 &first_peer,
10904 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10905 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10906 )
10907 .await;
10908 let other_peer = admit_bounded_responder(
10909 &semaphore,
10910 &inflight,
10911 &second_peer,
10912 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10913 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10914 )
10915 .await;
10916
10917 assert!(matches!(
10918 duplicate,
10919 Err(ResponderAdmissionFailure {
10920 reason: ResponderRejectReason::PerPeerCapFull,
10921 ..
10922 })
10923 ));
10924 assert!(other_peer.is_ok());
10925 drop(first_guard);
10926 drop(other_peer);
10927 }
10928
10929 /// One flooding peer must not be able to hold every fresh-offer slot.
10930 ///
10931 /// This is the eviction primitive the per-peer share closes: with only a
10932 /// global bound, a single source occupies the pool, every honest offer in
10933 /// that window is refused, and because a refusal reads as absence to the
10934 /// sender's delayed possession check those refusals land as
10935 /// audit-severity penalties on *this* node.
10936 #[tokio::test]
10937 async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
10938 let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
10939 let inflight = Arc::new(RwLock::new(HashMap::new()));
10940 let flooder = test_peer(0xC1);
10941 let honest = test_peer(0xC2);
10942
10943 let mut held = Vec::new();
10944 for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
10945 held.push(
10946 admit_bounded_responder(
10947 &semaphore,
10948 &inflight,
10949 &flooder,
10950 FRESH_OFFER_MAX_OUTSTANDING,
10951 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10952 )
10953 .await
10954 .expect("offers within the per-peer share are admitted"),
10955 );
10956 }
10957
10958 let flooder_excess = admit_bounded_responder(
10959 &semaphore,
10960 &inflight,
10961 &flooder,
10962 FRESH_OFFER_MAX_OUTSTANDING,
10963 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10964 )
10965 .await;
10966 assert!(
10967 matches!(
10968 flooder_excess,
10969 Err(ResponderAdmissionFailure {
10970 reason: ResponderRejectReason::PerPeerCapFull,
10971 ..
10972 })
10973 ),
10974 "one source must not exceed its fresh-offer share"
10975 );
10976
10977 let honest_offer = admit_bounded_responder(
10978 &semaphore,
10979 &inflight,
10980 &honest,
10981 FRESH_OFFER_MAX_OUTSTANDING,
10982 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10983 )
10984 .await;
10985 assert!(
10986 honest_offer.is_ok(),
10987 "an honest sender must still be admitted while another peer floods"
10988 );
10989
10990 assert!(
10991 usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
10992 < FRESH_OFFER_MAX_OUTSTANDING,
10993 "the per-peer share must leave room for other sources"
10994 );
10995
10996 drop(held);
10997 drop(honest_offer);
10998 }
10999
11000 /// Paid notifies get the same per-source treatment as every other class.
11001 #[tokio::test]
11002 async fn paid_notify_admission_reserves_capacity_for_other_peers() {
11003 let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
11004 let inflight = Arc::new(RwLock::new(HashMap::new()));
11005 let flooder = test_peer(0xC3);
11006 let honest = test_peer(0xC4);
11007
11008 let mut held = Vec::new();
11009 for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
11010 held.push(
11011 admit_bounded_responder(
11012 &semaphore,
11013 &inflight,
11014 &flooder,
11015 PAID_NOTIFY_MAX_OUTSTANDING,
11016 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11017 )
11018 .await
11019 .expect("notifies within the per-peer share are admitted"),
11020 );
11021 }
11022
11023 assert!(
11024 matches!(
11025 admit_bounded_responder(
11026 &semaphore,
11027 &inflight,
11028 &flooder,
11029 PAID_NOTIFY_MAX_OUTSTANDING,
11030 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11031 )
11032 .await,
11033 Err(ResponderAdmissionFailure {
11034 reason: ResponderRejectReason::PerPeerCapFull,
11035 ..
11036 })
11037 ),
11038 "one source must not exceed its paid-notify share"
11039 );
11040 assert!(
11041 admit_bounded_responder(
11042 &semaphore,
11043 &inflight,
11044 &honest,
11045 PAID_NOTIFY_MAX_OUTSTANDING,
11046 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11047 )
11048 .await
11049 .is_ok(),
11050 "an honest sender must still be admitted while another peer floods"
11051 );
11052
11053 drop(held);
11054 }
11055
11056 /// The fresh-offer per-source bound must guarantee headroom for a peer
11057 /// holding nothing, without throttling a single legitimate fan-out.
11058 ///
11059 /// Sized as a quota rather than a reserve, this bound refused offers during
11060 /// an ordinary upload (see `tests/e2e/fresh_offer_capacity.rs`), and every
11061 /// refusal is charged to THIS node at audit severity because the sender
11062 /// never reads it.
11063 #[test]
11064 fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
11065 let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
11066
11067 assert_eq!(
11068 FRESH_OFFER_MAX_OUTSTANDING - share,
11069 FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
11070 "a source holding none must always find a free slot"
11071 );
11072 assert!(
11073 share < FRESH_OFFER_MAX_OUTSTANDING,
11074 "one peer must not be able to take the whole pool"
11075 );
11076 // The failure this pins: a share sized like the request/response
11077 // classes (fetch 2, verification 1, neighbor sync 1) binds on ordinary
11078 // one-way bulk traffic.
11079 assert!(
11080 share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
11081 "fresh offers are one-way bulk, not request/response — their share \
11082 must not be sized like the request classes'"
11083 );
11084 }
11085
11086 /// A malformed offer must be refused before it can occupy an admission
11087 /// slot, so junk cannot hold capacity for the length of a verification.
11088 #[test]
11089 fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
11090 let key = test_key(0xC5);
11091
11092 let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11093
11094 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
11095 .expect("an offer with no proof must be refused");
11096 assert!(
11097 rejection.penalise,
11098 "an honest sender always attaches a proof"
11099 );
11100
11101 // A proof is retained per queued sender, so its size has to be bounded
11102 // here rather than at the verifier, which only sees it on a worker.
11103 let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
11104 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
11105 .expect("an undersized proof must be refused");
11106 assert!(
11107 rejection.penalise,
11108 "no honest sender constructs an undersized proof"
11109 );
11110 let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
11111 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
11112 .expect("an oversized proof must be refused");
11113 assert!(
11114 rejection.penalise,
11115 "no honest sender constructs an oversized proof"
11116 );
11117
11118 let rejection = fresh_offer_structural_rejection(
11119 &key,
11120 &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
11121 &valid_proof,
11122 )
11123 .expect("an oversized offer must be refused");
11124 assert!(
11125 rejection.penalise,
11126 "no honest sender constructs an oversized offer"
11127 );
11128
11129 let data = vec![0u8; 1];
11130 assert!(
11131 fresh_offer_structural_rejection(
11132 &crate::client::compute_address(&data),
11133 &data,
11134 &valid_proof
11135 )
11136 .is_none(),
11137 "a well-formed offer must reach admission"
11138 );
11139 }
11140
11141 /// Knowing a key must not be enough to enter its entry.
11142 ///
11143 /// Opening an entry on an unverified key/bytes association would let a peer
11144 /// that has only *learned* the key — every recipient of its `PaidNotify`,
11145 /// not just the close group that gets the chunk — seize it with junk.
11146 /// Joining one would be worse: the handler tries each queued proof against
11147 /// the *opener's* bytes, so an unchecked joiner could have its proof spent
11148 /// on bytes it never offered.
11149 #[test]
11150 fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
11151 let genuine_data = vec![0x5Au8; 128];
11152 let key = crate::client::compute_address(&genuine_data);
11153 let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11154
11155 let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
11156 .expect("bytes that do not hash to the advertised key must be refused");
11157 assert!(
11158 rejection.penalise,
11159 "no honest sender offers bytes that do not hash to the advertised key"
11160 );
11161
11162 // Dispatch reaches the entry only past that rejection, so the forged
11163 // offer never touched the key and the genuine one still opens it.
11164 assert!(
11165 fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
11166 "the offer that actually carries the key's bytes must reach the entry"
11167 );
11168
11169 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
11170 assert!(
11171 matches!(
11172 admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
11173 FreshOfferAdmission::Opened(_)
11174 ),
11175 "an offer refused on payload shape must leave the key openable"
11176 );
11177 }
11178
11179 #[tokio::test]
11180 async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
11181 let peer = test_peer(0xA5);
11182 let key = test_key(0xA5);
11183 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11184 let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11185 let is_bootstrapping = Arc::new(RwLock::new(true));
11186 let bootstrap_complete_notify = Arc::new(Notify::new());
11187
11188 let now = Instant::now();
11189 queues.write().await.add_pending_verify(
11190 key,
11191 VerificationEntry {
11192 state: VerificationState::PendingVerify,
11193 verified_sources: Vec::new(),
11194 tried_sources: HashSet::new(),
11195 created_at: now,
11196 next_verify_at: now,
11197 hint_sources: HashSet::from([peer]),
11198 replica_hint_sources: HashSet::from([peer]),
11199 unresolved_retries: 0,
11200 no_holder_reported: false,
11201 },
11202 );
11203 super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
11204 super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11205 {
11206 let q = queues.read().await;
11207 assert!(
11208 !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
11209 "capacity rejection should initially block bootstrap drain"
11210 );
11211 }
11212
11213 update_bootstrap_after_peer_removed(
11214 &peer,
11215 &bootstrap_state,
11216 &queues,
11217 &is_bootstrapping,
11218 &bootstrap_complete_notify,
11219 )
11220 .await;
11221
11222 let state = bootstrap_state.read().await;
11223 assert!(state.capacity_rejected_sources.is_empty());
11224 assert!(state.pending_keys.is_empty());
11225 assert!(state.is_drained());
11226 drop(state);
11227 assert!(!*is_bootstrapping.read().await);
11228 }
11229
11230 /// A fairness displacement forfeits the key but must not stamp its former
11231 /// owner: the owner did nothing wrong, and stamping it lets a flooding
11232 /// source block bootstrap drain through an unrelated honest peer.
11233 #[tokio::test]
11234 async fn fairness_displacement_does_not_stamp_its_victim() {
11235 let displaced_owner = test_peer(0xB1);
11236 let incoming_source = test_peer(0xB2);
11237 let displaced_key = test_key(0xB1);
11238 let admitted_key = test_key(0xB2);
11239 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11240 {
11241 let mut state = bootstrap_state.write().await;
11242 state.pending_keys.insert(displaced_key);
11243 state
11244 .capacity_rejected_sources
11245 .insert(incoming_source, Instant::now());
11246 }
11247 let outcomes = [(
11248 incoming_source,
11249 AdmissionOutcome {
11250 discovered: HashSet::from([admitted_key]),
11251 capacity_rejected_count: 0,
11252 displaced: vec![CapacityDisplacement {
11253 key: displaced_key,
11254 owner: displaced_owner,
11255 }],
11256 },
11257 )];
11258
11259 publish_bootstrap_admission_outcomes(
11260 &bootstrap_state,
11261 &outcomes,
11262 &HashSet::from([admitted_key]),
11263 )
11264 .await;
11265
11266 let state = bootstrap_state.read().await;
11267 assert!(!state.pending_keys.contains(&displaced_key));
11268 assert!(state.pending_keys.contains(&admitted_key));
11269 assert!(
11270 !state
11271 .capacity_rejected_sources
11272 .contains_key(&displaced_owner),
11273 "the displaced owner must not be charged for our own fairness reclaim"
11274 );
11275 assert!(!state
11276 .capacity_rejected_sources
11277 .contains_key(&incoming_source));
11278 }
11279
11280 /// A source that keeps overflowing us must not keep its own record fresh.
11281 ///
11282 /// This is the wedge the first-seen stamp closes: with refresh-on-every-
11283 /// rejection the debt could never age out, so `check_bootstrap_drained`
11284 /// stayed false forever and auditing never started (Invariant 19).
11285 #[tokio::test]
11286 async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
11287 const REJECTION_ROUNDS: usize = 5;
11288
11289 let source = test_peer(0xB3);
11290 let key = test_key(0xB3);
11291 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11292
11293 let first_seen = {
11294 let outcomes = [(
11295 source,
11296 AdmissionOutcome {
11297 discovered: HashSet::new(),
11298 capacity_rejected_count: 1,
11299 displaced: Vec::new(),
11300 },
11301 )];
11302 publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
11303 .await;
11304 bootstrap_state
11305 .read()
11306 .await
11307 .capacity_rejected_sources
11308 .get(&source)
11309 .copied()
11310 .expect("first rejection recorded")
11311 };
11312
11313 for _ in 0..REJECTION_ROUNDS {
11314 let outcomes = [(
11315 source,
11316 AdmissionOutcome {
11317 discovered: HashSet::from([key]),
11318 capacity_rejected_count: 1,
11319 displaced: Vec::new(),
11320 },
11321 )];
11322 publish_bootstrap_admission_outcomes(
11323 &bootstrap_state,
11324 &outcomes,
11325 &HashSet::from([key]),
11326 )
11327 .await;
11328 }
11329
11330 let recorded = bootstrap_state
11331 .read()
11332 .await
11333 .capacity_rejected_sources
11334 .get(&source)
11335 .copied()
11336 .expect("debt still outstanding");
11337 assert_eq!(
11338 recorded, first_seen,
11339 "repeat rejections must not restart the expiry clock"
11340 );
11341 }
11342
11343 /// The verification-worker tick's self-heal path: a capacity rejection
11344 /// recorded after the peer's `PeerRemoved` cleanup (the TOCTOU orphan)
11345 /// blocks drain until the TTL expires it, at which point the same tick
11346 /// completes bootstrap without any external event.
11347 #[tokio::test]
11348 async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
11349 let peer = test_peer(0xA6);
11350 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11351 let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11352 let is_bootstrapping = Arc::new(RwLock::new(true));
11353 let bootstrap_complete_notify = Arc::new(Notify::new());
11354
11355 // PeerRemoved was fully processed before the rejection landed, so no
11356 // future event will ever clear this entry.
11357 super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11358
11359 // Within the TTL the tick keeps waiting for re-delivery.
11360 expire_and_recheck_bootstrap_drain(
11361 &bootstrap_state,
11362 &queues,
11363 &is_bootstrapping,
11364 &bootstrap_complete_notify,
11365 ReplicationConfig::default().capacity_rejected_max_age(),
11366 )
11367 .await;
11368 assert!(!bootstrap_state.read().await.is_drained());
11369 assert!(*is_bootstrapping.read().await);
11370
11371 // Past the TTL the tick expires the orphan and completes bootstrap.
11372 expire_and_recheck_bootstrap_drain(
11373 &bootstrap_state,
11374 &queues,
11375 &is_bootstrapping,
11376 &bootstrap_complete_notify,
11377 Duration::ZERO,
11378 )
11379 .await;
11380 assert!(bootstrap_state.read().await.is_drained());
11381 assert!(!*is_bootstrapping.read().await);
11382 }
11383
11384 #[test]
11385 fn first_audit_terminal_outcomes_are_stable() {
11386 let peer = test_peer(1);
11387 let passed = AuditTickResult::Passed {
11388 challenged_peer: peer,
11389 keys_checked: 1,
11390 };
11391 let timed_out = AuditTickResult::Failed {
11392 evidence: FailureEvidence::AuditFailure {
11393 challenge_id: 1,
11394 challenged_peer: peer,
11395 confirmed_failed_keys: vec![test_key(1)],
11396 summary: crate::replication::types::AuditFailureSummary::default(),
11397 reason: AuditFailureReason::Timeout,
11398 },
11399 no_response_class: Some("timeout"),
11400 };
11401
11402 assert_eq!(
11403 first_audit_terminal_outcome(&passed),
11404 FirstAuditTerminalOutcome::Passed
11405 );
11406 assert_eq!(
11407 first_audit_terminal_outcome(&timed_out),
11408 FirstAuditTerminalOutcome::Timeout
11409 );
11410 assert_eq!(
11411 first_audit_terminal_outcome(&AuditTickResult::Idle),
11412 FirstAuditTerminalOutcome::Idle
11413 );
11414 assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
11415 assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
11416 assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
11417 assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
11418 assert_eq!(
11419 FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
11420 "insufficient_keys"
11421 );
11422 assert_eq!(
11423 FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
11424 "bootstrap_claim"
11425 );
11426 }
11427
11428 #[test]
11429 fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
11430 let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11431 let mut rng = StdRng::seed_from_u64(7);
11432 let peer = test_peer(1);
11433 let base = MonetizedPinEvent {
11434 peer,
11435 pin: [1; 32],
11436 key_count: 100,
11437 quote_ts: SystemTime::now(),
11438 };
11439
11440 // First insert into an empty slot: Queued.
11441 assert_eq!(
11442 coalesce_first_audit_event(&mut pending, base, true, &mut rng),
11443 FirstAuditQueueOutcome::Queued
11444 );
11445
11446 // A strictly LOWER-count same-peer nomination must NOT displace it.
11447 let lower = MonetizedPinEvent {
11448 pin: [2; 32],
11449 key_count: 50,
11450 ..base
11451 };
11452 assert_eq!(
11453 coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
11454 FirstAuditQueueOutcome::SuppressedLower
11455 );
11456 assert_eq!(
11457 pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11458 Some(([1; 32], 100)),
11459 "the higher-count pin is retained"
11460 );
11461
11462 // A HIGHER-count same-peer nomination wins (the inflated pin to audit).
11463 let higher = MonetizedPinEvent {
11464 pin: [3; 32],
11465 key_count: 400,
11466 ..base
11467 };
11468 assert_eq!(
11469 coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
11470 FirstAuditQueueOutcome::Coalesced
11471 );
11472 assert_eq!(
11473 pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11474 Some(([3; 32], 400))
11475 );
11476
11477 // EQUAL count: an ordinary (newer) enqueue replaces for freshness...
11478 let equal_newer = MonetizedPinEvent {
11479 pin: [4; 32],
11480 key_count: 400,
11481 ..base
11482 };
11483 assert_eq!(
11484 coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
11485 FirstAuditQueueOutcome::Coalesced
11486 );
11487 assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11488 // ...but an equal-count OLDER requeue (incoming_is_newer=false) does not.
11489 let equal_older = MonetizedPinEvent {
11490 pin: [5; 32],
11491 key_count: 400,
11492 ..base
11493 };
11494 assert_eq!(
11495 coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
11496 FirstAuditQueueOutcome::RetainedOnTie
11497 );
11498 assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11499
11500 // A different peer at capacity 1 evicts the LRU (a DIFFERENT peer).
11501 let other_peer = MonetizedPinEvent {
11502 peer: test_peer(2),
11503 pin: [6; 32],
11504 key_count: 100,
11505 ..base
11506 };
11507 assert_eq!(
11508 coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
11509 FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
11510 );
11511 assert_eq!(pending.len(), 1);
11512 assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
11513 }
11514
11515 // -- ADR-0004 Amendment 2: first-audit launch limiter --------------------
11516
11517 #[test]
11518 fn first_audit_limiter_enforces_burst_then_refills() {
11519 let base = Instant::now();
11520 let mut limiter = FirstAuditLimiter::new(base);
11521 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11522
11523 // The full burst is admitted back-to-back (distinct peers).
11524 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11525 let peer = test_peer(u8::try_from(i).expect("small burst"));
11526 assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11527 limiter.commit_launch(peer, 10, base);
11528 }
11529 // Bucket empty: the next distinct peer is deferred, never dropped.
11530 let extra = test_peer(0xEE);
11531 assert_eq!(
11532 limiter.assess(&extra, 10, base, 0),
11533 LimiterVerdict::RateDeferred
11534 );
11535
11536 // One full interval later exactly one token is available again.
11537 let later = base + interval;
11538 assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
11539 limiter.commit_launch(extra, 10, later);
11540 let extra2 = test_peer(0xEF);
11541 assert_eq!(
11542 limiter.assess(&extra2, 10, later, 0),
11543 LimiterVerdict::RateDeferred
11544 );
11545 }
11546
11547 #[test]
11548 fn first_audit_limiter_refill_keeps_fractional_remainder() {
11549 let base = Instant::now();
11550 let mut limiter = FirstAuditLimiter::new(base);
11551 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11552 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11553 let peer = test_peer(u8::try_from(i).expect("small burst"));
11554 assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
11555 limiter.commit_launch(peer, 1, base);
11556 }
11557 // 1.5 intervals later one token is earned and the half interval is
11558 // NOT lost to drift...
11559 let at_1_5 = base + interval + interval / 2;
11560 let p = test_peer(0xAA);
11561 assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
11562 limiter.commit_launch(p, 1, at_1_5);
11563 // ...so the next token arrives at 2.0 intervals, not 2.5.
11564 let at_2_0 = base + interval * 2;
11565 let q = test_peer(0xAB);
11566 assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
11567 }
11568
11569 #[test]
11570 fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
11571 let base = Instant::now();
11572 let mut limiter = FirstAuditLimiter::new(base);
11573 let peer = test_peer(1);
11574 assert_eq!(
11575 limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
11576 LimiterVerdict::RateDeferred
11577 );
11578 // A freed slot admits without any clock movement.
11579 assert_eq!(
11580 limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
11581 LimiterVerdict::Admit
11582 );
11583 }
11584
11585 #[test]
11586 fn first_audit_limiter_assess_consumes_nothing() {
11587 let base = Instant::now();
11588 let mut limiter = FirstAuditLimiter::new(base);
11589 let peer = test_peer(3);
11590 // Repeated assessment must not burn budget or stamp the window: only
11591 // `commit_launch` consumes (the cooldown gate between assess and
11592 // commit can defer, and that deferral must be free).
11593 for _ in 0..10 {
11594 assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
11595 }
11596 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11597 let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
11598 assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
11599 limiter.commit_launch(p, 5, base);
11600 }
11601 }
11602
11603 #[test]
11604 fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
11605 let base = Instant::now();
11606 let mut limiter = FirstAuditLimiter::new(base);
11607 let peer = test_peer(7);
11608 assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
11609 limiter.commit_launch(peer, 100, base);
11610
11611 // A rotated pin with a similar count inside the window is dropped...
11612 let soon = base + Duration::from_secs(60);
11613 assert_eq!(
11614 limiter.assess(&peer, 100, soon, 0),
11615 LimiterVerdict::WindowDeduped
11616 );
11617 // ...even at the exact jump boundary (new*DEN == old*NUM is no jump)...
11618 assert_eq!(
11619 limiter.assess(&peer, 150, soon, 0),
11620 LimiterVerdict::WindowDeduped
11621 );
11622 // ...but a >1.5x committed-count jump re-nominates immediately (an
11623 // inflated sidecar-only pin is invisible to the gossip lottery, so
11624 // the window must not shield it).
11625 assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
11626
11627 // Window expiry re-admits an unchanged count.
11628 let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
11629 assert_eq!(
11630 limiter.assess(&peer, 100, expired, 0),
11631 LimiterVerdict::Admit
11632 );
11633 }
11634
11635 #[test]
11636 fn first_audit_limiter_window_verdict_outranks_empty_budget() {
11637 // A window-deduped nomination must be DROPPED, not kept pending as
11638 // rate-deferred, even when the bucket is also empty: re-queuing a
11639 // suppressed rotation would hold a pending slot for two hours.
11640 let base = Instant::now();
11641 let mut limiter = FirstAuditLimiter::new(base);
11642 let peer = test_peer(9);
11643 assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11644 limiter.commit_launch(peer, 10, base);
11645 let other = test_peer(10);
11646 assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
11647 limiter.commit_launch(other, 10, base);
11648 assert_eq!(
11649 limiter.assess(&peer, 10, base, 0),
11650 LimiterVerdict::WindowDeduped
11651 );
11652 }
11653
11654 /// ADR-0004 Amendment 2 (E'): the B horizon prefilter rejects a quote that
11655 /// is answerable now but would age out of the answerability window during
11656 /// the launch jitter, so scheduling state is only ever committed for a pin
11657 /// that can still be challenged when it actually sends.
11658 #[test]
11659 fn first_audit_horizon_prefilter_boundary() {
11660 let now = SystemTime::now();
11661 // C = the too-old cutoff; H = the worst-case send horizon.
11662 let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
11663 let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
11664 // A quote whose age is exactly C at `now + H` (in the past, since C > H).
11665 let boundary = now
11666 .checked_add(h)
11667 .and_then(|t| t.checked_sub(c))
11668 .expect("boundary time");
11669
11670 // In window at `now` (age = C - H < C)...
11671 assert!(quote_within_audit_window(boundary, now));
11672 // ...but the horizon prefilter rejects it (age == C at now + H).
11673 assert!(!quote_answerable_through_nominal_jitter(boundary, now));
11674
11675 // A hair newer stays answerable through the horizon; a hair older does
11676 // not. Use 1µs (not 1ns): Windows `SystemTime` has 100ns granularity, so
11677 // a nanosecond step would round to the same instant there.
11678 let newer = boundary
11679 .checked_add(Duration::from_micros(1))
11680 .expect("newer");
11681 let older = boundary
11682 .checked_sub(Duration::from_micros(1))
11683 .expect("older");
11684 assert!(quote_answerable_through_nominal_jitter(newer, now));
11685 assert!(!quote_answerable_through_nominal_jitter(older, now));
11686
11687 // A quote too far in the FUTURE is rejected at `now`, independent of the
11688 // horizon.
11689 let future = now
11690 .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
11691 .and_then(|t| t.checked_add(Duration::from_secs(60)))
11692 .expect("future");
11693 assert!(!quote_answerable_through_nominal_jitter(future, now));
11694 }
11695
11696 /// ADR-0004 Amendment 2 (E'): a reservation whose AUTHORITATIVE post-jitter
11697 /// answerability check fails at promotion is fully state-neutral — it stamps
11698 /// no `first_audited`, no per-peer window, refunds its token, releases its
11699 /// in-flight slot, does not flip the lane, and does not count a launch — and
11700 /// a same-peer, same-count successor enqueued DURING the reservation is
11701 /// retained and becomes the next reservation after the cancel. This is the
11702 /// exact hole the reviewer flagged: suppression must never outlive a launch
11703 /// that did not send.
11704 /// A pending pin that has aged past the answerability horizon must not
11705 /// suppress a live lower-count nomination for the same peer: under token
11706 /// starvation no reserve scan ever collects the dead entry, so without the
11707 /// enqueue-time check the peer would stay unauditable through this path
11708 /// indefinitely (e.g. after a prune legitimately lowered its key count).
11709 #[test]
11710 fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
11711 let obs = Arc::new(FirstAuditObservability::default());
11712 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11713 let peer = test_peer(1);
11714
11715 let dead_quote = SystemTime::now()
11716 .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11717 .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11718 .expect("past wall time");
11719 let stale_high = MonetizedPinEvent {
11720 peer,
11721 pin: [1; 32],
11722 key_count: 400,
11723 quote_ts: dead_quote,
11724 };
11725 scheduler.enqueue(stale_high, &obs);
11726 assert_eq!(scheduler.pending_len(), 1);
11727
11728 // A fresh, lower-count nomination (a post-prune commitment).
11729 let fresh_lower = MonetizedPinEvent {
11730 peer,
11731 pin: [2; 32],
11732 key_count: 100,
11733 quote_ts: SystemTime::now(),
11734 };
11735 scheduler.enqueue(fresh_lower, &obs);
11736
11737 assert_eq!(scheduler.pending_len(), 1);
11738 assert_eq!(
11739 scheduler.pending.peek(&peer).map(|e| e.pin),
11740 Some([2; 32]),
11741 "the live nomination replaced the dead incumbent"
11742 );
11743 assert_eq!(
11744 obs.suppressed_lower.load(Ordering::Relaxed),
11745 0,
11746 "no self-erasure signal for displacing a dead pin"
11747 );
11748 assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
11749 assert_eq!(
11750 obs.outside_answerability_window.load(Ordering::Relaxed),
11751 1,
11752 "the dead incumbent is accounted as an expiry"
11753 );
11754 }
11755
11756 /// The self-erasure defence is untouched for LIVE incumbents: a lower-count
11757 /// nomination still loses to an answerable higher-count pending pin.
11758 #[test]
11759 fn first_audit_live_incumbent_still_suppresses_lower_count() {
11760 let obs = Arc::new(FirstAuditObservability::default());
11761 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11762 let peer = test_peer(1);
11763
11764 let live_high = MonetizedPinEvent {
11765 peer,
11766 pin: [1; 32],
11767 key_count: 400,
11768 quote_ts: SystemTime::now(),
11769 };
11770 scheduler.enqueue(live_high, &obs);
11771 let cheaper = MonetizedPinEvent {
11772 peer,
11773 pin: [2; 32],
11774 key_count: 100,
11775 quote_ts: SystemTime::now(),
11776 };
11777 scheduler.enqueue(cheaper, &obs);
11778
11779 assert_eq!(scheduler.pending_len(), 1);
11780 assert_eq!(
11781 scheduler.pending.peek(&peer).map(|e| e.pin),
11782 Some([1; 32]),
11783 "the higher-count live pin is retained"
11784 );
11785 assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
11786 assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
11787 }
11788
11789 /// A fresh nomination for peer `b` (distinct pin per peer).
11790 fn live_nomination(b: u8) -> MonetizedPinEvent {
11791 MonetizedPinEvent {
11792 peer: test_peer(b),
11793 pin: [b; 32],
11794 key_count: 100,
11795 quote_ts: SystemTime::now(),
11796 }
11797 }
11798
11799 /// The pending admission cap must equal the number of usable launches the
11800 /// token budget can perform inside one answerability window, counted by
11801 /// SIMULATING the shipped reserve-time predicate instant-by-instant (burst
11802 /// tokens at age zero, one refill per launch interval), not by repeating
11803 /// the derivation formula. Any larger and admitted work is guaranteed to
11804 /// expire unlaunched; any smaller and the budget idles while nominations
11805 /// are displaced.
11806 #[test]
11807 fn first_audit_pending_cap_matches_strict_launch_horizon() {
11808 let quote_ts = SystemTime::now();
11809 // Burst launches fire at age zero and must pass the reserve predicate.
11810 assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
11811 let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
11812 let mut refill = 1u32;
11813 loop {
11814 let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
11815 let at = quote_ts + age;
11816 if !quote_answerable_through_nominal_jitter(quote_ts, at) {
11817 break;
11818 }
11819 usable += 1;
11820 refill += 1;
11821 assert!(refill < 10_000, "runaway horizon simulation");
11822 }
11823 assert_eq!(
11824 FIRST_AUDIT_PENDING_CAP, usable,
11825 "cap must match the simulated strict launch horizon"
11826 );
11827 }
11828
11829 /// The pending queue is sized to the launch budget while the dedup set
11830 /// keeps the commitment-cache bound: shrinking `first_audited` would
11831 /// forget audited pins and re-admit duplicates.
11832 #[test]
11833 fn first_audit_pending_cap_independent_of_dedup_cap() {
11834 let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11835 assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
11836 assert_eq!(
11837 scheduler.first_audited.cap().get(),
11838 MAX_LAST_COMMITMENT_BY_PEER
11839 );
11840 }
11841
11842 /// Admission beyond the cap displaces exactly one incumbent per overflow
11843 /// and every displacement is accounted as `capacity_evicted` — the steady
11844 /// overload signal — never silent loss, and never an admission refusal.
11845 #[test]
11846 fn first_audit_admission_beyond_cap_displaces_and_counts() {
11847 let obs = Arc::new(FirstAuditObservability::default());
11848 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11849 let overflow: usize = 5;
11850 let total = FIRST_AUDIT_PENDING_CAP + overflow;
11851
11852 for i in 0..total {
11853 let b = u8::try_from(i + 1).expect("test peer count fits u8");
11854 scheduler.enqueue(live_nomination(b), &obs);
11855 }
11856
11857 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11858 assert_eq!(
11859 obs.capacity_evicted.load(Ordering::Relaxed),
11860 u64::try_from(overflow).expect("overflow fits u64"),
11861 "each admission past the cap displaces exactly one entry"
11862 );
11863 assert_eq!(
11864 obs.queued.load(Ordering::Relaxed),
11865 u64::try_from(total).expect("total fits u64"),
11866 "displacement is not an admission refusal"
11867 );
11868 // Every arrival was admitted (the newest always enters the sample).
11869 let last = u8::try_from(total).expect("test peer count fits u8");
11870 assert!(
11871 scheduler.pending.peek(&test_peer(last)).is_some(),
11872 "the newest arrival always enters the sample"
11873 );
11874 }
11875
11876 /// The reviewer-demonstrated suppression route: a target followed by an
11877 /// ordered batch of distinct-peer nominations, all inside one ingress
11878 /// drain batch (`pending_cap < batch <= FIRST_AUDIT_DRAIN_BATCH`), with
11879 /// the token bucket EMPTY so no reservation can intervene. Under the old
11880 /// keep-newest LRU the target was evicted with certainty; under random
11881 /// displacement its per-overflow eviction probability is `1/cap`, so
11882 /// across repeated trials the target must survive some runs and be
11883 /// displaced in others — never deterministically flushed, and every
11884 /// displacement accounted.
11885 #[test]
11886 fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
11887 let flood: usize = 60; // pending_cap < 60 <= FIRST_AUDIT_DRAIN_BATCH
11888 assert!(FIRST_AUDIT_PENDING_CAP < flood);
11889 assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
11890
11891 let trials = 100u64;
11892 let mut survived = 0u32;
11893 let mut evicted = 0u32;
11894 for trial in 0..trials {
11895 let obs = Arc::new(FirstAuditObservability::default());
11896 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11897 // Deterministic per-trial seed: the run is fully reproducible (no
11898 // flake budget at all) while still exercising 100 distinct
11899 // eviction sequences.
11900 scheduler.rng = StdRng::seed_from_u64(trial);
11901 // Drain the burst tokens so the pre-overflow reservation
11902 // opportunity cannot fire: this isolates pure retention.
11903 scheduler.limiter.reserve_token();
11904 scheduler.limiter.reserve_token();
11905
11906 let target = test_peer(200);
11907 scheduler.enqueue(live_nomination(200), &obs);
11908 for i in 0..flood {
11909 let b = u8::try_from(i + 1).expect("flood peer fits u8");
11910 scheduler.enqueue(live_nomination(b), &obs);
11911 }
11912
11913 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11914 let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
11915 .expect("overflow count fits u64");
11916 assert_eq!(
11917 obs.capacity_evicted.load(Ordering::Relaxed),
11918 overflows,
11919 "every overflow past the cap is accounted, none silent"
11920 );
11921 if scheduler.pending.peek(&target).is_some() {
11922 survived += 1;
11923 } else {
11924 evicted += 1;
11925 }
11926 }
11927 // With eviction probability 1/cap per overflow, P(target survives one
11928 // trial) ~= (1 - 1/31)^30 ~= 0.37, so both outcomes appear across the
11929 // 100 seeded trials — and the seeds make the split exactly
11930 // reproducible rather than a (vanishingly small) flake budget.
11931 assert!(
11932 survived > 0,
11933 "target must survive some ordered floods — deterministic eviction \
11934 would mean keep-newest retention regressed"
11935 );
11936 assert!(
11937 evicted > 0,
11938 "target must also be displaceable — otherwise overflow is refusing \
11939 admissions instead of sampling"
11940 );
11941 }
11942
11943 /// With a token AVAILABLE, an overflowing arrival must first give pending
11944 /// work a launch opportunity: the drainer's pre-overflow reservation pulls
11945 /// one entry out of the queue, so admission proceeds without any eviction.
11946 #[test]
11947 fn first_audit_overflow_reserves_before_destructive_eviction() {
11948 let obs = Arc::new(FirstAuditObservability::default());
11949 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11950 let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11951
11952 for i in 0..FIRST_AUDIT_PENDING_CAP {
11953 let b = u8::try_from(i + 1).expect("test peer count fits u8");
11954 scheduler.enqueue(live_nomination(b), &obs);
11955 }
11956 let overflowing = live_nomination(250);
11957 assert!(scheduler.would_displace(&overflowing));
11958
11959 // The drainer's pre-overflow sequence: reserve, then enqueue.
11960 assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
11961 assert!(
11962 !scheduler.would_displace(&overflowing),
11963 "a successful reservation frees the slot"
11964 );
11965 scheduler.enqueue(overflowing, &obs);
11966
11967 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11968 assert_eq!(
11969 obs.capacity_evicted.load(Ordering::Relaxed),
11970 0,
11971 "no destructive eviction when a launch opportunity existed"
11972 );
11973 }
11974
11975 /// Displacement stamps no suppression state: a displaced peer's next
11976 /// nomination re-enters like any newcomer (it is NOT window-deduped or
11977 /// treated as a duplicate), so under overload every peer keeps an
11978 /// unpredictable chance of prompt first audit.
11979 #[test]
11980 fn first_audit_displaced_peer_may_be_renominated() {
11981 let obs = Arc::new(FirstAuditObservability::default());
11982 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11983 let total = FIRST_AUDIT_PENDING_CAP + 1;
11984
11985 for i in 0..total {
11986 let b = u8::try_from(i + 1).expect("test peer count fits u8");
11987 scheduler.enqueue(live_nomination(b), &obs);
11988 }
11989 assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
11990 // Find whichever peer the random displacement removed.
11991 let displaced = (1..=total)
11992 .map(|i| u8::try_from(i).expect("test peer count fits u8"))
11993 .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
11994 .expect("exactly one admitted peer was displaced");
11995
11996 scheduler.enqueue(live_nomination(displaced), &obs);
11997
11998 assert!(
11999 scheduler.pending.peek(&test_peer(displaced)).is_some(),
12000 "the displaced peer re-enters the sample"
12001 );
12002 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12003 assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
12004 assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
12005 assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
12006 }
12007
12008 /// The periodic sweep collects expired pending entries even when the token
12009 /// bucket is empty — the reserve path returns at the budget gate and never
12010 /// scans — keeping the capped pending queue and the pending/oldest-age telemetry
12011 /// honest under fleet-wide starvation.
12012 #[test]
12013 fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
12014 let obs = Arc::new(FirstAuditObservability::default());
12015 let mono = Instant::now();
12016 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12017
12018 let dead_quote = SystemTime::now()
12019 .checked_sub(GOSSIP_ANSWERABILITY_TTL)
12020 .and_then(|t| t.checked_sub(Duration::from_secs(60)))
12021 .expect("past wall time");
12022 scheduler.enqueue(
12023 MonetizedPinEvent {
12024 peer: test_peer(1),
12025 pin: [1; 32],
12026 key_count: 100,
12027 quote_ts: dead_quote,
12028 },
12029 &obs,
12030 );
12031 scheduler.enqueue(
12032 MonetizedPinEvent {
12033 peer: test_peer(2),
12034 pin: [2; 32],
12035 key_count: 100,
12036 quote_ts: SystemTime::now(),
12037 },
12038 &obs,
12039 );
12040 assert_eq!(scheduler.pending_len(), 2);
12041
12042 // Empty the bucket so the reserve path is budget-gated (fleet-wide
12043 // starvation) and cannot collect the dead entry itself.
12044 scheduler.limiter.tokens = 0;
12045 let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12046 assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
12047 assert_eq!(
12048 scheduler.pending_len(),
12049 2,
12050 "budget-gated reserve scans nothing"
12051 );
12052
12053 let wall_now = SystemTime::now();
12054 assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
12055 assert_eq!(scheduler.pending_len(), 1);
12056 assert!(
12057 scheduler.pending.peek(&test_peer(2)).is_some(),
12058 "the live entry survives the sweep"
12059 );
12060 assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
12061 let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
12062 assert!(
12063 Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
12064 "the age gauge reflects only live work after the sweep"
12065 );
12066 }
12067
12068 #[test]
12069 #[allow(clippy::too_many_lines)]
12070 fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
12071 let obs = Arc::new(FirstAuditObservability::default());
12072 let mono = Instant::now();
12073 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12074
12075 // A pre-existing window sentinel for an UNRELATED peer must survive the
12076 // cancel byte-for-byte (cancel never touches `recent`).
12077 let sentinel_peer = test_peer(0xAA);
12078 scheduler.limiter.promote(sentinel_peer, 500, mono);
12079 let sentinel_before = scheduler
12080 .limiter
12081 .recent
12082 .peek(&sentinel_peer)
12083 .copied()
12084 .expect("sentinel present");
12085
12086 let peer = test_peer(1);
12087 let a = MonetizedPinEvent {
12088 peer,
12089 pin: [1; 32],
12090 key_count: 100,
12091 quote_ts: SystemTime::now(), // fresh: passes the horizon prefilter now
12092 };
12093 scheduler.enqueue(a, &obs);
12094
12095 let tokens_before = scheduler.tokens();
12096 let lane_before = scheduler.oldest_first_lane;
12097 let launched_before = obs.launched.load(Ordering::Relaxed);
12098 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12099
12100 // Reserve A (jitter 0 so it is immediately due).
12101 let inflight0 = obs.inflight.load(Ordering::Relaxed);
12102 assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
12103 assert_eq!(scheduler.reserved_peer(), Some(peer));
12104 assert_eq!(
12105 scheduler.tokens(),
12106 tokens_before - 1,
12107 "reserve consumes a token"
12108 );
12109 assert_eq!(
12110 obs.inflight.load(Ordering::Relaxed),
12111 1,
12112 "reserve holds a slot"
12113 );
12114
12115 // A same-peer, same-count successor arrives DURING the reservation. It
12116 // must be retained (bypasses the window for the reserved peer) and must
12117 // NOT create a second reservation.
12118 let b = MonetizedPinEvent {
12119 peer,
12120 pin: [2; 32],
12121 key_count: 100,
12122 quote_ts: SystemTime::now(),
12123 };
12124 scheduler.enqueue(b, &obs);
12125 assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
12126 assert!(
12127 !scheduler.try_reserve(
12128 mono,
12129 obs.inflight.load(Ordering::Relaxed),
12130 Duration::ZERO,
12131 &cooldown,
12132 &obs
12133 ),
12134 "no second reservation while one is outstanding"
12135 );
12136
12137 // Resolve A with an injected wall time PAST A's answerability cutoff.
12138 let reservation = scheduler
12139 .take_due_reservation(mono)
12140 .expect("A is due at jitter 0");
12141 let wall_fail = a
12142 .quote_ts
12143 .checked_add(GOSSIP_ANSWERABILITY_TTL)
12144 .and_then(|t| t.checked_add(Duration::from_secs(1)))
12145 .expect("past-cutoff wall time");
12146 let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
12147 assert!(
12148 promoted.is_none(),
12149 "answerability lapsed -> cancelled, not promoted"
12150 );
12151
12152 // State-neutral cancel.
12153 assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
12154 assert!(
12155 scheduler.limiter.recent.peek(&peer).is_none(),
12156 "cancel stamps no per-peer window"
12157 );
12158 assert_eq!(
12159 scheduler.limiter.recent.peek(&sentinel_peer).copied(),
12160 Some(sentinel_before),
12161 "unrelated window sentinel untouched"
12162 );
12163 assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
12164 assert_eq!(
12165 scheduler.tokens(),
12166 tokens_before,
12167 "token refunded on cancel"
12168 );
12169 assert_eq!(
12170 obs.inflight.load(Ordering::Relaxed),
12171 0,
12172 "in-flight slot released"
12173 );
12174 assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
12175 assert_eq!(
12176 obs.launched.load(Ordering::Relaxed),
12177 launched_before,
12178 "no launch counted"
12179 );
12180 assert_eq!(
12181 obs.outside_answerability_window.load(Ordering::Relaxed),
12182 1,
12183 "the cancel reason is recorded"
12184 );
12185
12186 // The successor is still pending and is now fully schedulable: a fresh
12187 // reserve makes B the next reservation (proving eligibility, not merely
12188 // that the limiter would admit it).
12189 assert_eq!(
12190 scheduler.pending_len(),
12191 1,
12192 "successor still pending after cancel"
12193 );
12194 assert!(scheduler.reserved.is_none());
12195 assert!(scheduler.try_reserve(
12196 mono,
12197 obs.inflight.load(Ordering::Relaxed),
12198 Duration::ZERO,
12199 &cooldown,
12200 &obs
12201 ));
12202 assert_eq!(
12203 scheduler.reserved_peer(),
12204 Some(peer),
12205 "the retained successor becomes the next reservation"
12206 );
12207 }
12208
12209 /// ADR-0004 Amendment 2 (E'): when a promotion loses the shared-cooldown
12210 /// race, the reserved event is requeued ONLY if no same-peer successor is
12211 /// already pending. A successor arrived after the reservation, so it is the
12212 /// newer nomination (e.g. a count jump) and must not be overwritten by the
12213 /// older reserved event.
12214 #[test]
12215 fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
12216 let obs = Arc::new(FirstAuditObservability::default());
12217 let mono = Instant::now();
12218 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12219 let peer = test_peer(1);
12220
12221 // Reserve A.
12222 let a = MonetizedPinEvent {
12223 peer,
12224 pin: [1; 32],
12225 key_count: 100,
12226 quote_ts: SystemTime::now(),
12227 };
12228 scheduler.enqueue(a, &obs);
12229 let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
12230 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
12231
12232 // A newer same-peer successor B (a count jump) arrives during the
12233 // reservation and is retained.
12234 let b = MonetizedPinEvent {
12235 peer,
12236 pin: [2; 32],
12237 key_count: 400,
12238 quote_ts: SystemTime::now(),
12239 };
12240 scheduler.enqueue(b, &obs);
12241 assert_eq!(scheduler.pending_len(), 1);
12242
12243 // Resolve A: answerability PASSES (fresh quote) but the shared cooldown
12244 // is already stamped for the peer, so promotion loses the race.
12245 let reservation = scheduler.take_due_reservation(mono).expect("due");
12246 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12247 cooldown.insert(peer, mono); // freshly on cooldown
12248 let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
12249 assert!(promoted.is_none(), "cooldown race -> not promoted");
12250
12251 // B (newer) is preserved; A did NOT overwrite it.
12252 assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
12253 assert_eq!(
12254 scheduler.pending.peek(&peer).map(|e| e.pin),
12255 Some([2; 32]),
12256 "the newer successor B is retained, not the older reserved A"
12257 );
12258 assert!(scheduler.first_audited.is_empty());
12259 assert!(scheduler.limiter.recent.peek(&peer).is_none());
12260 }
12261
12262 /// The oldest-pending-quote-age gauge reports the age of the OLDEST quote
12263 /// still awaiting a first audit (not the newest), is `0` on an empty queue,
12264 /// and saturates to `0` for a future-dated quote (clock skew) without
12265 /// panicking. A climbing value is the pending-work-aging-out signal.
12266 #[test]
12267 fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
12268 let now = SystemTime::now();
12269 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12270 assert_eq!(
12271 scheduler.oldest_pending_quote_age_ms(now),
12272 0,
12273 "empty pending -> zero"
12274 );
12275
12276 // Two peers: quotes 10s and 2s old. The gauge must track the older.
12277 for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
12278 let _ = coalesce_first_audit_event(
12279 &mut scheduler.pending,
12280 MonetizedPinEvent {
12281 peer: test_peer(peer_id),
12282 pin,
12283 key_count: 100,
12284 quote_ts: now - Duration::from_secs(secs),
12285 },
12286 true,
12287 &mut scheduler.rng,
12288 );
12289 }
12290 assert_eq!(
12291 scheduler.oldest_pending_quote_age_ms(now),
12292 10_000,
12293 "tracks the oldest (10s), not the newest (2s)"
12294 );
12295
12296 // A future-dated quote (clock skew) saturates to zero, never panics.
12297 let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12298 let _ = coalesce_first_audit_event(
12299 &mut skewed.pending,
12300 MonetizedPinEvent {
12301 peer: test_peer(3),
12302 pin: [3; 32],
12303 key_count: 100,
12304 quote_ts: now + Duration::from_secs(5),
12305 },
12306 true,
12307 &mut skewed.rng,
12308 );
12309 assert_eq!(
12310 skewed.oldest_pending_quote_age_ms(now),
12311 0,
12312 "future quote_ts saturates to zero"
12313 );
12314 }
12315
12316 /// A flood of strictly-lower-count same-peer nominations must neither
12317 /// displace the retained higher pin NOR disturb its recency position (each
12318 /// is suppressed via `peek`, no `push`), and each must be counted as
12319 /// `suppressed_lower` — the attempted cheaper-pin self-erasure signal.
12320 /// Recency is asserted DIRECTLY via the queue's MRU-to-LRU iteration order
12321 /// (the documented `lru` contract that also drives the reserve scan's lane
12322 /// ordering), deliberately independent of the overflow policy: eviction is
12323 /// random-victim, so no assertion may require a particular peer to be
12324 /// displaced.
12325 #[test]
12326 fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
12327 let mut pending: LruCache<PeerId, MonetizedPinEvent> =
12328 LruCache::new(NonZeroUsize::new(2).unwrap());
12329 let mut rng = StdRng::seed_from_u64(11);
12330 let victim = test_peer(1);
12331 let other = test_peer(2);
12332 // Victim (high count) inserted first (older), then `other` (newer/MRU).
12333 let _ = coalesce_first_audit_event(
12334 &mut pending,
12335 MonetizedPinEvent {
12336 peer: victim,
12337 pin: [1; 32],
12338 key_count: 400,
12339 quote_ts: SystemTime::now(),
12340 },
12341 true,
12342 &mut rng,
12343 );
12344 let _ = coalesce_first_audit_event(
12345 &mut pending,
12346 MonetizedPinEvent {
12347 peer: other,
12348 pin: [9; 32],
12349 key_count: 100,
12350 quote_ts: SystemTime::now(),
12351 },
12352 true,
12353 &mut rng,
12354 );
12355 let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12356 assert_eq!(
12357 order_before,
12358 vec![other, victim],
12359 "sanity: `other` is MRU, the victim is LRU"
12360 );
12361
12362 // Flood the victim with cheaper nominations.
12363 let mut suppressed = 0u64;
12364 for i in 0..8u8 {
12365 let out = coalesce_first_audit_event(
12366 &mut pending,
12367 MonetizedPinEvent {
12368 peer: victim,
12369 pin: [i; 32],
12370 key_count: 50,
12371 quote_ts: SystemTime::now(),
12372 },
12373 true,
12374 &mut rng,
12375 );
12376 assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
12377 suppressed += 1;
12378 }
12379 assert_eq!(suppressed, 8);
12380 // Victim pin/count unchanged.
12381 assert_eq!(
12382 pending.peek(&victim).map(|e| (e.pin, e.key_count)),
12383 Some(([1; 32], 400))
12384 );
12385 // Recency untouched: the iteration order (which the reserve lanes
12386 // consume) is byte-for-byte what it was before the flood.
12387 let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12388 assert_eq!(
12389 order_after, order_before,
12390 "the suppressed-lower flood must not have changed any recency position"
12391 );
12392 }
12393
12394 /// The cooldown-race requeue counts a genuine different-peer capacity
12395 /// eviction (the ADR promises capacity loss is observable).
12396 #[test]
12397 fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
12398 let obs = Arc::new(FirstAuditObservability::default());
12399 let mono = Instant::now();
12400 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12401 // Pending capacity 1 so a requeue of a different peer must evict.
12402 scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
12403 let reserved_peer = test_peer(1);
12404 let other_peer = test_peer(2);
12405
12406 // Reserve peer 1.
12407 scheduler.enqueue(
12408 MonetizedPinEvent {
12409 peer: reserved_peer,
12410 pin: [1; 32],
12411 key_count: 100,
12412 quote_ts: SystemTime::now(),
12413 },
12414 &obs,
12415 );
12416 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12417 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12418
12419 // A DIFFERENT peer fills the single pending slot during the reservation.
12420 scheduler.enqueue(
12421 MonetizedPinEvent {
12422 peer: other_peer,
12423 pin: [2; 32],
12424 key_count: 100,
12425 quote_ts: SystemTime::now(),
12426 },
12427 &obs,
12428 );
12429 assert_eq!(scheduler.pending_len(), 1);
12430
12431 // Resolve peer 1: cooldown race -> requeue peer 1, evicting peer 2.
12432 let reservation = scheduler.take_due_reservation(mono).expect("due");
12433 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12434 cooldown.insert(reserved_peer, mono);
12435 let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
12436 assert!(scheduler
12437 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12438 .is_none());
12439 assert_eq!(
12440 obs.capacity_evicted.load(Ordering::Relaxed),
12441 cap_before + 1,
12442 "the requeue eviction of a different peer is counted"
12443 );
12444 assert_eq!(
12445 scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
12446 Some([1; 32])
12447 );
12448 }
12449
12450 /// ADR-0004 Amendment 2 (reviewer blocker): a strictly-lower-count same-peer
12451 /// nomination arriving while an inflated pin is PENDING must not displace it.
12452 /// The inflated pin stays and is the one launched.
12453 #[test]
12454 fn first_audit_pending_lower_count_does_not_replace_higher() {
12455 let obs = Arc::new(FirstAuditObservability::default());
12456 let mono = Instant::now();
12457 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12458 let peer = test_peer(1);
12459
12460 // Inflated (high-count) sidecar pin lands in pending.
12461 scheduler.enqueue(
12462 MonetizedPinEvent {
12463 peer,
12464 pin: [1; 32],
12465 key_count: 400,
12466 quote_ts: SystemTime::now(),
12467 },
12468 &obs,
12469 );
12470 // A cheaper same-peer settlement arrives right after.
12471 scheduler.enqueue(
12472 MonetizedPinEvent {
12473 peer,
12474 pin: [2; 32],
12475 key_count: 100,
12476 quote_ts: SystemTime::now(),
12477 },
12478 &obs,
12479 );
12480
12481 assert_eq!(scheduler.pending_len(), 1);
12482 assert_eq!(
12483 scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12484 Some(([1; 32], 400)),
12485 "the inflated pin must not be erased by the cheaper successor"
12486 );
12487 // The dropped cheaper nomination is counted through the enqueue path.
12488 assert_eq!(
12489 obs.suppressed_lower.load(Ordering::Relaxed),
12490 1,
12491 "the attempted cheaper-pin self-erasure is observable"
12492 );
12493
12494 // It reserves and promotes as the inflated pin/count.
12495 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12496 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12497 let reservation = scheduler.take_due_reservation(mono).expect("due");
12498 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12499 let (event, _slot) = scheduler
12500 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12501 .expect("promotes");
12502 assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12503 }
12504
12505 /// ADR-0004 Amendment 2 (reviewer blocker): a RESERVED inflated pin that
12506 /// loses the cooldown race must be requeued OVER a lower-count same-peer
12507 /// successor that arrived during its jitter, and must remain launchable once
12508 /// the shared cooldown expires — the cheaper successor cannot suppress it.
12509 #[test]
12510 fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
12511 let obs = Arc::new(FirstAuditObservability::default());
12512 let mono = Instant::now();
12513 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12514 let peer = test_peer(1);
12515
12516 // Reserve the inflated pin.
12517 scheduler.enqueue(
12518 MonetizedPinEvent {
12519 peer,
12520 pin: [1; 32],
12521 key_count: 400,
12522 quote_ts: SystemTime::now(),
12523 },
12524 &obs,
12525 );
12526 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12527 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12528
12529 // A cheaper successor arrives during the reservation (bypasses the
12530 // window as the reserved peer) and sits in pending.
12531 scheduler.enqueue(
12532 MonetizedPinEvent {
12533 peer,
12534 pin: [2; 32],
12535 key_count: 100,
12536 quote_ts: SystemTime::now(),
12537 },
12538 &obs,
12539 );
12540 assert_eq!(scheduler.pending_len(), 1);
12541
12542 // Resolve: answerability passes but the shared cooldown is already
12543 // stamped, so the reservation loses the race and requeues.
12544 let reservation = scheduler.take_due_reservation(mono).expect("due");
12545 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12546 cooldown.insert(peer, mono);
12547 assert!(scheduler
12548 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12549 .is_none());
12550
12551 // The inflated pin (400) replaced the cheaper successor (100).
12552 assert_eq!(scheduler.pending_len(), 1);
12553 assert_eq!(
12554 scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12555 Some(([1; 32], 400)),
12556 "the inflated reserved pin must survive the requeue over the cheaper successor"
12557 );
12558 assert!(scheduler.first_audited.is_empty());
12559 assert!(scheduler.limiter.recent.peek(&peer).is_none());
12560
12561 // Once the shared cooldown expires, the inflated pin reserves and
12562 // promotes with its intended pin/count.
12563 let later = mono
12564 .checked_add(Duration::from_secs(
12565 config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
12566 ))
12567 .expect("later");
12568 let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
12569 assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
12570 let reservation = scheduler.take_due_reservation(later).expect("due");
12571 let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
12572 let (event, _slot) = scheduler
12573 .resolve(
12574 reservation,
12575 SystemTime::now(),
12576 later,
12577 &mut cooldown_later,
12578 &obs,
12579 )
12580 .expect("promotes after cooldown");
12581 assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12582 }
12583
12584 /// ADR-0004 Amendment 2 (E'): consecutive PROMOTIONS strictly alternate the
12585 /// launch lane, driven through the real scheduler (reserve -> resolve ->
12586 /// promote), so a stream of fresh nominations cannot keep every launch on
12587 /// the newest lane and starve the oldest.
12588 #[test]
12589 fn first_audit_lane_alternates_across_promotions() {
12590 let obs = Arc::new(FirstAuditObservability::default());
12591 let mono = Instant::now();
12592 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12593 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12594
12595 // Two distinct peers; the newest-inserted is the MRU (newest lane end).
12596 let oldest_peer = test_peer(1);
12597 let newest_peer = test_peer(2);
12598 scheduler.enqueue(
12599 MonetizedPinEvent {
12600 peer: oldest_peer,
12601 pin: [1; 32],
12602 key_count: 100,
12603 quote_ts: SystemTime::now(),
12604 },
12605 &obs,
12606 );
12607 scheduler.enqueue(
12608 MonetizedPinEvent {
12609 peer: newest_peer,
12610 pin: [2; 32],
12611 key_count: 100,
12612 quote_ts: SystemTime::now(),
12613 },
12614 &obs,
12615 );
12616
12617 let mut launched_peers = Vec::new();
12618 for _ in 0..2 {
12619 assert!(scheduler.try_reserve(
12620 mono,
12621 obs.inflight.load(Ordering::Relaxed),
12622 Duration::ZERO,
12623 &cooldown,
12624 &obs
12625 ));
12626 let reservation = scheduler.take_due_reservation(mono).expect("due");
12627 // Answerable wall time == the quote's own time (age 0).
12628 let (event, _slot) = scheduler
12629 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12630 .expect("fresh in-window quote promotes");
12631 launched_peers.push(event.peer);
12632 }
12633
12634 // First launch takes the newest lane (lane starts false = newest), the
12635 // second takes the oldest lane: strict alternation.
12636 assert_eq!(
12637 launched_peers,
12638 vec![newest_peer, oldest_peer],
12639 "consecutive promotions alternate newest-then-oldest lane"
12640 );
12641 }
12642
12643 #[test]
12644 fn first_audit_count_jump_boundaries() {
12645 // Exactly 1.5x is NOT a jump; strictly above is.
12646 assert!(!first_audit_count_jump(100, 150));
12647 assert!(first_audit_count_jump(100, 151));
12648 // Anything beats an audited zero; zero never jumps.
12649 assert!(first_audit_count_jump(0, 1));
12650 assert!(!first_audit_count_jump(0, 0));
12651 // Equal max counts must not jump (and must not overflow).
12652 assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
12653 }
12654
12655 /// A verified payment's quote list includes the local node's own quote, so
12656 /// the verifier emits a monetized-pin event for the local peer on every
12657 /// payment it verifies. The node cannot network-audit itself, so the
12658 /// scheduler must drop such an event at ingress: never queued, and hence
12659 /// never launched nor marked first-audited.
12660 #[test]
12661 fn first_audit_queue_drops_self_targeting_events() {
12662 let obs = Arc::new(FirstAuditObservability::default());
12663 let self_peer = test_peer(1);
12664 let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
12665 let self_event = MonetizedPinEvent {
12666 peer: self_peer,
12667 pin: [7; 32],
12668 key_count: 1,
12669 quote_ts: SystemTime::now(),
12670 };
12671
12672 scheduler.enqueue(self_event, &obs);
12673 assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
12674 assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
12675 assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
12676
12677 // A remote peer's event still queues normally under the same filter.
12678 let remote_event = MonetizedPinEvent {
12679 peer: test_peer(2),
12680 pin: [8; 32],
12681 ..self_event
12682 };
12683 scheduler.enqueue(remote_event, &obs);
12684 assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
12685 assert_eq!(scheduler.pending_len(), 1);
12686 assert_eq!(
12687 obs.self_target_skipped.load(Ordering::Relaxed),
12688 1,
12689 "remote event must not count as a self-target skip"
12690 );
12691 }
12692
12693 #[test]
12694 fn fresh_offer_runs_store_admission_payment_checks() {
12695 let context = fresh_offer_payment_context();
12696 assert_eq!(context, VerificationContext::FreshReplication);
12697 // Fresh replication must keep verifying exactly like a direct client
12698 // PUT (store-strength cache, same live checks); the variant only
12699 // exists so price-floor telemetry can tell the two paths apart.
12700 assert!(context.is_store_admission());
12701 }
12702
12703 #[test]
12704 fn paid_notify_uses_paid_list_admission_payment_checks() {
12705 assert_eq!(
12706 paid_notify_payment_context(),
12707 VerificationContext::PaidListAdmission
12708 );
12709 }
12710
12711 /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
12712 /// signed quote inside the answerability window, fail-closed on BOTH ends so a
12713 /// stale or future/skewed client-forwarded quote cannot frame an honest node.
12714 #[test]
12715 fn monetized_quote_audit_window_fails_closed_both_ends() {
12716 let now = SystemTime::now();
12717 // Fresh (just quoted) and small future/past skew -> audited.
12718 assert!(quote_within_audit_window(now, now));
12719 assert!(quote_within_audit_window(
12720 now + Duration::from_secs(60),
12721 now
12722 ));
12723 assert!(quote_within_audit_window(
12724 now - Duration::from_secs(3600),
12725 now
12726 ));
12727 // Far future (badly-skewed / replayed) -> skipped.
12728 assert!(!quote_within_audit_window(
12729 now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_secs(60),
12730 now
12731 ));
12732 // Older than the window -> skipped (pin may have aged out).
12733 assert!(!quote_within_audit_window(
12734 now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
12735 now
12736 ));
12737 }
12738
12739 #[tokio::test]
12740 async fn replication_branch_lagged_events_are_counted() {
12741 let before = audit_metrics::replication_event_lagged_total();
12742 let flow = handle_replication_event_recv_error(
12743 &tokio::sync::broadcast::error::RecvError::Lagged(3),
12744 );
12745 assert_eq!(flow, std::ops::ControlFlow::Continue(()));
12746 let after = audit_metrics::replication_event_lagged_total();
12747 assert_eq!(after.saturating_sub(before), 3);
12748 }
12749
12750 #[tokio::test]
12751 async fn replication_branch_closed_events_stop_the_loop() {
12752 let flow =
12753 handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
12754 assert_eq!(flow, std::ops::ControlFlow::Break(()));
12755 }
12756
12757 #[tokio::test]
12758 async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
12759 let (sender, mut receiver) = mpsc::channel(1);
12760 let dropped_body =
12761 ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
12762 keys: Vec::new(),
12763 paid_list_check_indices: Vec::new(),
12764 });
12765 let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12766 let first = InboundReplicationMessage {
12767 source: test_peer(0xC1),
12768 msg: ReplicationMessage {
12769 request_id: 1,
12770 body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
12771 key: test_key(1),
12772 }),
12773 },
12774 rr_message_id: None,
12775 received_at: Instant::now(),
12776 };
12777 let second = InboundReplicationMessage {
12778 source: test_peer(0xC2),
12779 msg: ReplicationMessage {
12780 request_id: 2,
12781 body: dropped_body.clone(),
12782 },
12783 rr_message_id: None,
12784 received_at: Instant::now(),
12785 };
12786
12787 assert!(try_enqueue_serial_message(&sender, first).is_ok());
12788 let dropped = try_enqueue_serial_message(&sender, second)
12789 .expect_err("a full serial queue must refuse the second message");
12790 assert_eq!(dropped.reason, SerialQueueDropReason::Full);
12791 assert_eq!(dropped.message_class, "verification_request");
12792 assert_eq!(dropped.queue_depth, 1);
12793 let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12794 assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
12795
12796 let queued = receiver
12797 .recv()
12798 .await
12799 .expect("first message should remain queued");
12800 assert_eq!(queued.msg.request_id, 1);
12801 assert!(receiver.try_recv().is_err());
12802 }
12803
12804 #[tokio::test]
12805 async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
12806 let peer = test_peer(0x44);
12807 let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
12808
12809 let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
12810 let mut digest_guards = Vec::new();
12811 for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
12812 let guard = admit_audit_responder(
12813 &semaphore,
12814 &digest_inflight,
12815 &peer,
12816 AuditResponderClass::Digest,
12817 )
12818 .await;
12819 assert!(guard.is_ok());
12820 digest_guards.push(guard);
12821 }
12822 assert!(
12823 admit_audit_responder(
12824 &semaphore,
12825 &digest_inflight,
12826 &peer,
12827 AuditResponderClass::Digest,
12828 )
12829 .await
12830 .is_err(),
12831 "digest class must stop at its documented per-source cap"
12832 );
12833 drop(digest_guards);
12834
12835 let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
12836 let mut subtree_guards = Vec::new();
12837 for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
12838 let guard = admit_audit_responder(
12839 &semaphore,
12840 &subtree_inflight,
12841 &peer,
12842 AuditResponderClass::Subtree,
12843 )
12844 .await;
12845 assert!(guard.is_ok());
12846 subtree_guards.push(guard);
12847 }
12848 assert!(
12849 admit_audit_responder(
12850 &semaphore,
12851 &subtree_inflight,
12852 &peer,
12853 AuditResponderClass::Subtree,
12854 )
12855 .await
12856 .is_err(),
12857 "subtree class must retain the deployed cap of two"
12858 );
12859 drop(subtree_guards);
12860 }
12861
12862 #[test]
12863 fn in_scope_audit_deadlines_share_one_formula() {
12864 let config = config::ReplicationConfig::default();
12865 for key_count in [1, 4, 16] {
12866 assert_eq!(
12867 audit::responsible_audit_response_timeout(&config, key_count),
12868 config.audit_response_timeout(key_count)
12869 );
12870 assert_eq!(
12871 pruning::prune_audit_response_timeout(&config, key_count),
12872 config.audit_response_timeout(key_count)
12873 );
12874 }
12875 assert_eq!(
12876 possession::possession_probe_response_timeout(&config),
12877 config.audit_response_timeout(1)
12878 );
12879 }
12880
12881 #[test]
12882 fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
12883 const EXISTING_SOURCE_ID: u8 = 1;
12884 const HINT_SENDER_ID: u8 = 2;
12885
12886 let existing_source = test_peer(EXISTING_SOURCE_ID);
12887 let hint_sender = test_peer(HINT_SENDER_ID);
12888 let mut sources = vec![existing_source];
12889
12890 let hint_sources = HashSet::from([hint_sender]);
12891 add_replica_hint_sources(&mut sources, &hint_sources);
12892 add_replica_hint_sources(&mut sources, &hint_sources);
12893
12894 // A paid-only advertiser leaves the claim set empty (see
12895 // `queue_admitted_hints`), so it contributes no fetch source.
12896 add_replica_hint_sources(&mut sources, &HashSet::new());
12897
12898 assert_eq!(sources, vec![existing_source, hint_sender]);
12899 }
12900
12901 #[test]
12902 fn audit_timeout_preserves_active_bootstrap_claim() {
12903 assert!(!audit_failure_clears_bootstrap_claim(
12904 &AuditFailureReason::Timeout
12905 ));
12906 }
12907
12908 fn strike_peer(b: u8) -> PeerId {
12909 let mut bytes = [0u8; 32];
12910 bytes[0] = b;
12911 PeerId::from_bytes(bytes)
12912 }
12913
12914 // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
12915 // cooldown must collapse a gossip flood into at most one audit per window.
12916
12917 #[test]
12918 fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
12919 let peer = strike_peer(1);
12920 let mut map: HashMap<PeerId, Instant> = HashMap::new();
12921 let t0 = Instant::now();
12922 // First gossip in the window passes; a burst of further gossips at the
12923 // same instant are all suppressed.
12924 assert!(cooldown_allows_audit(&mut map, &peer, t0));
12925 let mut passed = 1;
12926 for _ in 0..100 {
12927 if cooldown_allows_audit(&mut map, &peer, t0) {
12928 passed += 1;
12929 }
12930 }
12931 assert_eq!(
12932 passed, 1,
12933 "a flood at one instant must trigger exactly one audit"
12934 );
12935 }
12936
12937 // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
12938 // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
12939 // consumes the window. This is the property the isolated cooldown tests above
12940 // cannot see: they never sample the lottery, so a regression that reordered
12941 // the gates (sample probability first, only stamp the cooldown on a win)
12942 // would still pass them while breaking flood-resistance: a flood would then
12943 // re-roll the lottery on EVERY message until one won, multiplying audits.
12944 //
12945 // We model the exact production gate order (attempt-window, lottery,
12946 // shared cooldown) with a lottery driven by a fixed outcome instead of
12947 // `gen_bool(..)`. The first message LOSES the lottery; the remaining flood
12948 // messages all WIN. With the production order, the losing first ticket
12949 // burns the ATTEMPT window and every later winner in the same window is
12950 // blocked, so there are 0 audits this window. If the gates were flipped,
12951 // the second message's winning ticket would slip through. The window only
12952 // reopens after it elapses.
12953 //
12954 // FLIPS IF: the lottery is sampled before the attempt-window
12955 // check-and-stamp (a losing ticket no longer consumes the window),
12956 // re-enabling a flood-amplified audit storm.
12957 #[test]
12958 fn losing_lottery_still_consumes_attempt_window() {
12959 // Calls the SHIPPED `audit_launch_decision` (the same function
12960 // `maybe_trigger_gossip_audit` uses), so a reorder of the gates in
12961 // production fails this test — not a local reimplementation.
12962 let peer = strike_peer(3);
12963 let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12964 let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12965 let t0 = Instant::now();
12966
12967 // First flooded message at t0 LOSES the lottery, but the attempt window
12968 // is stamped BEFORE the lottery is consulted, so the window is consumed.
12969 assert!(
12970 !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
12971 "a losing ticket launches no audit"
12972 );
12973
12974 // 99 more flooded messages at the same instant would all WIN the lottery,
12975 // yet every one must be blocked by the attempt window the loser stamped.
12976 // (If production sampled the lottery FIRST, these would each get a fresh
12977 // roll and audits would multiply — this assertion catches that reorder.)
12978 let mut audits = 0;
12979 for _ in 0..99 {
12980 if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
12981 audits += 1;
12982 }
12983 }
12984 assert_eq!(
12985 audits, 0,
12986 "a losing first ticket must consume the attempt window so no later \
12987 flooded message in the same window can audit"
12988 );
12989
12990 // The window only reopens after it elapses; the next winning ticket
12991 // then launches exactly one audit and stamps the SHARED cooldown.
12992 let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12993 assert!(
12994 audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
12995 "after the window a winning ticket audits again"
12996 );
12997 assert!(
12998 launched.contains_key(&peer),
12999 "a real launch stamps the shared cooldown"
13000 );
13001 }
13002
13003 /// The reviewer-flagged suppression route: a LOSING gossip lottery must not
13004 /// stamp the SHARED audit cooldown, otherwise repeated losses (one per
13005 /// 30-minute window, no challenge ever sent) keep a paid monetized pin's
13006 /// first audit deferred until its answerability window expires.
13007 ///
13008 /// FLIPS IF: `audit_launch_decision` stamps the shared `launched` map on a
13009 /// loss (the pre-split behavior, where both paths shared one map).
13010 #[test]
13011 fn losing_lottery_does_not_suppress_monetized_first_audit() {
13012 let peer = strike_peer(4);
13013 let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13014 let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13015 let t0 = Instant::now();
13016
13017 // A losing ticket consumes the gossip attempt window...
13018 assert!(!audit_launch_decision(
13019 &mut attempts,
13020 &mut launched,
13021 &peer,
13022 t0,
13023 false
13024 ));
13025 // ...but leaves the shared map untouched, so the first-audit reserve
13026 // gate (read-only) and the authoritative promotion check-and-stamp both
13027 // still allow the paid audit to launch immediately.
13028 assert!(
13029 cooldown_would_allow(&launched, &peer, t0),
13030 "reserve gate must not see a losing ticket as audit coverage"
13031 );
13032 assert!(
13033 cooldown_allows_audit(&mut launched, &peer, t0),
13034 "promotion must not be deferred by a losing ticket"
13035 );
13036
13037 // Conversely a WINNING ticket (real audit sent) does suppress the
13038 // first audit for the window, which is the intended shared semantics.
13039 let peer_won = strike_peer(5);
13040 assert!(audit_launch_decision(
13041 &mut attempts,
13042 &mut launched,
13043 &peer_won,
13044 t0,
13045 true
13046 ));
13047 assert!(
13048 !cooldown_would_allow(&launched, &peer_won, t0),
13049 "a real gossip audit still covers the peer for the window"
13050 );
13051 }
13052
13053 #[test]
13054 fn cooldown_lets_audit_through_after_the_window() {
13055 let peer = strike_peer(2);
13056 let mut map: HashMap<PeerId, Instant> = HashMap::new();
13057 let t0 = Instant::now();
13058 assert!(cooldown_allows_audit(&mut map, &peer, t0));
13059 // Within the window: suppressed.
13060 let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
13061 assert!(!cooldown_allows_audit(&mut map, &peer, within));
13062 // Past the window: allowed again.
13063 let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13064 assert!(cooldown_allows_audit(&mut map, &peer, after));
13065 }
13066
13067 #[test]
13068 fn cooldown_is_per_peer_independent() {
13069 let mut map: HashMap<PeerId, Instant> = HashMap::new();
13070 let t0 = Instant::now();
13071 // Different peers each get their own first-audit pass at the same instant.
13072 for i in 0..20u8 {
13073 assert!(
13074 cooldown_allows_audit(&mut map, &strike_peer(i), t0),
13075 "peer {i} should be auditable independently"
13076 );
13077 }
13078 }
13079
13080 #[test]
13081 fn audit_on_gossip_constants_match_adr() {
13082 // Tripwire on the ADR-locked tunables. The spot-check count sits at the
13083 // top of the auditor's 3..=5 band (the auditor clamps to that band, so
13084 // values above 5 would silently never be requested).
13085 assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
13086 assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
13087 assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
13088 }
13089
13090 // (d) A confirmed storage-integrity failure penalizes immediately and
13091 // revokes credit; it is not a timeout.
13092 #[test]
13093 fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
13094 assert!(audit_failure_clears_bootstrap_claim(
13095 &AuditFailureReason::DigestMismatch
13096 ));
13097 assert!(audit_failure_revokes_holder_credit(
13098 &AuditFailureReason::DigestMismatch
13099 ));
13100 }
13101
13102 /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
13103 /// uses: confirmed failures revoke credit, `Timeout` does not.
13104 #[test]
13105 fn confirmed_failures_revoke_credit_timeout_does_not() {
13106 for reason in [
13107 AuditFailureReason::MalformedResponse,
13108 AuditFailureReason::DigestMismatch,
13109 AuditFailureReason::KeyAbsent,
13110 AuditFailureReason::Rejected,
13111 ] {
13112 assert!(
13113 audit_failure_revokes_holder_credit(&reason),
13114 "confirmed failure {reason:?} must revoke holder credit"
13115 );
13116 }
13117 assert!(
13118 !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
13119 "Timeout must NOT revoke credit (single dropped packet != storage loss)"
13120 );
13121 }
13122
13123 /// Wiring test for the security fix: the helper the handler calls
13124 /// actually strips a credited peer on a confirmed failure
13125 /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
13126 /// Records genuine credit first so neither assertion is vacuous;
13127 /// this fails if `forget_peer` stops being called, or if the
13128 /// `Timeout` exclusion is dropped (both verified by mutation).
13129 #[test]
13130 fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
13131 let peer = test_peer(0xAB);
13132 let key = test_key(1);
13133 let hash = [0xCD; 32];
13134
13135 // Confirmed failure -> credit revoked.
13136 let mut provers = RecentProvers::new();
13137 provers.record_proof(key, peer, hash, Instant::now());
13138 assert!(
13139 provers.is_credited_holder(&key, &peer, &hash),
13140 "precondition: peer credited before failure"
13141 );
13142 apply_audit_failure_credit_revocation(
13143 &mut provers,
13144 &peer,
13145 &AuditFailureReason::DigestMismatch,
13146 );
13147 assert!(
13148 !provers.is_credited_holder(&key, &peer, &hash),
13149 "DigestMismatch must strip the peer's holder credit"
13150 );
13151
13152 // Timeout -> credit retained.
13153 let mut provers_timeout = RecentProvers::new();
13154 provers_timeout.record_proof(key, peer, hash, Instant::now());
13155 apply_audit_failure_credit_revocation(
13156 &mut provers_timeout,
13157 &peer,
13158 &AuditFailureReason::Timeout,
13159 );
13160 assert!(
13161 provers_timeout.is_credited_holder(&key, &peer, &hash),
13162 "Timeout must retain holder credit (deliberate liveness cushion)"
13163 );
13164 }
13165
13166 #[test]
13167 fn decoded_audit_failures_clear_active_bootstrap_claim() {
13168 for reason in [
13169 AuditFailureReason::MalformedResponse,
13170 AuditFailureReason::DigestMismatch,
13171 AuditFailureReason::KeyAbsent,
13172 AuditFailureReason::Rejected,
13173 ] {
13174 assert!(
13175 audit_failure_clears_bootstrap_claim(&reason),
13176 "decoded non-bootstrap failure {reason:?} should clear active claim"
13177 );
13178 }
13179 }
13180
13181 #[test]
13182 fn first_failed_key_label_truncates_to_16_hex_chars() {
13183 // The high-order 8 bytes of the XorName determine the label so an
13184 // operator can group audit-failures on the same chunk prefix.
13185 let mut key = [0u8; 32];
13186 key[0] = 0x18;
13187 key[7] = 0xff;
13188 // Low-order bytes (positions 8..32) are deliberately set to 0xAA
13189 // to verify they are NOT included in the label.
13190 for byte in &mut key[8..] {
13191 *byte = 0xAA;
13192 }
13193 let label = first_failed_key_label(&[key]);
13194 // Only the first 8 bytes are encoded, low-order bytes are dropped.
13195 assert_eq!(label, "0x18000000000000ff");
13196 assert_eq!(label.len(), "0x".len() + 16);
13197 }
13198
13199 #[test]
13200 fn first_failed_key_label_falls_back_when_empty() {
13201 // Should never happen in production (audit failure handling rejects
13202 // empty sets), but the formatter must still produce a valid label
13203 // so the log line doesn't contain a misleading default.
13204 assert_eq!(first_failed_key_label(&[]), "0x");
13205 }
13206
13207 #[test]
13208 fn first_failed_key_label_uses_first_key_only() {
13209 let first = [0x11u8; 32];
13210 let second = [0x22u8; 32];
13211 assert_eq!(
13212 first_failed_key_label(&[first, second]),
13213 format!("0x{}", hex::encode(&first[..8]))
13214 );
13215 }
13216
13217 // -- apply_fetch_result --------------------------------------------------
13218 //
13219 // The worker's disposition of a fetch outcome. Note there is no trust
13220 // handle in `apply_fetch_result`'s signature: the worker cannot report a
13221 // trust event for ANY outcome, and `execute_single_fetch` returns
13222 // `NoLongerResponsible` before its trust-reporting paths — the source did
13223 // nothing wrong when this node's own responsibility lapsed.
13224
13225 /// Route `key` through the real pipeline stages (pending → promoted →
13226 /// dequeued → in-flight) so it carries a verification retry-slot
13227 /// reservation, exactly as a worker-dequeued key does. Returns the
13228 /// in-flight source.
13229 fn drive_key_in_flight(
13230 q: &mut ReplicationQueues,
13231 key: XorName,
13232 sources: Vec<PeerId>,
13233 ) -> PeerId {
13234 let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
13235 let now = Instant::now();
13236 let entry = VerificationEntry {
13237 state: VerificationState::PendingVerify,
13238 verified_sources: Vec::new(),
13239 tried_sources: HashSet::new(),
13240 created_at: now,
13241 next_verify_at: now,
13242 hint_sources: HashSet::from([hinter]),
13243 replica_hint_sources: HashSet::from([hinter]),
13244 unresolved_retries: 0,
13245 no_holder_reported: false,
13246 };
13247 assert!(q.add_pending_verify(key, entry).admitted());
13248 assert!(q.promote_pending_to_fetch(key, key, sources));
13249 let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
13250 let source = *candidate.sources.first().expect("candidate has a source");
13251 q.start_dequeued_fetch(candidate, source);
13252 source
13253 }
13254
13255 #[test]
13256 fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
13257 const RETRY_AFTER: Duration = Duration::from_secs(60);
13258
13259 let mut q = ReplicationQueues::new();
13260 let key = test_key(0xAB);
13261 drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
13262 assert_eq!(q.retry_reserved_slot_count(), 1);
13263
13264 let follow_up =
13265 apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
13266
13267 assert_eq!(
13268 follow_up,
13269 FetchFollowUp::Terminal,
13270 "lapsed responsibility must run the caller's terminal bootstrap accounting"
13271 );
13272 assert!(
13273 !q.contains_key(&key),
13274 "the key must leave every pipeline stage — alternate sources included"
13275 );
13276 assert_eq!(
13277 q.pending_count(),
13278 0,
13279 "a lapsed-responsibility key must not be requeued for verification"
13280 );
13281 assert_eq!(
13282 q.retry_reserved_slot_count(),
13283 0,
13284 "terminal exit must release the verification retry-slot reservation"
13285 );
13286 }
13287
13288 #[test]
13289 fn no_longer_responsible_shares_the_stored_terminal_path() {
13290 const RETRY_AFTER: Duration = Duration::from_secs(60);
13291
13292 // Both variants must walk the identical terminal gate so the
13293 // battle-tested Stored accounting (retry-slot release + bootstrap
13294 // pending-set shrink in the caller) covers lapsed responsibility too.
13295 for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
13296 let mut q = ReplicationQueues::new();
13297 let key = test_key(0xCD);
13298 drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
13299
13300 let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
13301
13302 assert_eq!(follow_up, FetchFollowUp::Terminal);
13303 assert!(!q.contains_key(&key));
13304 assert_eq!(q.retry_reserved_slot_count(), 0);
13305 }
13306 }
13307
13308 #[test]
13309 fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
13310 const RETRY_AFTER: Duration = Duration::from_secs(60);
13311
13312 let mut q = ReplicationQueues::new();
13313 let key = test_key(0xEF);
13314 let first = test_peer(0x04);
13315 let second = test_peer(0x05);
13316 drive_key_in_flight(&mut q, key, vec![first, second]);
13317
13318 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13319 assert_eq!(
13320 follow_up,
13321 FetchFollowUp::RetryFrom(second),
13322 "a failed source must not abandon the remaining verified sources"
13323 );
13324 assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
13325
13326 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13327 assert_eq!(
13328 follow_up,
13329 FetchFollowUp::RequeuedForVerification,
13330 "exhausted sources must restore the reserved verification entry"
13331 );
13332 assert_eq!(q.pending_count(), 1);
13333 assert_eq!(
13334 q.retry_reserved_slot_count(),
13335 0,
13336 "the reservation converts back into the pending entry itself"
13337 );
13338 }
13339
13340 #[test]
13341 fn source_failure_without_retry_metadata_is_terminal() {
13342 const RETRY_AFTER: Duration = Duration::from_secs(60);
13343
13344 // Direct enqueue (no pending entry) models a fetch with no
13345 // verification retry reservation to restore.
13346 let mut q = ReplicationQueues::new();
13347 let key = test_key(0x1F);
13348 let source = test_peer(0x06);
13349 assert!(q.enqueue_fetch(key, key, vec![source]));
13350 let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13351 q.start_dequeued_fetch(candidate, source);
13352
13353 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13354
13355 assert_eq!(follow_up, FetchFollowUp::Terminal);
13356 assert!(!q.contains_key(&key));
13357 }
13358
13359 #[test]
13360 fn already_held_key_leaves_the_pipeline_terminally() {
13361 const RETRY_AFTER: Duration = Duration::from_secs(60);
13362
13363 let mut q = ReplicationQueues::new();
13364 let key = test_key(0x4C);
13365 let source = test_peer(0x0B);
13366 drive_key_in_flight(&mut q, key, vec![source, test_peer(0x0C)]);
13367
13368 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::AlreadyHeld, RETRY_AFTER);
13369
13370 assert_eq!(
13371 follow_up,
13372 FetchFollowUp::Terminal,
13373 "holding the key already discharges the duty, so the key must leave \
13374 the pipeline exactly as a completed fetch does — requeueing it \
13375 would re-verify a key that needs nothing"
13376 );
13377 assert!(!q.contains_key(&key));
13378 assert_eq!(
13379 q.retry_reserved_slot_count(),
13380 0,
13381 "the terminal path must release the retry-slot reservation, or the \
13382 owner's verification budget leaks"
13383 );
13384 }
13385
13386 #[test]
13387 fn local_write_failure_does_not_conscript_the_remaining_sources() {
13388 const RETRY_AFTER: Duration = Duration::from_secs(60);
13389
13390 let mut q = ReplicationQueues::new();
13391 let key = test_key(0x2A);
13392 let first = test_peer(0x07);
13393 let second = test_peer(0x08);
13394 let third = test_peer(0x09);
13395 drive_key_in_flight(&mut q, key, vec![first, second, third]);
13396
13397 let follow_up =
13398 apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13399
13400 assert_eq!(
13401 follow_up,
13402 FetchFollowUp::RequeuedForVerification,
13403 "a local write failure must go straight back to verification: the two \
13404 untried sources would each re-upload the same chunk into the same \
13405 full disk, and neither of them did anything wrong"
13406 );
13407 assert_eq!(q.in_flight_count(), 0);
13408 assert_eq!(
13409 q.pending_count(),
13410 1,
13411 "the key must come back — capacity frees up, and a stranded key is \
13412 a replica this node silently stops owing"
13413 );
13414 assert_eq!(q.retry_reserved_slot_count(), 0);
13415 }
13416
13417 #[test]
13418 fn local_write_failure_without_retry_metadata_is_terminal() {
13419 const RETRY_AFTER: Duration = Duration::from_secs(60);
13420
13421 // No pending entry to restore, so the only way not to strand the key
13422 // in `in_flight_fetch` forever — which would also stall bootstrap
13423 // drain — is the terminal path.
13424 let mut q = ReplicationQueues::new();
13425 let key = test_key(0x3B);
13426 let source = test_peer(0x0A);
13427 assert!(q.enqueue_fetch(key, key, vec![source]));
13428 let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13429 q.start_dequeued_fetch(candidate, source);
13430
13431 let follow_up =
13432 apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13433
13434 assert_eq!(follow_up, FetchFollowUp::Terminal);
13435 assert!(!q.contains_key(&key));
13436 assert_eq!(q.retry_reserved_slot_count(), 0);
13437 }
13438}