Skip to main content

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 bootstrap;
20pub mod commitment;
21pub mod commitment_state;
22pub mod config;
23pub mod fresh;
24pub mod neighbor_sync;
25pub mod paid_list;
26pub mod possession;
27pub mod protocol;
28pub mod pruning;
29pub mod quorum;
30pub mod recent_provers;
31pub mod scheduling;
32pub mod storage_commitment_audit;
33pub mod subtree;
34pub mod types;
35
36use std::collections::{HashMap, HashSet};
37use std::fmt;
38use std::num::NonZeroUsize;
39use std::path::{Path, PathBuf};
40use std::sync::atomic::{AtomicU64, Ordering};
41use std::sync::Arc;
42use std::time::{Duration, Instant, SystemTime};
43
44use lru::LruCache;
45use std::pin::Pin;
46
47use crate::logging::{debug, error, info, warn};
48use futures::stream::FuturesUnordered;
49use futures::{Future, StreamExt};
50use rand::Rng;
51use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
52use tokio::task::JoinHandle;
53use tokio_util::sync::CancellationToken;
54
55use crate::ant_protocol::XorName;
56use crate::error::{Error, Result};
57use crate::payment::{PaymentVerifier, VerificationContext};
58use crate::replication::audit::AuditTickResult;
59use crate::replication::commitment::{commitment_hash, StorageCommitment};
60use crate::replication::commitment_state::{
61    PeerCommitmentRecord, PersistedRetention, ResponderCommitmentState, GOSSIP_ANSWERABILITY_TTL,
62};
63use crate::replication::config::{
64    max_parallel_fetch, storage_admission_width, ReplicationConfig, MAX_AUDIT_RESPONSES_PER_PEER,
65    MAX_CONCURRENT_AUDIT_RESPONSES, MAX_CONCURRENT_REPLICATION_SENDS, REPLICATION_PROTOCOL_ID,
66};
67use crate::replication::paid_list::PaidList;
68use crate::replication::protocol::{
69    FreshReplicationResponse, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
70    VerificationResponse,
71};
72use crate::replication::quorum::KeyVerificationOutcome;
73use crate::replication::recent_provers::RecentProvers;
74use crate::replication::scheduling::ReplicationQueues;
75use crate::replication::types::{
76    AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence, HintPipeline,
77    NeighborSyncState, PeerSyncRecord, RepairProofs, VerificationEntry, VerificationState,
78};
79use crate::storage::LmdbStorage;
80use saorsa_core::identity::{NodeIdentity, PeerId};
81use saorsa_core::{DhtNetworkEvent, P2PEvent, P2PNode, TrustEvent};
82use saorsa_pqc::api::sig::{MlDsaSecretKey, MlDsaVariant};
83
84#[derive(Default)]
85struct FirstAuditObservability {
86    received: AtomicU64,
87    queued: AtomicU64,
88    coalesced: AtomicU64,
89    duplicates: AtomicU64,
90    capacity_evicted: AtomicU64,
91    cooldown_deferred_attempts: AtomicU64,
92    launched: AtomicU64,
93    passed: AtomicU64,
94    timed_out: AtomicU64,
95    failed: AtomicU64,
96    bootstrap_claims: AtomicU64,
97    idle: AtomicU64,
98    insufficient_keys: AtomicU64,
99    outside_answerability_window: AtomicU64,
100    inflight: AtomicU64,
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104enum FirstAuditTerminalOutcome {
105    Passed,
106    Timeout,
107    Failed,
108    BootstrapClaim,
109    Idle,
110    InsufficientKeys,
111}
112
113impl FirstAuditTerminalOutcome {
114    #[cfg(any(feature = "logging", test))]
115    const fn as_str(self) -> &'static str {
116        match self {
117            Self::Passed => "passed",
118            Self::Timeout => "timeout",
119            Self::Failed => "failed",
120            Self::BootstrapClaim => "bootstrap_claim",
121            Self::Idle => "idle",
122            Self::InsufficientKeys => "insufficient_keys",
123        }
124    }
125}
126
127fn first_audit_terminal_outcome(result: &AuditTickResult) -> FirstAuditTerminalOutcome {
128    match result {
129        AuditTickResult::Passed { .. } => FirstAuditTerminalOutcome::Passed,
130        AuditTickResult::Failed {
131            evidence:
132                FailureEvidence::AuditFailure {
133                    reason: AuditFailureReason::Timeout,
134                    ..
135                },
136        } => FirstAuditTerminalOutcome::Timeout,
137        AuditTickResult::Failed { .. } => FirstAuditTerminalOutcome::Failed,
138        AuditTickResult::BootstrapClaim { .. } => FirstAuditTerminalOutcome::BootstrapClaim,
139        AuditTickResult::Idle => FirstAuditTerminalOutcome::Idle,
140        AuditTickResult::InsufficientKeys => FirstAuditTerminalOutcome::InsufficientKeys,
141    }
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145enum FirstAuditQueueOutcome {
146    Queued,
147    Coalesced,
148    CapacityEvicted { peer: PeerId, pin: [u8; 32] },
149}
150
151/// Insert newest-per-peer work while exposing the bounded LRU's otherwise
152/// silent capacity eviction. This preserves `LruCache::put` semantics exactly.
153fn queue_first_audit_event(
154    pending: &mut LruCache<PeerId, MonetizedPinEvent>,
155    event: MonetizedPinEvent,
156) -> FirstAuditQueueOutcome {
157    match pending.push(event.peer, event) {
158        None => FirstAuditQueueOutcome::Queued,
159        Some((replaced_peer, _)) if replaced_peer == event.peer => {
160            FirstAuditQueueOutcome::Coalesced
161        }
162        Some((evicted_peer, evicted)) => FirstAuditQueueOutcome::CapacityEvicted {
163            peer: evicted_peer,
164            pin: evicted.pin,
165        },
166    }
167}
168
169// ---------------------------------------------------------------------------
170// Constants
171// ---------------------------------------------------------------------------
172
173/// Prefix used by saorsa-core's request-response mechanism.
174const RR_PREFIX: &str = "/rr/";
175
176fn fresh_offer_payment_context() -> VerificationContext {
177    VerificationContext::ClientPut
178}
179
180fn paid_notify_payment_context() -> VerificationContext {
181    VerificationContext::PaidListAdmission
182}
183
184/// Boxed future type for in-flight fetch tasks.
185type FetchFuture = Pin<Box<dyn Future<Output = (XorName, Option<FetchOutcome>)> + Send>>;
186
187/// Shared dependencies for one verification worker cycle.
188struct VerificationCycleContext<'a> {
189    p2p_node: &'a Arc<P2PNode>,
190    paid_list: &'a Arc<PaidList>,
191    storage: &'a Arc<LmdbStorage>,
192    queues: &'a Arc<RwLock<ReplicationQueues>>,
193    config: &'a ReplicationConfig,
194    bootstrap_state: &'a Arc<RwLock<BootstrapState>>,
195    is_bootstrapping: &'a Arc<RwLock<bool>>,
196    bootstrap_complete_notify: &'a Arc<Notify>,
197    /// v12 §6 holder-eligibility inputs. The verifier downgrades a
198    /// peer's Present claim to Unresolved unless they're a credited
199    /// holder of the key (i.e. they recently passed a commitment-bound
200    /// audit on it under their currently-credited commitment hash).
201    last_commitment_by_peer: &'a Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
202    ever_capable_peers: &'a Arc<RwLock<HashSet<PeerId>>>,
203    recent_provers: &'a Arc<RwLock<RecentProvers>>,
204}
205
206/// Fetch worker polling interval in milliseconds.
207const FETCH_WORKER_POLL_MS: u64 = 100;
208
209/// Verification worker polling interval in milliseconds.
210const VERIFICATION_WORKER_POLL_MS: u64 = 250;
211
212/// Verification cycle duration that is worth surfacing at info level.
213const VERIFICATION_CYCLE_SLOW_LOG_MS: u128 = 500;
214
215/// Standard trust event weight for per-operation success/failure signals.
216///
217/// Used for individual replication fetch outcomes, integrity check failures,
218/// and bootstrap claim abuse. Distinct from `AUDIT_FAILURE_TRUST_WEIGHT` which
219/// is reserved for confirmed audit failures.
220const REPLICATION_TRUST_WEIGHT: f64 = 1.0;
221
222/// Bootstrap drain check interval in seconds.
223const BOOTSTRAP_DRAIN_CHECK_SECS: u64 = 5;
224
225/// How often the responder rebuilds + rotates its storage commitment.
226///
227/// Each rebuild scans LMDB to compute leaf hashes; for ~10k keys this is
228/// sub-100ms (BLAKE3 + tree build). Retention is gossip-anchored, NOT
229/// rotation-anchored: the responder stays answerable for the current
230/// commitment plus every root it recently gossiped that is still in-window
231/// (~2 in steady state), each kept for `GOSSIP_ANSWERABILITY_TTL` (3 h) after
232/// its last emission (see `commitment_state`). So the rotation cadence does
233/// not by itself bound answerability — a gossiped commitment stays
234/// answerable across rotations until its gossip TTL lapses.
235///
236/// Default: 1 hour, aligned with the worst-case neighbor-sync cooldown
237/// (`NEIGHBOR_SYNC_COOLDOWN_SECS = 3600`). Because the gossip TTL (3 h)
238/// comfortably exceeds the gap between our rotation and the next gossip
239/// arrival at a remote peer, this prevents the "unknown commitment hash" ->
240/// Idle audit-skip pattern from being the common case.
241///
242/// Why not faster: the v12 pin is bound to a specific point-in-time
243/// commitment, so rotation isn't security-critical for pin freshness —
244/// only for keeping the committed key set current as the responder
245/// writes new keys. 1 hour is plenty for that, and slow enough that
246/// honest auditors mostly hit `current` or `previous` rather than the
247/// "rotated past" case.
248const COMMITMENT_ROTATION_INTERVAL_SECS: u64 = 3600;
249
250/// How often the responder retention snapshot is flushed to disk (ADR-0004 A1).
251/// Short relative to the answerability TTL (3 h) so a gossip-stamp refresh is
252/// durable well before it could matter to a restart, while the write-on-change
253/// guard keeps idle nodes from needless disk writes.
254const RETENTION_PERSIST_INTERVAL_SECS: u64 = 30;
255
256/// Cadence of the `replication traffic summary (cumulative)` INFO lines
257/// (V2-623). A `const` so testnets can drop it to 60s; 300s is the production
258/// default that keeps log volume negligible.
259const TRAFFIC_SUMMARY_INTERVAL_SECS: u64 = 300;
260
261/// Maximum tolerated auditor↔responder wall-clock skew for the first-audit
262/// in-window screen (ADR-0004 A1 guardrail A). The screen accepts a monetized pin
263/// for first audit only if its SIGNED `quote_ts` lands in
264/// `[now - (GOSSIP_ANSWERABILITY_TTL - MONETIZED_AUDIT_SKEW_MARGIN), now + MONETIZED_AUDIT_SKEW_MARGIN]`
265/// — fail-closed on BOTH ends: a quote dated too far in the future (a
266/// badly-skewed or replayed quote) and one too old (the responder may have aged
267/// the pin out) are both skipped, so — with grace removed — a stale/skewed quote
268/// cannot frame an honest node. This assumes bounded clock skew (nodes NTP-synced
269/// within this margin); a legit first audit fires moments after payment
270/// (`quote_ts ≈ now`), far from either bound. The gossip-lottery path (which pins
271/// the responder's OWN freshly-gossiped root) is the clock-skew-immune backstop.
272/// 30 min dwarfs any realistic honest skew while leaving a wide audit window.
273const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_secs(30 * 60);
274
275/// ADR-0004 A1 (guardrail A): whether a monetized pin's SIGNED `quote_ts` lands
276/// inside the answerability window relative to `now`, so first-auditing it cannot
277/// false-convict once grace is removed. Fail-closed on BOTH ends (see
278/// [`MONETIZED_AUDIT_SKEW_MARGIN`]): a quote more than the skew margin in the
279/// future, or older than `GOSSIP_ANSWERABILITY_TTL - margin`, is out of window.
280/// All comparisons use `duration_since` (no `Duration` overflow).
281fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
282    let too_future = quote_ts
283        .duration_since(now)
284        .is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
285    let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
286    let too_old = now
287        .duration_since(quote_ts)
288        .is_ok_and(|age| age >= audit_cutoff);
289    !(too_future || too_old)
290}
291
292/// Minimum interval between commitment signature verifications for a
293/// single peer (v10/v12 §2 step 3 + §11 `DoS`).
294///
295/// A sybil that bypasses the routing-table gate (e.g. by transient
296/// bucket pollution) could otherwise force one ML-DSA-65 verify (~1 ms)
297/// per gossip message. This rate limit caps the verify-per-peer rate
298/// at 1/min, which is comfortably above the legitimate gossip cadence
299/// (the 10-20 min neighbor-sync round on each peer).
300const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_secs(60);
301
302/// Hard cap on the size of `last_commitment_by_peer`.
303///
304/// Bounds the per-process memory cost of the auditor's per-peer
305/// commitment cache. Each entry holds a `StorageCommitment`
306/// (~5 KiB: 1952-byte pubkey + 3293-byte signature + small fields).
307/// At 4096 entries the cache is ~20 MiB, which comfortably covers a
308/// realistic close-group neighborhood. When the cap is hit, one
309/// arbitrary existing entry is evicted on insert (`HashMap` iteration
310/// order is unspecified; we do not track insertion order). The
311/// `PeerRemoved` handler proactively drops entries as the DHT
312/// detects departures, and `ingest_peer_commitment` only admits
313/// commitments from peers currently in the routing table — together
314/// the cap is the third line of defence against sybil/churn flooding.
315const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
316
317/// Cap on the sticky `ever_capable_peers` set. Bounds memory so a
318/// long-running bootstrap node cannot have the set grow without limit
319/// from peer-id churn. Sized at 4x `MAX_LAST_COMMITMENT_BY_PEER` so
320/// the set comfortably outlives normal LRU churn but still caps the
321/// blast radius of identity-rotation attacks. Once full we refuse new
322/// inserts (no eviction) — keeps the historic set stable; new v12
323/// peers above the cap are treated as legacy on rejoin, which matches
324/// the behaviour before this set existed, not a security regression.
325const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
326
327// ---------------------------------------------------------------------------
328// ReplicationEngine
329// ---------------------------------------------------------------------------
330
331/// The replication engine manages all replication background tasks and state.
332pub struct ReplicationEngine {
333    /// Replication configuration (shared across spawned tasks).
334    config: Arc<ReplicationConfig>,
335    /// P2P networking node.
336    p2p_node: Arc<P2PNode>,
337    /// Local chunk storage.
338    storage: Arc<LmdbStorage>,
339    /// Persistent paid-for-list.
340    paid_list: Arc<PaidList>,
341    /// Payment verifier for `PoP` validation.
342    payment_verifier: Arc<PaymentVerifier>,
343    /// Replication pipeline queues.
344    queues: Arc<RwLock<ReplicationQueues>>,
345    /// Neighbor sync cycle state.
346    sync_state: Arc<RwLock<NeighborSyncState>>,
347    /// Per-peer sync history (for `RepairOpportunity`).
348    ///
349    /// This map grows with peer churn and is intentionally unbounded: entries
350    /// are lightweight (`PeerSyncRecord` is two fields) and peer IDs are
351    /// naturally bounded by the routing table's k-bucket capacity.
352    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
353    /// Per-peer cooldown for gossip-triggered subtree audits (ADR-0002).
354    ///
355    /// Records when each peer was last audited so a burst of gossiped
356    /// commitment changes cannot spawn back-to-back audits of the same peer.
357    /// Bounded by routing-table membership and cleaned on `PeerRemoved`.
358    audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
359    /// Completed local neighbor-sync cycle epoch for proof maturity.
360    sync_cycle_epoch: Arc<RwLock<u64>>,
361    /// Per-key repair proof tracking for audit eligibility.
362    repair_proofs: Arc<RwLock<RepairProofs>>,
363    /// Bootstrap state tracking.
364    bootstrap_state: Arc<RwLock<BootstrapState>>,
365    /// Whether this node is currently bootstrapping.
366    is_bootstrapping: Arc<RwLock<bool>>,
367    /// Trigger for early neighbor sync (signalled on topology changes).
368    sync_trigger: Arc<Notify>,
369    /// Notified when `is_bootstrapping` transitions from `true` to `false`.
370    bootstrap_complete_notify: Arc<Notify>,
371    /// Node identity (for signing storage commitments).
372    ///
373    /// Phase 3 of the v12 storage-bound audit design. The responder
374    /// uses this to sign its periodically-built `StorageCommitment`.
375    identity: Arc<NodeIdentity>,
376    /// Responder-side commitment state (two-slot atomic rotation).
377    ///
378    /// Periodically rebuilt from the live LMDB key set; gossiped on
379    /// outbound `NeighborSyncRequest`/`Response`; consulted by the
380    /// commitment-bound audit handler.
381    commitment_state: Arc<ResponderCommitmentState>,
382    /// Path to the persisted responder retention snapshot
383    /// (`{root_dir}/commitment_retention.bin`): reloaded on startup so an honest
384    /// node's answerability survives restart (ADR-0004 A1), which is what makes
385    /// removing audit grace safe (an unanswerable in-window pin is then provable
386    /// misbehaviour, not an honest crash-restart).
387    retention_path: PathBuf,
388    /// Auditor-side per-peer commitment record (last known commitment +
389    /// sticky `commitment_capable` flag).
390    ///
391    /// Populated whenever an inbound gossip carries a verified
392    /// commitment from the sender. Used by `audit_tick` to snapshot
393    /// `expected_commitment_hash` into outbound challenges, and by
394    /// holder-eligibility (§6) to decide whether a peer's `recent_provers`
395    /// proof should be honoured. The sticky `commitment_capable` flag
396    /// flips true on first successful ingest and never reverts (§2
397    /// step 5).
398    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
399    /// Sticky set of peer IDs we have EVER seen carrying a v12
400    /// commitment, independent of whether their commitment bytes are
401    /// still in `last_commitment_by_peer`. The §6 holder-eligibility
402    /// closure consults this set to keep treating churned-out
403    /// previously-v12 peers as v12-capable (rather than degrading them
404    /// to "legacy" credit-unconditionally) when they re-appear on the
405    /// network before their next gossip arrives. Bounded growth: even
406    /// at one million peers seen over the node's lifetime, the set is
407    /// 32 MB.
408    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
409    /// Auditor-side holder-eligibility cache (v12 §6).
410    ///
411    /// Recorded on successful commitment-bound audit; read by future
412    /// quorum / paid-list eligibility checks (phase-3 stretch).
413    recent_provers: Arc<RwLock<RecentProvers>>,
414    /// Per-peer last sig-verify attempt timestamp for the §2 step 3 /
415    /// §11 `DoS` rate limit. Bumped on EVERY verify attempt (success or
416    /// failure) so a peer we've never successfully verified can't burn
417    /// CPU on a flood of structurally-plausible-but-invalid gossips.
418    /// Lives separately from `last_commitment_by_peer` because that
419    /// map's records only exist after a successful verify.
420    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
421    /// Limits concurrent outbound replication sends to prevent bandwidth
422    /// saturation on home broadband connections.
423    send_semaphore: Arc<Semaphore>,
424    /// Bounds concurrent IN-FLIGHT audit-responder tasks (subtree round 1 +
425    /// byte round 2). Those are spawned off the serial message loop so disk
426    /// reads don't block replication; the semaphore restores a global
427    /// backpressure ceiling so the node can't fan out unbounded `get_raw` reads
428    /// / multi-MiB byte serves.
429    audit_responder_semaphore: Arc<Semaphore>,
430    /// Per-source in-flight audit-responder counts, capped at
431    /// [`MAX_AUDIT_RESPONSES_PER_PEER`]. The GLOBAL semaphore alone is not
432    /// flood-fair: one peer spamming challenges could occupy every slot and
433    /// starve honest auditors, whose dropped challenges then convert to
434    /// audit timeouts against HONEST peers (codex-r2 A). This
435    /// per-peer cap guarantees no single source can hold more than its share,
436    /// so a flood self-throttles without denying service to everyone else.
437    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
438    /// Receiver for fresh-write events from the chunk PUT handler.
439    ///
440    /// When present, `start()` spawns a drainer task that calls
441    /// `replicate_fresh` for each event.
442    fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
443    /// Sender for delayed possession-check events (ADR-0003). The fresh-write
444    /// drainer pushes the responsible close-group peers here after each fresh
445    /// replication; the possession-check scheduler drains the paired receiver.
446    possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
447    /// Receiver paired with `possession_check_tx`; taken by the scheduler task.
448    possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
449    /// ADR-0004: sender the payment verifier clones to surface monetized pins
450    /// for a deterministic first audit. The matching receiver is drained by
451    /// `start_first_audit_drainer`.
452    monetized_pin_tx: mpsc::UnboundedSender<MonetizedPinEvent>,
453    /// ADR-0004: receiver half of the monetized-pin channel, taken by
454    /// `start_first_audit_drainer`.
455    monetized_pin_rx: Option<mpsc::UnboundedReceiver<MonetizedPinEvent>>,
456    /// Shutdown token.
457    shutdown: CancellationToken,
458    /// Background task handles.
459    task_handles: Vec<JoinHandle<()>>,
460}
461
462impl ReplicationEngine {
463    /// Create a new replication engine.
464    ///
465    /// # Errors
466    ///
467    /// Returns an error if the `PaidList` LMDB environment cannot be opened
468    /// or if the configuration fails validation.
469    #[allow(clippy::too_many_arguments)]
470    pub async fn new(
471        config: ReplicationConfig,
472        p2p_node: Arc<P2PNode>,
473        storage: Arc<LmdbStorage>,
474        payment_verifier: Arc<PaymentVerifier>,
475        identity: Arc<NodeIdentity>,
476        root_dir: &Path,
477        fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
478        shutdown: CancellationToken,
479    ) -> Result<Self> {
480        config.validate().map_err(Error::Config)?;
481
482        let paid_list = Arc::new(
483            PaidList::new(root_dir)
484                .await
485                .map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
486        );
487
488        let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
489        let config = Arc::new(config);
490        let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
491
492        // ADR-0004: monetized-pin channel (verifier -> first-audit drainer).
493        let (monetized_pin_tx, monetized_pin_rx) = mpsc::unbounded_channel();
494
495        let engine = Self {
496            config: Arc::clone(&config),
497            p2p_node,
498            storage,
499            paid_list,
500            payment_verifier,
501            queues: Arc::new(RwLock::new(ReplicationQueues::new())),
502            sync_state: Arc::new(RwLock::new(initial_neighbors)),
503            sync_history: Arc::new(RwLock::new(HashMap::new())),
504            audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
505            sync_cycle_epoch: Arc::new(RwLock::new(0)),
506            repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
507            bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
508            is_bootstrapping: Arc::new(RwLock::new(true)),
509            sync_trigger: Arc::new(Notify::new()),
510            bootstrap_complete_notify: Arc::new(Notify::new()),
511            identity,
512            commitment_state: Arc::new(ResponderCommitmentState::new()),
513            retention_path: root_dir.join("commitment_retention.bin"),
514            last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
515            ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
516            recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
517            sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
518            send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
519            audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
520            audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
521            fresh_write_rx: Some(fresh_write_rx),
522            possession_check_tx,
523            possession_check_rx: Some(possession_check_rx),
524            monetized_pin_tx,
525            monetized_pin_rx: Some(monetized_pin_rx),
526            shutdown,
527            task_handles: Vec::new(),
528        };
529        // ADR-0004 A1: reload persisted responder retention BEFORE any task
530        // spawns, so an honest restarted node is answerable for its pre-restart
531        // pins from the first audit it serves, and the persist loop never races
532        // an empty snapshot over the good on-disk file.
533        load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
534        Ok(engine)
535    }
536
537    /// ADR-0004: a sender the payment verifier uses to surface monetized pins
538    /// (commitments that backed a payment) for a deterministic first audit.
539    /// Cloneable; the engine drains the matching receiver.
540    #[must_use]
541    pub fn monetized_pin_sender(&self) -> mpsc::UnboundedSender<MonetizedPinEvent> {
542        self.monetized_pin_tx.clone()
543    }
544
545    /// Get a reference to the `PaidList`.
546    #[must_use]
547    pub fn paid_list(&self) -> &Arc<PaidList> {
548        &self.paid_list
549    }
550
551    /// Get a reference to the responder's commitment state. Used by audit
552    /// handlers to look up commitments by hash; used by the rotation tick
553    /// to install fresh ones.
554    #[must_use]
555    pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
556        &self.commitment_state
557    }
558
559    /// Get a reference to the auditor's last-commitment-by-peer table.
560    #[must_use]
561    pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
562        &self.last_commitment_by_peer
563    }
564
565    /// Get a reference to the holder-eligibility cache. Phase-3 stretch:
566    /// will be read by quorum / paid-list eligibility checks.
567    #[must_use]
568    pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
569        &self.recent_provers
570    }
571
572    /// Test-only: rebuild + rotate this node's storage commitment now over its
573    /// current key set (normally on a 1h timer). Lets a test commit to chunks it
574    /// just stored without waiting for the rotation cadence.
575    ///
576    /// # Errors
577    ///
578    /// Propagates any error from reading the local key set or building/signing
579    /// the commitment.
580    #[cfg(any(test, feature = "test-utils"))]
581    pub async fn rebuild_commitment_now(&self) -> Result<()> {
582        rebuild_and_rotate_commitment(
583            &self.storage,
584            &self.identity,
585            &self.commitment_state,
586            &self.p2p_node,
587            &self.config,
588        )
589        .await
590    }
591
592    /// Test-only: directly seed this node's cached commitment for `peer`,
593    /// simulating "we received `peer`'s gossiped commitment" without depending
594    /// on neighbor-sync propagation timing. Lets a two-node audit test pin the
595    /// peer's commitment deterministically.
596    #[cfg(any(feature = "test-utils", test))]
597    pub async fn inject_peer_commitment_for_test(
598        &self,
599        peer: &PeerId,
600        commitment: StorageCommitment,
601    ) {
602        let now = Instant::now();
603        self.last_commitment_by_peer
604            .write()
605            .await
606            .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
607        self.ever_capable_peers.write().await.insert(*peer);
608    }
609
610    /// Test-only: run ONE subtree audit against `peer` right now, pinned to the
611    /// commitment this node has cached for it (from gossip), over the live wire.
612    /// Returns the audit outcome so tests can assert honest-pass / adversary-fail
613    /// in a real two-node setting without waiting for the gossip cadence.
614    ///
615    /// Returns `AuditTickResult::Idle` if we have no cached commitment for the
616    /// peer yet (gossip hasn't reached us). Gated to test builds.
617    #[cfg(any(test, feature = "test-utils"))]
618    pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
619        let target = {
620            let map = self.last_commitment_by_peer.read().await;
621            map.get(peer)
622                .and_then(PeerCommitmentRecord::last_commitment)
623                .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
624        };
625        let Some((pin, key_count)) = target else {
626            return audit::AuditTickResult::Idle;
627        };
628        let credit = storage_commitment_audit::AuditCredit {
629            recent_provers: &self.recent_provers,
630        };
631        storage_commitment_audit::run_subtree_audit(
632            &self.p2p_node,
633            &self.config,
634            peer,
635            pin,
636            key_count,
637            Some(&credit),
638        )
639        .await
640    }
641
642    /// Test-only: run the possession check immediately for `key` against
643    /// `peers`, bypassing the scheduler's randomised 5-15 minute settle delay.
644    ///
645    /// Penalises any peer that does not hold `key` at `AuditChallenge`
646    /// severity (ADR-0003). Lets e2e tests assert the detection+penalty path
647    /// deterministically without waiting for the scheduled check.
648    #[cfg(any(test, feature = "test-utils"))]
649    pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
650        possession::run_possession_check(
651            key,
652            peers,
653            &self.p2p_node,
654            &self.storage,
655            &self.config,
656            &self.sync_state,
657            &self.shutdown,
658        )
659        .await;
660    }
661
662    /// Start all background tasks.
663    ///
664    /// `dht_events` must be subscribed **before** `P2PNode::start()` so that
665    /// the `BootstrapComplete` event emitted during DHT bootstrap is not
666    /// missed by the bootstrap-sync gate.
667    pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
668        if !self.task_handles.is_empty() {
669            error!("ReplicationEngine::start() called while already running — ignoring");
670            return;
671        }
672        info!("Starting replication engine");
673
674        self.start_message_handler();
675        self.start_neighbor_sync_loop();
676        self.start_self_lookup_loop();
677        // Audit #2 (responsible-chunk): periodic tick auditing peers for the
678        // chunks they SHOULD store (responsibility + prior hint).
679        self.start_audit_loop();
680        // Audit #1 (storage-commitment) is gossip-triggered in the message
681        // handler when a peer's commitment is ingested, not on a periodic tick.
682        self.start_commitment_rotation_loop();
683        self.start_retention_persist_loop();
684        self.start_fetch_worker();
685        self.start_verification_worker();
686        self.start_bootstrap_sync(dht_events);
687        self.start_fresh_write_drainer();
688        self.start_possession_check_scheduler();
689        // ADR-0004: deterministic first audit of commitments that backed a
690        // payment (surfaced by the verifier cross-check).
691        self.start_first_audit_drainer();
692        // V2-623: periodic cumulative per-variant traffic accounting.
693        self.start_traffic_summary_loop();
694
695        info!(
696            "Replication engine started with {} background tasks",
697            self.task_handles.len()
698        );
699    }
700
701    /// Returns `true` if the node is still in the replication bootstrap phase.
702    ///
703    /// During bootstrap, audit challenges return `Bootstrapping` instead of
704    /// digests, and neighbor sync responses carry `bootstrapping: true`.
705    pub async fn is_bootstrapping(&self) -> bool {
706        *self.is_bootstrapping.read().await
707    }
708
709    /// Wait until the replication bootstrap phase completes.
710    ///
711    /// Returns immediately if bootstrap has already completed. Useful for
712    /// readiness probes, health checks, and test harnesses that need the
713    /// node to be fully operational before proceeding.
714    ///
715    /// Returns `true` if bootstrap completed within the timeout, `false`
716    /// if the timeout elapsed first.
717    pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
718        // Register the notification future *before* checking the flag so that
719        // a transition between the read and the await is not missed.
720        let notified = self.bootstrap_complete_notify.notified();
721        tokio::pin!(notified);
722        notified.as_mut().enable();
723
724        if !*self.is_bootstrapping.read().await {
725            return true;
726        }
727
728        tokio::time::timeout(timeout, notified).await.is_ok()
729    }
730
731    /// Cancel all background tasks and wait for them to terminate.
732    ///
733    /// This must be awaited before dropping the engine when the caller needs
734    /// the `Arc<LmdbStorage>` references held by background tasks to be
735    /// released (e.g. before reopening the same LMDB environment).
736    pub async fn shutdown(&mut self) {
737        self.shutdown.cancel();
738        for (i, mut handle) in self.task_handles.drain(..).enumerate() {
739            match tokio::time::timeout(std::time::Duration::from_secs(10), &mut handle).await {
740                Ok(Ok(())) => {}
741                Ok(Err(e)) if e.is_cancelled() => {}
742                Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
743                Err(_) => {
744                    warn!("Replication task {i} did not stop within 10s, aborting");
745                    handle.abort();
746                }
747            }
748        }
749    }
750
751    /// Trigger an early neighbor sync round.
752    ///
753    /// Useful after topology changes (new nodes joining, network heal after
754    /// partition) when the caller wants replication to converge faster than
755    /// the regular 10-20 minute cadence.
756    pub fn trigger_neighbor_sync(&self) {
757        self.sync_trigger.notify_one();
758    }
759
760    /// Execute fresh replication for a newly stored record, then schedule the
761    /// delayed possession check for the responsible close-group peers
762    /// (ADR-0003). The production PUT path schedules via the fresh-write
763    /// drainer; this direct entry point schedules here so callers (and tests)
764    /// that drive replication directly still get the possession check.
765    pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
766        let peers = fresh::replicate_fresh(
767            key,
768            data,
769            proof_of_payment,
770            &self.p2p_node,
771            &self.paid_list,
772            &self.config,
773            &self.send_semaphore,
774        )
775        .await;
776        if !peers.is_empty() {
777            let _ = self
778                .possession_check_tx
779                .send(possession::PossessionCheckEvent { key: *key, peers });
780        }
781    }
782
783    // =======================================================================
784    // Background task launchers
785    // =======================================================================
786
787    /// Spawn a task that drains the fresh-write channel and triggers
788    /// replication for each newly-stored chunk.
789    fn start_fresh_write_drainer(&mut self) {
790        let Some(mut rx) = self.fresh_write_rx.take() else {
791            return;
792        };
793        let p2p = Arc::clone(&self.p2p_node);
794        let paid_list = Arc::clone(&self.paid_list);
795        let config = Arc::clone(&self.config);
796        let send_semaphore = Arc::clone(&self.send_semaphore);
797        let possession_tx = self.possession_check_tx.clone();
798        let shutdown = self.shutdown.clone();
799
800        let handle = tokio::spawn(async move {
801            loop {
802                tokio::select! {
803                    () = shutdown.cancelled() => break,
804                    event = rx.recv() => {
805                        let Some(event) = event else { break };
806                        let peers = fresh::replicate_fresh(
807                            &event.key,
808                            &event.data,
809                            &event.payment_proof,
810                            &p2p,
811                            &paid_list,
812                            &config,
813                            &send_semaphore,
814                        )
815                        .await;
816                        // Schedule the delayed possession check (ADR-0003) for
817                        // the responsible close-group peers. A closed receiver
818                        // (engine shutting down) is ignored.
819                        if !peers.is_empty() {
820                            let _ = possession_tx.send(possession::PossessionCheckEvent {
821                                key: event.key,
822                                peers,
823                            });
824                        }
825                    }
826                }
827            }
828            debug!("Fresh-write drainer shut down");
829        });
830        self.task_handles.push(handle);
831    }
832
833    /// Spawn the possession-check scheduler (ADR-0003).
834    ///
835    /// Drains scheduled possession-check events and, for each, waits a
836    /// randomised 5-15 minute settle delay before probing every responsible
837    /// peer for actual possession. A peer that cryptographically fails to prove
838    /// possession, including by timeout, is penalised at `AuditChallenge`
839    /// severity.
840    fn start_possession_check_scheduler(&mut self) {
841        let Some(mut rx) = self.possession_check_rx.take() else {
842            return;
843        };
844        let p2p = Arc::clone(&self.p2p_node);
845        let storage = Arc::clone(&self.storage);
846        let config = Arc::clone(&self.config);
847        let sync_state = Arc::clone(&self.sync_state);
848        let shutdown = self.shutdown.clone();
849
850        let handle = tokio::spawn(async move {
851            loop {
852                tokio::select! {
853                    () = shutdown.cancelled() => break,
854                    event = rx.recv() => {
855                        let Some(event) = event else { break };
856                        // Spawn a per-chunk delayed check so the drain loop
857                        // keeps pace with the write rate. Each check sleeps the
858                        // randomised settle delay, then probes every peer.
859                        let p2p = Arc::clone(&p2p);
860                        let storage = Arc::clone(&storage);
861                        let config = Arc::clone(&config);
862                        let sync_state = Arc::clone(&sync_state);
863                        let shutdown = shutdown.clone();
864                        let delay_min = config.possession_check_delay_min;
865                        let delay_max = config.possession_check_delay_max;
866                        tokio::spawn(async move {
867                            let delay = possession::random_delay(delay_min, delay_max);
868                            tokio::select! {
869                                () = shutdown.cancelled() => {}
870                                () = tokio::time::sleep(delay) => {
871                                    possession::run_possession_check(
872                                        event.key,
873                                        event.peers,
874                                        &p2p,
875                                        &storage,
876                                        &config,
877                                        &sync_state,
878                                        &shutdown,
879                                    )
880                                    .await;
881                                }
882                            }
883                        });
884                    }
885                }
886            }
887            debug!("Possession-check scheduler shut down");
888        });
889        self.task_handles.push(handle);
890    }
891
892    /// ADR-0004: drain monetized pins surfaced by the verifier cross-check and
893    /// run a **deterministic first audit** of each — the same `run_subtree_audit`
894    /// as the gossip path, under the same per-peer cooldown and concurrency
895    /// caps, but with the probability lottery BYPASSED (the lottery governs
896    /// re-audits only). Deduped by pin via a bounded set so a pin gets one
897    /// deterministic first audit; a peer minting fresh pins faster than the
898    /// cooldown forfeits the older ones' coverage, never the newest's (the
899    /// channel surfaces newest pins as they are monetized).
900    #[allow(clippy::too_many_lines)]
901    fn start_first_audit_drainer(&mut self) {
902        let Some(mut rx) = self.monetized_pin_rx.take() else {
903            return;
904        };
905        let gossip_audit = GossipAuditTrigger {
906            p2p_node: Arc::clone(&self.p2p_node),
907            config: Arc::clone(&self.config),
908            recent_provers: Arc::clone(&self.recent_provers),
909            sync_state: Arc::clone(&self.sync_state),
910            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
911        };
912        let shutdown = self.shutdown.clone();
913        let observability = Arc::new(FirstAuditObservability::default());
914
915        let handle = tokio::spawn(async move {
916            // Bounded dedup of pins that have ALREADY been given their
917            // deterministic first audit. A pin is inserted ONLY when an audit is
918            // actually launched (never on a cooldown skip), so a pin skipped now
919            // can still be first-audited later.
920            let mut first_audited: LruCache<[u8; 32], ()> = LruCache::new(
921                NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
922            );
923            // PERSISTENT pending queue: the most-recently-monetized pin per peer
924            // that has NOT yet been first-audited. A pin stays here until it is
925            // ACTUALLY first-audited (enters `first_audited`) — never removed for
926            // any weaker reason (e.g. a cooldown stamp), so an unaudited monetized
927            // pin is never silently forgotten. Newest-per-peer: a fresher pin for
928            // the same peer replaces the older one. Memory is bounded by an LRU:
929            // each entry needs a SETTLED on-chain payment, so the realistic count
930            // is tiny; the LRU is a pure DoS backstop that, only under an absurd
931            // flood, evicts the LEAST-RECENTLY-MONETIZED peer (the one most likely
932            // already superseded) — never the newest.
933            let mut pending: LruCache<PeerId, MonetizedPinEvent> = LruCache::new(
934                NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
935            );
936            // Periodic retry tick for pending (cooldown-blocked) pins. Created
937            // once; `Skip` so a backlog of missed ticks collapses to one.
938            let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
939            tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
940            let mut last_summary = Instant::now();
941            loop {
942                // Wake on: shutdown, a new monetized pin, OR a periodic tick so
943                // pending (cooldown-blocked) pins get retried once their window
944                // reopens even if no new pin arrives.
945                let drained_new = tokio::select! {
946                    () = shutdown.cancelled() => break,
947                    event = rx.recv() => match event {
948                        Some(e) => {
949                            observability.received.fetch_add(1, Ordering::Relaxed);
950                            // Newest-per-peer: a fresher pin replaces the older one,
951                            // BUT only if it is not already first-audited — an
952                            // already-audited duplicate must never overwrite an
953                            // unaudited pending pin for the same peer (it would then
954                            // be dropped as "done" and the unaudited pin lost). Cap
955                            // the per-wake batch drain (FIRST_AUDIT_DRAIN_BATCH) so a
956                            // sustained flood can't starve the audit-launch phase.
957                            if first_audited.contains(&e.pin) {
958                                observability.duplicates.fetch_add(1, Ordering::Relaxed);
959                                debug!(
960                                    "First-audit scheduler: audit_trigger=first_monetized outcome=duplicate peer={} pin={} key_count={} pending={}",
961                                    e.peer, hex::encode(e.pin), e.key_count, pending.len()
962                                );
963                            } else {
964                                match queue_first_audit_event(&mut pending, e) {
965                                    FirstAuditQueueOutcome::Queued => {
966                                        observability.queued.fetch_add(1, Ordering::Relaxed);
967                                        debug!(
968                                            "First-audit scheduler: audit_trigger=first_monetized outcome=queued peer={} pin={} key_count={} pending={}",
969                                            e.peer, hex::encode(e.pin), e.key_count, pending.len()
970                                        );
971                                    }
972                                    FirstAuditQueueOutcome::Coalesced => {
973                                        observability.coalesced.fetch_add(1, Ordering::Relaxed);
974                                        debug!(
975                                            "First-audit scheduler: audit_trigger=first_monetized outcome=coalesced peer={} pin={} key_count={} pending={}",
976                                            e.peer, hex::encode(e.pin), e.key_count, pending.len()
977                                        );
978                                    }
979                                    FirstAuditQueueOutcome::CapacityEvicted { peer, pin } => {
980                                        observability.queued.fetch_add(1, Ordering::Relaxed);
981                                        observability
982                                            .capacity_evicted
983                                            .fetch_add(1, Ordering::Relaxed);
984                                        debug!(
985                                            "First-audit scheduler: audit_trigger=first_monetized outcome=queued capacity_evicted=true evicted_peer={peer} evicted_pin={} replacement_peer={} replacement_pin={} pending={}",
986                                            hex::encode(pin), e.peer, hex::encode(e.pin), pending.len()
987                                        );
988                                    }
989                                }
990                            }
991                            let mut drained = 1usize;
992                            while drained < config::FIRST_AUDIT_DRAIN_BATCH {
993                                match rx.try_recv() {
994                                    Ok(e) => {
995                                        observability.received.fetch_add(1, Ordering::Relaxed);
996                                        if first_audited.contains(&e.pin) {
997                                            observability
998                                                .duplicates
999                                                .fetch_add(1, Ordering::Relaxed);
1000                                        } else {
1001                                            match queue_first_audit_event(&mut pending, e) {
1002                                                FirstAuditQueueOutcome::Queued => {
1003                                                    observability
1004                                                        .queued
1005                                                        .fetch_add(1, Ordering::Relaxed);
1006                                                }
1007                                                FirstAuditQueueOutcome::Coalesced => {
1008                                                    observability
1009                                                        .coalesced
1010                                                        .fetch_add(1, Ordering::Relaxed);
1011                                                }
1012                                                FirstAuditQueueOutcome::CapacityEvicted { .. } => {
1013                                                    observability
1014                                                        .queued
1015                                                        .fetch_add(1, Ordering::Relaxed);
1016                                                    observability
1017                                                        .capacity_evicted
1018                                                        .fetch_add(1, Ordering::Relaxed);
1019                                                }
1020                                            }
1021                                        }
1022                                        drained += 1;
1023                                    }
1024                                    Err(_) => break,
1025                                }
1026                            }
1027                            true
1028                        }
1029                        None => break,
1030                    },
1031                    _ = tick.tick() => false,
1032                };
1033                let _ = drained_new;
1034
1035                if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
1036                    info!(
1037                        "First-audit scheduler summary: audit_trigger=first_monetized received={} queued={} coalesced={} duplicates={} capacity_evicted={} cooldown_deferred_attempts={} launched={} passed={} timeout={} failed={} bootstrap_claims={} idle={} insufficient_keys={} outside_answerability_window={} pending={} inflight={}",
1038                        observability.received.load(Ordering::Relaxed),
1039                        observability.queued.load(Ordering::Relaxed),
1040                        observability.coalesced.load(Ordering::Relaxed),
1041                        observability.duplicates.load(Ordering::Relaxed),
1042                        observability.capacity_evicted.load(Ordering::Relaxed),
1043                        observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
1044                        observability.launched.load(Ordering::Relaxed),
1045                        observability.passed.load(Ordering::Relaxed),
1046                        observability.timed_out.load(Ordering::Relaxed),
1047                        observability.failed.load(Ordering::Relaxed),
1048                        observability.bootstrap_claims.load(Ordering::Relaxed),
1049                        observability.idle.load(Ordering::Relaxed),
1050                        observability.insufficient_keys.load(Ordering::Relaxed),
1051                        observability.outside_answerability_window.load(Ordering::Relaxed),
1052                        pending.len(),
1053                        observability.inflight.load(Ordering::Relaxed),
1054                    );
1055                    last_summary = Instant::now();
1056                }
1057
1058                if pending.is_empty() {
1059                    continue;
1060                }
1061
1062                // Try to launch an audit for each pending peer; keep the ones
1063                // still blocked by cooldown for the next tick. Drain into a vec
1064                // first so we can re-insert the still-blocked ones afterwards
1065                // (LruCache has no drain). `iter()` yields most- to least-recently-
1066                // used; we reverse so re-inserting blocked entries below restores
1067                // their relative recency (oldest re-put first → stays the eviction
1068                // victim, newest stays most-recently-used).
1069                let snapshot: Vec<(PeerId, MonetizedPinEvent)> =
1070                    pending.iter().rev().map(|(p, e)| (*p, *e)).collect();
1071                pending.clear();
1072                for (peer, event) in snapshot {
1073                    // Dedup: a pin already first-audited is dropped (done).
1074                    if first_audited.contains(&event.pin) {
1075                        observability.duplicates.fetch_add(1, Ordering::Relaxed);
1076                        continue;
1077                    }
1078                    // ADR-0004 A1 (guardrail A): only first-audit a pin whose SIGNED
1079                    // quote_ts lands inside the answerability window. With grace
1080                    // removed, auditing an out-of-window pin the responder may have
1081                    // aged out would false-convict, so a stale OR far-future/skewed
1082                    // quote is skipped. Legit first-audits fire moments after
1083                    // payment (quote_ts ≈ now); a skipped pin can still be
1084                    // gossip-lottery audited.
1085                    if !quote_within_audit_window(event.quote_ts, SystemTime::now()) {
1086                        observability
1087                            .outside_answerability_window
1088                            .fetch_add(1, Ordering::Relaxed);
1089                        debug!(
1090                            "First-audit scheduler: audit_trigger=first_monetized outcome=outside_answerability_window peer={peer} pin={} key_count={} pending={}",
1091                            hex::encode(event.pin), event.key_count, pending.len()
1092                        );
1093                        continue;
1094                    }
1095                    // Cooldown: if the peer's per-peer audit window is closed, keep
1096                    // this pin pending and retry on a later tick once it reopens.
1097                    // We do NOT treat "cooldown closed" as "already audited" (a
1098                    // losing gossip lottery can stamp the window without auditing),
1099                    // so the pin stays pending until it gets a REAL first audit; it
1100                    // is only ever evicted by the LRU memory backstop above, which
1101                    // drops the least-recently-monetized peer, not this newest one.
1102                    {
1103                        let now = Instant::now();
1104                        let mut map = gossip_audit.cooldown.write().await;
1105                        if !cooldown_allows_audit(&mut map, &peer, now) {
1106                            pending.put(peer, event);
1107                            observability
1108                                .cooldown_deferred_attempts
1109                                .fetch_add(1, Ordering::Relaxed);
1110                            debug!(
1111                                "First-audit scheduler: audit_trigger=first_monetized outcome=cooldown_deferred peer={peer} pin={} key_count={} pending={}",
1112                                hex::encode(event.pin), event.key_count, pending.len()
1113                            );
1114                            continue;
1115                        }
1116                    }
1117                    // Audit is launching: now mark the pin first-audited.
1118                    first_audited.put(event.pin, ());
1119                    observability.launched.fetch_add(1, Ordering::Relaxed);
1120                    observability.inflight.fetch_add(1, Ordering::Relaxed);
1121                    debug!(
1122                        "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={peer} pin={} key_count={} pending={} inflight={}",
1123                        hex::encode(event.pin), event.key_count, pending.len(),
1124                        observability.inflight.load(Ordering::Relaxed)
1125                    );
1126                    let trigger = gossip_audit.clone();
1127                    let audit_observability = Arc::clone(&observability);
1128                    tokio::spawn(async move {
1129                        let started = Instant::now();
1130                        let credit = storage_commitment_audit::AuditCredit {
1131                            recent_provers: &trigger.recent_provers,
1132                        };
1133                        let result = storage_commitment_audit::run_subtree_audit(
1134                            &trigger.p2p_node,
1135                            &trigger.config,
1136                            &event.peer,
1137                            event.pin,
1138                            event.key_count,
1139                            Some(&credit),
1140                        )
1141                        .await;
1142                        let outcome = first_audit_terminal_outcome(&result);
1143                        match outcome {
1144                            FirstAuditTerminalOutcome::Passed => {
1145                                audit_observability.passed.fetch_add(1, Ordering::Relaxed);
1146                            }
1147                            FirstAuditTerminalOutcome::Timeout => {
1148                                audit_observability
1149                                    .timed_out
1150                                    .fetch_add(1, Ordering::Relaxed);
1151                            }
1152                            FirstAuditTerminalOutcome::Failed => {
1153                                audit_observability.failed.fetch_add(1, Ordering::Relaxed);
1154                            }
1155                            FirstAuditTerminalOutcome::BootstrapClaim => {
1156                                audit_observability
1157                                    .bootstrap_claims
1158                                    .fetch_add(1, Ordering::Relaxed);
1159                            }
1160                            FirstAuditTerminalOutcome::Idle => {
1161                                audit_observability.idle.fetch_add(1, Ordering::Relaxed);
1162                            }
1163                            FirstAuditTerminalOutcome::InsufficientKeys => {
1164                                audit_observability
1165                                    .insufficient_keys
1166                                    .fetch_add(1, Ordering::Relaxed);
1167                            }
1168                        }
1169                        audit_observability.inflight.fetch_sub(1, Ordering::Relaxed);
1170                        debug!(
1171                            "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
1172                            outcome.as_str(),
1173                            event.peer, hex::encode(event.pin), event.key_count,
1174                            started.elapsed().as_millis(),
1175                            audit_observability.inflight.load(Ordering::Relaxed)
1176                        );
1177                        handle_subtree_audit_result(
1178                            &result,
1179                            &trigger.p2p_node,
1180                            &trigger.sync_state,
1181                            &trigger.recent_provers,
1182                            &trigger.config,
1183                        )
1184                        .await;
1185                    });
1186                }
1187            }
1188            debug!("First-audit drainer shut down");
1189        });
1190        self.task_handles.push(handle);
1191    }
1192
1193    #[allow(clippy::too_many_lines)]
1194    fn start_message_handler(&mut self) {
1195        let mut p2p_events = self.p2p_node.subscribe_events();
1196        let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
1197        let p2p = Arc::clone(&self.p2p_node);
1198        let storage = Arc::clone(&self.storage);
1199        let paid_list = Arc::clone(&self.paid_list);
1200        let payment_verifier = Arc::clone(&self.payment_verifier);
1201        let queues = Arc::clone(&self.queues);
1202        let config = Arc::clone(&self.config);
1203        let shutdown = self.shutdown.clone();
1204        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
1205        let bootstrap_state = Arc::clone(&self.bootstrap_state);
1206        let sync_history = Arc::clone(&self.sync_history);
1207        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
1208        let repair_proofs = Arc::clone(&self.repair_proofs);
1209        let sync_trigger = Arc::clone(&self.sync_trigger);
1210        let my_commitment_state = Arc::clone(&self.commitment_state);
1211        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
1212        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
1213        let recent_provers = Arc::clone(&self.recent_provers);
1214        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
1215        let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
1216        let sync_state = Arc::clone(&self.sync_state);
1217        let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
1218        let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
1219
1220        // ADR-0002 gossip-audit trigger: bundled state so an ingested *changed*
1221        // commitment can spawn a probabilistic, cooldown-gated subtree audit.
1222        let gossip_audit = GossipAuditTrigger {
1223            p2p_node: Arc::clone(&p2p),
1224            config: Arc::clone(&config),
1225            recent_provers: Arc::clone(&recent_provers),
1226            sync_state: Arc::clone(&sync_state),
1227            cooldown: Arc::clone(&audit_on_gossip_cooldown),
1228        };
1229
1230        let handle = tokio::spawn(async move {
1231            loop {
1232                tokio::select! {
1233                    () = shutdown.cancelled() => break,
1234                    event = p2p_events.recv() => {
1235                        let Ok(event) = event else { continue };
1236                        if let P2PEvent::Message {
1237                            topic,
1238                            source: Some(source),
1239                            data,
1240                            ..
1241                        } = event {
1242                            // Determine if this is a replication message
1243                            // and whether it arrived via the /rr/ request-response
1244                            // path (which wraps payloads in RequestResponseEnvelope).
1245                            let rr_info = if topic == REPLICATION_PROTOCOL_ID {
1246                                Some((data.clone(), None))
1247                            } else if topic.starts_with(RR_PREFIX)
1248                                && &topic[RR_PREFIX.len()..] == REPLICATION_PROTOCOL_ID
1249                            {
1250                                P2PNode::parse_request_envelope(&data)
1251                                    .filter(|(_, is_resp, _)| !is_resp)
1252                                    .map(|(msg_id, _, payload)| (payload, Some(msg_id)))
1253                            } else {
1254                                None
1255                            };
1256                            if let Some((payload, rr_message_id)) = rr_info {
1257                                match handle_replication_message(
1258                                    &source,
1259                                    &payload,
1260                                    &p2p,
1261                                    &storage,
1262                                    &paid_list,
1263                                    &payment_verifier,
1264                                    &queues,
1265                                    &config,
1266                                    &is_bootstrapping,
1267                                    &bootstrap_state,
1268                                    &sync_history,
1269                                    &sync_cycle_epoch,
1270                                    &repair_proofs,
1271                                    &last_commitment_by_peer,
1272                                    &ever_capable_peers,
1273                                    &sig_verify_attempts,
1274                                    &my_commitment_state,
1275                                    &gossip_audit,
1276                                    &audit_responder_semaphore,
1277                                    &audit_responder_inflight,
1278                                    rr_message_id.as_deref(),
1279                                ).await {
1280                                    Ok(()) => {}
1281                                    Err(e) => {
1282                                        debug!(
1283                                            "Replication message from {source} error: {e}"
1284                                        );
1285                                    }
1286                                }
1287                            }
1288                        }
1289                    }
1290                    // Gap 4: Topology churn handling (Section 13).
1291                    //
1292                    // The DHT routing table emits KClosestPeersChanged when the
1293                    // K-closest peer set actually changes, which is the precise
1294                    // signal for triggering neighbor sync. This replaces the
1295                    // previous approach of checking every PeerConnected /
1296                    // PeerDisconnected event against the close group.
1297                    dht_event = dht_events.recv() => {
1298                        let Ok(dht_event) = dht_event else { continue };
1299                        match dht_event {
1300                            DhtNetworkEvent::KClosestPeersChanged { old, new } => {
1301                                let old_peers = old
1302                                    .iter()
1303                                    .take(config.neighbor_sync_scope)
1304                                    .copied()
1305                                    .collect::<HashSet<_>>();
1306                                let new_scoped = new
1307                                    .iter()
1308                                    .take(config.neighbor_sync_scope)
1309                                    .copied()
1310                                    .collect::<Vec<_>>();
1311                                let new_peers =
1312                                    new_scoped.iter().copied().collect::<HashSet<_>>();
1313                                let entrants = new_scoped
1314                                    .iter()
1315                                    .copied()
1316                                    .filter(|peer| !old_peers.contains(peer))
1317                                    .collect::<Vec<_>>();
1318                                let entrant_count = entrants.len();
1319                                let (priority_insertions, sync_removals) = {
1320                                    let mut state = sync_state.write().await;
1321                                    let sync_removals = state.retain_sync_peers(&new_peers);
1322                                    let priority_insertions = state.queue_priority_peers(entrants);
1323                                    (priority_insertions, sync_removals)
1324                                };
1325                                if priority_insertions > 0 {
1326                                    debug!(
1327                                        "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
1328                                    );
1329                                } else {
1330                                    debug!(
1331                                        "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
1332                                    );
1333                                }
1334                                sync_trigger.notify_one();
1335                            }
1336                            DhtNetworkEvent::PeerRemoved { peer_id } => {
1337                                sync_state.write().await.remove_peer(&peer_id);
1338                                repair_proofs.write().await.remove_peer(&peer_id);
1339                                // v12: drop the commitment bytes and the
1340                                // recent-prover credit so a churn / sybil
1341                                // attacker cannot leave behind one
1342                                // StorageCommitment per identity in
1343                                // `last_commitment_by_peer`. Also drop the
1344                                // sig-verify rate-limit timestamp.
1345                                last_commitment_by_peer.write().await.remove(&peer_id);
1346                                recent_provers.write().await.forget_peer(&peer_id);
1347                                sig_verify_attempts.write().await.remove(&peer_id);
1348                                // Same for the gossip-audit cooldown (ADR-0002).
1349                                audit_on_gossip_cooldown.write().await.remove(&peer_id);
1350                                // The sticky `commitment_capable` flag is
1351                                // preserved orthogonally via
1352                                // `ever_capable_peers` — even after this
1353                                // removal, a re-joining peer continues to
1354                                // be treated as v12-capable rather than
1355                                // legacy (§3 shield).
1356                            }
1357                            _ => {}
1358                        }
1359                    }
1360                }
1361            }
1362            debug!("Replication message handler shut down");
1363        });
1364        self.task_handles.push(handle);
1365    }
1366
1367    fn start_neighbor_sync_loop(&mut self) {
1368        let p2p = Arc::clone(&self.p2p_node);
1369        let storage = Arc::clone(&self.storage);
1370        let paid_list = Arc::clone(&self.paid_list);
1371        let queues = Arc::clone(&self.queues);
1372        let config = Arc::clone(&self.config);
1373        let shutdown = self.shutdown.clone();
1374        let sync_state = Arc::clone(&self.sync_state);
1375        let sync_history = Arc::clone(&self.sync_history);
1376        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
1377        let repair_proofs = Arc::clone(&self.repair_proofs);
1378        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
1379        let bootstrap_state = Arc::clone(&self.bootstrap_state);
1380        let sync_trigger = Arc::clone(&self.sync_trigger);
1381        let commitment_state = Arc::clone(&self.commitment_state);
1382        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
1383        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
1384        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
1385        // ADR-0002: a peer's commitment also arrives on the sync RESPONSE path
1386        // (we initiated, they piggybacked theirs). Carry a gossip-audit trigger
1387        // here too so a peer that only ever answers — never initiates sync —
1388        // is still audited; otherwise it could fully evade auditing.
1389        let gossip_audit = GossipAuditTrigger {
1390            p2p_node: Arc::clone(&p2p),
1391            config: Arc::clone(&config),
1392            recent_provers: Arc::clone(&self.recent_provers),
1393            sync_state: Arc::clone(&sync_state),
1394            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
1395        };
1396
1397        let handle = tokio::spawn(async move {
1398            loop {
1399                let interval = config.random_neighbor_sync_interval();
1400                tokio::select! {
1401                    () = shutdown.cancelled() => break,
1402                    () = tokio::time::sleep(interval) => {}
1403                    () = sync_trigger.notified() => {
1404                        debug!("Neighbor sync triggered by topology change");
1405                    }
1406                }
1407                // Wrap the sync round in a select so shutdown cancels
1408                // in-progress network operations rather than waiting for
1409                // the full round to complete.
1410                tokio::select! {
1411                    () = shutdown.cancelled() => break,
1412                    () = run_neighbor_sync_round(
1413                        &p2p,
1414                        &storage,
1415                        &paid_list,
1416                        &queues,
1417                        &config,
1418                        &sync_state,
1419                        &sync_history,
1420                        &sync_cycle_epoch,
1421                        &repair_proofs,
1422                        &is_bootstrapping,
1423                        &bootstrap_state,
1424                        &commitment_state,
1425                        &last_commitment_by_peer,
1426                        &ever_capable_peers,
1427                        &sig_verify_attempts,
1428                        &gossip_audit,
1429                    ) => {}
1430                }
1431            }
1432            debug!("Neighbor sync loop shut down");
1433        });
1434        self.task_handles.push(handle);
1435    }
1436
1437    fn start_self_lookup_loop(&mut self) {
1438        let p2p = Arc::clone(&self.p2p_node);
1439        let config = Arc::clone(&self.config);
1440        let shutdown = self.shutdown.clone();
1441
1442        let handle = tokio::spawn(async move {
1443            loop {
1444                let interval = config.random_self_lookup_interval();
1445                tokio::select! {
1446                    () = shutdown.cancelled() => break,
1447                    () = tokio::time::sleep(interval) => {
1448                        if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
1449                            debug!("Self-lookup failed: {e}");
1450                        }
1451                    }
1452                }
1453            }
1454            debug!("Self-lookup loop shut down");
1455        });
1456        self.task_handles.push(handle);
1457    }
1458
1459    /// Periodic responsible-chunk audit loop (audit #2): every
1460    /// [`ReplicationConfig::random_audit_tick_interval`] (~10-20 min), audit one
1461    /// eligible close peer for the chunks it *should* be storing (by
1462    /// responsibility and prior repair hint), independent of the gossip-triggered
1463    /// storage-commitment audit. Waits for bootstrap to drain, then runs one tick
1464    /// immediately and periodically thereafter.
1465    fn start_audit_loop(&mut self) {
1466        let p2p = Arc::clone(&self.p2p_node);
1467        let storage = Arc::clone(&self.storage);
1468        let config = Arc::clone(&self.config);
1469        let shutdown = self.shutdown.clone();
1470        let sync_history = Arc::clone(&self.sync_history);
1471        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
1472        let repair_proofs = Arc::clone(&self.repair_proofs);
1473        let bootstrap_state = Arc::clone(&self.bootstrap_state);
1474        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
1475        let sync_state = Arc::clone(&self.sync_state);
1476
1477        let handle = tokio::spawn(async move {
1478            // Invariant 19: wait for bootstrap to drain before starting audits.
1479            loop {
1480                tokio::select! {
1481                    () = shutdown.cancelled() => return,
1482                    () = tokio::time::sleep(
1483                        std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
1484                    ) => {
1485                        if bootstrap_state.read().await.is_drained() {
1486                            break;
1487                        }
1488                    }
1489                }
1490            }
1491
1492            // Run one audit tick immediately after bootstrap drain.
1493            {
1494                let bootstrapping = *is_bootstrapping.read().await;
1495                let result = {
1496                    let history = sync_history.read().await;
1497                    let current_sync_epoch = *sync_cycle_epoch.read().await;
1498                    audit::audit_tick_with_repair_proofs(
1499                        &p2p,
1500                        &storage,
1501                        &config,
1502                        &history,
1503                        &repair_proofs,
1504                        current_sync_epoch,
1505                        bootstrapping,
1506                    )
1507                    .await
1508                };
1509                handle_audit_result(&result, &p2p, &sync_state, &config).await;
1510            }
1511
1512            // Then run periodically.
1513            loop {
1514                let interval = config.random_audit_tick_interval();
1515                tokio::select! {
1516                    () = shutdown.cancelled() => break,
1517                    () = tokio::time::sleep(interval) => {
1518                        let bootstrapping = *is_bootstrapping.read().await;
1519                        let result = {
1520                            let history = sync_history.read().await;
1521                            let current_sync_epoch = *sync_cycle_epoch.read().await;
1522                            audit::audit_tick_with_repair_proofs(
1523                                &p2p,
1524                                &storage,
1525                                &config,
1526                                &history,
1527                                &repair_proofs,
1528                                current_sync_epoch,
1529                                bootstrapping,
1530                            )
1531                            .await
1532                        };
1533                        handle_audit_result(&result, &p2p, &sync_state, &config).await;
1534                    }
1535                }
1536            }
1537            debug!("Audit loop shut down");
1538        });
1539        self.task_handles.push(handle);
1540    }
1541
1542    /// Periodically rebuild + sign + rotate the responder's storage
1543    /// commitment.
1544    ///
1545    /// Phase 3 of the v12 storage-bound audit. Once per
1546    /// [`COMMITMENT_ROTATION_INTERVAL_SECS`], the responder reads the
1547    /// current LMDB key set, builds a Merkle tree (for content-addressed
1548    /// chunks `bytes_hash == key`, so no chunk re-read is needed), signs
1549    /// the root with the node's `MlDsaSecretKey`, and rotates the result
1550    /// into `commitment_state`. Old `previous` slot is dropped by the
1551    /// rotate (per `ResponderCommitmentState::rotate`).
1552    ///
1553    /// Skips if the key set is empty (no commitment to make) — the
1554    /// auditor side falls back to the legacy plain-digest path for
1555    /// peers that have never gossiped a commitment.
1556    fn start_commitment_rotation_loop(&mut self) {
1557        let storage = Arc::clone(&self.storage);
1558        let identity = Arc::clone(&self.identity);
1559        let commitment_state = Arc::clone(&self.commitment_state);
1560        let shutdown = self.shutdown.clone();
1561        let p2p = Arc::clone(&self.p2p_node);
1562        let config = Arc::clone(&self.config);
1563        let sync_trigger = Arc::clone(&self.sync_trigger);
1564        let recent_provers = Arc::clone(&self.recent_provers);
1565
1566        let handle = tokio::spawn(async move {
1567            // Build the first commitment immediately on startup so a
1568            // restarted node can answer commitment-bound audits right
1569            // away — otherwise current() stays None for a full rotation
1570            // interval and audits silently fall back to legacy.
1571            //
1572            // After the first build, trigger an immediate neighbor-sync
1573            // round so the new commitment gossips out within seconds.
1574            // Without this, after a restart remote auditors keep pinning
1575            // the pre-restart (rotated-away) hash until their normal
1576            // sync cadence elapses — up to 1 h in the worst case,
1577            // during which time commitment-bound audits hit "unknown
1578            // commitment hash" -> Idle no-ops.
1579            // ML-DSA signatures are randomized so we cannot reproduce
1580            // the pre-restart hash; the only honest path to recovery
1581            // is fast re-gossip.
1582            // ADR-0004 A1: retention was reloaded in `new()` (before any task
1583            // spawned), so this initial rebuild no-ops when the key set is
1584            // unchanged — preserving the reloaded current pin; otherwise the
1585            // reloaded roots stay answerable as retained slots until their gossip
1586            // TTL lapses. Persistence is handled by the retention-persist loop.
1587            if let Err(e) =
1588                rebuild_and_rotate_commitment(&storage, &identity, &commitment_state, &p2p, &config)
1589                    .await
1590            {
1591                warn!("Initial commitment build failed: {e}");
1592            } else {
1593                sync_trigger.notify_one();
1594            }
1595            loop {
1596                tokio::select! {
1597                    () = shutdown.cancelled() => break,
1598                    () = tokio::time::sleep(
1599                        std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
1600                    ) => {
1601                        if let Err(e) = rebuild_and_rotate_commitment(
1602                            &storage,
1603                            &identity,
1604                            &commitment_state,
1605                            &p2p,
1606                            &config,
1607                        ).await {
1608                            warn!("Commitment rotation failed: {e}");
1609                        }
1610                        // Piggyback a sweep of expired recent_provers
1611                        // entries on the rotation tick (same cadence,
1612                        // 1 h). is_credited_holder already honours the
1613                        // TTL on read, but the sweep reclaims memory
1614                        // for entries we'll never re-read.
1615                        let dropped = recent_provers.write().await.sweep_expired(
1616                            std::time::Instant::now()
1617                        );
1618                        if dropped > 0 {
1619                            debug!("recent_provers: swept {dropped} expired entries");
1620                        }
1621                    }
1622                }
1623            }
1624            debug!("Commitment rotation loop shut down");
1625        });
1626        self.task_handles.push(handle);
1627    }
1628
1629    /// ADR-0004 A1: periodically flush the responder retention snapshot to disk
1630    /// (write-on-change) so answerability — including gossip-stamp refreshes and
1631    /// rotations — survives a restart. Flushes once immediately, then every
1632    /// `RETENTION_PERSIST_INTERVAL_SECS`, and once more on shutdown.
1633    fn start_retention_persist_loop(&mut self) {
1634        let commitment_state = Arc::clone(&self.commitment_state);
1635        let retention_path = self.retention_path.clone();
1636        let shutdown = self.shutdown.clone();
1637        let handle = tokio::spawn(async move {
1638            let mut last: Option<Vec<u8>> = None;
1639            persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
1640            loop {
1641                tokio::select! {
1642                    () = shutdown.cancelled() => {
1643                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
1644                            .await;
1645                        break;
1646                    }
1647                    () = tokio::time::sleep(std::time::Duration::from_secs(
1648                        RETENTION_PERSIST_INTERVAL_SECS,
1649                    )) => {
1650                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
1651                            .await;
1652                    }
1653                }
1654            }
1655            debug!("Commitment retention persist loop shut down");
1656        });
1657        self.task_handles.push(handle);
1658    }
1659
1660    /// Periodically emit the cumulative per-variant replication traffic
1661    /// summary (V2-623). Reads the process-global counter table maintained by
1662    /// [`protocol::ReplicationMessage::encode`]/`decode`; needs no engine state.
1663    fn start_traffic_summary_loop(&mut self) {
1664        let shutdown = self.shutdown.clone();
1665        let handle = tokio::spawn(async move {
1666            loop {
1667                tokio::select! {
1668                    () = shutdown.cancelled() => break,
1669                    () = tokio::time::sleep(std::time::Duration::from_secs(
1670                        TRAFFIC_SUMMARY_INTERVAL_SECS,
1671                    )) => {
1672                        protocol::log_traffic_summary();
1673                    }
1674                }
1675            }
1676            debug!("Replication traffic summary loop shut down");
1677        });
1678        self.task_handles.push(handle);
1679    }
1680
1681    #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
1682    fn start_fetch_worker(&mut self) {
1683        let p2p = Arc::clone(&self.p2p_node);
1684        let storage = Arc::clone(&self.storage);
1685        let queues = Arc::clone(&self.queues);
1686        let config = Arc::clone(&self.config);
1687        let shutdown = self.shutdown.clone();
1688        let bootstrap_state = Arc::clone(&self.bootstrap_state);
1689        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
1690        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
1691        let concurrency = max_parallel_fetch();
1692
1693        info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
1694
1695        let handle = tokio::spawn(async move {
1696            // Each in-flight future yields (key, Option<FetchOutcome>) so we
1697            // always recover the key — even if the inner task panics.
1698            let mut in_flight = FuturesUnordered::<FetchFuture>::new();
1699
1700            loop {
1701                // Fill up to `concurrency` slots from the queue.
1702                {
1703                    let mut q = queues.write().await;
1704                    while in_flight.len() < concurrency {
1705                        let Some(candidate) = q.dequeue_fetch() else {
1706                            break;
1707                        };
1708                        let Some(&source) = candidate.sources.first() else {
1709                            warn!(
1710                                "Fetch candidate {} has no sources — dropping",
1711                                hex::encode(candidate.key)
1712                            );
1713                            continue;
1714                        };
1715                        q.start_fetch(candidate.key, source, candidate.sources.clone());
1716
1717                        let p2p = Arc::clone(&p2p);
1718                        let storage = Arc::clone(&storage);
1719                        let config = Arc::clone(&config);
1720                        let token = shutdown.clone();
1721                        let fetch_key = candidate.key;
1722                        in_flight.push(Box::pin(async move {
1723                            let handle = tokio::spawn(async move {
1724                                // Cancel-aware: abort when the engine shuts down.
1725                                tokio::select! {
1726                                    () = token.cancelled() => FetchOutcome {
1727                                        key: fetch_key,
1728                                        result: FetchResult::SourceFailed,
1729                                    },
1730                                    outcome = execute_single_fetch(
1731                                        p2p, storage, config, fetch_key, source,
1732                                    ) => outcome,
1733                                }
1734                            });
1735                            match handle.await {
1736                                Ok(outcome) => (outcome.key, Some(outcome)),
1737                                Err(e) => {
1738                                    error!(
1739                                        "Fetch task for {} panicked: {e}",
1740                                        hex::encode(fetch_key)
1741                                    );
1742                                    (fetch_key, None)
1743                                }
1744                            }
1745                        }));
1746                    }
1747                } // release queues write lock
1748
1749                if in_flight.is_empty() {
1750                    // No work — wait for new items or shutdown.
1751                    tokio::select! {
1752                        () = shutdown.cancelled() => break,
1753                        () = tokio::time::sleep(
1754                            std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
1755                        ) => continue,
1756                    }
1757                }
1758
1759                // Wait for the next fetch to complete and process the result.
1760                tokio::select! {
1761                    () = shutdown.cancelled() => break,
1762                    Some((key, maybe_outcome)) = in_flight.next() => {
1763                        let mut q = queues.write().await;
1764                        let terminal = if let Some(outcome) = maybe_outcome {
1765                            match outcome.result {
1766                                FetchResult::Stored => {
1767                                    q.complete_fetch(&key);
1768                                    true
1769                                }
1770                                FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
1771                                    if let Some(next_peer) = q.retry_fetch(&key) {
1772                                        // Spawn a new fetch task for the next source.
1773                                        let p2p = Arc::clone(&p2p);
1774                                        let storage = Arc::clone(&storage);
1775                                        let config = Arc::clone(&config);
1776                                        let token = shutdown.clone();
1777                                        let fetch_key = key;
1778                                        in_flight.push(Box::pin(async move {
1779                                            let handle = tokio::spawn(async move {
1780                                                tokio::select! {
1781                                                    () = token.cancelled() => FetchOutcome {
1782                                                        key: fetch_key,
1783                                                        result: FetchResult::SourceFailed,
1784                                                    },
1785                                                    outcome = execute_single_fetch(
1786                                                        p2p, storage, config, fetch_key, next_peer,
1787                                                    ) => outcome,
1788                                                }
1789                                            });
1790                                            match handle.await {
1791                                                Ok(outcome) => (outcome.key, Some(outcome)),
1792                                                Err(e) => {
1793                                                    error!(
1794                                                        "Fetch task for {} panicked: {e}",
1795                                                        hex::encode(fetch_key)
1796                                                    );
1797                                                    (fetch_key, None)
1798                                                }
1799                                            }
1800                                        }));
1801                                        false
1802                                    } else {
1803                                        q.complete_fetch(&key);
1804                                        true
1805                                    }
1806                                }
1807                            }
1808                        } else {
1809                            // Task panicked — reclaim the in-flight slot.
1810                            q.complete_fetch(&key);
1811                            true
1812                        };
1813
1814                        // Shrink bootstrap pending set on terminal exit.
1815                        if terminal {
1816                            drop(q); // release queues lock before acquiring bootstrap_state
1817                            if !bootstrap_state.read().await.is_drained() {
1818                                bootstrap_state.write().await.remove_key(&key);
1819                                let q = queues.read().await;
1820                                if bootstrap::check_bootstrap_drained(
1821                                    &bootstrap_state,
1822                                    &q,
1823                                )
1824                                .await
1825                                {
1826                                    complete_bootstrap(
1827                                        &is_bootstrapping,
1828                                        &bootstrap_complete_notify,
1829                                    ).await;
1830                                }
1831                            }
1832                        }
1833                    }
1834                }
1835            }
1836
1837            // Cancel and drain remaining in-flight fetches on shutdown.
1838            // The CancellationToken is already cancelled by this point, so
1839            // spawned tasks will see cancellation via their select! branches.
1840            while in_flight.next().await.is_some() {}
1841            debug!("Fetch worker shut down");
1842        });
1843        self.task_handles.push(handle);
1844    }
1845
1846    fn start_verification_worker(&mut self) {
1847        let p2p = Arc::clone(&self.p2p_node);
1848        let storage = Arc::clone(&self.storage);
1849        let queues = Arc::clone(&self.queues);
1850        let paid_list = Arc::clone(&self.paid_list);
1851        let config = Arc::clone(&self.config);
1852        let shutdown = self.shutdown.clone();
1853        let bootstrap_state = Arc::clone(&self.bootstrap_state);
1854        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
1855        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
1856        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
1857        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
1858        let recent_provers = Arc::clone(&self.recent_provers);
1859
1860        let handle = tokio::spawn(async move {
1861            loop {
1862                tokio::select! {
1863                    () = shutdown.cancelled() => break,
1864                    () = tokio::time::sleep(
1865                        std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
1866                    ) => {
1867                        let ctx = VerificationCycleContext {
1868                            p2p_node: &p2p,
1869                            paid_list: &paid_list,
1870                            storage: &storage,
1871                            queues: &queues,
1872                            config: &config,
1873                            bootstrap_state: &bootstrap_state,
1874                            is_bootstrapping: &is_bootstrapping,
1875                            bootstrap_complete_notify: &bootstrap_complete_notify,
1876                            last_commitment_by_peer: &last_commitment_by_peer,
1877                            ever_capable_peers: &ever_capable_peers,
1878                            recent_provers: &recent_provers,
1879                        };
1880                        run_verification_cycle(ctx).await;
1881                    }
1882                }
1883            }
1884            debug!("Verification worker shut down");
1885        });
1886        self.task_handles.push(handle);
1887    }
1888
1889    /// Gap 3: Run a one-shot bootstrap sync on startup.
1890    ///
1891    /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
1892    /// (indicating the routing table is populated) before snapshotting
1893    /// close neighbors. Falls back after a timeout so bootstrap nodes
1894    /// (which have no peers and therefore never receive the event) still
1895    /// proceed.
1896    ///
1897    /// After the gate, finds close neighbors, syncs with each in
1898    /// round-robin batches, admits returned hints into the verification
1899    /// pipeline, and tracks discovered keys for bootstrap drain detection.
1900    #[allow(clippy::too_many_lines)]
1901    fn start_bootstrap_sync(
1902        &mut self,
1903        dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
1904    ) {
1905        let p2p = Arc::clone(&self.p2p_node);
1906        let storage = Arc::clone(&self.storage);
1907        let paid_list = Arc::clone(&self.paid_list);
1908        let queues = Arc::clone(&self.queues);
1909        let config = Arc::clone(&self.config);
1910        let shutdown = self.shutdown.clone();
1911        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
1912        let bootstrap_state = Arc::clone(&self.bootstrap_state);
1913        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
1914        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
1915        let repair_proofs = Arc::clone(&self.repair_proofs);
1916        let my_commitment_state = Arc::clone(&self.commitment_state);
1917        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
1918        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
1919        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
1920
1921        let handle = tokio::spawn(async move {
1922            // Wait for DHT bootstrap to complete before snapshotting
1923            // neighbors. The routing table is empty until saorsa-core
1924            // finishes its FIND_NODE rounds and bucket refreshes.
1925            let gate = bootstrap::wait_for_bootstrap_complete(
1926                dht_events,
1927                config.bootstrap_complete_timeout_secs,
1928                &shutdown,
1929            )
1930            .await;
1931
1932            if gate == bootstrap::BootstrapGateResult::Shutdown {
1933                return;
1934            }
1935
1936            let self_id = *p2p.peer_id();
1937            let neighbors =
1938                neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
1939                    .await;
1940
1941            if neighbors.is_empty() {
1942                info!("Bootstrap sync: no close neighbors found, marking drained");
1943                bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
1944                complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
1945                return;
1946            }
1947
1948            let neighbor_count = neighbors.len();
1949            info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
1950
1951            // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
1952            for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
1953                if shutdown.is_cancelled() {
1954                    break;
1955                }
1956
1957                let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
1958                    batch,
1959                    &storage,
1960                    &paid_list,
1961                    &p2p,
1962                    config.close_group_size,
1963                    config.paid_list_close_group_size,
1964                )
1965                .await;
1966
1967                for peer in batch {
1968                    if shutdown.is_cancelled() {
1969                        break;
1970                    }
1971
1972                    // Re-read on each iteration so peers see current state.
1973                    let bootstrapping = *is_bootstrapping.read().await;
1974
1975                    bootstrap::increment_pending_requests(&bootstrap_state, 1).await;
1976
1977                    let hints = hints_by_peer.remove(peer).unwrap_or_default();
1978                    let outcome = neighbor_sync::sync_with_peer_with_hints(
1979                        peer,
1980                        &p2p,
1981                        &config,
1982                        bootstrapping,
1983                        hints,
1984                        // Atomically snapshot + mark-gossiped: emitted in the
1985                        // bootstrap-sync request, so we stay answerable for it
1986                        // (ADR-0002). One critical section avoids a TOCTOU where a
1987                        // concurrent retire/rotate drops the slot between read and
1988                        // mark.
1989                        my_commitment_state
1990                            .current_for_gossip()
1991                            .map(|b| b.commitment().clone()),
1992                    )
1993                    .await;
1994
1995                    bootstrap::decrement_pending_requests(&bootstrap_state, 1).await;
1996
1997                    if let Some(outcome) = outcome {
1998                        // Ingest the peer's piggybacked commitment from the
1999                        // response (same verification as the request path).
2000                        // Bootstrap is the FIRST gossip we receive from most
2001                        // peers, so this populates last_commitment_by_peer.
2002                        //
2003                        // We intentionally do NOT trigger a gossip-audit here:
2004                        // during bootstrap this node may itself still be
2005                        // bootstrapping (audits are gated on that), and the
2006                        // close-group/RT view is not yet stable. The peer is
2007                        // audited on the first STEADY-STATE neighbor-sync round
2008                        // after bootstrap drains (request + response paths both
2009                        // trigger), which is within one sync cycle — so caching
2010                        // the commitment here is sufficient and there is no
2011                        // coverage gap (ADR-0002).
2012                        ingest_peer_commitment(
2013                            peer,
2014                            outcome.response.commitment.as_ref(),
2015                            &p2p,
2016                            &last_commitment_by_peer,
2017                            &ever_capable_peers,
2018                            &sig_verify_attempts,
2019                        )
2020                        .await; // sig_verify_attempts in scope from line ~1080
2021
2022                        if !outcome.response.bootstrapping {
2023                            record_sent_replica_hints(
2024                                peer,
2025                                &outcome.sent_replica_hints,
2026                                &repair_proofs,
2027                                &sync_cycle_epoch,
2028                            )
2029                            .await;
2030                            // Admit hints into verification pipeline.
2031                            let outcome = admit_and_queue_hints(
2032                                &self_id,
2033                                peer,
2034                                &outcome.response.replica_hints,
2035                                &outcome.response.paid_hints,
2036                                &p2p,
2037                                &config,
2038                                &storage,
2039                                &paid_list,
2040                                &queues,
2041                            )
2042                            .await;
2043
2044                            // Track discovered keys for drain detection.
2045                            if !outcome.discovered.is_empty() {
2046                                bootstrap::track_discovered_keys(
2047                                    &bootstrap_state,
2048                                    &outcome.discovered,
2049                                )
2050                                .await;
2051                            }
2052
2053                            // Record / retire capacity rejections so the
2054                            // drain check correctly reflects whether each
2055                            // source still owes us re-hinted work after
2056                            // queue overflow.
2057                            if outcome.capacity_rejected_count > 0 {
2058                                bootstrap::note_capacity_rejected(&bootstrap_state, *peer).await;
2059                            } else {
2060                                bootstrap::clear_capacity_rejected(&bootstrap_state, peer).await;
2061                            }
2062                        }
2063                    }
2064                }
2065            }
2066
2067            // Check drain condition.
2068            {
2069                let q = queues.read().await;
2070                if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
2071                    complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
2072                }
2073            }
2074
2075            info!("Bootstrap sync completed");
2076        });
2077        self.task_handles.push(handle);
2078    }
2079}
2080
2081// ===========================================================================
2082// Free functions for background tasks
2083// ===========================================================================
2084
2085/// Which ceiling rejected an audit-responder admission attempt.
2086///
2087/// Stable, machine-readable so a production log-scrape can bucket drops by
2088/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
2089/// single opaque "capacity reached" line; this splits the two distinct causes
2090/// so the next such investigation can tell a global-pool exhaustion (the whole
2091/// node is saturated) from a per-peer cap hit (one source is self-throttling)
2092/// without re-instrumenting.
2093///
2094/// This branch runs a SINGLE shared audit-responder pool for all challenge
2095/// kinds (responsible / subtree / byte), so there is no separate slow/fast
2096/// pool to distinguish here — the `kind=` log field already separates the
2097/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
2098/// dedicated slow pool is later split out, add its variants here.
2099#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2100enum AuditResponderRejectReason {
2101    /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
2102    /// free; the per-peer cap was not the binding constraint.
2103    GlobalPoolFull,
2104    /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
2105    /// share, so the global permit was never attempted.
2106    PerPeerCapFull,
2107}
2108
2109impl AuditResponderRejectReason {
2110    /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
2111    /// frozen — production log tooling greps for them.
2112    fn as_str(self) -> &'static str {
2113        match self {
2114            Self::GlobalPoolFull => "global_pool_full",
2115            Self::PerPeerCapFull => "per_peer_cap_full",
2116        }
2117    }
2118}
2119
2120/// Why an audit-responder admission attempt failed, with the decision-time
2121/// capacity counters that let a drop be logged with full context.
2122///
2123/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
2124/// decision was made (the two ceilings are read under different locks, so they
2125/// are not a single atomic view), but they are exact enough to tell a saturated
2126/// node from a single self-throttling flooder.
2127#[derive(Debug, Clone, Copy)]
2128struct AuditResponderAdmissionFailure {
2129    reason: AuditResponderRejectReason,
2130    /// Global permits in use across the whole engine at decision time.
2131    global_inflight: usize,
2132    /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
2133    global_limit: usize,
2134    /// In-flight audit responders already held for `source` at decision time.
2135    peer_inflight: u32,
2136    /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
2137    peer_limit: u32,
2138}
2139
2140impl fmt::Display for AuditResponderAdmissionFailure {
2141    /// Renders the stable `reason=... global_inflight=... global_limit=...
2142    /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
2143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2144        write!(
2145            f,
2146            "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
2147            self.reason.as_str(),
2148            self.global_inflight,
2149            self.global_limit,
2150            self.peer_inflight,
2151            self.peer_limit,
2152        )
2153    }
2154}
2155
2156/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
2157/// on drop, decrements the PER-PEER in-flight count. Moving this into the
2158/// spawned task ties both bounds to the task's exact lifetime — no manual
2159/// decrement to forget on an early return or panic.
2160struct AuditResponderGuard {
2161    _permit: tokio::sync::OwnedSemaphorePermit,
2162    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
2163    peer: PeerId,
2164}
2165
2166impl Drop for AuditResponderGuard {
2167    fn drop(&mut self) {
2168        // Decrement (and prune to keep the map bounded) without blocking the
2169        // async runtime: a short lock on a tiny map.
2170        //
2171        // Fast path: if the (uncontended, tiny) lock is free, decrement inline
2172        // with no spawn. Otherwise defer to a task — but only if a runtime is
2173        // actually current, so `Drop` during shutdown (no runtime) can never
2174        // panic. A missed decrement at shutdown is harmless: the whole map is
2175        // being dropped with the engine.
2176        let peer = self.peer;
2177        if let Ok(mut map) = self.inflight.try_write() {
2178            if let Some(n) = map.get_mut(&peer) {
2179                *n = n.saturating_sub(1);
2180                if *n == 0 {
2181                    map.remove(&peer);
2182                }
2183            }
2184            return;
2185        }
2186        if let Ok(handle) = tokio::runtime::Handle::try_current() {
2187            let inflight = Arc::clone(&self.inflight);
2188            handle.spawn(async move {
2189                let mut map = inflight.write().await;
2190                if let Some(n) = map.get_mut(&peer) {
2191                    *n = n.saturating_sub(1);
2192                    if *n == 0 {
2193                        map.remove(&peer);
2194                    }
2195                }
2196            });
2197        }
2198    }
2199}
2200
2201/// Try to admit one audit-responder task for `source`: take a global permit AND
2202/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
2203/// its decision-time counters (caller drops the challenge, leaving the remote
2204/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
2205/// so one flooder can neither exhaust the global pool's effect on others nor
2206/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
2207/// log exactly WHY the drop happened rather than a single opaque "capacity
2208/// reached".
2209async fn admit_audit_responder(
2210    semaphore: &Arc<Semaphore>,
2211    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
2212    source: &PeerId,
2213) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
2214    let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
2215    let peer_limit = MAX_AUDIT_RESPONSES_PER_PEER;
2216    // `available_permits()` is a cheap atomic load; `global_limit - available`
2217    // is the best-effort in-flight count at decision time. Not synchronized with
2218    // the per-peer lock, so it is a snapshot, not a single atomic view.
2219    let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
2220
2221    // Per-peer cap first (cheap, and the fairness-critical bound), committed
2222    // under the write lock so concurrent challenges from the same peer can't
2223    // both slip past the cap.
2224    {
2225        let mut map = inflight.write().await;
2226        let entry = map.entry(*source).or_insert(0);
2227        if *entry >= peer_limit {
2228            let peer_inflight = *entry;
2229            drop(map); // release before the (unrelated) semaphore read
2230            return Err(AuditResponderAdmissionFailure {
2231                reason: AuditResponderRejectReason::PerPeerCapFull,
2232                global_inflight: global_inflight(semaphore),
2233                global_limit,
2234                peer_inflight,
2235                peer_limit,
2236            });
2237        }
2238        *entry += 1;
2239    }
2240    // Then the global ceiling. If it's exhausted, give back the per-peer slot we
2241    // just claimed so it isn't leaked.
2242    let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
2243        let peer_inflight = {
2244            let mut map = inflight.write().await;
2245            map.remove(source).map_or(0, |n| {
2246                // Report the per-peer occupancy AFTER releasing our rolled-back
2247                // slot: the share still held by this source's other in-flight
2248                // tasks (below the cap, since the per-peer check passed).
2249                let remaining = n.saturating_sub(1);
2250                if remaining > 0 {
2251                    map.insert(*source, remaining);
2252                }
2253                remaining
2254            })
2255        };
2256        return Err(AuditResponderAdmissionFailure {
2257            reason: AuditResponderRejectReason::GlobalPoolFull,
2258            global_inflight: global_inflight(semaphore),
2259            global_limit,
2260            peer_inflight,
2261            peer_limit,
2262        });
2263    };
2264    Ok(AuditResponderGuard {
2265        _permit: permit,
2266        inflight: Arc::clone(inflight),
2267        peer: *source,
2268    })
2269}
2270
2271/// Handle an incoming replication protocol message.
2272///
2273/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
2274/// request-response path and the response must be sent via `send_response`
2275/// so saorsa-core can route it back to the waiting `send_request` caller.
2276#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
2277async fn handle_replication_message(
2278    source: &PeerId,
2279    data: &[u8],
2280    p2p_node: &Arc<P2PNode>,
2281    storage: &Arc<LmdbStorage>,
2282    paid_list: &Arc<PaidList>,
2283    payment_verifier: &Arc<PaymentVerifier>,
2284    queues: &Arc<RwLock<ReplicationQueues>>,
2285    config: &ReplicationConfig,
2286    is_bootstrapping: &Arc<RwLock<bool>>,
2287    bootstrap_state: &Arc<RwLock<BootstrapState>>,
2288    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
2289    sync_cycle_epoch: &Arc<RwLock<u64>>,
2290    repair_proofs: &Arc<RwLock<RepairProofs>>,
2291    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
2292    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
2293    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
2294    my_commitment_state: &Arc<ResponderCommitmentState>,
2295    gossip_audit: &GossipAuditTrigger,
2296    audit_responder_semaphore: &Arc<Semaphore>,
2297    audit_responder_inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
2298    rr_message_id: Option<&str>,
2299) -> Result<()> {
2300    let msg = ReplicationMessage::decode(data)
2301        .map_err(|e| Error::Protocol(format!("Failed to decode replication message: {e}")))?;
2302
2303    match msg.body {
2304        ReplicationMessageBody::FreshReplicationOffer(ref offer) => {
2305            handle_fresh_offer(
2306                source,
2307                offer,
2308                storage,
2309                paid_list,
2310                payment_verifier,
2311                p2p_node,
2312                config,
2313                msg.request_id,
2314                rr_message_id,
2315            )
2316            .await
2317        }
2318        ReplicationMessageBody::PaidNotify(ref notify) => {
2319            handle_paid_notify(
2320                source,
2321                notify,
2322                paid_list,
2323                payment_verifier,
2324                p2p_node,
2325                config,
2326            )
2327            .await
2328        }
2329        ReplicationMessageBody::NeighborSyncRequest(ref request) => {
2330            let bootstrapping = *is_bootstrapping.read().await;
2331            // Phase-3 storage-bound audit: store the sender's
2332            // commitment for use as `expected_commitment_hash` in
2333            // future audits. Verify signature before storing so a peer
2334            // cannot inject a forged commitment for someone else.
2335            if let Some(target) = ingest_peer_commitment(
2336                source,
2337                request.commitment.as_ref(),
2338                p2p_node,
2339                last_commitment_by_peer,
2340                ever_capable_peers,
2341                sig_verify_attempts,
2342            )
2343            .await
2344            {
2345                maybe_trigger_gossip_audit(gossip_audit, source, target).await;
2346            }
2347            handle_neighbor_sync_request(
2348                source,
2349                request,
2350                p2p_node,
2351                storage,
2352                paid_list,
2353                queues,
2354                config,
2355                bootstrapping,
2356                bootstrap_state,
2357                sync_history,
2358                sync_cycle_epoch,
2359                repair_proofs,
2360                // Atomically snapshot + mark-gossiped: emitted in the sync
2361                // response, so we must stay answerable for it (ADR-0002).
2362                my_commitment_state
2363                    .current_for_gossip()
2364                    .map(|b| b.commitment().clone()),
2365                msg.request_id,
2366                rr_message_id,
2367            )
2368            .await
2369        }
2370        ReplicationMessageBody::VerificationRequest(ref request) => {
2371            handle_verification_request(
2372                source,
2373                request,
2374                storage,
2375                paid_list,
2376                p2p_node,
2377                msg.request_id,
2378                rr_message_id,
2379            )
2380            .await
2381        }
2382        ReplicationMessageBody::FetchRequest(ref request) => {
2383            handle_fetch_request(
2384                source,
2385                request,
2386                storage,
2387                p2p_node,
2388                msg.request_id,
2389                rr_message_id,
2390            )
2391            .await
2392        }
2393        ReplicationMessageBody::AuditChallenge(challenge) => {
2394            // Responsible-chunk audit (audit #2) responder: answer with per-key
2395            // possession digests. This same handler also answers the
2396            // prune-confirmation audit, which sends the same `AuditChallenge`
2397            // wire message.
2398            //
2399            // Answering digests the stored bytes of every challenged key, so —
2400            // like the subtree/byte audits below — run it on a detached task off
2401            // this serial message loop. Handling it inline lets one challenge
2402            // block all other replication traffic until its digests complete
2403            // (head-of-line blocking). The same flood-fair admission applies: a
2404            // global ceiling AND a per-peer cap, dropping the challenge if either
2405            // is hit. Responsible/prune audit timeouts are penalised by the
2406            // caller, so the caps must remain high enough for honest audit load;
2407            // the per-peer share still prevents one flooder from starving others.
2408            let guard = match admit_audit_responder(
2409                audit_responder_semaphore,
2410                audit_responder_inflight,
2411                source,
2412            )
2413            .await
2414            {
2415                Ok(guard) => guard,
2416                Err(failure) => {
2417                    warn!(
2418                        "Audit challenge reply not sent: kind=responsible response=dropped \
2419                         source={source} {failure}"
2420                    );
2421                    return Ok(());
2422                }
2423            };
2424            let bootstrapping = *is_bootstrapping.read().await;
2425            let storage = Arc::clone(storage);
2426            let p2p_node = Arc::clone(p2p_node);
2427            let source = *source;
2428            let request_id = msg.request_id;
2429            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
2430            tokio::spawn(async move {
2431                let _guard = guard; // global permit + per-peer slot, held until done
2432                if let Err(e) = handle_audit_challenge_msg(
2433                    &source,
2434                    &challenge,
2435                    &storage,
2436                    &p2p_node,
2437                    bootstrapping,
2438                    request_id,
2439                    rr_message_id.as_deref(),
2440                )
2441                .await
2442                {
2443                    debug!("Audit challenge from {source} error: {e}");
2444                }
2445            });
2446            Ok(())
2447        }
2448        ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
2449            // Gossip-triggered storage-bound subtree audit (ADR-0002). The
2450            // responder rebuilds the WHOLE nonce-selected subtree, reading every
2451            // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
2452            // detached task so this serial message loop is never blocked on disk
2453            // I/O — otherwise one audit stalls all replication traffic (§5).
2454            //
2455            // A bounded, flood-fair admission restores backpressure (codex#1 +
2456            // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
2457            // we drop this challenge. Subtree auditors grace timeout
2458            // non-responses, so capacity drops throttle flooders without turning
2459            // into trust penalties (and one source cannot starve other peers,
2460            // since its share is capped per-peer).
2461            info!(
2462                "Audit challenge received: kind=subtree source={source} request_response={}",
2463                rr_message_id.is_some(),
2464            );
2465            let guard = match admit_audit_responder(
2466                audit_responder_semaphore,
2467                audit_responder_inflight,
2468                source,
2469            )
2470            .await
2471            {
2472                Ok(guard) => guard,
2473                Err(failure) => {
2474                    warn!(
2475                        "Audit challenge reply not sent: kind=subtree response=dropped \
2476                         source={source} {failure}"
2477                    );
2478                    return Ok(());
2479                }
2480            };
2481            let bootstrapping = *is_bootstrapping.read().await;
2482            let storage = Arc::clone(storage);
2483            let p2p_node = Arc::clone(p2p_node);
2484            let my_commitment_state = Arc::clone(my_commitment_state);
2485            let source = *source;
2486            let request_id = msg.request_id;
2487            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
2488            tokio::spawn(async move {
2489                let _guard = guard; // global permit + per-peer slot, held until done
2490                let response = storage_commitment_audit::handle_subtree_challenge(
2491                    &challenge,
2492                    &storage,
2493                    p2p_node.peer_id(),
2494                    bootstrapping,
2495                    Some(&my_commitment_state),
2496                )
2497                .await;
2498                let response_kind = subtree_audit_response_kind(&response);
2499                let sent = send_replication_response_checked(
2500                    &source,
2501                    &p2p_node,
2502                    request_id,
2503                    ReplicationMessageBody::SubtreeAuditResponse(response),
2504                    rr_message_id.as_deref(),
2505                )
2506                .await;
2507                if sent {
2508                    info!(
2509                        "Audit challenge reply sent: kind=subtree response={response_kind} \
2510                         source={source} request_response={}",
2511                        rr_message_id.is_some(),
2512                    );
2513                } else {
2514                    warn!(
2515                        "Audit challenge reply not sent: kind=subtree response={response_kind} \
2516                         source={source} request_response={}",
2517                        rr_message_id.is_some(),
2518                    );
2519                }
2520            });
2521            Ok(())
2522        }
2523        ReplicationMessageBody::SubtreeByteChallenge(challenge) => {
2524            // Round 2 of the storage audit (ADR-0002): serve the original bytes
2525            // for the auditor's spot-check keys, or signal `Absent` for a
2526            // committed key we can no longer produce. Reads chunk bytes from
2527            // disk, so likewise spawned off the serial loop (§5) under the same
2528            // flood-fair admission (codex#1 + codex-r2 A).
2529            info!(
2530                "Audit challenge received: kind=byte source={source} request_response={}",
2531                rr_message_id.is_some(),
2532            );
2533            let guard = match admit_audit_responder(
2534                audit_responder_semaphore,
2535                audit_responder_inflight,
2536                source,
2537            )
2538            .await
2539            {
2540                Ok(guard) => guard,
2541                Err(failure) => {
2542                    warn!(
2543                        "Audit challenge reply not sent: kind=byte response=dropped \
2544                         source={source} {failure}"
2545                    );
2546                    return Ok(());
2547                }
2548            };
2549            let bootstrapping = *is_bootstrapping.read().await;
2550            let storage = Arc::clone(storage);
2551            let p2p_node = Arc::clone(p2p_node);
2552            let my_commitment_state = Arc::clone(my_commitment_state);
2553            let source = *source;
2554            let request_id = msg.request_id;
2555            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
2556            tokio::spawn(async move {
2557                let _guard = guard; // global permit + per-peer slot, held until done
2558                let response = storage_commitment_audit::handle_subtree_byte_challenge(
2559                    &challenge,
2560                    &storage,
2561                    p2p_node.peer_id(),
2562                    bootstrapping,
2563                    Some(&my_commitment_state),
2564                )
2565                .await;
2566                let response_kind = subtree_byte_response_kind(&response);
2567                let sent = send_replication_response_checked(
2568                    &source,
2569                    &p2p_node,
2570                    request_id,
2571                    ReplicationMessageBody::SubtreeByteResponse(response),
2572                    rr_message_id.as_deref(),
2573                )
2574                .await;
2575                if sent {
2576                    info!(
2577                        "Audit challenge reply sent: kind=byte response={response_kind} \
2578                         source={source} request_response={}",
2579                        rr_message_id.is_some(),
2580                    );
2581                } else {
2582                    warn!(
2583                        "Audit challenge reply not sent: kind=byte response={response_kind} \
2584                         source={source} request_response={}",
2585                        rr_message_id.is_some(),
2586                    );
2587                }
2588            });
2589            Ok(())
2590        }
2591        ReplicationMessageBody::GetCommitmentByPin(ref request) => {
2592            // ADR-0004: answer a commitment-by-pin fetch from the retained set
2593            // only. `lookup_by_hash` is an allocation-light read over the
2594            // bounded slot set; it returns the live current commitment or any
2595            // still-answerable recently-gossiped/quoted one. A miss is reported
2596            // as `NotRetained` (graced, never confirmed) rather than an error,
2597            // so an aged-out pin can never brand an honest node.
2598            //
2599            // Reuse the audit-responder admission guard (global ceiling + per-peer
2600            // cap) so a flood of fetches cannot drive unbounded commitment
2601            // clone/encode/send work; over-limit is dropped, which the fetching
2602            // peer graces exactly like a missed audit response.
2603            let _guard = match admit_audit_responder(
2604                audit_responder_semaphore,
2605                audit_responder_inflight,
2606                source,
2607            )
2608            .await
2609            {
2610                Ok(guard) => guard,
2611                Err(failure) => {
2612                    debug!("GetCommitmentByPin from {source} dropped: {failure}");
2613                    return Ok(());
2614                }
2615            };
2616            let response = my_commitment_state.lookup_by_hash(&request.pin).map_or(
2617                protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
2618                |built| protocol::GetCommitmentByPinResponse::Found {
2619                    commitment: built.commitment().clone(),
2620                },
2621            );
2622            send_replication_response(
2623                source,
2624                p2p_node,
2625                msg.request_id,
2626                ReplicationMessageBody::GetCommitmentByPinResponse(response),
2627                rr_message_id,
2628            )
2629            .await;
2630            Ok(())
2631        }
2632        // Response messages are handled by their respective request initiators.
2633        ReplicationMessageBody::FreshReplicationResponse(_)
2634        | ReplicationMessageBody::NeighborSyncResponse(_)
2635        | ReplicationMessageBody::VerificationResponse(_)
2636        | ReplicationMessageBody::FetchResponse(_)
2637        | ReplicationMessageBody::AuditResponse(_)
2638        | ReplicationMessageBody::SubtreeAuditResponse(_)
2639        | ReplicationMessageBody::SubtreeByteResponse(_)
2640        | ReplicationMessageBody::GetCommitmentByPinResponse(_) => Ok(()),
2641    }
2642}
2643
2644// ---------------------------------------------------------------------------
2645// Per-message-type handlers
2646// ---------------------------------------------------------------------------
2647
2648#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
2649async fn handle_fresh_offer(
2650    source: &PeerId,
2651    offer: &protocol::FreshReplicationOffer,
2652    storage: &Arc<LmdbStorage>,
2653    paid_list: &Arc<PaidList>,
2654    payment_verifier: &Arc<PaymentVerifier>,
2655    p2p_node: &Arc<P2PNode>,
2656    config: &ReplicationConfig,
2657    request_id: u64,
2658    rr_message_id: Option<&str>,
2659) -> Result<()> {
2660    let self_id = *p2p_node.peer_id();
2661
2662    // Rule 5: reject if PoP is missing.
2663    if offer.proof_of_payment.is_empty() {
2664        send_replication_response(
2665            source,
2666            p2p_node,
2667            request_id,
2668            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
2669                key: offer.key,
2670                reason: "Missing proof of payment".to_string(),
2671            }),
2672            rr_message_id,
2673        )
2674        .await;
2675        return Ok(());
2676    }
2677
2678    // Enforce chunk size invariant: the normal PUT path rejects data larger
2679    // than MAX_CHUNK_SIZE; the replication receive path must do the same to
2680    // prevent peers from pushing oversized records through replication.
2681    if offer.data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
2682        warn!(
2683            "Rejecting fresh offer for key {}: data size {} exceeds MAX_CHUNK_SIZE {}",
2684            hex::encode(offer.key),
2685            offer.data.len(),
2686            crate::ant_protocol::MAX_CHUNK_SIZE,
2687        );
2688        p2p_node
2689            .report_trust_event(
2690                source,
2691                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
2692            )
2693            .await;
2694        send_replication_response(
2695            source,
2696            p2p_node,
2697            request_id,
2698            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
2699                key: offer.key,
2700                reason: format!(
2701                    "Data size {} exceeds maximum chunk size {}",
2702                    offer.data.len(),
2703                    crate::ant_protocol::MAX_CHUNK_SIZE,
2704                ),
2705            }),
2706            rr_message_id,
2707        )
2708        .await;
2709        return Ok(());
2710    }
2711
2712    // Mirror the normal PUT path: the advertised key must be the content
2713    // address of the supplied bytes before any expensive payment verification.
2714    let computed_key = crate::client::compute_address(&offer.data);
2715    if computed_key != offer.key {
2716        warn!(
2717            "Rejecting fresh offer for key {}: content address mismatch, computed {}",
2718            hex::encode(offer.key),
2719            hex::encode(computed_key),
2720        );
2721        p2p_node
2722            .report_trust_event(
2723                source,
2724                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
2725            )
2726            .await;
2727        send_replication_response(
2728            source,
2729            p2p_node,
2730            request_id,
2731            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
2732                key: offer.key,
2733                reason: format!(
2734                    "Content address mismatch: expected {}, computed {}",
2735                    hex::encode(offer.key),
2736                    hex::encode(computed_key),
2737                ),
2738            }),
2739            rr_message_id,
2740        )
2741        .await;
2742        return Ok(());
2743    }
2744
2745    // Rule 7: check storage admission. Fresh chunk receivers accept across the
2746    // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
2747    // the same width client PUTs use), not just the close group plus a small
2748    // margin (ADR-0003). During full-node shunning a healthy replica's routing
2749    // table may still list closer full nodes it hasn't evicted yet, ranking it
2750    // outside the narrow window in its own view; the wider accept window absorbs
2751    // that transient skew so the chunk still lands. Retention (pruning) stays at
2752    // `storage_admission_width`, so steady-state replication is unchanged.
2753    if !admission::is_responsible(
2754        &self_id,
2755        &offer.key,
2756        p2p_node,
2757        config.paid_list_close_group_size,
2758    )
2759    .await
2760    {
2761        send_replication_response(
2762            source,
2763            p2p_node,
2764            request_id,
2765            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
2766                key: offer.key,
2767                reason: "Not in storage-admission range for this key".to_string(),
2768            }),
2769            rr_message_id,
2770        )
2771        .await;
2772        return Ok(());
2773    }
2774
2775    // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
2776    // never store this record, so reject it before the expensive payment
2777    // verification (EVM on-chain query / merkle pool work) rather than verifying
2778    // and only then failing at `storage.put` below. Reuses the cached capacity
2779    // check (passing results only, so freed space is detected promptly), and the
2780    // store path keeps its own check as defence-in-depth.
2781    if let Err(e) = storage.check_capacity() {
2782        info!(
2783            target: "ant_node::storage::disk_precheck",
2784            key = %hex::encode(offer.key),
2785            "Rejecting fresh replication offer before payment verification: {e}"
2786        );
2787        send_replication_response(
2788            source,
2789            p2p_node,
2790            request_id,
2791            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
2792                key: offer.key,
2793                reason: e.to_string(),
2794            }),
2795            rr_message_id,
2796        )
2797        .await;
2798        return Ok(());
2799    }
2800
2801    // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
2802    // part of the immediate write fan-out: this receiver is about to store the
2803    // record as if the client had PUT it here directly. Storage admission
2804    // was checked above before proof work. ClientPut verification applies
2805    // store-strength cache semantics, paid-quote issuer K-closeness checks
2806    // for single-node proofs, and merkle candidate closeness for merkle
2807    // proofs.
2808    match payment_verifier
2809        .verify_payment(
2810            &offer.key,
2811            Some(&offer.proof_of_payment),
2812            fresh_offer_payment_context(),
2813        )
2814        .await
2815    {
2816        Ok(status) if status.can_store() => {
2817            debug!(
2818                "PoP validated for fresh offer key {}",
2819                hex::encode(offer.key)
2820            );
2821        }
2822        Ok(_) => {
2823            send_replication_response(
2824                source,
2825                p2p_node,
2826                request_id,
2827                ReplicationMessageBody::FreshReplicationResponse(
2828                    FreshReplicationResponse::Rejected {
2829                        key: offer.key,
2830                        reason: "Payment verification failed: payment required".to_string(),
2831                    },
2832                ),
2833                rr_message_id,
2834            )
2835            .await;
2836            return Ok(());
2837        }
2838        Err(e) => {
2839            warn!(
2840                "PoP verification error for key {}: {e}",
2841                hex::encode(offer.key)
2842            );
2843            send_replication_response(
2844                source,
2845                p2p_node,
2846                request_id,
2847                ReplicationMessageBody::FreshReplicationResponse(
2848                    FreshReplicationResponse::Rejected {
2849                        key: offer.key,
2850                        reason: format!("Payment verification error: {e}"),
2851                    },
2852                ),
2853                rr_message_id,
2854            )
2855            .await;
2856            return Ok(());
2857        }
2858    }
2859
2860    // Rule 6: add to PaidForList.
2861    if let Err(e) = paid_list.insert(&offer.key).await {
2862        warn!("Failed to add key to PaidForList: {e}");
2863    }
2864
2865    // Store the record.
2866    match storage.put(&offer.key, &offer.data).await {
2867        Ok(_) => {
2868            send_replication_response(
2869                source,
2870                p2p_node,
2871                request_id,
2872                ReplicationMessageBody::FreshReplicationResponse(
2873                    FreshReplicationResponse::Accepted { key: offer.key },
2874                ),
2875                rr_message_id,
2876            )
2877            .await;
2878        }
2879        Err(e) => {
2880            send_replication_response(
2881                source,
2882                p2p_node,
2883                request_id,
2884                ReplicationMessageBody::FreshReplicationResponse(
2885                    FreshReplicationResponse::Rejected {
2886                        key: offer.key,
2887                        reason: e.to_string(),
2888                    },
2889                ),
2890                rr_message_id,
2891            )
2892            .await;
2893        }
2894    }
2895
2896    Ok(())
2897}
2898
2899async fn handle_paid_notify(
2900    _source: &PeerId,
2901    notify: &protocol::PaidNotify,
2902    paid_list: &Arc<PaidList>,
2903    payment_verifier: &Arc<PaymentVerifier>,
2904    p2p_node: &Arc<P2PNode>,
2905    config: &ReplicationConfig,
2906) -> Result<()> {
2907    let self_id = *p2p_node.peer_id();
2908
2909    // Rule 3: validate PoP presence before adding.
2910    if notify.proof_of_payment.is_empty() {
2911        return Ok(());
2912    }
2913
2914    // Check if we're in PaidCloseGroup for this key.
2915    if !admission::is_in_paid_close_group(
2916        &self_id,
2917        &notify.key,
2918        p2p_node,
2919        config.paid_list_close_group_size,
2920    )
2921    .await
2922    {
2923        return Ok(());
2924    }
2925
2926    // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
2927    // paid-list metadata, so local paid-list close-group membership was checked
2928    // above before proof work. The verifier then runs the same payment proof
2929    // checks as ClientPut while writing a paid-list-strength cache entry.
2930    match payment_verifier
2931        .verify_payment(
2932            &notify.key,
2933            Some(&notify.proof_of_payment),
2934            paid_notify_payment_context(),
2935        )
2936        .await
2937    {
2938        Ok(status) if status.can_store() => {
2939            debug!(
2940                "PoP validated for paid notify key {}",
2941                hex::encode(notify.key)
2942            );
2943        }
2944        Ok(_) => {
2945            warn!(
2946                "Paid notify rejected: payment required for key {}",
2947                hex::encode(notify.key)
2948            );
2949            return Ok(());
2950        }
2951        Err(e) => {
2952            warn!(
2953                "PoP verification error for paid notify key {}: {e}",
2954                hex::encode(notify.key)
2955            );
2956            return Ok(());
2957        }
2958    }
2959
2960    if let Err(e) = paid_list.insert(&notify.key).await {
2961        warn!("Failed to add paid notify key to PaidForList: {e}");
2962    }
2963
2964    Ok(())
2965}
2966
2967#[allow(clippy::too_many_arguments)]
2968async fn handle_neighbor_sync_request(
2969    source: &PeerId,
2970    request: &protocol::NeighborSyncRequest,
2971    p2p_node: &Arc<P2PNode>,
2972    storage: &Arc<LmdbStorage>,
2973    paid_list: &Arc<PaidList>,
2974    queues: &Arc<RwLock<ReplicationQueues>>,
2975    config: &ReplicationConfig,
2976    is_bootstrapping: bool,
2977    bootstrap_state: &Arc<RwLock<BootstrapState>>,
2978    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
2979    sync_cycle_epoch: &Arc<RwLock<u64>>,
2980    repair_proofs: &Arc<RwLock<RepairProofs>>,
2981    my_commitment: Option<StorageCommitment>,
2982    request_id: u64,
2983    rr_message_id: Option<&str>,
2984) -> Result<()> {
2985    let self_id = *p2p_node.peer_id();
2986
2987    // No per-request hint count limit: the wire message size limit
2988    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
2989    // challenges, sync hints don't drive expensive computation — they just
2990    // enter the verification queue. A per-request limit here would break
2991    // bootstrap replication for newly-joined nodes with 0 stored chunks.
2992
2993    // Build response (outbound hints).
2994    let (response, sent_replica_hints, sender_in_rt) =
2995        neighbor_sync::handle_sync_request_with_proofs(
2996            source,
2997            request,
2998            p2p_node,
2999            storage,
3000            paid_list,
3001            config,
3002            is_bootstrapping,
3003            my_commitment.clone(),
3004        )
3005        .await;
3006
3007    // Send response.
3008    let response_sent = send_replication_response_checked(
3009        source,
3010        p2p_node,
3011        request_id,
3012        ReplicationMessageBody::NeighborSyncResponse(response),
3013        rr_message_id,
3014    )
3015    .await;
3016
3017    // Process inbound hints only if sender is in LocalRT (Rule 4-6).
3018    if !sender_in_rt {
3019        return Ok(());
3020    }
3021
3022    // Update sync history for this peer before recording repair proofs so a
3023    // same-tick audit cannot combine a fresh key proof with stale peer maturity.
3024    {
3025        let mut history = sync_history.write().await;
3026        let record = history.entry(*source).or_insert(PeerSyncRecord {
3027            last_sync: None,
3028            cycles_since_sync: 0,
3029        });
3030        record.last_sync = Some(Instant::now());
3031        record.cycles_since_sync = 0;
3032    }
3033
3034    if response_sent && !request.bootstrapping {
3035        record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
3036            .await;
3037    }
3038
3039    // Admit inbound hints and queue for verification.
3040    let outcome = admit_and_queue_hints(
3041        &self_id,
3042        source,
3043        &request.replica_hints,
3044        &request.paid_hints,
3045        p2p_node,
3046        config,
3047        storage,
3048        paid_list,
3049        queues,
3050    )
3051    .await;
3052
3053    // Track discovered keys for bootstrap drain detection so that hints
3054    // admitted via inbound sync requests are not missed. Capacity-rejected
3055    // hints keep this source on the "not yet drained" list until its next
3056    // sync re-admits them; a clean cycle clears the source.
3057    if is_bootstrapping {
3058        if !outcome.discovered.is_empty() {
3059            bootstrap::track_discovered_keys(bootstrap_state, &outcome.discovered).await;
3060        }
3061        if outcome.capacity_rejected_count > 0 {
3062            bootstrap::note_capacity_rejected(bootstrap_state, *source).await;
3063        } else {
3064            bootstrap::clear_capacity_rejected(bootstrap_state, source).await;
3065        }
3066    }
3067
3068    Ok(())
3069}
3070
3071async fn handle_verification_request(
3072    source: &PeerId,
3073    request: &protocol::VerificationRequest,
3074    storage: &Arc<LmdbStorage>,
3075    paid_list: &Arc<PaidList>,
3076    p2p_node: &Arc<P2PNode>,
3077    request_id: u64,
3078    rr_message_id: Option<&str>,
3079) -> Result<()> {
3080    // No per-request key count limit: the wire message size limit
3081    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Verification
3082    // does cheap storage lookups per key, not expensive computation like
3083    // audit digest generation.
3084
3085    #[allow(clippy::cast_possible_truncation)]
3086    let keys_len = request.keys.len() as u32;
3087    let paid_check_set: HashSet<u32> = request
3088        .paid_list_check_indices
3089        .iter()
3090        .copied()
3091        .filter(|&idx| {
3092            if idx >= keys_len {
3093                warn!(
3094                    "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
3095                    request.keys.len(),
3096                );
3097                false
3098            } else {
3099                true
3100            }
3101        })
3102        .collect();
3103
3104    let mut results = Vec::with_capacity(request.keys.len());
3105    for (i, key) in request.keys.iter().enumerate() {
3106        let present = storage.exists(key).unwrap_or(false);
3107        let paid = if paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX)) {
3108            Some(paid_list.contains(key).unwrap_or(false))
3109        } else {
3110            None
3111        };
3112        results.push(protocol::KeyVerificationResult {
3113            key: *key,
3114            present,
3115            paid,
3116        });
3117    }
3118
3119    send_replication_response(
3120        source,
3121        p2p_node,
3122        request_id,
3123        ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
3124        rr_message_id,
3125    )
3126    .await;
3127
3128    Ok(())
3129}
3130
3131async fn handle_fetch_request(
3132    source: &PeerId,
3133    request: &protocol::FetchRequest,
3134    storage: &Arc<LmdbStorage>,
3135    p2p_node: &Arc<P2PNode>,
3136    request_id: u64,
3137    rr_message_id: Option<&str>,
3138) -> Result<()> {
3139    let response = match storage.get(&request.key).await {
3140        Ok(Some(data)) => protocol::FetchResponse::Success {
3141            key: request.key,
3142            data,
3143        },
3144        Ok(None) => protocol::FetchResponse::NotFound { key: request.key },
3145        Err(e) => protocol::FetchResponse::Error {
3146            key: request.key,
3147            reason: format!("{e}"),
3148        },
3149    };
3150
3151    send_replication_response(
3152        source,
3153        p2p_node,
3154        request_id,
3155        ReplicationMessageBody::FetchResponse(response),
3156        rr_message_id,
3157    )
3158    .await;
3159
3160    Ok(())
3161}
3162
3163/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
3164/// the prune-confirmation audit, which reuses the same wire message): reply with
3165/// per-key possession digests.
3166async fn handle_audit_challenge_msg(
3167    source: &PeerId,
3168    challenge: &protocol::AuditChallenge,
3169    storage: &Arc<LmdbStorage>,
3170    p2p_node: &Arc<P2PNode>,
3171    is_bootstrapping: bool,
3172    request_id: u64,
3173    rr_message_id: Option<&str>,
3174) -> Result<()> {
3175    #[allow(clippy::cast_possible_truncation)]
3176    let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
3177    info!(
3178        "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
3179        challenge.keys.len(),
3180        is_bootstrapping,
3181        rr_message_id.is_some(),
3182    );
3183
3184    let response = audit::handle_audit_challenge(
3185        challenge,
3186        storage,
3187        p2p_node.peer_id(),
3188        is_bootstrapping,
3189        stored_chunks,
3190    )
3191    .await;
3192    let response_kind = audit_response_kind(&response);
3193
3194    let sent = send_replication_response_checked(
3195        source,
3196        p2p_node,
3197        request_id,
3198        ReplicationMessageBody::AuditResponse(response),
3199        rr_message_id,
3200    )
3201    .await;
3202    if sent {
3203        info!(
3204            "Audit challenge reply sent: kind=responsible response={} keys={} request_response={}",
3205            response_kind,
3206            challenge.keys.len(),
3207            rr_message_id.is_some(),
3208        );
3209    } else {
3210        warn!(
3211            "Audit challenge reply not sent: kind=responsible response={} keys={} request_response={}",
3212            response_kind,
3213            challenge.keys.len(),
3214            rr_message_id.is_some(),
3215        );
3216    }
3217
3218    Ok(())
3219}
3220
3221fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
3222    match response {
3223        protocol::AuditResponse::Digests { .. } => "digests",
3224        protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
3225        protocol::AuditResponse::Rejected { .. } => "rejected",
3226    }
3227}
3228
3229fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
3230    match response {
3231        protocol::SubtreeAuditResponse::Proof { .. } => "proof",
3232        protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
3233        protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
3234    }
3235}
3236
3237fn subtree_byte_response_kind(response: &protocol::SubtreeByteResponse) -> &'static str {
3238    match response {
3239        protocol::SubtreeByteResponse::Items { .. } => "items",
3240        protocol::SubtreeByteResponse::Bootstrapping { .. } => "bootstrapping",
3241        protocol::SubtreeByteResponse::Rejected { .. } => "rejected",
3242    }
3243}
3244
3245// ---------------------------------------------------------------------------
3246// Message sending helper
3247// ---------------------------------------------------------------------------
3248
3249/// Send a replication response message as a best-effort reply.
3250///
3251/// Encode and send failures are logged by the checked helper. Most response
3252/// paths do not need to branch on send success, so this wrapper keeps those
3253/// call sites explicit about their best-effort behavior.
3254async fn send_replication_response(
3255    peer: &PeerId,
3256    p2p_node: &Arc<P2PNode>,
3257    request_id: u64,
3258    body: ReplicationMessageBody,
3259    rr_message_id: Option<&str>,
3260) {
3261    let _ =
3262        send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id).await;
3263}
3264
3265/// Send a replication response message and report whether it was accepted.
3266///
3267/// Returns `true` after the message is encoded and accepted by the P2P send
3268/// path. Returns `false` after logging an encode or send failure. Repair-proof
3269/// recording uses this to avoid trusting hints that were not actually sent.
3270///
3271/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
3272/// request-response path so saorsa-core can route it back to the caller's
3273/// `send_request` future. Otherwise it is sent as a plain message.
3274async fn send_replication_response_checked(
3275    peer: &PeerId,
3276    p2p_node: &Arc<P2PNode>,
3277    request_id: u64,
3278    body: ReplicationMessageBody,
3279    rr_message_id: Option<&str>,
3280) -> bool {
3281    let msg = ReplicationMessage { request_id, body };
3282    let encoded = match msg.encode() {
3283        Ok(data) => data,
3284        Err(e) => {
3285            warn!("Failed to encode replication response: {e}");
3286            return false;
3287        }
3288    };
3289    let result = if let Some(msg_id) = rr_message_id {
3290        p2p_node
3291            .send_response(peer, REPLICATION_PROTOCOL_ID, msg_id, encoded)
3292            .await
3293    } else {
3294        p2p_node
3295            .send_message(peer, REPLICATION_PROTOCOL_ID, encoded, &[])
3296            .await
3297    };
3298    if let Err(e) = result {
3299        debug!("Failed to send replication response to {peer}: {e}");
3300        return false;
3301    }
3302    true
3303}
3304
3305async fn record_sent_replica_hints(
3306    peer: &PeerId,
3307    hints: &[neighbor_sync::SentReplicaHint],
3308    repair_proofs: &Arc<RwLock<RepairProofs>>,
3309    sync_cycle_epoch: &Arc<RwLock<u64>>,
3310) {
3311    if hints.is_empty() {
3312        return;
3313    }
3314
3315    let hinted_at_epoch = *sync_cycle_epoch.read().await;
3316    let mut proofs = repair_proofs.write().await;
3317    for hint in hints {
3318        if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
3319            debug!(
3320                "Recorded repair hint proof for peer {peer} and key {}",
3321                hex::encode(hint.key)
3322            );
3323        }
3324    }
3325}
3326
3327// ---------------------------------------------------------------------------
3328// Neighbor sync round
3329// ---------------------------------------------------------------------------
3330
3331/// Run one neighbor sync round.
3332#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
3333async fn run_neighbor_sync_round(
3334    p2p_node: &Arc<P2PNode>,
3335    storage: &Arc<LmdbStorage>,
3336    paid_list: &Arc<PaidList>,
3337    queues: &Arc<RwLock<ReplicationQueues>>,
3338    config: &ReplicationConfig,
3339    sync_state: &Arc<RwLock<NeighborSyncState>>,
3340    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
3341    sync_cycle_epoch: &Arc<RwLock<u64>>,
3342    repair_proofs: &Arc<RwLock<RepairProofs>>,
3343    is_bootstrapping: &Arc<RwLock<bool>>,
3344    bootstrap_state: &Arc<RwLock<BootstrapState>>,
3345    commitment_state: &Arc<ResponderCommitmentState>,
3346    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
3347    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
3348    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
3349    gossip_audit: &GossipAuditTrigger,
3350) {
3351    let self_id = *p2p_node.peer_id();
3352    let bootstrapping = *is_bootstrapping.read().await;
3353
3354    // Check if cycle is complete; start new one if needed.
3355    // We check under a read lock, then release it before the expensive
3356    // prune pass and DHT snapshot so other tasks are not starved.
3357    let cycle_complete = sync_state.read().await.is_cycle_complete();
3358    if cycle_complete {
3359        // A completed local neighbor-sync cycle advances the epoch component
3360        // of repair-proof maturity. The per-key wall-clock minimum age is
3361        // checked when audits are selected.
3362        {
3363            let mut history = sync_history.write().await;
3364            for record in history.values_mut() {
3365                record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
3366            }
3367        }
3368        {
3369            let mut epoch = sync_cycle_epoch.write().await;
3370            *epoch = epoch.saturating_add(1);
3371        }
3372
3373        // Post-cycle pruning (Section 11) — runs without holding sync_state.
3374        // Prune candidacy is unconditional once the hysteresis elapses;
3375        // bootstrap state only defers the remote prune-confirmation audits
3376        // until bootstrap has drained.
3377        let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
3378        pruning::run_prune_pass_with_context(pruning::PrunePassContext {
3379            self_id: &self_id,
3380            storage,
3381            paid_list,
3382            p2p_node,
3383            config,
3384            sync_state,
3385            repair_proofs,
3386            allow_remote_prune_audits,
3387            commitment_state: Some(commitment_state),
3388        })
3389        .await;
3390
3391        // Take fresh close-neighbor snapshot (DHT query, no lock held).
3392        let neighbors =
3393            neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
3394                .await;
3395
3396        // Now re-acquire write lock and re-check before swapping cycle.
3397        let mut state = sync_state.write().await;
3398        if state.is_cycle_complete() {
3399            // Preserve cooldown and bootstrap-claim tracking across cycles.
3400            // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
3401            // would reset the abuse detection timer every cycle.
3402            let old_sync_times = std::mem::take(&mut state.last_sync_times);
3403            let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
3404            let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
3405            let old_prune_cursor = state.prune_cursor;
3406            *state = NeighborSyncState::new_cycle(neighbors);
3407            state.last_sync_times = old_sync_times;
3408            state.bootstrap_claims = old_bootstrap_claims;
3409            state.bootstrap_claim_history = old_bootstrap_claim_history;
3410            state.prune_cursor = old_prune_cursor;
3411        }
3412    }
3413
3414    // Select batch of peers.
3415    let batch = {
3416        let mut state = sync_state.write().await;
3417        neighbor_sync::select_sync_batch(
3418            &mut state,
3419            config.neighbor_sync_peer_count,
3420            config.neighbor_sync_cooldown,
3421        )
3422    };
3423
3424    if batch.is_empty() {
3425        return;
3426    }
3427
3428    debug!("Neighbor sync: syncing with {} peers", batch.len());
3429
3430    // Snapshot our current commitment once per round so all peers in
3431    // this batch see the same thing (gossip is the responder's attestation;
3432    // same value across the batch is fine and reduces RwLock churn). Atomically
3433    // snapshot + mark-gossiped so we stay answerable for exactly what we emit
3434    // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
3435    let my_commitment = commitment_state
3436        .current_for_gossip()
3437        .map(|b| b.commitment().clone());
3438
3439    let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
3440        &batch,
3441        storage,
3442        paid_list,
3443        p2p_node,
3444        config.close_group_size,
3445        config.paid_list_close_group_size,
3446    )
3447    .await;
3448
3449    // Sync with each peer in the batch.
3450    for peer in &batch {
3451        let hints = hints_by_peer.remove(peer).unwrap_or_default();
3452        let outcome = neighbor_sync::sync_with_peer_with_hints(
3453            peer,
3454            p2p_node,
3455            config,
3456            bootstrapping,
3457            hints,
3458            my_commitment.clone(),
3459        )
3460        .await;
3461
3462        if let Some(outcome) = outcome {
3463            handle_sync_response(
3464                &self_id,
3465                peer,
3466                &outcome.response,
3467                &outcome.sent_replica_hints,
3468                p2p_node,
3469                config,
3470                bootstrapping,
3471                bootstrap_state,
3472                storage,
3473                paid_list,
3474                queues,
3475                sync_state,
3476                sync_history,
3477                sync_cycle_epoch,
3478                repair_proofs,
3479                last_commitment_by_peer,
3480                ever_capable_peers,
3481                sig_verify_attempts,
3482                gossip_audit,
3483            )
3484            .await;
3485        } else {
3486            // Sync failed -- remove peer and try to fill slot.
3487            let replacement = {
3488                let mut state = sync_state.write().await;
3489                neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
3490            };
3491
3492            // Attempt sync with the replacement peer (if one was found).
3493            if let Some(replacement_peer) = replacement {
3494                let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
3495                    std::slice::from_ref(&replacement_peer),
3496                    storage,
3497                    paid_list,
3498                    p2p_node,
3499                    config.close_group_size,
3500                    config.paid_list_close_group_size,
3501                )
3502                .await;
3503                let hints = replacement_hints
3504                    .remove(&replacement_peer)
3505                    .unwrap_or_default();
3506                let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
3507                    &replacement_peer,
3508                    p2p_node,
3509                    config,
3510                    bootstrapping,
3511                    hints,
3512                    my_commitment.clone(),
3513                )
3514                .await;
3515
3516                if let Some(outcome) = replacement_outcome {
3517                    handle_sync_response(
3518                        &self_id,
3519                        &replacement_peer,
3520                        &outcome.response,
3521                        &outcome.sent_replica_hints,
3522                        p2p_node,
3523                        config,
3524                        bootstrapping,
3525                        bootstrap_state,
3526                        storage,
3527                        paid_list,
3528                        queues,
3529                        sync_state,
3530                        sync_history,
3531                        sync_cycle_epoch,
3532                        repair_proofs,
3533                        last_commitment_by_peer,
3534                        ever_capable_peers,
3535                        sig_verify_attempts,
3536                        gossip_audit,
3537                    )
3538                    .await;
3539                }
3540            }
3541        }
3542    }
3543}
3544
3545/// Process a successful neighbor sync response: record the sync, check for
3546/// bootstrap claim abuse, and admit inbound hints.
3547#[allow(clippy::too_many_arguments)]
3548async fn handle_sync_response(
3549    self_id: &PeerId,
3550    peer: &PeerId,
3551    resp: &NeighborSyncResponse,
3552    sent_replica_hints: &[neighbor_sync::SentReplicaHint],
3553    p2p_node: &Arc<P2PNode>,
3554    config: &ReplicationConfig,
3555    bootstrapping: bool,
3556    bootstrap_state: &Arc<RwLock<BootstrapState>>,
3557    storage: &Arc<LmdbStorage>,
3558    paid_list: &Arc<PaidList>,
3559    queues: &Arc<RwLock<ReplicationQueues>>,
3560    sync_state: &Arc<RwLock<NeighborSyncState>>,
3561    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
3562    sync_cycle_epoch: &Arc<RwLock<u64>>,
3563    repair_proofs: &Arc<RwLock<RepairProofs>>,
3564    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
3565    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
3566    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
3567    gossip_audit: &GossipAuditTrigger,
3568) {
3569    // Ingest the peer's commitment if they piggybacked one on the response.
3570    // Same verification as the request path (peer-id binding + signature);
3571    // forged commitments are dropped at the edge. A *changed* commitment here
3572    // is a gossip-audit trigger just like on the request path — so a peer that
3573    // only ever answers sync (never initiates) is still audited (ADR-0002).
3574    if let Some(target) = ingest_peer_commitment(
3575        peer,
3576        resp.commitment.as_ref(),
3577        p2p_node,
3578        last_commitment_by_peer,
3579        ever_capable_peers,
3580        sig_verify_attempts,
3581    )
3582    .await
3583    {
3584        maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
3585    }
3586
3587    // Record successful sync.
3588    {
3589        let mut state = sync_state.write().await;
3590        neighbor_sync::record_successful_sync(&mut state, peer);
3591    }
3592    {
3593        let mut history = sync_history.write().await;
3594        let record = history.entry(*peer).or_insert(PeerSyncRecord {
3595            last_sync: None,
3596            cycles_since_sync: 0,
3597        });
3598        record.last_sync = Some(Instant::now());
3599        record.cycles_since_sync = 0;
3600    }
3601
3602    // Process inbound hints from response (skip if peer is bootstrapping).
3603    if resp.bootstrapping {
3604        // Gap 6: BootstrapClaimAbuse grace period enforcement.
3605        // Separate state mutation from network I/O to avoid holding the
3606        // write lock across report_trust_event.
3607        let should_report = {
3608            let now = Instant::now();
3609            let mut state = sync_state.write().await;
3610            match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
3611                BootstrapClaimObservation::WithinGrace { .. } => false,
3612                BootstrapClaimObservation::PastGrace { first_seen } => {
3613                    warn!(
3614                        "Peer {peer} has been claiming bootstrap for {:?}, \
3615                         exceeding grace period of {:?} — reporting abuse",
3616                        now.duration_since(first_seen),
3617                        config.bootstrap_claim_grace_period,
3618                    );
3619                    true
3620                }
3621                BootstrapClaimObservation::Repeated { first_seen } => {
3622                    warn!(
3623                        "Peer {peer} repeated bootstrap claim after previously stopping; \
3624                         first claim was {:?} ago — reporting abuse",
3625                        now.duration_since(first_seen),
3626                    );
3627                    true
3628                }
3629            }
3630        };
3631        if should_report {
3632            p2p_node
3633                .report_trust_event(
3634                    peer,
3635                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
3636                )
3637                .await;
3638        }
3639    } else {
3640        // Peer is not claiming bootstrap; clear active claim while retaining
3641        // history so the peer cannot start a second grace window later.
3642        {
3643            let mut state = sync_state.write().await;
3644            state.clear_active_bootstrap_claim(peer);
3645        }
3646        record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
3647        let outcome = admit_and_queue_hints(
3648            self_id,
3649            peer,
3650            &resp.replica_hints,
3651            &resp.paid_hints,
3652            p2p_node,
3653            config,
3654            storage,
3655            paid_list,
3656            queues,
3657        )
3658        .await;
3659
3660        // Track discovered keys for bootstrap drain detection so that hints
3661        // admitted via regular neighbor sync are not missed. Capacity-
3662        // rejected hints keep this source on the "not yet drained" list
3663        // until its next sync replays them; a clean cycle clears it.
3664        if bootstrapping {
3665            if !outcome.discovered.is_empty() {
3666                bootstrap::track_discovered_keys(bootstrap_state, &outcome.discovered).await;
3667            }
3668            if outcome.capacity_rejected_count > 0 {
3669                bootstrap::note_capacity_rejected(bootstrap_state, *peer).await;
3670            } else {
3671                bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
3672            }
3673        }
3674    }
3675}
3676
3677/// Admit hints and queue them for verification, returning newly-discovered keys.
3678///
3679/// Shared by neighbor-sync request handling, response handling, and bootstrap
3680/// sync so that admission + queueing logic lives in one place.
3681#[allow(clippy::too_many_arguments)]
3682/// Outcome of [`admit_and_queue_hints`].
3683///
3684/// `capacity_rejected_count` is non-zero when one or more legitimately
3685/// admissible hints were dropped because `pending_verify`'s global or
3686/// per-source bound was hit. Callers that care about completeness
3687/// (bootstrap drain accounting) MUST NOT treat their work as complete while
3688/// this is > 0 — the source will need to re-hint after capacity frees up.
3689struct AdmissionOutcome {
3690    discovered: HashSet<XorName>,
3691    capacity_rejected_count: usize,
3692}
3693
3694#[allow(clippy::too_many_arguments)]
3695async fn admit_and_queue_hints(
3696    self_id: &PeerId,
3697    source_peer: &PeerId,
3698    replica_hints: &[XorName],
3699    paid_hints: &[XorName],
3700    p2p_node: &Arc<P2PNode>,
3701    config: &ReplicationConfig,
3702    storage: &Arc<LmdbStorage>,
3703    paid_list: &Arc<PaidList>,
3704    queues: &Arc<RwLock<ReplicationQueues>>,
3705) -> AdmissionOutcome {
3706    let pending_keys: HashSet<XorName> = {
3707        let q = queues.read().await;
3708        q.pending_keys().into_iter().collect()
3709    };
3710
3711    let admitted = admission::admit_hints(
3712        self_id,
3713        replica_hints,
3714        paid_hints,
3715        p2p_node,
3716        config,
3717        storage,
3718        paid_list,
3719        &pending_keys,
3720    )
3721    .await;
3722
3723    let mut discovered = HashSet::new();
3724    let mut capacity_rejected_count: usize = 0;
3725    let mut q = queues.write().await;
3726    let now = Instant::now();
3727
3728    for key in admitted.replica_keys {
3729        if !storage.exists(&key).unwrap_or(false) {
3730            let result = q.add_pending_verify(
3731                key,
3732                VerificationEntry {
3733                    state: VerificationState::PendingVerify,
3734                    pipeline: HintPipeline::Replica,
3735                    verified_sources: Vec::new(),
3736                    tried_sources: HashSet::new(),
3737                    created_at: now,
3738                    hint_sender: *source_peer,
3739                },
3740            );
3741            match result {
3742                crate::replication::scheduling::AdmissionResult::Admitted => {
3743                    discovered.insert(key);
3744                }
3745                crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
3746                crate::replication::scheduling::AdmissionResult::CapacityRejected => {
3747                    capacity_rejected_count += 1;
3748                }
3749            }
3750        }
3751    }
3752
3753    for key in admitted.paid_only_keys {
3754        let result = q.add_pending_verify(
3755            key,
3756            VerificationEntry {
3757                state: VerificationState::PendingVerify,
3758                pipeline: HintPipeline::PaidOnly,
3759                verified_sources: Vec::new(),
3760                tried_sources: HashSet::new(),
3761                created_at: now,
3762                hint_sender: *source_peer,
3763            },
3764        );
3765        match result {
3766            crate::replication::scheduling::AdmissionResult::Admitted => {
3767                discovered.insert(key);
3768            }
3769            crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
3770            crate::replication::scheduling::AdmissionResult::CapacityRejected => {
3771                capacity_rejected_count += 1;
3772            }
3773        }
3774    }
3775
3776    if capacity_rejected_count > 0 {
3777        debug!(
3778            "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
3779             rejected at queue capacity; source will need to re-hint after pending_verify drains"
3780        );
3781    }
3782
3783    AdmissionOutcome {
3784        discovered,
3785        capacity_rejected_count,
3786    }
3787}
3788
3789// ---------------------------------------------------------------------------
3790// Verification cycle
3791// ---------------------------------------------------------------------------
3792
3793/// Run one verification cycle: process pending keys through quorum checks.
3794#[allow(clippy::too_many_lines)]
3795async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
3796    let cycle_started = Instant::now();
3797    let VerificationCycleContext {
3798        p2p_node,
3799        paid_list,
3800        storage,
3801        queues,
3802        config,
3803        bootstrap_state,
3804        is_bootstrapping,
3805        bootstrap_complete_notify,
3806        last_commitment_by_peer,
3807        ever_capable_peers,
3808        recent_provers,
3809    } = ctx;
3810
3811    // Evict stale entries that have been pending too long (e.g. unreachable
3812    // verification targets during a network partition).
3813    {
3814        let mut q = queues.write().await;
3815        q.evict_stale(config::PENDING_VERIFY_MAX_AGE);
3816    }
3817
3818    let pending_keys = {
3819        let q = queues.read().await;
3820        q.pending_keys()
3821    };
3822
3823    if pending_keys.is_empty() {
3824        return;
3825    }
3826    let initial_pending_count = pending_keys.len();
3827
3828    let self_id = *p2p_node.peer_id();
3829
3830    // Step 1: Check local PaidForList for fast-path authorization (Section 9,
3831    // step 4).
3832    let mut local_paid_presence_probe_keys = Vec::new();
3833    let mut local_paid_paid_only_keys = Vec::new();
3834    let mut keys_needing_network = Vec::new();
3835    let mut terminal_keys: Vec<XorName> = Vec::new();
3836    {
3837        let mut q = queues.write().await;
3838        for key in &pending_keys {
3839            if paid_list.contains(key).unwrap_or(false) {
3840                if let Some(pipeline) =
3841                    q.set_pending_state(key, VerificationState::PaidListVerified)
3842                {
3843                    match pipeline {
3844                        HintPipeline::PaidOnly => {
3845                            // Paid-only + local paid state needs one more
3846                            // storage-admission check outside this lock: if we
3847                            // are also in the close group plus storage margin,
3848                            // the hint can repair a missing replica.
3849                            local_paid_paid_only_keys.push(*key);
3850                        }
3851                        HintPipeline::Replica => {
3852                            // Local paid-list membership authorizes the key.
3853                            // We still need a presence probe to discover fetch
3854                            // sources, but we must not require remote paid
3855                            // majority or presence quorum.
3856                            local_paid_presence_probe_keys.push(*key);
3857                        }
3858                    }
3859                }
3860            } else {
3861                keys_needing_network.push(*key);
3862            }
3863        }
3864    }
3865
3866    if !local_paid_paid_only_keys.is_empty() {
3867        let mut terminal_paid_only = Vec::new();
3868        for key in local_paid_paid_only_keys {
3869            if storage.exists(&key).unwrap_or(false) {
3870                terminal_paid_only.push(key);
3871            } else if admission::is_responsible(
3872                &self_id,
3873                &key,
3874                p2p_node,
3875                storage_admission_width(config.close_group_size),
3876            )
3877            .await
3878            {
3879                local_paid_presence_probe_keys.push(key);
3880            } else {
3881                terminal_paid_only.push(key);
3882            }
3883        }
3884
3885        if !terminal_paid_only.is_empty() {
3886            let mut q = queues.write().await;
3887            for key in terminal_paid_only {
3888                q.remove_pending(&key);
3889                terminal_keys.push(key);
3890            }
3891        }
3892    }
3893
3894    let local_paid_probe_count = local_paid_presence_probe_keys.len();
3895    let keys_needing_network_count = keys_needing_network.len();
3896
3897    // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
3898    // step 4, authorization succeeds immediately; run a presence-only probe
3899    // to find any holder we can fetch from.
3900    if !local_paid_presence_probe_keys.is_empty() {
3901        let targets = quorum::compute_presence_targets(
3902            &local_paid_presence_probe_keys,
3903            p2p_node,
3904            config,
3905            &self_id,
3906        )
3907        .await;
3908        let evidence = quorum::run_verification_round(
3909            &local_paid_presence_probe_keys,
3910            &targets,
3911            p2p_node,
3912            config,
3913        )
3914        .await;
3915
3916        let mut q = queues.write().await;
3917        for key in local_paid_presence_probe_keys {
3918            if storage.exists(&key).unwrap_or(false) {
3919                q.remove_pending(&key);
3920                terminal_keys.push(key);
3921                continue;
3922            }
3923            let sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
3924                quorum::present_sources_for_key(&key, ev, &targets)
3925            });
3926            if sources.is_empty() {
3927                // Terminal failure: remove pending and report. No fetch path.
3928                q.remove_pending(&key);
3929                warn!(
3930                    "Locally paid key {} has no responding holders (possible data loss)",
3931                    hex::encode(key)
3932                );
3933                terminal_keys.push(key);
3934            } else {
3935                let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
3936                // Atomic remove+enqueue: if fetch_queue is at capacity, the
3937                // pending entry is preserved and retried next cycle (no
3938                // silent drop of verified replica-repair work).
3939                let _ = q.promote_pending_to_fetch(key, distance, sources);
3940            }
3941        }
3942    }
3943
3944    // Steps 2-5: Network verification (skipped if all keys resolved locally).
3945    if !keys_needing_network.is_empty() {
3946        // Step 2: Compute targets and run network verification round.
3947        let targets =
3948            quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
3949                .await;
3950
3951        let evidence =
3952            quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
3953
3954        // Step 3: Evaluate results — collect outcomes without holding the write
3955        // lock across paid-list I/O.
3956        //
3957        // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
3958        // table and recent_provers cache up front so the synchronous
3959        // evaluate_key_evidence_with_holder_check predicate can consult
3960        // them without awaiting. The predicate downgrades a Present
3961        // claim to Unresolved unless the peer is credited for that key.
3962        // Snapshot per-peer commitment data. We need two views:
3963        //   - `commitment_by_peer_snapshot`: peers that currently have
3964        //     a verified commitment record on file (used to look up
3965        //     their current hash).
3966        //   - `capable_peer_snapshot`: the sticky "ever v12-capable"
3967        //     set. Sourced from a separate set rather than the
3968        //     commitment map so eviction (PeerRemoved cleanup, sybil
3969        //     cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
3970        //     a previously-v12 peer to "legacy" credit-unconditionally.
3971        //     Legacy / pre-v12 peers that have never sent a commitment
3972        //     remain absent from the set and are credited via the
3973        //     legacy path so mixed-version networks stay live.
3974        let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
3975            let map = last_commitment_by_peer.read().await;
3976            map.iter()
3977                // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
3978                // of every peer's ~5 KiB commitment.
3979                .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
3980                .collect()
3981        };
3982        let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
3983        // Take a full snapshot of recent_provers under the read lock,
3984        // then release. The cache is bounded (16/key × keys), so the
3985        // clone is cheap.
3986        let provers_snapshot = recent_provers.read().await.clone();
3987        // For the replica-fetch path, we need to know whether THIS
3988        // node already holds the key being verified. The v12 §6
3989        // holder-credit gate is meant to prevent uncredited Present
3990        // claims from contributing to paid-list / reward quorum for
3991        // keys we DO hold (and could audit ourselves). For keys we
3992        // are trying to FETCH (i.e. not in local storage), there is
3993        // no possible local audit credit, and gating the presence
3994        // quorum on credit would deadlock replica-repair in a
3995        // fully v12-capable close group.
3996        let mut locally_held: HashSet<XorName> = HashSet::new();
3997        for key in &keys_needing_network {
3998            if storage.exists(key).unwrap_or(false) {
3999                locally_held.insert(*key);
4000            }
4001        }
4002        let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
4003            if !locally_held.contains(key) {
4004                // Replica-fetch path: we don't hold this key, so we
4005                // cannot have collected audit credit for it. Trust
4006                // Present claims to drive fetch-source promotion;
4007                // chunk-PUT payment_verifier is the security backstop
4008                // when the bytes actually arrive.
4009                return true;
4010            }
4011            if !capable_peer_snapshot.contains(peer) {
4012                // Pre-v12 / legacy peer that has never gossiped a
4013                // commitment. The v12 §6 holder-eligibility check
4014                // doesn't apply: their Present evidence comes through
4015                // the legacy path and we credit it unconditionally
4016                // so a mixed-version network stays live during
4017                // transition.
4018                return true;
4019            }
4020            let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
4021                // Peer is commitment_capable (sticky) but currently
4022                // has no live commitment record on file (e.g. their
4023                // last gossip was evicted from the LRU cache, or it
4024                // failed verification). Withhold credit until they
4025                // re-prove storage under a fresh commitment.
4026                return false;
4027            };
4028            provers_snapshot.is_credited_holder(key, peer, hash)
4029        };
4030
4031        let mut evaluated: Vec<(XorName, KeyVerificationOutcome, HintPipeline)> = Vec::new();
4032        {
4033            let q = queues.read().await;
4034            for key in &keys_needing_network {
4035                let Some(ev) = evidence.get(key) else {
4036                    continue;
4037                };
4038                let Some(entry) = q.get_pending(key) else {
4039                    continue;
4040                };
4041                let outcome = quorum::evaluate_key_evidence_with_holder_check(
4042                    key,
4043                    ev,
4044                    &targets,
4045                    config,
4046                    holder_credit,
4047                );
4048                evaluated.push((*key, outcome, entry.pipeline));
4049            }
4050        } // read lock released
4051
4052        // Step 4: Insert verified keys into PaidForList (no lock held).
4053        let mut paid_insert_keys: Vec<XorName> = Vec::new();
4054        for (key, outcome, _) in &evaluated {
4055            if matches!(
4056                outcome,
4057                KeyVerificationOutcome::QuorumVerified { .. }
4058                    | KeyVerificationOutcome::PaidListVerified { .. }
4059            ) {
4060                paid_insert_keys.push(*key);
4061            }
4062        }
4063        for key in &paid_insert_keys {
4064            if let Err(e) = paid_list.insert(key).await {
4065                warn!("Failed to add verified key to PaidForList: {e}");
4066            }
4067        }
4068
4069        // Paid-only hints normally update PaidForList only. If this node is
4070        // also within the storage-admission group for the key, a verified
4071        // paid-only hint can safely repair a missing replica using sources
4072        // from the same verification round.
4073        let mut paid_only_fetch_keys: HashSet<XorName> = HashSet::new();
4074        for (key, outcome, pipeline) in &evaluated {
4075            if *pipeline == HintPipeline::PaidOnly
4076                && matches!(
4077                    outcome,
4078                    KeyVerificationOutcome::QuorumVerified { .. }
4079                        | KeyVerificationOutcome::PaidListVerified { .. }
4080                )
4081                && !storage.exists(key).unwrap_or(false)
4082                && admission::is_responsible(
4083                    &self_id,
4084                    key,
4085                    p2p_node,
4086                    storage_admission_width(config.close_group_size),
4087                )
4088                .await
4089            {
4090                paid_only_fetch_keys.insert(*key);
4091            }
4092        }
4093
4094        // Step 5: Update queues with the evaluated outcomes.
4095        let mut q = queues.write().await;
4096        for (key, outcome, pipeline) in evaluated {
4097            match outcome {
4098                KeyVerificationOutcome::QuorumVerified { sources }
4099                | KeyVerificationOutcome::PaidListVerified { sources } => {
4100                    let fetch_eligible =
4101                        pipeline == HintPipeline::Replica || paid_only_fetch_keys.contains(&key);
4102                    if fetch_eligible && !sources.is_empty() {
4103                        let distance =
4104                            crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
4105                        // Atomic remove+enqueue: on fetch_queue capacity miss
4106                        // the pending entry is preserved so this verified key
4107                        // is retried on the next cycle (no silent drop).
4108                        let _ = q.promote_pending_to_fetch(key, distance, sources);
4109                        // Not terminal — either moved to fetch queue, or
4110                        // retained as pending until queue drains.
4111                    } else if fetch_eligible && sources.is_empty() {
4112                        warn!(
4113                            "Verified storage-admitted key {} has no holders (possible data loss)",
4114                            hex::encode(key)
4115                        );
4116                        q.remove_pending(&key);
4117                        terminal_keys.push(key);
4118                    } else {
4119                        q.remove_pending(&key);
4120                        terminal_keys.push(key);
4121                    }
4122                }
4123                KeyVerificationOutcome::QuorumFailed
4124                | KeyVerificationOutcome::QuorumInconclusive => {
4125                    q.remove_pending(&key);
4126                    terminal_keys.push(key);
4127                }
4128            }
4129        }
4130    }
4131
4132    // Step 6: Remove terminal keys from bootstrap pending set and re-check
4133    // the drain condition.
4134    update_bootstrap_after_verification(
4135        &terminal_keys,
4136        bootstrap_state,
4137        queues,
4138        is_bootstrapping,
4139        bootstrap_complete_notify,
4140    )
4141    .await;
4142
4143    let (pending_after, fetch_after, in_flight_after) = {
4144        let q = queues.read().await;
4145        (
4146            q.pending_count(),
4147            q.fetch_queue_count(),
4148            q.in_flight_count(),
4149        )
4150    };
4151    let terminal_key_count = terminal_keys.len();
4152    let elapsed_ms = cycle_started.elapsed().as_millis();
4153
4154    if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
4155        info!(
4156            target: "ant_node::replication::verification",
4157            "Slow replication verification cycle: pending_start={initial_pending_count}, local_paid_probe={local_paid_probe_count}, network_verify={keys_needing_network_count}, terminal={terminal_key_count}, pending_after={pending_after}, fetch_after={fetch_after}, in_flight_after={in_flight_after}, elapsed_ms={elapsed_ms}",
4158        );
4159    } else {
4160        debug!(
4161            target: "ant_node::replication::verification",
4162            "Replication verification cycle: pending_start={initial_pending_count}, local_paid_probe={local_paid_probe_count}, network_verify={keys_needing_network_count}, terminal={terminal_key_count}, pending_after={pending_after}, fetch_after={fetch_after}, in_flight_after={in_flight_after}, elapsed_ms={elapsed_ms}",
4163        );
4164    }
4165}
4166
4167/// Post-verification bootstrap bookkeeping: remove terminal keys from the
4168/// bootstrap pending set and transition out of bootstrapping when drained.
4169async fn update_bootstrap_after_verification(
4170    terminal_keys: &[XorName],
4171    bootstrap_state: &Arc<RwLock<BootstrapState>>,
4172    queues: &Arc<RwLock<ReplicationQueues>>,
4173    is_bootstrapping: &Arc<RwLock<bool>>,
4174    bootstrap_complete_notify: &Arc<Notify>,
4175) {
4176    if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
4177        return;
4178    }
4179    {
4180        let mut bs = bootstrap_state.write().await;
4181        for key in terminal_keys {
4182            bs.remove_key(key);
4183        }
4184    }
4185    let q = queues.read().await;
4186    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
4187        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
4188    }
4189}
4190
4191/// Set `is_bootstrapping` to `false` and wake all waiters.
4192async fn complete_bootstrap(
4193    is_bootstrapping: &Arc<RwLock<bool>>,
4194    bootstrap_complete_notify: &Arc<Notify>,
4195) {
4196    *is_bootstrapping.write().await = false;
4197    bootstrap_complete_notify.notify_waiters();
4198    info!("Replication bootstrap complete");
4199}
4200
4201// ---------------------------------------------------------------------------
4202// Fetch types and single-fetch executor
4203// ---------------------------------------------------------------------------
4204
4205/// Result classification for a single fetch attempt.
4206enum FetchResult {
4207    /// Data fetched, integrity-checked, and stored successfully.
4208    Stored,
4209    /// Content-address integrity check failed — do not retry.
4210    IntegrityFailed,
4211    /// Source failed (network error or non-success response) — retryable.
4212    SourceFailed,
4213}
4214
4215/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
4216/// worker loop to update queue state.
4217struct FetchOutcome {
4218    key: XorName,
4219    result: FetchResult,
4220}
4221
4222#[allow(clippy::too_many_lines)]
4223/// Execute a single fetch request against `source` for `key`.
4224///
4225/// Handles encoding, network I/O, integrity checking, storage, and trust
4226/// event reporting.  Returns a [`FetchOutcome`] so the caller can update
4227/// queue state without holding any locks during the network round-trip.
4228async fn execute_single_fetch(
4229    p2p_node: Arc<P2PNode>,
4230    storage: Arc<LmdbStorage>,
4231    config: Arc<ReplicationConfig>,
4232    key: XorName,
4233    source: PeerId,
4234) -> FetchOutcome {
4235    let request = protocol::FetchRequest { key };
4236    let msg = ReplicationMessage {
4237        request_id: rand::thread_rng().gen::<u64>(),
4238        body: ReplicationMessageBody::FetchRequest(request),
4239    };
4240
4241    let encoded = match msg.encode() {
4242        Ok(data) => data,
4243        Err(e) => {
4244            warn!("Failed to encode fetch request: {e}");
4245            return FetchOutcome {
4246                key,
4247                result: FetchResult::SourceFailed,
4248            };
4249        }
4250    };
4251
4252    let result = p2p_node
4253        .send_request(
4254            &source,
4255            REPLICATION_PROTOCOL_ID,
4256            encoded,
4257            config.fetch_request_timeout,
4258        )
4259        .await;
4260
4261    match result {
4262        Ok(response) => {
4263            let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
4264                p2p_node
4265                    .report_trust_event(
4266                        &source,
4267                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4268                    )
4269                    .await;
4270                return FetchOutcome {
4271                    key,
4272                    result: FetchResult::SourceFailed,
4273                };
4274            };
4275
4276            match resp_msg.body {
4277                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
4278                    key: resp_key,
4279                    data,
4280                }) => {
4281                    // Validate the response key matches the requested key.
4282                    // A malicious peer could serve valid data for a different
4283                    // key, passing integrity checks while the requested key
4284                    // is falsely marked as fetched.
4285                    if resp_key != key {
4286                        warn!(
4287                            "Fetch response key mismatch: requested {}, got {}",
4288                            hex::encode(key),
4289                            hex::encode(resp_key)
4290                        );
4291                        p2p_node
4292                            .report_trust_event(
4293                                &source,
4294                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4295                            )
4296                            .await;
4297                        return FetchOutcome {
4298                            key,
4299                            result: FetchResult::IntegrityFailed,
4300                        };
4301                    }
4302
4303                    // Enforce chunk size invariant on fetched data.
4304                    // Checked before the content-address hash to avoid
4305                    // hashing up to 10 MiB of oversized junk data.
4306                    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
4307                        warn!(
4308                            "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
4309                            hex::encode(resp_key),
4310                            data.len(),
4311                            crate::ant_protocol::MAX_CHUNK_SIZE,
4312                        );
4313                        p2p_node
4314                            .report_trust_event(
4315                                &source,
4316                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4317                            )
4318                            .await;
4319                        return FetchOutcome {
4320                            key,
4321                            result: FetchResult::IntegrityFailed,
4322                        };
4323                    }
4324
4325                    // Content-address integrity check.
4326                    let computed = crate::client::compute_address(&data);
4327                    if computed != resp_key {
4328                        warn!(
4329                            "Fetched record integrity check failed: expected {}, got {}",
4330                            hex::encode(resp_key),
4331                            hex::encode(computed)
4332                        );
4333                        p2p_node
4334                            .report_trust_event(
4335                                &source,
4336                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4337                            )
4338                            .await;
4339                        return FetchOutcome {
4340                            key,
4341                            result: FetchResult::IntegrityFailed,
4342                        };
4343                    }
4344
4345                    if let Err(e) = storage.put(&resp_key, &data).await {
4346                        warn!(
4347                            "Failed to store fetched record {}: {e}",
4348                            hex::encode(resp_key)
4349                        );
4350                        return FetchOutcome {
4351                            key,
4352                            result: FetchResult::SourceFailed,
4353                        };
4354                    }
4355
4356                    FetchOutcome {
4357                        key,
4358                        result: FetchResult::Stored,
4359                    }
4360                }
4361                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::NotFound {
4362                    ..
4363                }) => {
4364                    // This peer was selected as a fetch source because it
4365                    // recently answered `Present` during verification. A
4366                    // subsequent NotFound is evidence of a stale/false claim
4367                    // or chunk wiping, so penalize lightly and try another
4368                    // verified source.
4369                    warn!(
4370                        "Fetch: verified source {source} returned NotFound for {}",
4371                        hex::encode(key)
4372                    );
4373                    p2p_node
4374                        .report_trust_event(
4375                            &source,
4376                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4377                        )
4378                        .await;
4379                    FetchOutcome {
4380                        key,
4381                        result: FetchResult::SourceFailed,
4382                    }
4383                }
4384                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Error {
4385                    reason,
4386                    ..
4387                }) => {
4388                    warn!(
4389                        "Fetch: peer {source} returned error for {}: {reason}",
4390                        hex::encode(key)
4391                    );
4392                    p2p_node
4393                        .report_trust_event(
4394                            &source,
4395                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4396                        )
4397                        .await;
4398                    FetchOutcome {
4399                        key,
4400                        result: FetchResult::SourceFailed,
4401                    }
4402                }
4403                _ => {
4404                    // Unexpected message type — treat as malformed.
4405                    p2p_node
4406                        .report_trust_event(
4407                            &source,
4408                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4409                        )
4410                        .await;
4411                    FetchOutcome {
4412                        key,
4413                        result: FetchResult::SourceFailed,
4414                    }
4415                }
4416            }
4417        }
4418        Err(e) => {
4419            debug!("Fetch request to {source} failed: {e}");
4420            // No ApplicationFailure here — P2PNode::send_request() already
4421            // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
4422            FetchOutcome {
4423                key,
4424                result: FetchResult::SourceFailed,
4425            }
4426        }
4427    }
4428}
4429
4430// ---------------------------------------------------------------------------
4431// Audit result handler
4432// ---------------------------------------------------------------------------
4433
4434/// Format the first confirmed-failed key as a 16-hex-char label.
4435///
4436/// Pairs with `challenged_peer` to form a stable cross-host correlation
4437/// handle in the audit-failure log line, e.g.
4438///
4439/// ```text
4440/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
4441/// ```
4442///
4443/// Falls back to `"0x"` when the list is empty so the log line never
4444/// contains a misleading default.
4445fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
4446    confirmed_failed_keys.first().map_or_else(
4447        || "0x".to_string(),
4448        |k| format!("0x{}", hex::encode(&k[..8])),
4449    )
4450}
4451
4452/// Execute the side effects for a subtree storage-commitment audit failure.
4453///
4454/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
4455/// legitimately time out on slow or loaded honest peers, so it never touches the
4456/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
4457/// failures still penalise immediately and revoke holder credit.
4458async fn handle_subtree_failed_audit(
4459    challenged_peer: &PeerId,
4460    confirmed_failed_key_count: usize,
4461    reason: &AuditFailureReason,
4462    p2p_node: &Arc<P2PNode>,
4463    sync_state: &Arc<RwLock<NeighborSyncState>>,
4464    recent_provers: &Arc<RwLock<RecentProvers>>,
4465) {
4466    if matches!(reason, AuditFailureReason::Timeout) {
4467        debug!(
4468            "Audit timeout for {challenged_peer} fully graced \
4469             (subtree audit does not evict on timeout)"
4470        );
4471        return;
4472    }
4473
4474    // The caller already logged the rich failure line with reason + per-category
4475    // summary; avoid a redundant second error log here.
4476    let _ = confirmed_failed_key_count;
4477    {
4478        let mut state = sync_state.write().await;
4479        state.clear_active_bootstrap_claim(challenged_peer);
4480    }
4481    {
4482        let mut provers_guard = recent_provers.write().await;
4483        apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
4484    }
4485    p2p_node
4486        .report_trust_event(
4487            challenged_peer,
4488            TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
4489        )
4490        .await;
4491}
4492
4493/// Handle audit result: log findings and emit trust events.
4494async fn handle_subtree_audit_result(
4495    result: &AuditTickResult,
4496    p2p_node: &Arc<P2PNode>,
4497    sync_state: &Arc<RwLock<NeighborSyncState>>,
4498    recent_provers: &Arc<RwLock<RecentProvers>>,
4499    config: &ReplicationConfig,
4500) {
4501    match result {
4502        AuditTickResult::Passed {
4503            challenged_peer,
4504            keys_checked,
4505        } => {
4506            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
4507            // Peer responded normally — clear the active bootstrap claim while
4508            // retaining history so a later claim is treated as repeated abuse.
4509            {
4510                let mut state = sync_state.write().await;
4511                state.clear_active_bootstrap_claim(challenged_peer);
4512            }
4513            p2p_node
4514                .report_trust_event(
4515                    challenged_peer,
4516                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
4517                )
4518                .await;
4519        }
4520        AuditTickResult::Failed { evidence } => {
4521            if let FailureEvidence::AuditFailure {
4522                challenged_peer,
4523                confirmed_failed_keys,
4524                summary,
4525                reason,
4526                ..
4527            } = evidence
4528            {
4529                // Rich diagnostics (from main's audit-failure logging) + the
4530                // first-failed-key correlation handle.
4531                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
4532                error!(
4533                    "Audit failure for {challenged_peer}: reason={reason:?}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
4534                    confirmed_failed_keys.len(),
4535                    summary.challenged_keys,
4536                    summary.absent_keys,
4537                    summary.digest_mismatch_keys,
4538                );
4539                // Route the side effects through the subtree-only failure path.
4540                // Responsible-chunk `AuditChallenge` handling intentionally uses
4541                // its own old immediate-penalty handler below.
4542                handle_subtree_failed_audit(
4543                    challenged_peer,
4544                    confirmed_failed_keys.len(),
4545                    reason,
4546                    p2p_node,
4547                    sync_state,
4548                    recent_provers,
4549                )
4550                .await;
4551            }
4552        }
4553        AuditTickResult::BootstrapClaim { peer } => {
4554            // Gap 6: BootstrapClaimAbuse grace period in audit path.
4555            // Separate state mutation from network I/O to avoid holding the
4556            // write lock across report_trust_event.
4557            let should_report = {
4558                let now = Instant::now();
4559                let mut state = sync_state.write().await;
4560                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
4561                {
4562                    BootstrapClaimObservation::WithinGrace { .. } => {
4563                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
4564                        false
4565                    }
4566                    BootstrapClaimObservation::PastGrace { first_seen } => {
4567                        warn!(
4568                            "Audit: peer {peer} claiming bootstrap past grace period \
4569                             ({:?} > {:?}), reporting abuse",
4570                            now.duration_since(first_seen),
4571                            config.bootstrap_claim_grace_period,
4572                        );
4573                        true
4574                    }
4575                    BootstrapClaimObservation::Repeated { first_seen } => {
4576                        warn!(
4577                            "Audit: peer {peer} repeated bootstrap claim after previously \
4578                             stopping; first claim was {:?} ago, reporting abuse",
4579                            now.duration_since(first_seen),
4580                        );
4581                        true
4582                    }
4583                }
4584            };
4585            if should_report {
4586                p2p_node
4587                    .report_trust_event(
4588                        peer,
4589                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4590                    )
4591                    .await;
4592            }
4593        }
4594        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
4595    }
4596}
4597
4598/// Whether a confirmed audit failure with this reason clears the peer's active
4599/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
4600/// bootstrapping); every confirmed storage-integrity reason does.
4601///
4602/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
4603/// the bootstrap claim but are still reported as audit failures, matching the
4604/// pre-ADR-0002 behaviour.
4605fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
4606    !matches!(reason, AuditFailureReason::Timeout)
4607}
4608
4609/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
4610/// events and manage bootstrap-claim state.
4611///
4612/// This is intentionally separate from the subtree audit result handler. A
4613/// responsible-chunk `AuditChallenge` `Failed` result reports
4614/// `ApplicationFailure` immediately for every reason, including `Timeout`,
4615/// restoring the pre-ADR-0002 behaviour.
4616async fn handle_audit_result(
4617    result: &AuditTickResult,
4618    p2p_node: &Arc<P2PNode>,
4619    sync_state: &Arc<RwLock<NeighborSyncState>>,
4620    config: &ReplicationConfig,
4621) {
4622    match result {
4623        AuditTickResult::Passed {
4624            challenged_peer,
4625            keys_checked,
4626        } => {
4627            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
4628            {
4629                let mut state = sync_state.write().await;
4630                state.clear_active_bootstrap_claim(challenged_peer);
4631            }
4632            p2p_node
4633                .report_trust_event(
4634                    challenged_peer,
4635                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
4636                )
4637                .await;
4638        }
4639        AuditTickResult::Failed { evidence } => {
4640            if let FailureEvidence::AuditFailure {
4641                challenged_peer,
4642                confirmed_failed_keys,
4643                summary,
4644                reason,
4645                ..
4646            } = evidence
4647            {
4648                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
4649                error!(
4650                    "Audit failure for {challenged_peer}: reason={reason:?}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
4651                    confirmed_failed_keys.len(),
4652                    summary.challenged_keys,
4653                    summary.absent_keys,
4654                    summary.digest_mismatch_keys,
4655                );
4656                if audit_failure_clears_bootstrap_claim(reason) {
4657                    let mut state = sync_state.write().await;
4658                    state.clear_active_bootstrap_claim(challenged_peer);
4659                } else {
4660                    debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
4661                }
4662                p2p_node
4663                    .report_trust_event(
4664                        challenged_peer,
4665                        TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
4666                    )
4667                    .await;
4668            }
4669        }
4670        AuditTickResult::BootstrapClaim { peer } => {
4671            let should_report = {
4672                let now = Instant::now();
4673                let mut state = sync_state.write().await;
4674                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
4675                {
4676                    BootstrapClaimObservation::WithinGrace { .. } => {
4677                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
4678                        false
4679                    }
4680                    BootstrapClaimObservation::PastGrace { first_seen } => {
4681                        warn!(
4682                            "Audit: peer {peer} claiming bootstrap past grace period \
4683                             ({:?} > {:?}), reporting abuse",
4684                            now.duration_since(first_seen),
4685                            config.bootstrap_claim_grace_period,
4686                        );
4687                        true
4688                    }
4689                    BootstrapClaimObservation::Repeated { first_seen } => {
4690                        warn!(
4691                            "Audit: peer {peer} repeated bootstrap claim after previously \
4692                             stopping; first claim was {:?} ago, reporting abuse",
4693                            now.duration_since(first_seen),
4694                        );
4695                        true
4696                    }
4697                }
4698            };
4699            if should_report {
4700                p2p_node
4701                    .report_trust_event(
4702                        peer,
4703                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4704                    )
4705                    .await;
4706            }
4707        }
4708        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
4709    }
4710}
4711
4712/// Whether a confirmed audit failure with this reason should revoke the
4713/// peer's `recent_provers` holder credit immediately (v12 §6).
4714///
4715/// `true` for any reason where the peer actually answered (or admitted
4716/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
4717/// bytes for committed key"), `MalformedResponse` — these prove the
4718/// peer no longer holds what it committed to, so it must not keep
4719/// holder credit for the proof TTL. `false` for `Timeout`: a single
4720/// dropped packet must not strip an honest peer; the 40-min TTL is the
4721/// deliberate liveness cushion there.
4722fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
4723    !matches!(reason, AuditFailureReason::Timeout)
4724}
4725
4726/// Apply the holder-credit revocation decision for a confirmed audit
4727/// failure. Pure over `RecentProvers` so the handler wiring is unit-
4728/// testable without a live `P2PNode`: the production `Failed` arm of
4729/// `handle_subtree_audit_result` calls exactly this.
4730fn apply_audit_failure_credit_revocation(
4731    provers: &mut RecentProvers,
4732    challenged_peer: &PeerId,
4733    reason: &AuditFailureReason,
4734) {
4735    if audit_failure_revokes_holder_credit(reason) {
4736        provers.forget_peer(challenged_peer);
4737    }
4738}
4739
4740// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
4741
4742// ---------------------------------------------------------------------------
4743// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
4744// ---------------------------------------------------------------------------
4745
4746/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
4747/// message handler passes one value instead of a long argument list; all
4748/// fields are cheap `Arc` clones.
4749#[derive(Clone)]
4750struct GossipAuditTrigger {
4751    p2p_node: Arc<P2PNode>,
4752    config: Arc<ReplicationConfig>,
4753    recent_provers: Arc<RwLock<RecentProvers>>,
4754    sync_state: Arc<RwLock<NeighborSyncState>>,
4755    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4756}
4757
4758/// What a gossip ingest yields for the audit trigger: the commitment hash to
4759/// pin and the `key_count` needed to size the response deadline from the actual
4760/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
4761/// or not) so a stable-keyset node stays auditable — not just on its first
4762/// commitment.
4763#[derive(Debug, Clone, Copy)]
4764struct AuditTarget {
4765    pin_hash: [u8; 32],
4766    key_count: u32,
4767}
4768
4769/// ADR-0004: a commitment that backed a payment, surfaced by the payment
4770/// verifier's cross-check so it can receive a **deterministic first audit**.
4771///
4772/// Sent from the verifier to the replication engine's first-audit drainer. The
4773/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
4774/// audits of the same peer revert to the gossip lottery), orders most-recently-
4775/// monetized first, and runs the same `run_subtree_audit` under the same
4776/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
4777#[derive(Debug, Clone, Copy)]
4778pub struct MonetizedPinEvent {
4779    /// The peer whose commitment backed the payment.
4780    pub peer: PeerId,
4781    /// The pinned commitment hash.
4782    pub pin: [u8; 32],
4783    /// The committed key count (sizes the audit deadline).
4784    pub key_count: u32,
4785    /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
4786    /// pin whose quote is older than the answerability window (ADR-0004 A1
4787    /// guardrail A): with grace removed, challenging an aged-out pin would
4788    /// false-convict, so a stale client-forwarded quote must not trigger an audit.
4789    pub quote_ts: SystemTime,
4790}
4791
4792/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
4793/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
4794/// stamps `now`), `false` if it was audited within
4795/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
4796/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
4797/// without a live node: a burst of gossips from one peer yields at most one
4798/// `true` per cooldown window.
4799fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
4800    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
4801    let known = match map.get(peer) {
4802        Some(&last) => {
4803            if now.saturating_duration_since(last) < cooldown {
4804                return false;
4805            }
4806            true
4807        }
4808        None => false,
4809    };
4810    // Bound the map under churn like its siblings (drop the oldest stamp) before
4811    // admitting a brand-new peer.
4812    if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
4813        if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
4814            map.remove(&victim);
4815        }
4816    }
4817    map.insert(*peer, now);
4818    true
4819}
4820
4821/// The gossip-audit launch decision in ONE place so the ordering is shared
4822/// between production and its test (ADR-0002 "occasional surprise exams").
4823///
4824/// Order matters and is the security-relevant property: the per-peer cooldown is
4825/// checked-and-stamped FIRST, THEN the probability lottery (`lottery_wins`) is
4826/// applied. If the lottery were sampled first, a gossip flood would re-roll it on
4827/// every message until one won, multiplying audits. Because the cooldown is
4828/// stamped before the lottery is consulted, a LOSING ticket still consumes the
4829/// window — so each peer gets at most one audit lottery per cooldown window
4830/// regardless of how often it gossips. Production calls this with
4831/// `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the test calls it with
4832/// a deterministic `lottery_wins`, so a reorder regression here fails the test.
4833fn audit_launch_decision(
4834    map: &mut HashMap<PeerId, Instant>,
4835    peer: &PeerId,
4836    now: Instant,
4837    lottery_wins: bool,
4838) -> bool {
4839    // Gate 1: cooldown check-and-stamp (consumes the window even on a loss).
4840    if !cooldown_allows_audit(map, peer, now) {
4841        return false;
4842    }
4843    // Gate 2: the probability lottery.
4844    lottery_wins
4845}
4846
4847/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
4848/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
4849/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
4850/// handling is never blocked on a network round-trip.
4851async fn maybe_trigger_gossip_audit(
4852    trigger: &GossipAuditTrigger,
4853    peer: &PeerId,
4854    target: AuditTarget,
4855) {
4856    // The launch decision (cooldown-then-lottery ordering) lives in the pure
4857    // `audit_launch_decision` so the ordering is shared with its test. Sample
4858    // the lottery here, then let the helper apply it AFTER the cooldown stamp.
4859    let now = Instant::now();
4860    let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
4861    {
4862        let mut map = trigger.cooldown.write().await;
4863        if !audit_launch_decision(&mut map, peer, now, lottery_wins) {
4864            return;
4865        }
4866    }
4867
4868    let trigger = trigger.clone();
4869    let peer = *peer;
4870    tokio::spawn(async move {
4871        let credit = storage_commitment_audit::AuditCredit {
4872            recent_provers: &trigger.recent_provers,
4873        };
4874        let result = storage_commitment_audit::run_subtree_audit(
4875            &trigger.p2p_node,
4876            &trigger.config,
4877            &peer,
4878            target.pin_hash,
4879            target.key_count,
4880            Some(&credit),
4881        )
4882        .await;
4883        handle_subtree_audit_result(
4884            &result,
4885            &trigger.p2p_node,
4886            &trigger.sync_state,
4887            &trigger.recent_provers,
4888            &trigger.config,
4889        )
4890        .await;
4891    });
4892}
4893
4894/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
4895///
4896/// Returns `true` if a signature verify is allowed now (and stamps the attempt
4897/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
4898/// of its last attempt. Holds one write lock across the decision so two
4899/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
4900/// caller's expensive verify so a slow/failed verify still rate-limits the next
4901/// message. Bounds the map under a flood of distinct peer ids.
4902async fn sig_verify_rate_limit_ok(
4903    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
4904    source: &PeerId,
4905    now: Instant,
4906) -> bool {
4907    let mut attempts = sig_verify_attempts.write().await;
4908    if let Some(&last) = attempts.get(source) {
4909        if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
4910            return false;
4911        }
4912    }
4913    if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
4914        if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
4915            attempts.remove(&victim);
4916        }
4917    }
4918    attempts.insert(*source, now);
4919    true
4920}
4921
4922/// Verify + store an inbound commitment from a gossip peer.
4923///
4924/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
4925/// the bootstrap-sync loop. Drops the commitment unless all five gates
4926/// pass:
4927///   1. `source` is in our DHT routing table (sybil/churn cap).
4928///   2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
4929///      binding to the authenticated transport peer).
4930///   3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
4931///      (the embedded pubkey actually belongs to the claimed identity —
4932///      saorsa-core derives `PeerId = BLAKE3(pubkey)`).
4933///   4. `verify_commitment_signature(commitment)` succeeds against the
4934///      embedded public key. The signed payload binds the pubkey, so an
4935///      adversary cannot swap the key while keeping the body.
4936///   5. The cache has room or this is an update for an existing entry
4937///      (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
4938///
4939/// On all-pass, the commitment is stored as the auditor's per-peer
4940/// "last known commitment" for use as `expected_commitment_hash` in
4941/// future audits.
4942///
4943/// Failures (no commitment / mismatched peer id / bad signature) are
4944/// silent drops — gossip is best-effort and a malformed commitment from
4945/// one peer should not affect anything else.
4946///
4947/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
4948/// or not its root changed), so the caller can run a probabilistic,
4949/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
4950/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
4951/// being auditable, so it cannot pass one audit and then delete data while
4952/// re-gossiping the same root forever. The cooldown + probability bound the
4953/// audit frequency. Returns `None` only if the commitment was dropped (failed a
4954/// gate) or there is nothing to pin.
4955///
4956/// Handle a capable peer gossiping `None` (a commitment downgrade).
4957///
4958/// A capable peer that previously gossiped a commitment but now gossips `None`
4959/// is trying to drop off the audit path. Within the answerability window we keep
4960/// the cached commitment pinned AND return it as an audit target so this gossip
4961/// still schedules a subtree audit against the peer's last known commitment — if
4962/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
4963/// the trigger MUST fire here or the downgrade is never re-challenged).
4964///
4965/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
4966/// honours for its own retired commitment: once that elapses since we last
4967/// received the peer's commitment, an honest peer has legitimately retired that
4968/// root (its responder side `retire_current`s and lets it age out) and can no
4969/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
4970/// failure, so we then forget the cached commitment (keeping the sticky
4971/// `commitment_capable` bit) and stop pinning it.
4972async fn handle_commitment_downgrade(
4973    source: &PeerId,
4974    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4975) -> Option<AuditTarget> {
4976    let now = Instant::now();
4977    let cached = {
4978        let map = last_commitment_by_peer.read().await;
4979        map.get(source).and_then(|rec| {
4980            if !rec.commitment_capable {
4981                return None;
4982            }
4983            let last = rec.last_commitment()?;
4984            let pin = rec.commitment_hash()?;
4985            let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
4986            Some((pin, last.key_count, fresh))
4987        })
4988    };
4989    match cached {
4990        Some((pin, key_count, true)) => {
4991            warn!(
4992                "ingest_peer_commitment: commitment-capable peer {source} sent None \
4993                 (downgrade attempt); auditing against its last cached commitment"
4994            );
4995            Some(AuditTarget {
4996                pin_hash: pin,
4997                key_count,
4998            })
4999        }
5000        Some((_, _, false)) => {
5001            // Cached commitment has aged past the answerability window — forget
5002            // it so we stop pinning a root the peer is no longer obliged to
5003            // answer. Keep `commitment_capable` (sticky). Re-check freshness
5004            // UNDER the write lock (compare-and-clear): a concurrent valid gossip
5005            // from this peer may have refreshed `received_at` in the gap between
5006            // our read and write locks; if so, leave its fresh commitment intact.
5007            if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
5008                let still_stale =
5009                    now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
5010                if still_stale {
5011                    rec.clear_commitment();
5012                    debug!(
5013                        "ingest_peer_commitment: capable peer {source} sent None and its cached \
5014                         commitment aged past the answerability TTL; forgetting it"
5015                    );
5016                }
5017            }
5018            None
5019        }
5020        None => None,
5021    }
5022}
5023
5024async fn ingest_peer_commitment(
5025    source: &PeerId,
5026    commitment: Option<&StorageCommitment>,
5027    p2p_node: &Arc<P2PNode>,
5028    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
5029    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
5030    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
5031) -> Option<AuditTarget> {
5032    let Some(c) = commitment else {
5033        return handle_commitment_downgrade(source, last_commitment_by_peer).await;
5034    };
5035    // RT-membership gate: only accept commitments from peers in our
5036    // routing table. Off-RT senders (sybils, drive-by relays) cannot
5037    // populate the cache, which closes the hole where a flood of
5038    // off-RT identities could fill the cap and evict honest
5039    // peers. The neighbor-sync request handler applies the same gate
5040    // before admitting inbound replication hints (see neighbor_sync.rs
5041    // `sender_in_rt`); we mirror that policy here for the commitment
5042    // piggyback.
5043    if !p2p_node.dht_manager().is_in_routing_table(source).await {
5044        debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
5045        return None;
5046    }
5047    // Peer-id binding: the commitment's claimed sender must match the
5048    // authenticated transport peer (`source`). Defeats relay/replay
5049    // and also pins which embedded public key we are about to verify
5050    // against — the verify itself trusts the embedded key, so the
5051    // peer-id binding is the link to a real identity.
5052    if &c.sender_peer_id != source.as_bytes() {
5053        warn!(
5054            "ingest_peer_commitment: sender_peer_id mismatch from {source} \
5055             (dropped, possible relay attempt)"
5056        );
5057        return None;
5058    }
5059    // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
5060    // BLAKE3(pubkey_bytes). Without this check, a responder could sign
5061    // with a throwaway key they own and lie about which identity it
5062    // belongs to (the embedded-key signature would verify trivially).
5063    let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
5064    if derived_peer_id != c.sender_peer_id {
5065        warn!(
5066            "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
5067             {source} (dropped, throwaway-key attack)"
5068        );
5069        return None;
5070    }
5071    // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
5072    // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
5073    // sybil/RT-membership-bypassing peer that flooded valid-looking
5074    // gossip would otherwise burn CPU on every message. The rate
5075    // limit is checked AFTER cheap structural gates (RT, peer-id
5076    // binding, pubkey-binding) and BEFORE the expensive sig verify.
5077    //
5078    // Tracked in `sig_verify_attempts` (separate from
5079    // last_commitment_by_peer) so EVERY attempt — successful or not —
5080    // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
5081    // would skip the cap for peers we've never successfully verified,
5082    // letting a flood of invalid-but-structurally-plausible gossips
5083    // burn CPU.
5084    let now = Instant::now();
5085    if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
5086        debug!(
5087            "ingest_peer_commitment: rate-limited sig verify from {source} \
5088             (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
5089        );
5090        return None;
5091    }
5092    // Signature verify, using the public key embedded in the commitment
5093    // itself. The pubkey is bound by the signature payload (see
5094    // commitment_signed_payload) so an adversary cannot keep the body
5095    // and swap the key to one they hold the secret for.
5096    if !crate::replication::commitment::verify_commitment_signature(c) {
5097        warn!(
5098            "ingest_peer_commitment: signature did not verify under embedded key for {source} \
5099             (dropped, forged commitment)"
5100        );
5101        return None;
5102    }
5103    // The new commitment's hash, used to store and to pin for the audit target.
5104    let new_hash = commitment_hash(c);
5105    let mut map = last_commitment_by_peer.write().await;
5106    // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
5107    // evict an arbitrary existing entry to make room. Updates for peers
5108    // already in the map are always accepted (they replace, not grow).
5109    if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
5110        // Drop one arbitrary entry. HashMap iter order is random which
5111        // is fine — over time PeerRemoved cleanup keeps the working set
5112        // anchored on the real RT membership; this cap only fires under
5113        // active flooding attempts.
5114        if let Some(victim) = map.keys().next().copied() {
5115            map.remove(&victim);
5116            warn!(
5117                "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
5118                 evicted {victim} to admit {source}"
5119            );
5120        }
5121    }
5122    // Preserve sticky commitment_capable across updates — once true,
5123    // always true. New entries start with capable = true (we just
5124    // verified a valid commitment from this peer).
5125    map.entry(*source)
5126        .and_modify(|r| {
5127            // set_commitment refreshes the cached hash (§13) alongside the
5128            // commitment + received_at so they never drift.
5129            r.set_commitment(c.clone(), now);
5130            r.last_sig_verify_at = now;
5131            r.commitment_capable = true; // sticky-redundant but explicit
5132        })
5133        .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
5134    drop(map);
5135    // Record the sticky "ever v12-capable" bit in a set independent of
5136    // `last_commitment_by_peer` (whose entries can be evicted by
5137    // `PeerRemoved` and the sybil cap). This is what the §3 audit
5138    // shield and the §6 holder-eligibility closure consult to decide
5139    // whether the peer is expected to speak v12.
5140    //
5141    // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
5142    // identity-rotation attacks: once full, new entries are refused.
5143    // Refusal degrades over-cap peers to the behaviour before this set
5144    // existed (treated as legacy on rejoin), which is not a security
5145    // regression and preserves the historic set stable.
5146    {
5147        let mut set = ever_capable_peers.write().await;
5148        if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
5149            set.insert(*source);
5150        } else {
5151            warn!(
5152                "ingest_peer_commitment: ever_capable_peers at cap \
5153                 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
5154            );
5155        }
5156    }
5157    // Return an audit target for EVERY valid stored commitment (changed or
5158    // not), so the caller's cooldown+probability-gated trigger keeps a
5159    // stable-keyset peer auditable over time (ADR-0002). Only a serialization
5160    // failure (new_hash == None, unreachable for a real commitment) yields None.
5161    new_hash.map(|pin_hash| AuditTarget {
5162        pin_hash,
5163        key_count: c.key_count,
5164    })
5165}
5166
5167// ---------------------------------------------------------------------------
5168// Storage-bound audit (v12) — responder commitment rotation
5169// ---------------------------------------------------------------------------
5170
5171/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
5172/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
5173/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
5174async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
5175    let bytes = match tokio::fs::read(path).await {
5176        Ok(b) => b,
5177        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
5178            debug!(
5179                "Commitment retention: no snapshot at {} (fresh start)",
5180                path.display()
5181            );
5182            return;
5183        }
5184        Err(e) => {
5185            warn!(
5186                "Commitment retention: failed to read {}: {e}",
5187                path.display()
5188            );
5189            return;
5190        }
5191    };
5192    if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
5193        state.restore(&persisted);
5194        info!(
5195            "Commitment retention: reloaded {} slot(s) from {}",
5196            state.retained_slot_count(),
5197            path.display()
5198        );
5199    } else {
5200        warn!(
5201            "Commitment retention: corrupt snapshot at {}; starting with empty retention",
5202            path.display()
5203        );
5204    }
5205}
5206
5207/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
5208/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
5209/// needless disk writes on idle nodes. On success updates `last` to the bytes
5210/// written; on a serialization/write error the existing on-disk snapshot is left
5211/// intact (never truncated).
5212async fn persist_retention_if_changed(
5213    state: &ResponderCommitmentState,
5214    path: &Path,
5215    last: &mut Option<Vec<u8>>,
5216) {
5217    let Some(bytes) = state.snapshot().to_bytes() else {
5218        warn!("Commitment retention: serialization failed; keeping previous snapshot");
5219        return;
5220    };
5221    if last.as_deref() == Some(bytes.as_slice()) {
5222        return;
5223    }
5224    if write_retention_atomic(path, bytes.clone()).await {
5225        *last = Some(bytes);
5226    }
5227}
5228
5229/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
5230/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
5231/// success. Only the retention-persist loop writes this path, so a fixed temp
5232/// name is safe.
5233async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
5234    let path = path.to_path_buf();
5235    let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
5236        let tmp = path.with_extension("tmp");
5237        std::fs::write(&tmp, &bytes)?;
5238        std::fs::File::open(&tmp)?.sync_all()?;
5239        std::fs::rename(&tmp, &path)?;
5240        // Fsync the directory so the rename (the durable-commit point) is not
5241        // lost on a crash right after it. An empty parent (relative filename)
5242        // means the current directory.
5243        let dir = path
5244            .parent()
5245            .filter(|p| !p.as_os_str().is_empty())
5246            .unwrap_or_else(|| Path::new("."));
5247        std::fs::File::open(dir)?.sync_all()?;
5248        Ok(())
5249    })
5250    .await;
5251    match res {
5252        Ok(Ok(())) => true,
5253        Ok(Err(e)) => {
5254            warn!("Commitment retention: persist failed: {e}");
5255            false
5256        }
5257        Err(e) => {
5258            warn!("Commitment retention: persist task join failed: {e}");
5259            false
5260        }
5261    }
5262}
5263
5264/// Read the current LMDB key set, build + sign a fresh
5265/// `StorageCommitment`, and rotate it into `state` as the new `current`.
5266/// The prior `current` is demoted to `previous`; the prior `previous` is
5267/// dropped (per `ResponderCommitmentState::rotate`).
5268///
5269/// For content-addressed chunks (Autonomi's chunk store), `address ==
5270/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
5271/// re-read each chunk's bytes to compute the leaf hash.
5272///
5273/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
5274/// rotate. The auditor side handles "no commitment for this peer" by
5275/// falling back to the legacy plain-digest audit path.
5276async fn rebuild_and_rotate_commitment(
5277    storage: &Arc<LmdbStorage>,
5278    identity: &Arc<NodeIdentity>,
5279    state: &Arc<ResponderCommitmentState>,
5280    p2p: &Arc<P2PNode>,
5281    config: &Arc<ReplicationConfig>,
5282) -> Result<()> {
5283    let stored_keys = storage
5284        .all_keys()
5285        .await
5286        .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
5287
5288    // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
5289    // everything currently on disk ("hold"). This is the half of the retention
5290    // contract that lets out-of-range chunks age out: a key that has left our
5291    // close group is excluded from the NEXT commitment, so once its last gossip
5292    // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
5293    // set, `ResponderCommitmentState::is_held` goes false,
5294    // and the pruner (which until then vetoes its deletion) reclaims it. Without
5295    // this filter the pruner's reprieve would keep re-committing stale keys
5296    // forever (the rebuild reads all_keys, so a retained-on-disk key would be
5297    // re-committed and re-gossiped every rotation — a permanent pin).
5298    let storage_empty = stored_keys.is_empty();
5299    let self_id = *p2p.peer_id();
5300    let mut keys = Vec::with_capacity(stored_keys.len());
5301    for k in stored_keys {
5302        if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
5303            keys.push(k);
5304        }
5305    }
5306
5307    if keys.is_empty() {
5308        if storage_empty {
5309            // Storage is genuinely empty — there is nothing to answer for, so
5310            // drop the previously advertised commitment immediately. Keeping it
5311            // would leave remote auditors pinning a hash we can never satisfy
5312            // again (the bytes are gone).
5313            if state.retained_slot_count() > 0 {
5314                debug!("Commitment rotation: storage empty, clearing retained slots");
5315                state.clear_all();
5316            }
5317            return Ok(());
5318        }
5319        // Bytes are still on disk but no key is currently in range. We must NOT
5320        // clear retention here: a peer may still be pinning a root we gossiped
5321        // moments ago and could demand its bytes in a round-2 challenge, which
5322        // we can still answer (the bytes are present). But we must STOP
5323        // advertising the stale commitment: retire it so `current()` returns
5324        // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
5325        // The retired slot then ages out by its gossip-answerability TTL while
5326        // remaining answerable for in-flight pins until then. Once it ages out,
5327        // `is_held` flips false and the pruner reclaims the now-uncommitted,
5328        // out-of-range chunks. (Calling `age_out` alone would leave `current()`
5329        // pointing at the stale root, which the gossip loop would keep
5330        // re-stamping — pinning its keys forever.)
5331        debug!(
5332            "Commitment rotation: no responsible keys to commit to; retiring current commitment \
5333             (stays answerable until its gossip TTL lapses, bytes still on disk)"
5334        );
5335        state.retire_current();
5336        return Ok(());
5337    }
5338
5339    // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
5340    // to more than the protocol limit; auditor would reject the
5341    // commitment otherwise).
5342    let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
5343    if keys.len() > cap {
5344        warn!(
5345            "Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
5346             truncating — investigate as this likely means a misconfiguration",
5347            keys.len(),
5348            cap
5349        );
5350    }
5351
5352    // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
5353    // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
5354    // full chunk re-read per rotation.
5355    //
5356    // Consequence to be precise about: because the leaf is `(key, key)`,
5357    // the Merkle root commits to the SET OF KEYS, not to the bytes. The
5358    // commitment therefore binds "which keys I claim to hold"; it does NOT
5359    // by itself prove byte possession. Byte possession is enforced by the
5360    // audit-verify path, which recomputes `bytes_hash == BLAKE3(local_bytes)`
5361    // and the per-key digest against the AUDITOR'S OWN local copy of the
5362    // bytes — so a responder that holds the key list but dropped the bytes
5363    // still fails (`missing bytes for committed key` / digest mismatch).
5364    // This is sound ONLY while keys are content addresses. If this module
5365    // is ever reused for non-content-addressed records (`bytes_hash != key`),
5366    // the `(k, k)` shortcut would let a byte-less node forge a valid root and
5367    // MUST be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
5368    let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
5369
5370    // No-op-rotation guard: compute just the Merkle root from `entries`
5371    // and compare against the currently-advertised commitment's root.
5372    // If they match, the key set is unchanged and a new rotation would
5373    // only swap a randomized ML-DSA signature for a fresh one — same
5374    // content, different commitment_hash. That invalidates every
5375    // outstanding `recent_provers` credit on this node across the
5376    // close group with no security benefit, breaking steady-state
5377    // quorum liveness on large nodes that can't re-audit every key
5378    // every rotation interval. Skip the rotation entirely when the
5379    // tree is unchanged.
5380    // Build the tree ONCE here (moving `entries`): it serves both the no-op
5381    // root check below and, if we proceed, the signed commitment via
5382    // `build_from_tree` (§11 — previously the tree was built here and AGAIN
5383    // inside `BuiltCommitment::build`).
5384    let candidate_tree = commitment::MerkleTree::build(entries)
5385        .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
5386    let candidate_root = candidate_tree.root();
5387    if let Some(current) = state.current() {
5388        if current.commitment().root == candidate_root {
5389            debug!(
5390                "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
5391                hex::encode(candidate_root)
5392            );
5393            // Even though we skip re-signing (to avoid invalidating holder
5394            // credit), retention must still advance on the wall clock: a
5395            // previously-gossiped commitment that holds a now-out-of-range key
5396            // must be able to age out of the answerability window even when the
5397            // committed key set is frozen here for many rotations. Without this,
5398            // the no-op guard would pin a stale slot — and its key — forever.
5399            state.age_out();
5400            return Ok(());
5401        }
5402    }
5403
5404    let sk_bytes = identity.secret_key_bytes().to_vec();
5405    let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
5406        .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
5407    let pk_bytes = identity.public_key().as_bytes().to_vec();
5408    let peer_id_bytes = *p2p.peer_id().as_bytes();
5409
5410    let built = commitment_state::BuiltCommitment::build_from_tree(
5411        candidate_tree,
5412        &peer_id_bytes,
5413        &sk,
5414        &pk_bytes,
5415    )
5416    .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
5417
5418    let hash = hex::encode(built.hash());
5419    let key_count = built.commitment().key_count;
5420    state.rotate(built);
5421    info!("Storage commitment rotated: hash={hash} key_count={key_count}");
5422    Ok(())
5423}
5424
5425#[cfg(test)]
5426#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
5427mod tests {
5428    use super::*;
5429
5430    fn test_peer(b: u8) -> PeerId {
5431        let mut bytes = [0u8; 32];
5432        bytes[0] = b;
5433        PeerId::from_bytes(bytes)
5434    }
5435
5436    fn test_key(b: u8) -> crate::ant_protocol::XorName {
5437        let mut k = [0u8; 32];
5438        k[0] = b;
5439        k
5440    }
5441
5442    #[tokio::test]
5443    async fn audit_responder_admission_reports_per_peer_cap_full() {
5444        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
5445        let inflight = Arc::new(RwLock::new(HashMap::new()));
5446        let peer = test_peer(0xA1);
5447
5448        let mut guards = Vec::new();
5449        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
5450            match admit_audit_responder(&semaphore, &inflight, &peer).await {
5451                Ok(guard) => guards.push(guard),
5452                Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
5453            }
5454        }
5455
5456        let Err(err) = admit_audit_responder(&semaphore, &inflight, &peer).await else {
5457            panic!("admission should fail once per-peer cap is full");
5458        };
5459        assert_eq!(err.reason, AuditResponderRejectReason::PerPeerCapFull);
5460        assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
5461        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
5462        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
5463
5464        drop(guards);
5465    }
5466
5467    #[tokio::test]
5468    async fn audit_responder_admission_reports_global_pool_full() {
5469        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
5470        let inflight = Arc::new(RwLock::new(HashMap::new()));
5471        let peer = test_peer(0xA2);
5472
5473        let mut held_global_permits = Vec::new();
5474        for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
5475            held_global_permits.push(
5476                Arc::clone(&semaphore)
5477                    .try_acquire_owned()
5478                    .expect("test should be able to exhaust the global pool"),
5479            );
5480        }
5481
5482        let Err(err) = admit_audit_responder(&semaphore, &inflight, &peer).await else {
5483            panic!("admission should fail once global pool is full");
5484        };
5485        assert_eq!(err.reason, AuditResponderRejectReason::GlobalPoolFull);
5486        assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
5487        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
5488        assert_eq!(err.peer_inflight, 0);
5489        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
5490
5491        drop(held_global_permits);
5492    }
5493
5494    #[test]
5495    fn first_audit_terminal_outcomes_are_stable() {
5496        let peer = test_peer(1);
5497        let passed = AuditTickResult::Passed {
5498            challenged_peer: peer,
5499            keys_checked: 1,
5500        };
5501        let timed_out = AuditTickResult::Failed {
5502            evidence: FailureEvidence::AuditFailure {
5503                challenge_id: 1,
5504                challenged_peer: peer,
5505                confirmed_failed_keys: vec![test_key(1)],
5506                summary: crate::replication::types::AuditFailureSummary::default(),
5507                reason: AuditFailureReason::Timeout,
5508            },
5509        };
5510
5511        assert_eq!(
5512            first_audit_terminal_outcome(&passed),
5513            FirstAuditTerminalOutcome::Passed
5514        );
5515        assert_eq!(
5516            first_audit_terminal_outcome(&timed_out),
5517            FirstAuditTerminalOutcome::Timeout
5518        );
5519        assert_eq!(
5520            first_audit_terminal_outcome(&AuditTickResult::Idle),
5521            FirstAuditTerminalOutcome::Idle
5522        );
5523        assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
5524        assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
5525        assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
5526        assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
5527        assert_eq!(
5528            FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
5529            "insufficient_keys"
5530        );
5531        assert_eq!(
5532            FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
5533            "bootstrap_claim"
5534        );
5535    }
5536
5537    #[test]
5538    fn first_audit_queue_exposes_coalescing_and_capacity_eviction() {
5539        let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
5540        let first = MonetizedPinEvent {
5541            peer: test_peer(1),
5542            pin: [1; 32],
5543            key_count: 1,
5544            quote_ts: SystemTime::now(),
5545        };
5546        let replacement = MonetizedPinEvent {
5547            pin: [2; 32],
5548            ..first
5549        };
5550        let other_peer = MonetizedPinEvent {
5551            peer: test_peer(2),
5552            pin: [3; 32],
5553            ..first
5554        };
5555
5556        assert_eq!(
5557            queue_first_audit_event(&mut pending, first),
5558            FirstAuditQueueOutcome::Queued
5559        );
5560        assert_eq!(
5561            queue_first_audit_event(&mut pending, replacement),
5562            FirstAuditQueueOutcome::Coalesced
5563        );
5564        assert_eq!(
5565            queue_first_audit_event(&mut pending, other_peer),
5566            FirstAuditQueueOutcome::CapacityEvicted {
5567                peer: first.peer,
5568                pin: replacement.pin,
5569            }
5570        );
5571        assert_eq!(pending.len(), 1);
5572        assert_eq!(
5573            pending.peek(&other_peer.peer).map(|event| event.pin),
5574            Some([3; 32])
5575        );
5576    }
5577
5578    #[test]
5579    fn fresh_offer_runs_client_put_payment_checks() {
5580        assert_eq!(
5581            fresh_offer_payment_context(),
5582            VerificationContext::ClientPut
5583        );
5584    }
5585
5586    #[test]
5587    fn paid_notify_uses_paid_list_admission_payment_checks() {
5588        assert_eq!(
5589            paid_notify_payment_context(),
5590            VerificationContext::PaidListAdmission
5591        );
5592    }
5593
5594    /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
5595    /// signed quote inside the answerability window, fail-closed on BOTH ends so a
5596    /// stale or future/skewed client-forwarded quote cannot frame an honest node.
5597    #[test]
5598    fn monetized_quote_audit_window_fails_closed_both_ends() {
5599        let now = SystemTime::now();
5600        // Fresh (just quoted) and small future/past skew -> audited.
5601        assert!(quote_within_audit_window(now, now));
5602        assert!(quote_within_audit_window(
5603            now + Duration::from_secs(60),
5604            now
5605        ));
5606        assert!(quote_within_audit_window(
5607            now - Duration::from_secs(3600),
5608            now
5609        ));
5610        // Far future (badly-skewed / replayed) -> skipped.
5611        assert!(!quote_within_audit_window(
5612            now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_secs(60),
5613            now
5614        ));
5615        // Older than the window -> skipped (pin may have aged out).
5616        assert!(!quote_within_audit_window(
5617            now - GOSSIP_ANSWERABILITY_TTL,
5618            now
5619        ));
5620    }
5621
5622    #[test]
5623    fn audit_timeout_preserves_active_bootstrap_claim() {
5624        assert!(!audit_failure_clears_bootstrap_claim(
5625            &AuditFailureReason::Timeout
5626        ));
5627    }
5628
5629    fn strike_peer(b: u8) -> PeerId {
5630        let mut bytes = [0u8; 32];
5631        bytes[0] = b;
5632        PeerId::from_bytes(bytes)
5633    }
5634
5635    // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
5636    // cooldown must collapse a gossip flood into at most one audit per window.
5637
5638    #[test]
5639    fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
5640        let peer = strike_peer(1);
5641        let mut map: HashMap<PeerId, Instant> = HashMap::new();
5642        let t0 = Instant::now();
5643        // First gossip in the window passes; a burst of further gossips at the
5644        // same instant are all suppressed.
5645        assert!(cooldown_allows_audit(&mut map, &peer, t0));
5646        let mut passed = 1;
5647        for _ in 0..100 {
5648            if cooldown_allows_audit(&mut map, &peer, t0) {
5649                passed += 1;
5650            }
5651        }
5652        assert_eq!(
5653            passed, 1,
5654            "a flood at one instant must trigger exactly one audit"
5655        );
5656    }
5657
5658    // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
5659    // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
5660    // consumes the window. This is the property the isolated cooldown tests above
5661    // cannot see: they never sample the lottery, so a regression that reordered
5662    // the gates (sample probability first, only stamp the cooldown on a win)
5663    // would still pass them while breaking flood-resistance: a flood would then
5664    // re-roll the lottery on EVERY message until one won, multiplying audits.
5665    //
5666    // We model the exact production gate order (cooldown-then-lottery) with a
5667    // lottery driven by a fixed outcome instead of `gen_bool(..)`. The first
5668    // message LOSES the lottery; the remaining flood messages all WIN. With the
5669    // production order, the losing first ticket burns the window and every later
5670    // winner in the same window is blocked, so there are 0 audits this window. If
5671    // the gates were flipped, the second message's winning ticket would slip
5672    // through. The window only reopens after the cooldown elapses.
5673    //
5674    // FLIPS IF: the lottery is sampled before `cooldown_allows_audit` (a losing
5675    // ticket no longer consumes the window), re-enabling a flood-amplified audit
5676    // storm.
5677    #[test]
5678    fn losing_lottery_still_consumes_cooldown_window() {
5679        // Faithful re-implementation of the two gates in
5680        // `maybe_trigger_gossip_audit`, with the lottery outcome made
5681        // deterministic instead of `rand::thread_rng().gen_bool(..)`.
5682        // Calls the SHIPPED `audit_launch_decision` (the same function
5683        // `maybe_trigger_gossip_audit` uses), so a reorder of the two gates in
5684        // production fails this test — not a local reimplementation.
5685        let peer = strike_peer(3);
5686        let mut map: HashMap<PeerId, Instant> = HashMap::new();
5687        let t0 = Instant::now();
5688
5689        // First flooded message at t0 LOSES the lottery, but the cooldown is
5690        // stamped BEFORE the lottery is consulted, so the window is now consumed.
5691        assert!(
5692            !audit_launch_decision(&mut map, &peer, t0, false),
5693            "a losing ticket launches no audit"
5694        );
5695
5696        // 99 more flooded messages at the same instant would all WIN the lottery,
5697        // yet every one must be blocked by the cooldown the loser already stamped.
5698        // (If production sampled the lottery FIRST, these would each get a fresh
5699        // roll and audits would multiply — this assertion catches that reorder.)
5700        let mut audits = 0;
5701        for _ in 0..99 {
5702            if audit_launch_decision(&mut map, &peer, t0, true) {
5703                audits += 1;
5704            }
5705        }
5706        assert_eq!(
5707            audits, 0,
5708            "a losing first ticket must consume the window so no later flooded \
5709             message in the same window can audit"
5710        );
5711
5712        // The window only reopens after the cooldown elapses; the next winning
5713        // ticket then launches exactly one audit.
5714        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
5715        assert!(
5716            audit_launch_decision(&mut map, &peer, after, true),
5717            "after the cooldown a winning ticket audits again"
5718        );
5719    }
5720
5721    #[test]
5722    fn cooldown_lets_audit_through_after_the_window() {
5723        let peer = strike_peer(2);
5724        let mut map: HashMap<PeerId, Instant> = HashMap::new();
5725        let t0 = Instant::now();
5726        assert!(cooldown_allows_audit(&mut map, &peer, t0));
5727        // Within the window: suppressed.
5728        let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
5729        assert!(!cooldown_allows_audit(&mut map, &peer, within));
5730        // Past the window: allowed again.
5731        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
5732        assert!(cooldown_allows_audit(&mut map, &peer, after));
5733    }
5734
5735    #[test]
5736    fn cooldown_is_per_peer_independent() {
5737        let mut map: HashMap<PeerId, Instant> = HashMap::new();
5738        let t0 = Instant::now();
5739        // Different peers each get their own first-audit pass at the same instant.
5740        for i in 0..20u8 {
5741            assert!(
5742                cooldown_allows_audit(&mut map, &strike_peer(i), t0),
5743                "peer {i} should be auditable independently"
5744            );
5745        }
5746    }
5747
5748    #[test]
5749    fn audit_on_gossip_constants_match_adr() {
5750        // Tripwire on the ADR-locked tunables. The spot-check count sits at the
5751        // top of the auditor's 3..=5 band (the auditor clamps to that band, so
5752        // values above 5 would silently never be requested).
5753        assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
5754        assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
5755        assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
5756    }
5757
5758    // (d) A confirmed storage-integrity failure penalizes immediately and
5759    // revokes credit; it is not a timeout.
5760    #[test]
5761    fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
5762        assert!(audit_failure_clears_bootstrap_claim(
5763            &AuditFailureReason::DigestMismatch
5764        ));
5765        assert!(audit_failure_revokes_holder_credit(
5766            &AuditFailureReason::DigestMismatch
5767        ));
5768    }
5769
5770    /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
5771    /// uses: confirmed failures revoke credit, `Timeout` does not.
5772    #[test]
5773    fn confirmed_failures_revoke_credit_timeout_does_not() {
5774        for reason in [
5775            AuditFailureReason::MalformedResponse,
5776            AuditFailureReason::DigestMismatch,
5777            AuditFailureReason::KeyAbsent,
5778            AuditFailureReason::Rejected,
5779        ] {
5780            assert!(
5781                audit_failure_revokes_holder_credit(&reason),
5782                "confirmed failure {reason:?} must revoke holder credit"
5783            );
5784        }
5785        assert!(
5786            !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
5787            "Timeout must NOT revoke credit (single dropped packet != storage loss)"
5788        );
5789    }
5790
5791    /// Wiring test for the security fix: the helper the handler calls
5792    /// actually strips a credited peer on a confirmed failure
5793    /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
5794    /// Records genuine credit first so neither assertion is vacuous;
5795    /// this fails if `forget_peer` stops being called, or if the
5796    /// `Timeout` exclusion is dropped (both verified by mutation).
5797    #[test]
5798    fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
5799        let peer = test_peer(0xAB);
5800        let key = test_key(1);
5801        let hash = [0xCD; 32];
5802
5803        // Confirmed failure -> credit revoked.
5804        let mut provers = RecentProvers::new();
5805        provers.record_proof(key, peer, hash, Instant::now());
5806        assert!(
5807            provers.is_credited_holder(&key, &peer, &hash),
5808            "precondition: peer credited before failure"
5809        );
5810        apply_audit_failure_credit_revocation(
5811            &mut provers,
5812            &peer,
5813            &AuditFailureReason::DigestMismatch,
5814        );
5815        assert!(
5816            !provers.is_credited_holder(&key, &peer, &hash),
5817            "DigestMismatch must strip the peer's holder credit"
5818        );
5819
5820        // Timeout -> credit retained.
5821        let mut provers_timeout = RecentProvers::new();
5822        provers_timeout.record_proof(key, peer, hash, Instant::now());
5823        apply_audit_failure_credit_revocation(
5824            &mut provers_timeout,
5825            &peer,
5826            &AuditFailureReason::Timeout,
5827        );
5828        assert!(
5829            provers_timeout.is_credited_holder(&key, &peer, &hash),
5830            "Timeout must retain holder credit (deliberate liveness cushion)"
5831        );
5832    }
5833
5834    #[test]
5835    fn decoded_audit_failures_clear_active_bootstrap_claim() {
5836        for reason in [
5837            AuditFailureReason::MalformedResponse,
5838            AuditFailureReason::DigestMismatch,
5839            AuditFailureReason::KeyAbsent,
5840            AuditFailureReason::Rejected,
5841        ] {
5842            assert!(
5843                audit_failure_clears_bootstrap_claim(&reason),
5844                "decoded non-bootstrap failure {reason:?} should clear active claim"
5845            );
5846        }
5847    }
5848
5849    #[test]
5850    fn first_failed_key_label_truncates_to_16_hex_chars() {
5851        // The high-order 8 bytes of the XorName determine the label so an
5852        // operator can group audit-failures on the same chunk prefix.
5853        let mut key = [0u8; 32];
5854        key[0] = 0x18;
5855        key[7] = 0xff;
5856        // Low-order bytes (positions 8..32) are deliberately set to 0xAA
5857        // to verify they are NOT included in the label.
5858        for byte in &mut key[8..] {
5859            *byte = 0xAA;
5860        }
5861        let label = first_failed_key_label(&[key]);
5862        // Only the first 8 bytes are encoded, low-order bytes are dropped.
5863        assert_eq!(label, "0x18000000000000ff");
5864        assert_eq!(label.len(), "0x".len() + 16);
5865    }
5866
5867    #[test]
5868    fn first_failed_key_label_falls_back_when_empty() {
5869        // Should never happen in production (audit failure handling rejects
5870        // empty sets), but the formatter must still produce a valid label
5871        // so the log line doesn't contain a misleading default.
5872        assert_eq!(first_failed_key_label(&[]), "0x");
5873    }
5874
5875    #[test]
5876    fn first_failed_key_label_uses_first_key_only() {
5877        let first = [0x11u8; 32];
5878        let second = [0x22u8; 32];
5879        assert_eq!(
5880            first_failed_key_label(&[first, second]),
5881            format!("0x{}", hex::encode(&first[..8]))
5882        );
5883    }
5884}