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::FreshReplication
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 replication traffic summaries: the
1661    /// per-variant line (V2-623) and the per-peer top-10 served-bytes line
1662    /// (V2-684). Both read process-global counter tables maintained by the
1663    /// encode/decode and serve choke points in [`protocol`]; needs no engine
1664    /// state.
1665    fn start_traffic_summary_loop(&mut self) {
1666        let shutdown = self.shutdown.clone();
1667        let handle = tokio::spawn(async move {
1668            loop {
1669                tokio::select! {
1670                    () = shutdown.cancelled() => break,
1671                    () = tokio::time::sleep(std::time::Duration::from_secs(
1672                        TRAFFIC_SUMMARY_INTERVAL_SECS,
1673                    )) => {
1674                        protocol::log_traffic_summary();
1675                        protocol::log_served_peers_summary();
1676                    }
1677                }
1678            }
1679            debug!("Replication traffic summary loop shut down");
1680        });
1681        self.task_handles.push(handle);
1682    }
1683
1684    #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
1685    fn start_fetch_worker(&mut self) {
1686        let p2p = Arc::clone(&self.p2p_node);
1687        let storage = Arc::clone(&self.storage);
1688        let queues = Arc::clone(&self.queues);
1689        let config = Arc::clone(&self.config);
1690        let shutdown = self.shutdown.clone();
1691        let bootstrap_state = Arc::clone(&self.bootstrap_state);
1692        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
1693        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
1694        let concurrency = max_parallel_fetch();
1695
1696        info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
1697
1698        let handle = tokio::spawn(async move {
1699            // Each in-flight future yields (key, Option<FetchOutcome>) so we
1700            // always recover the key — even if the inner task panics.
1701            let mut in_flight = FuturesUnordered::<FetchFuture>::new();
1702
1703            loop {
1704                // Fill up to `concurrency` slots from the queue.
1705                {
1706                    let mut q = queues.write().await;
1707                    while in_flight.len() < concurrency {
1708                        let Some(candidate) = q.dequeue_fetch() else {
1709                            break;
1710                        };
1711                        let Some(&source) = candidate.sources.first() else {
1712                            warn!(
1713                                "Fetch candidate {} has no sources — dropping",
1714                                hex::encode(candidate.key)
1715                            );
1716                            continue;
1717                        };
1718                        q.start_fetch(candidate.key, source, candidate.sources.clone());
1719
1720                        let p2p = Arc::clone(&p2p);
1721                        let storage = Arc::clone(&storage);
1722                        let config = Arc::clone(&config);
1723                        let token = shutdown.clone();
1724                        let fetch_key = candidate.key;
1725                        in_flight.push(Box::pin(async move {
1726                            let handle = tokio::spawn(async move {
1727                                // Cancel-aware: abort when the engine shuts down.
1728                                tokio::select! {
1729                                    () = token.cancelled() => FetchOutcome {
1730                                        key: fetch_key,
1731                                        result: FetchResult::SourceFailed,
1732                                    },
1733                                    outcome = execute_single_fetch(
1734                                        p2p, storage, config, fetch_key, source,
1735                                    ) => outcome,
1736                                }
1737                            });
1738                            match handle.await {
1739                                Ok(outcome) => (outcome.key, Some(outcome)),
1740                                Err(e) => {
1741                                    error!(
1742                                        "Fetch task for {} panicked: {e}",
1743                                        hex::encode(fetch_key)
1744                                    );
1745                                    (fetch_key, None)
1746                                }
1747                            }
1748                        }));
1749                    }
1750                } // release queues write lock
1751
1752                if in_flight.is_empty() {
1753                    // No work — wait for new items or shutdown.
1754                    tokio::select! {
1755                        () = shutdown.cancelled() => break,
1756                        () = tokio::time::sleep(
1757                            std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
1758                        ) => continue,
1759                    }
1760                }
1761
1762                // Wait for the next fetch to complete and process the result.
1763                tokio::select! {
1764                    () = shutdown.cancelled() => break,
1765                    Some((key, maybe_outcome)) = in_flight.next() => {
1766                        let mut q = queues.write().await;
1767                        let terminal = if let Some(outcome) = maybe_outcome {
1768                            match outcome.result {
1769                                FetchResult::Stored => {
1770                                    q.complete_fetch(&key);
1771                                    true
1772                                }
1773                                FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
1774                                    if let Some(next_peer) = q.retry_fetch(&key) {
1775                                        // Spawn a new fetch task for the next source.
1776                                        let p2p = Arc::clone(&p2p);
1777                                        let storage = Arc::clone(&storage);
1778                                        let config = Arc::clone(&config);
1779                                        let token = shutdown.clone();
1780                                        let fetch_key = key;
1781                                        in_flight.push(Box::pin(async move {
1782                                            let handle = tokio::spawn(async move {
1783                                                tokio::select! {
1784                                                    () = token.cancelled() => FetchOutcome {
1785                                                        key: fetch_key,
1786                                                        result: FetchResult::SourceFailed,
1787                                                    },
1788                                                    outcome = execute_single_fetch(
1789                                                        p2p, storage, config, fetch_key, next_peer,
1790                                                    ) => outcome,
1791                                                }
1792                                            });
1793                                            match handle.await {
1794                                                Ok(outcome) => (outcome.key, Some(outcome)),
1795                                                Err(e) => {
1796                                                    error!(
1797                                                        "Fetch task for {} panicked: {e}",
1798                                                        hex::encode(fetch_key)
1799                                                    );
1800                                                    (fetch_key, None)
1801                                                }
1802                                            }
1803                                        }));
1804                                        false
1805                                    } else {
1806                                        q.complete_fetch(&key);
1807                                        true
1808                                    }
1809                                }
1810                            }
1811                        } else {
1812                            // Task panicked — reclaim the in-flight slot.
1813                            q.complete_fetch(&key);
1814                            true
1815                        };
1816
1817                        // Shrink bootstrap pending set on terminal exit.
1818                        if terminal {
1819                            drop(q); // release queues lock before acquiring bootstrap_state
1820                            if !bootstrap_state.read().await.is_drained() {
1821                                bootstrap_state.write().await.remove_key(&key);
1822                                let q = queues.read().await;
1823                                if bootstrap::check_bootstrap_drained(
1824                                    &bootstrap_state,
1825                                    &q,
1826                                )
1827                                .await
1828                                {
1829                                    complete_bootstrap(
1830                                        &is_bootstrapping,
1831                                        &bootstrap_complete_notify,
1832                                    ).await;
1833                                }
1834                            }
1835                        }
1836                    }
1837                }
1838            }
1839
1840            // Cancel and drain remaining in-flight fetches on shutdown.
1841            // The CancellationToken is already cancelled by this point, so
1842            // spawned tasks will see cancellation via their select! branches.
1843            while in_flight.next().await.is_some() {}
1844            debug!("Fetch worker shut down");
1845        });
1846        self.task_handles.push(handle);
1847    }
1848
1849    fn start_verification_worker(&mut self) {
1850        let p2p = Arc::clone(&self.p2p_node);
1851        let storage = Arc::clone(&self.storage);
1852        let queues = Arc::clone(&self.queues);
1853        let paid_list = Arc::clone(&self.paid_list);
1854        let config = Arc::clone(&self.config);
1855        let shutdown = self.shutdown.clone();
1856        let bootstrap_state = Arc::clone(&self.bootstrap_state);
1857        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
1858        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
1859        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
1860        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
1861        let recent_provers = Arc::clone(&self.recent_provers);
1862
1863        let handle = tokio::spawn(async move {
1864            loop {
1865                tokio::select! {
1866                    () = shutdown.cancelled() => break,
1867                    () = tokio::time::sleep(
1868                        std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
1869                    ) => {
1870                        let ctx = VerificationCycleContext {
1871                            p2p_node: &p2p,
1872                            paid_list: &paid_list,
1873                            storage: &storage,
1874                            queues: &queues,
1875                            config: &config,
1876                            bootstrap_state: &bootstrap_state,
1877                            is_bootstrapping: &is_bootstrapping,
1878                            bootstrap_complete_notify: &bootstrap_complete_notify,
1879                            last_commitment_by_peer: &last_commitment_by_peer,
1880                            ever_capable_peers: &ever_capable_peers,
1881                            recent_provers: &recent_provers,
1882                        };
1883                        run_verification_cycle(ctx).await;
1884                    }
1885                }
1886            }
1887            debug!("Verification worker shut down");
1888        });
1889        self.task_handles.push(handle);
1890    }
1891
1892    /// Gap 3: Run a one-shot bootstrap sync on startup.
1893    ///
1894    /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
1895    /// (indicating the routing table is populated) before snapshotting
1896    /// close neighbors. Falls back after a timeout so bootstrap nodes
1897    /// (which have no peers and therefore never receive the event) still
1898    /// proceed.
1899    ///
1900    /// After the gate, finds close neighbors, syncs with each in
1901    /// round-robin batches, admits returned hints into the verification
1902    /// pipeline, and tracks discovered keys for bootstrap drain detection.
1903    #[allow(clippy::too_many_lines)]
1904    fn start_bootstrap_sync(
1905        &mut self,
1906        dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
1907    ) {
1908        let p2p = Arc::clone(&self.p2p_node);
1909        let storage = Arc::clone(&self.storage);
1910        let paid_list = Arc::clone(&self.paid_list);
1911        let queues = Arc::clone(&self.queues);
1912        let config = Arc::clone(&self.config);
1913        let shutdown = self.shutdown.clone();
1914        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
1915        let bootstrap_state = Arc::clone(&self.bootstrap_state);
1916        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
1917        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
1918        let repair_proofs = Arc::clone(&self.repair_proofs);
1919        let my_commitment_state = Arc::clone(&self.commitment_state);
1920        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
1921        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
1922        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
1923
1924        let handle = tokio::spawn(async move {
1925            // Wait for DHT bootstrap to complete before snapshotting
1926            // neighbors. The routing table is empty until saorsa-core
1927            // finishes its FIND_NODE rounds and bucket refreshes.
1928            let gate = bootstrap::wait_for_bootstrap_complete(
1929                dht_events,
1930                config.bootstrap_complete_timeout_secs,
1931                &shutdown,
1932            )
1933            .await;
1934
1935            if gate == bootstrap::BootstrapGateResult::Shutdown {
1936                return;
1937            }
1938
1939            let self_id = *p2p.peer_id();
1940            let neighbors =
1941                neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
1942                    .await;
1943
1944            if neighbors.is_empty() {
1945                info!("Bootstrap sync: no close neighbors found, marking drained");
1946                bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
1947                complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
1948                return;
1949            }
1950
1951            let neighbor_count = neighbors.len();
1952            info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
1953
1954            // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
1955            for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
1956                if shutdown.is_cancelled() {
1957                    break;
1958                }
1959
1960                let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
1961                    batch,
1962                    &storage,
1963                    &paid_list,
1964                    &p2p,
1965                    config.close_group_size,
1966                    config.paid_list_close_group_size,
1967                )
1968                .await;
1969
1970                for peer in batch {
1971                    if shutdown.is_cancelled() {
1972                        break;
1973                    }
1974
1975                    // Re-read on each iteration so peers see current state.
1976                    let bootstrapping = *is_bootstrapping.read().await;
1977
1978                    bootstrap::increment_pending_requests(&bootstrap_state, 1).await;
1979
1980                    let hints = hints_by_peer.remove(peer).unwrap_or_default();
1981                    let outcome = neighbor_sync::sync_with_peer_with_hints(
1982                        peer,
1983                        &p2p,
1984                        &config,
1985                        bootstrapping,
1986                        hints,
1987                        // Atomically snapshot + mark-gossiped: emitted in the
1988                        // bootstrap-sync request, so we stay answerable for it
1989                        // (ADR-0002). One critical section avoids a TOCTOU where a
1990                        // concurrent retire/rotate drops the slot between read and
1991                        // mark.
1992                        my_commitment_state
1993                            .current_for_gossip()
1994                            .map(|b| b.commitment().clone()),
1995                    )
1996                    .await;
1997
1998                    bootstrap::decrement_pending_requests(&bootstrap_state, 1).await;
1999
2000                    if let Some(outcome) = outcome {
2001                        // Ingest the peer's piggybacked commitment from the
2002                        // response (same verification as the request path).
2003                        // Bootstrap is the FIRST gossip we receive from most
2004                        // peers, so this populates last_commitment_by_peer.
2005                        //
2006                        // We intentionally do NOT trigger a gossip-audit here:
2007                        // during bootstrap this node may itself still be
2008                        // bootstrapping (audits are gated on that), and the
2009                        // close-group/RT view is not yet stable. The peer is
2010                        // audited on the first STEADY-STATE neighbor-sync round
2011                        // after bootstrap drains (request + response paths both
2012                        // trigger), which is within one sync cycle — so caching
2013                        // the commitment here is sufficient and there is no
2014                        // coverage gap (ADR-0002).
2015                        ingest_peer_commitment(
2016                            peer,
2017                            outcome.response.commitment.as_ref(),
2018                            &p2p,
2019                            &last_commitment_by_peer,
2020                            &ever_capable_peers,
2021                            &sig_verify_attempts,
2022                        )
2023                        .await; // sig_verify_attempts in scope from line ~1080
2024
2025                        if !outcome.response.bootstrapping {
2026                            record_sent_replica_hints(
2027                                peer,
2028                                &outcome.sent_replica_hints,
2029                                &repair_proofs,
2030                                &sync_cycle_epoch,
2031                            )
2032                            .await;
2033                            // Admit hints into verification pipeline.
2034                            let outcome = admit_and_queue_hints(
2035                                &self_id,
2036                                peer,
2037                                &outcome.response.replica_hints,
2038                                &outcome.response.paid_hints,
2039                                &p2p,
2040                                &config,
2041                                &storage,
2042                                &paid_list,
2043                                &queues,
2044                            )
2045                            .await;
2046
2047                            // Track discovered keys for drain detection.
2048                            if !outcome.discovered.is_empty() {
2049                                bootstrap::track_discovered_keys(
2050                                    &bootstrap_state,
2051                                    &outcome.discovered,
2052                                )
2053                                .await;
2054                            }
2055
2056                            // Record / retire capacity rejections so the
2057                            // drain check correctly reflects whether each
2058                            // source still owes us re-hinted work after
2059                            // queue overflow.
2060                            if outcome.capacity_rejected_count > 0 {
2061                                bootstrap::note_capacity_rejected(&bootstrap_state, *peer).await;
2062                            } else {
2063                                bootstrap::clear_capacity_rejected(&bootstrap_state, peer).await;
2064                            }
2065                        }
2066                    }
2067                }
2068            }
2069
2070            // Check drain condition.
2071            {
2072                let q = queues.read().await;
2073                if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
2074                    complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
2075                }
2076            }
2077
2078            info!("Bootstrap sync completed");
2079        });
2080        self.task_handles.push(handle);
2081    }
2082}
2083
2084// ===========================================================================
2085// Free functions for background tasks
2086// ===========================================================================
2087
2088/// Which ceiling rejected an audit-responder admission attempt.
2089///
2090/// Stable, machine-readable so a production log-scrape can bucket drops by
2091/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
2092/// single opaque "capacity reached" line; this splits the two distinct causes
2093/// so the next such investigation can tell a global-pool exhaustion (the whole
2094/// node is saturated) from a per-peer cap hit (one source is self-throttling)
2095/// without re-instrumenting.
2096///
2097/// This branch runs a SINGLE shared audit-responder pool for all challenge
2098/// kinds (responsible / subtree / byte), so there is no separate slow/fast
2099/// pool to distinguish here — the `kind=` log field already separates the
2100/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
2101/// dedicated slow pool is later split out, add its variants here.
2102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2103enum AuditResponderRejectReason {
2104    /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
2105    /// free; the per-peer cap was not the binding constraint.
2106    GlobalPoolFull,
2107    /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
2108    /// share, so the global permit was never attempted.
2109    PerPeerCapFull,
2110}
2111
2112impl AuditResponderRejectReason {
2113    /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
2114    /// frozen — production log tooling greps for them.
2115    fn as_str(self) -> &'static str {
2116        match self {
2117            Self::GlobalPoolFull => "global_pool_full",
2118            Self::PerPeerCapFull => "per_peer_cap_full",
2119        }
2120    }
2121}
2122
2123/// Why an audit-responder admission attempt failed, with the decision-time
2124/// capacity counters that let a drop be logged with full context.
2125///
2126/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
2127/// decision was made (the two ceilings are read under different locks, so they
2128/// are not a single atomic view), but they are exact enough to tell a saturated
2129/// node from a single self-throttling flooder.
2130#[derive(Debug, Clone, Copy)]
2131struct AuditResponderAdmissionFailure {
2132    reason: AuditResponderRejectReason,
2133    /// Global permits in use across the whole engine at decision time.
2134    global_inflight: usize,
2135    /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
2136    global_limit: usize,
2137    /// In-flight audit responders already held for `source` at decision time.
2138    peer_inflight: u32,
2139    /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
2140    peer_limit: u32,
2141}
2142
2143impl fmt::Display for AuditResponderAdmissionFailure {
2144    /// Renders the stable `reason=... global_inflight=... global_limit=...
2145    /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
2146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2147        write!(
2148            f,
2149            "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
2150            self.reason.as_str(),
2151            self.global_inflight,
2152            self.global_limit,
2153            self.peer_inflight,
2154            self.peer_limit,
2155        )
2156    }
2157}
2158
2159/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
2160/// on drop, decrements the PER-PEER in-flight count. Moving this into the
2161/// spawned task ties both bounds to the task's exact lifetime — no manual
2162/// decrement to forget on an early return or panic.
2163struct AuditResponderGuard {
2164    _permit: tokio::sync::OwnedSemaphorePermit,
2165    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
2166    peer: PeerId,
2167}
2168
2169impl Drop for AuditResponderGuard {
2170    fn drop(&mut self) {
2171        // Decrement (and prune to keep the map bounded) without blocking the
2172        // async runtime: a short lock on a tiny map.
2173        //
2174        // Fast path: if the (uncontended, tiny) lock is free, decrement inline
2175        // with no spawn. Otherwise defer to a task — but only if a runtime is
2176        // actually current, so `Drop` during shutdown (no runtime) can never
2177        // panic. A missed decrement at shutdown is harmless: the whole map is
2178        // being dropped with the engine.
2179        let peer = self.peer;
2180        if let Ok(mut map) = self.inflight.try_write() {
2181            if let Some(n) = map.get_mut(&peer) {
2182                *n = n.saturating_sub(1);
2183                if *n == 0 {
2184                    map.remove(&peer);
2185                }
2186            }
2187            return;
2188        }
2189        if let Ok(handle) = tokio::runtime::Handle::try_current() {
2190            let inflight = Arc::clone(&self.inflight);
2191            handle.spawn(async move {
2192                let mut map = inflight.write().await;
2193                if let Some(n) = map.get_mut(&peer) {
2194                    *n = n.saturating_sub(1);
2195                    if *n == 0 {
2196                        map.remove(&peer);
2197                    }
2198                }
2199            });
2200        }
2201    }
2202}
2203
2204/// Try to admit one audit-responder task for `source`: take a global permit AND
2205/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
2206/// its decision-time counters (caller drops the challenge, leaving the remote
2207/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
2208/// so one flooder can neither exhaust the global pool's effect on others nor
2209/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
2210/// log exactly WHY the drop happened rather than a single opaque "capacity
2211/// reached".
2212async fn admit_audit_responder(
2213    semaphore: &Arc<Semaphore>,
2214    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
2215    source: &PeerId,
2216) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
2217    let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
2218    let peer_limit = MAX_AUDIT_RESPONSES_PER_PEER;
2219    // `available_permits()` is a cheap atomic load; `global_limit - available`
2220    // is the best-effort in-flight count at decision time. Not synchronized with
2221    // the per-peer lock, so it is a snapshot, not a single atomic view.
2222    let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
2223
2224    // Per-peer cap first (cheap, and the fairness-critical bound), committed
2225    // under the write lock so concurrent challenges from the same peer can't
2226    // both slip past the cap.
2227    {
2228        let mut map = inflight.write().await;
2229        let entry = map.entry(*source).or_insert(0);
2230        if *entry >= peer_limit {
2231            let peer_inflight = *entry;
2232            drop(map); // release before the (unrelated) semaphore read
2233            return Err(AuditResponderAdmissionFailure {
2234                reason: AuditResponderRejectReason::PerPeerCapFull,
2235                global_inflight: global_inflight(semaphore),
2236                global_limit,
2237                peer_inflight,
2238                peer_limit,
2239            });
2240        }
2241        *entry += 1;
2242    }
2243    // Then the global ceiling. If it's exhausted, give back the per-peer slot we
2244    // just claimed so it isn't leaked.
2245    let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
2246        let peer_inflight = {
2247            let mut map = inflight.write().await;
2248            map.remove(source).map_or(0, |n| {
2249                // Report the per-peer occupancy AFTER releasing our rolled-back
2250                // slot: the share still held by this source's other in-flight
2251                // tasks (below the cap, since the per-peer check passed).
2252                let remaining = n.saturating_sub(1);
2253                if remaining > 0 {
2254                    map.insert(*source, remaining);
2255                }
2256                remaining
2257            })
2258        };
2259        return Err(AuditResponderAdmissionFailure {
2260            reason: AuditResponderRejectReason::GlobalPoolFull,
2261            global_inflight: global_inflight(semaphore),
2262            global_limit,
2263            peer_inflight,
2264            peer_limit,
2265        });
2266    };
2267    Ok(AuditResponderGuard {
2268        _permit: permit,
2269        inflight: Arc::clone(inflight),
2270        peer: *source,
2271    })
2272}
2273
2274/// Handle an incoming replication protocol message.
2275///
2276/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
2277/// request-response path and the response must be sent via `send_response`
2278/// so saorsa-core can route it back to the waiting `send_request` caller.
2279#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
2280async fn handle_replication_message(
2281    source: &PeerId,
2282    data: &[u8],
2283    p2p_node: &Arc<P2PNode>,
2284    storage: &Arc<LmdbStorage>,
2285    paid_list: &Arc<PaidList>,
2286    payment_verifier: &Arc<PaymentVerifier>,
2287    queues: &Arc<RwLock<ReplicationQueues>>,
2288    config: &ReplicationConfig,
2289    is_bootstrapping: &Arc<RwLock<bool>>,
2290    bootstrap_state: &Arc<RwLock<BootstrapState>>,
2291    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
2292    sync_cycle_epoch: &Arc<RwLock<u64>>,
2293    repair_proofs: &Arc<RwLock<RepairProofs>>,
2294    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
2295    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
2296    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
2297    my_commitment_state: &Arc<ResponderCommitmentState>,
2298    gossip_audit: &GossipAuditTrigger,
2299    audit_responder_semaphore: &Arc<Semaphore>,
2300    audit_responder_inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
2301    rr_message_id: Option<&str>,
2302) -> Result<()> {
2303    let msg = ReplicationMessage::decode(data)
2304        .map_err(|e| Error::Protocol(format!("Failed to decode replication message: {e}")))?;
2305
2306    match msg.body {
2307        ReplicationMessageBody::FreshReplicationOffer(ref offer) => {
2308            handle_fresh_offer(
2309                source,
2310                offer,
2311                storage,
2312                paid_list,
2313                payment_verifier,
2314                p2p_node,
2315                config,
2316                msg.request_id,
2317                rr_message_id,
2318            )
2319            .await
2320        }
2321        ReplicationMessageBody::PaidNotify(ref notify) => {
2322            handle_paid_notify(
2323                source,
2324                notify,
2325                paid_list,
2326                payment_verifier,
2327                p2p_node,
2328                config,
2329            )
2330            .await
2331        }
2332        ReplicationMessageBody::NeighborSyncRequest(ref request) => {
2333            let bootstrapping = *is_bootstrapping.read().await;
2334            // Phase-3 storage-bound audit: store the sender's
2335            // commitment for use as `expected_commitment_hash` in
2336            // future audits. Verify signature before storing so a peer
2337            // cannot inject a forged commitment for someone else.
2338            if let Some(target) = ingest_peer_commitment(
2339                source,
2340                request.commitment.as_ref(),
2341                p2p_node,
2342                last_commitment_by_peer,
2343                ever_capable_peers,
2344                sig_verify_attempts,
2345            )
2346            .await
2347            {
2348                maybe_trigger_gossip_audit(gossip_audit, source, target).await;
2349            }
2350            handle_neighbor_sync_request(
2351                source,
2352                request,
2353                p2p_node,
2354                storage,
2355                paid_list,
2356                queues,
2357                config,
2358                bootstrapping,
2359                bootstrap_state,
2360                sync_history,
2361                sync_cycle_epoch,
2362                repair_proofs,
2363                // Atomically snapshot + mark-gossiped: emitted in the sync
2364                // response, so we must stay answerable for it (ADR-0002).
2365                my_commitment_state
2366                    .current_for_gossip()
2367                    .map(|b| b.commitment().clone()),
2368                msg.request_id,
2369                rr_message_id,
2370            )
2371            .await
2372        }
2373        ReplicationMessageBody::VerificationRequest(ref request) => {
2374            handle_verification_request(
2375                source,
2376                request,
2377                storage,
2378                paid_list,
2379                p2p_node,
2380                msg.request_id,
2381                rr_message_id,
2382            )
2383            .await
2384        }
2385        ReplicationMessageBody::FetchRequest(ref request) => {
2386            handle_fetch_request(
2387                source,
2388                request,
2389                storage,
2390                p2p_node,
2391                msg.request_id,
2392                rr_message_id,
2393            )
2394            .await
2395        }
2396        ReplicationMessageBody::AuditChallenge(challenge) => {
2397            // Responsible-chunk audit (audit #2) responder: answer with per-key
2398            // possession digests. This same handler also answers the
2399            // prune-confirmation audit, which sends the same `AuditChallenge`
2400            // wire message.
2401            //
2402            // Answering digests the stored bytes of every challenged key, so —
2403            // like the subtree/byte audits below — run it on a detached task off
2404            // this serial message loop. Handling it inline lets one challenge
2405            // block all other replication traffic until its digests complete
2406            // (head-of-line blocking). The same flood-fair admission applies: a
2407            // global ceiling AND a per-peer cap, dropping the challenge if either
2408            // is hit. Responsible/prune audit timeouts are penalised by the
2409            // caller, so the caps must remain high enough for honest audit load;
2410            // the per-peer share still prevents one flooder from starving others.
2411            let guard = match admit_audit_responder(
2412                audit_responder_semaphore,
2413                audit_responder_inflight,
2414                source,
2415            )
2416            .await
2417            {
2418                Ok(guard) => guard,
2419                Err(failure) => {
2420                    warn!(
2421                        "Audit challenge reply not sent: kind=responsible response=dropped \
2422                         source={source} {failure}"
2423                    );
2424                    return Ok(());
2425                }
2426            };
2427            let bootstrapping = *is_bootstrapping.read().await;
2428            let storage = Arc::clone(storage);
2429            let p2p_node = Arc::clone(p2p_node);
2430            let source = *source;
2431            let request_id = msg.request_id;
2432            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
2433            tokio::spawn(async move {
2434                let _guard = guard; // global permit + per-peer slot, held until done
2435                if let Err(e) = handle_audit_challenge_msg(
2436                    &source,
2437                    &challenge,
2438                    &storage,
2439                    &p2p_node,
2440                    bootstrapping,
2441                    request_id,
2442                    rr_message_id.as_deref(),
2443                )
2444                .await
2445                {
2446                    debug!("Audit challenge from {source} error: {e}");
2447                }
2448            });
2449            Ok(())
2450        }
2451        ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
2452            // Gossip-triggered storage-bound subtree audit (ADR-0002). The
2453            // responder rebuilds the WHOLE nonce-selected subtree, reading every
2454            // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
2455            // detached task so this serial message loop is never blocked on disk
2456            // I/O — otherwise one audit stalls all replication traffic (§5).
2457            //
2458            // A bounded, flood-fair admission restores backpressure (codex#1 +
2459            // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
2460            // we drop this challenge. Subtree auditors grace timeout
2461            // non-responses, so capacity drops throttle flooders without turning
2462            // into trust penalties (and one source cannot starve other peers,
2463            // since its share is capped per-peer).
2464            info!(
2465                "Audit challenge received: kind=subtree source={source} request_response={}",
2466                rr_message_id.is_some(),
2467            );
2468            let guard = match admit_audit_responder(
2469                audit_responder_semaphore,
2470                audit_responder_inflight,
2471                source,
2472            )
2473            .await
2474            {
2475                Ok(guard) => guard,
2476                Err(failure) => {
2477                    warn!(
2478                        "Audit challenge reply not sent: kind=subtree response=dropped \
2479                         source={source} {failure}"
2480                    );
2481                    return Ok(());
2482                }
2483            };
2484            let bootstrapping = *is_bootstrapping.read().await;
2485            let storage = Arc::clone(storage);
2486            let p2p_node = Arc::clone(p2p_node);
2487            let my_commitment_state = Arc::clone(my_commitment_state);
2488            let source = *source;
2489            let request_id = msg.request_id;
2490            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
2491            tokio::spawn(async move {
2492                let _guard = guard; // global permit + per-peer slot, held until done
2493                let response = storage_commitment_audit::handle_subtree_challenge(
2494                    &challenge,
2495                    &storage,
2496                    p2p_node.peer_id(),
2497                    bootstrapping,
2498                    Some(&my_commitment_state),
2499                )
2500                .await;
2501                let response_kind = subtree_audit_response_kind(&response);
2502                let sent = send_replication_response_checked(
2503                    &source,
2504                    &p2p_node,
2505                    request_id,
2506                    ReplicationMessageBody::SubtreeAuditResponse(response),
2507                    rr_message_id.as_deref(),
2508                )
2509                .await;
2510                if sent {
2511                    info!(
2512                        "Audit challenge reply sent: kind=subtree response={response_kind} \
2513                         source={source} request_response={}",
2514                        rr_message_id.is_some(),
2515                    );
2516                } else {
2517                    warn!(
2518                        "Audit challenge reply not sent: kind=subtree response={response_kind} \
2519                         source={source} request_response={}",
2520                        rr_message_id.is_some(),
2521                    );
2522                }
2523            });
2524            Ok(())
2525        }
2526        ReplicationMessageBody::SubtreeByteChallenge(challenge) => {
2527            // Round 2 of the storage audit (ADR-0002): serve the original bytes
2528            // for the auditor's spot-check keys, or signal `Absent` for a
2529            // committed key we can no longer produce. Reads chunk bytes from
2530            // disk, so likewise spawned off the serial loop (§5) under the same
2531            // flood-fair admission (codex#1 + codex-r2 A).
2532            info!(
2533                "Audit challenge received: kind=byte source={source} request_response={}",
2534                rr_message_id.is_some(),
2535            );
2536            let guard = match admit_audit_responder(
2537                audit_responder_semaphore,
2538                audit_responder_inflight,
2539                source,
2540            )
2541            .await
2542            {
2543                Ok(guard) => guard,
2544                Err(failure) => {
2545                    warn!(
2546                        "Audit challenge reply not sent: kind=byte response=dropped \
2547                         source={source} {failure}"
2548                    );
2549                    return Ok(());
2550                }
2551            };
2552            let bootstrapping = *is_bootstrapping.read().await;
2553            let storage = Arc::clone(storage);
2554            let p2p_node = Arc::clone(p2p_node);
2555            let my_commitment_state = Arc::clone(my_commitment_state);
2556            let source = *source;
2557            let request_id = msg.request_id;
2558            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
2559            tokio::spawn(async move {
2560                let _guard = guard; // global permit + per-peer slot, held until done
2561                let response = storage_commitment_audit::handle_subtree_byte_challenge(
2562                    &challenge,
2563                    &storage,
2564                    p2p_node.peer_id(),
2565                    bootstrapping,
2566                    Some(&my_commitment_state),
2567                )
2568                .await;
2569                let response_kind = subtree_byte_response_kind(&response);
2570                let sent = send_replication_response_checked(
2571                    &source,
2572                    &p2p_node,
2573                    request_id,
2574                    ReplicationMessageBody::SubtreeByteResponse(response),
2575                    rr_message_id.as_deref(),
2576                )
2577                .await;
2578                if sent {
2579                    info!(
2580                        "Audit challenge reply sent: kind=byte response={response_kind} \
2581                         source={source} request_response={}",
2582                        rr_message_id.is_some(),
2583                    );
2584                } else {
2585                    warn!(
2586                        "Audit challenge reply not sent: kind=byte response={response_kind} \
2587                         source={source} request_response={}",
2588                        rr_message_id.is_some(),
2589                    );
2590                }
2591            });
2592            Ok(())
2593        }
2594        ReplicationMessageBody::GetCommitmentByPin(ref request) => {
2595            // ADR-0004: answer a commitment-by-pin fetch from the retained set
2596            // only. `lookup_by_hash` is an allocation-light read over the
2597            // bounded slot set; it returns the live current commitment or any
2598            // still-answerable recently-gossiped/quoted one. A miss is reported
2599            // as `NotRetained` (graced, never confirmed) rather than an error,
2600            // so an aged-out pin can never brand an honest node.
2601            //
2602            // Reuse the audit-responder admission guard (global ceiling + per-peer
2603            // cap) so a flood of fetches cannot drive unbounded commitment
2604            // clone/encode/send work; over-limit is dropped, which the fetching
2605            // peer graces exactly like a missed audit response.
2606            let _guard = match admit_audit_responder(
2607                audit_responder_semaphore,
2608                audit_responder_inflight,
2609                source,
2610            )
2611            .await
2612            {
2613                Ok(guard) => guard,
2614                Err(failure) => {
2615                    debug!("GetCommitmentByPin from {source} dropped: {failure}");
2616                    return Ok(());
2617                }
2618            };
2619            let response = my_commitment_state.lookup_by_hash(&request.pin).map_or(
2620                protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
2621                |built| protocol::GetCommitmentByPinResponse::Found {
2622                    commitment: built.commitment().clone(),
2623                },
2624            );
2625            send_replication_response(
2626                source,
2627                p2p_node,
2628                msg.request_id,
2629                ReplicationMessageBody::GetCommitmentByPinResponse(response),
2630                rr_message_id,
2631            )
2632            .await;
2633            Ok(())
2634        }
2635        // Response messages are handled by their respective request initiators.
2636        ReplicationMessageBody::FreshReplicationResponse(_)
2637        | ReplicationMessageBody::NeighborSyncResponse(_)
2638        | ReplicationMessageBody::VerificationResponse(_)
2639        | ReplicationMessageBody::FetchResponse(_)
2640        | ReplicationMessageBody::AuditResponse(_)
2641        | ReplicationMessageBody::SubtreeAuditResponse(_)
2642        | ReplicationMessageBody::SubtreeByteResponse(_)
2643        | ReplicationMessageBody::GetCommitmentByPinResponse(_) => Ok(()),
2644    }
2645}
2646
2647// ---------------------------------------------------------------------------
2648// Per-message-type handlers
2649// ---------------------------------------------------------------------------
2650
2651#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
2652async fn handle_fresh_offer(
2653    source: &PeerId,
2654    offer: &protocol::FreshReplicationOffer,
2655    storage: &Arc<LmdbStorage>,
2656    paid_list: &Arc<PaidList>,
2657    payment_verifier: &Arc<PaymentVerifier>,
2658    p2p_node: &Arc<P2PNode>,
2659    config: &ReplicationConfig,
2660    request_id: u64,
2661    rr_message_id: Option<&str>,
2662) -> Result<()> {
2663    let self_id = *p2p_node.peer_id();
2664
2665    // Rule 5: reject if PoP is missing.
2666    if offer.proof_of_payment.is_empty() {
2667        send_replication_response(
2668            source,
2669            p2p_node,
2670            request_id,
2671            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
2672                key: offer.key,
2673                reason: "Missing proof of payment".to_string(),
2674            }),
2675            rr_message_id,
2676        )
2677        .await;
2678        return Ok(());
2679    }
2680
2681    // Enforce chunk size invariant: the normal PUT path rejects data larger
2682    // than MAX_CHUNK_SIZE; the replication receive path must do the same to
2683    // prevent peers from pushing oversized records through replication.
2684    if offer.data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
2685        warn!(
2686            "Rejecting fresh offer for key {}: data size {} exceeds MAX_CHUNK_SIZE {}",
2687            hex::encode(offer.key),
2688            offer.data.len(),
2689            crate::ant_protocol::MAX_CHUNK_SIZE,
2690        );
2691        p2p_node
2692            .report_trust_event(
2693                source,
2694                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
2695            )
2696            .await;
2697        send_replication_response(
2698            source,
2699            p2p_node,
2700            request_id,
2701            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
2702                key: offer.key,
2703                reason: format!(
2704                    "Data size {} exceeds maximum chunk size {}",
2705                    offer.data.len(),
2706                    crate::ant_protocol::MAX_CHUNK_SIZE,
2707                ),
2708            }),
2709            rr_message_id,
2710        )
2711        .await;
2712        return Ok(());
2713    }
2714
2715    // Mirror the normal PUT path: the advertised key must be the content
2716    // address of the supplied bytes before any expensive payment verification.
2717    let computed_key = crate::client::compute_address(&offer.data);
2718    if computed_key != offer.key {
2719        warn!(
2720            "Rejecting fresh offer for key {}: content address mismatch, computed {}",
2721            hex::encode(offer.key),
2722            hex::encode(computed_key),
2723        );
2724        p2p_node
2725            .report_trust_event(
2726                source,
2727                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
2728            )
2729            .await;
2730        send_replication_response(
2731            source,
2732            p2p_node,
2733            request_id,
2734            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
2735                key: offer.key,
2736                reason: format!(
2737                    "Content address mismatch: expected {}, computed {}",
2738                    hex::encode(offer.key),
2739                    hex::encode(computed_key),
2740                ),
2741            }),
2742            rr_message_id,
2743        )
2744        .await;
2745        return Ok(());
2746    }
2747
2748    // Rule 7: check storage admission. Fresh chunk receivers accept across the
2749    // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
2750    // the same width client PUTs use), not just the close group plus a small
2751    // margin (ADR-0003). During full-node shunning a healthy replica's routing
2752    // table may still list closer full nodes it hasn't evicted yet, ranking it
2753    // outside the narrow window in its own view; the wider accept window absorbs
2754    // that transient skew so the chunk still lands. Retention (pruning) stays at
2755    // `storage_admission_width`, so steady-state replication is unchanged.
2756    if !admission::is_responsible(
2757        &self_id,
2758        &offer.key,
2759        p2p_node,
2760        config.paid_list_close_group_size,
2761    )
2762    .await
2763    {
2764        send_replication_response(
2765            source,
2766            p2p_node,
2767            request_id,
2768            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
2769                key: offer.key,
2770                reason: "Not in storage-admission range for this key".to_string(),
2771            }),
2772            rr_message_id,
2773        )
2774        .await;
2775        return Ok(());
2776    }
2777
2778    // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
2779    // never store this record, so reject it before the expensive payment
2780    // verification (EVM on-chain query / merkle pool work) rather than verifying
2781    // and only then failing at `storage.put` below. Reuses the cached capacity
2782    // check (passing results only, so freed space is detected promptly), and the
2783    // store path keeps its own check as defence-in-depth.
2784    if let Err(e) = storage.check_capacity() {
2785        info!(
2786            target: "ant_node::storage::disk_precheck",
2787            key = %hex::encode(offer.key),
2788            "Rejecting fresh replication offer before payment verification: {e}"
2789        );
2790        send_replication_response(
2791            source,
2792            p2p_node,
2793            request_id,
2794            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
2795                key: offer.key,
2796                reason: e.to_string(),
2797            }),
2798            rr_message_id,
2799        )
2800        .await;
2801        return Ok(());
2802    }
2803
2804    // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
2805    // part of the immediate write fan-out: this receiver is about to store the
2806    // record as if the client had PUT it here directly. Storage admission
2807    // was checked above before proof work. FreshReplication verification is
2808    // identical to ClientPut — store-strength cache semantics, paid-quote
2809    // issuer K-closeness checks for single-node proofs, merkle candidate
2810    // closeness for merkle proofs, and the same price-floor policy — the
2811    // distinct context only labels price-floor telemetry.
2812    match payment_verifier
2813        .verify_payment(
2814            &offer.key,
2815            Some(&offer.proof_of_payment),
2816            fresh_offer_payment_context(),
2817        )
2818        .await
2819    {
2820        Ok(status) if status.can_store() => {
2821            debug!(
2822                "PoP validated for fresh offer key {}",
2823                hex::encode(offer.key)
2824            );
2825        }
2826        Ok(_) => {
2827            send_replication_response(
2828                source,
2829                p2p_node,
2830                request_id,
2831                ReplicationMessageBody::FreshReplicationResponse(
2832                    FreshReplicationResponse::Rejected {
2833                        key: offer.key,
2834                        reason: "Payment verification failed: payment required".to_string(),
2835                    },
2836                ),
2837                rr_message_id,
2838            )
2839            .await;
2840            return Ok(());
2841        }
2842        Err(e) => {
2843            warn!(
2844                "PoP verification error for key {}: {e}",
2845                hex::encode(offer.key)
2846            );
2847            send_replication_response(
2848                source,
2849                p2p_node,
2850                request_id,
2851                ReplicationMessageBody::FreshReplicationResponse(
2852                    FreshReplicationResponse::Rejected {
2853                        key: offer.key,
2854                        reason: format!("Payment verification error: {e}"),
2855                    },
2856                ),
2857                rr_message_id,
2858            )
2859            .await;
2860            return Ok(());
2861        }
2862    }
2863
2864    // Rule 6: add to PaidForList.
2865    if let Err(e) = paid_list.insert(&offer.key).await {
2866        warn!("Failed to add key to PaidForList: {e}");
2867    }
2868
2869    // Store the record.
2870    match storage.put(&offer.key, &offer.data).await {
2871        Ok(_) => {
2872            send_replication_response(
2873                source,
2874                p2p_node,
2875                request_id,
2876                ReplicationMessageBody::FreshReplicationResponse(
2877                    FreshReplicationResponse::Accepted { key: offer.key },
2878                ),
2879                rr_message_id,
2880            )
2881            .await;
2882        }
2883        Err(e) => {
2884            send_replication_response(
2885                source,
2886                p2p_node,
2887                request_id,
2888                ReplicationMessageBody::FreshReplicationResponse(
2889                    FreshReplicationResponse::Rejected {
2890                        key: offer.key,
2891                        reason: e.to_string(),
2892                    },
2893                ),
2894                rr_message_id,
2895            )
2896            .await;
2897        }
2898    }
2899
2900    Ok(())
2901}
2902
2903async fn handle_paid_notify(
2904    _source: &PeerId,
2905    notify: &protocol::PaidNotify,
2906    paid_list: &Arc<PaidList>,
2907    payment_verifier: &Arc<PaymentVerifier>,
2908    p2p_node: &Arc<P2PNode>,
2909    config: &ReplicationConfig,
2910) -> Result<()> {
2911    let self_id = *p2p_node.peer_id();
2912
2913    // Rule 3: validate PoP presence before adding.
2914    if notify.proof_of_payment.is_empty() {
2915        return Ok(());
2916    }
2917
2918    // Check if we're in PaidCloseGroup for this key.
2919    if !admission::is_in_paid_close_group(
2920        &self_id,
2921        &notify.key,
2922        p2p_node,
2923        config.paid_list_close_group_size,
2924    )
2925    .await
2926    {
2927        return Ok(());
2928    }
2929
2930    // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
2931    // paid-list metadata, so local paid-list close-group membership was checked
2932    // above before proof work. The verifier then runs the same payment proof
2933    // checks as ClientPut while writing a paid-list-strength cache entry.
2934    match payment_verifier
2935        .verify_payment(
2936            &notify.key,
2937            Some(&notify.proof_of_payment),
2938            paid_notify_payment_context(),
2939        )
2940        .await
2941    {
2942        Ok(status) if status.can_store() => {
2943            debug!(
2944                "PoP validated for paid notify key {}",
2945                hex::encode(notify.key)
2946            );
2947        }
2948        Ok(_) => {
2949            warn!(
2950                "Paid notify rejected: payment required for key {}",
2951                hex::encode(notify.key)
2952            );
2953            return Ok(());
2954        }
2955        Err(e) => {
2956            warn!(
2957                "PoP verification error for paid notify key {}: {e}",
2958                hex::encode(notify.key)
2959            );
2960            return Ok(());
2961        }
2962    }
2963
2964    if let Err(e) = paid_list.insert(&notify.key).await {
2965        warn!("Failed to add paid notify key to PaidForList: {e}");
2966    }
2967
2968    Ok(())
2969}
2970
2971#[allow(clippy::too_many_arguments)]
2972async fn handle_neighbor_sync_request(
2973    source: &PeerId,
2974    request: &protocol::NeighborSyncRequest,
2975    p2p_node: &Arc<P2PNode>,
2976    storage: &Arc<LmdbStorage>,
2977    paid_list: &Arc<PaidList>,
2978    queues: &Arc<RwLock<ReplicationQueues>>,
2979    config: &ReplicationConfig,
2980    is_bootstrapping: bool,
2981    bootstrap_state: &Arc<RwLock<BootstrapState>>,
2982    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
2983    sync_cycle_epoch: &Arc<RwLock<u64>>,
2984    repair_proofs: &Arc<RwLock<RepairProofs>>,
2985    my_commitment: Option<StorageCommitment>,
2986    request_id: u64,
2987    rr_message_id: Option<&str>,
2988) -> Result<()> {
2989    let self_id = *p2p_node.peer_id();
2990
2991    // No per-request hint count limit: the wire message size limit
2992    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
2993    // challenges, sync hints don't drive expensive computation — they just
2994    // enter the verification queue. A per-request limit here would break
2995    // bootstrap replication for newly-joined nodes with 0 stored chunks.
2996
2997    // Build response (outbound hints).
2998    let (response, sent_replica_hints, sender_in_rt) =
2999        neighbor_sync::handle_sync_request_with_proofs(
3000            source,
3001            request,
3002            p2p_node,
3003            storage,
3004            paid_list,
3005            config,
3006            is_bootstrapping,
3007            my_commitment.clone(),
3008        )
3009        .await;
3010
3011    // Send response.
3012    let response_sent = send_replication_response_checked(
3013        source,
3014        p2p_node,
3015        request_id,
3016        ReplicationMessageBody::NeighborSyncResponse(response),
3017        rr_message_id,
3018    )
3019    .await;
3020
3021    // Process inbound hints only if sender is in LocalRT (Rule 4-6).
3022    if !sender_in_rt {
3023        return Ok(());
3024    }
3025
3026    // Update sync history for this peer before recording repair proofs so a
3027    // same-tick audit cannot combine a fresh key proof with stale peer maturity.
3028    {
3029        let mut history = sync_history.write().await;
3030        let record = history.entry(*source).or_insert(PeerSyncRecord {
3031            last_sync: None,
3032            cycles_since_sync: 0,
3033        });
3034        record.last_sync = Some(Instant::now());
3035        record.cycles_since_sync = 0;
3036    }
3037
3038    if response_sent && !request.bootstrapping {
3039        record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
3040            .await;
3041    }
3042
3043    // Admit inbound hints and queue for verification.
3044    let outcome = admit_and_queue_hints(
3045        &self_id,
3046        source,
3047        &request.replica_hints,
3048        &request.paid_hints,
3049        p2p_node,
3050        config,
3051        storage,
3052        paid_list,
3053        queues,
3054    )
3055    .await;
3056
3057    // Track discovered keys for bootstrap drain detection so that hints
3058    // admitted via inbound sync requests are not missed. Capacity-rejected
3059    // hints keep this source on the "not yet drained" list until its next
3060    // sync re-admits them; a clean cycle clears the source.
3061    if is_bootstrapping {
3062        if !outcome.discovered.is_empty() {
3063            bootstrap::track_discovered_keys(bootstrap_state, &outcome.discovered).await;
3064        }
3065        if outcome.capacity_rejected_count > 0 {
3066            bootstrap::note_capacity_rejected(bootstrap_state, *source).await;
3067        } else {
3068            bootstrap::clear_capacity_rejected(bootstrap_state, source).await;
3069        }
3070    }
3071
3072    Ok(())
3073}
3074
3075async fn handle_verification_request(
3076    source: &PeerId,
3077    request: &protocol::VerificationRequest,
3078    storage: &Arc<LmdbStorage>,
3079    paid_list: &Arc<PaidList>,
3080    p2p_node: &Arc<P2PNode>,
3081    request_id: u64,
3082    rr_message_id: Option<&str>,
3083) -> Result<()> {
3084    // No per-request key count limit: the wire message size limit
3085    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Verification
3086    // does cheap storage lookups per key, not expensive computation like
3087    // audit digest generation.
3088
3089    #[allow(clippy::cast_possible_truncation)]
3090    let keys_len = request.keys.len() as u32;
3091    let paid_check_set: HashSet<u32> = request
3092        .paid_list_check_indices
3093        .iter()
3094        .copied()
3095        .filter(|&idx| {
3096            if idx >= keys_len {
3097                warn!(
3098                    "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
3099                    request.keys.len(),
3100                );
3101                false
3102            } else {
3103                true
3104            }
3105        })
3106        .collect();
3107
3108    let mut results = Vec::with_capacity(request.keys.len());
3109    for (i, key) in request.keys.iter().enumerate() {
3110        let present = storage.exists(key).unwrap_or(false);
3111        let paid = if paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX)) {
3112            Some(paid_list.contains(key).unwrap_or(false))
3113        } else {
3114            None
3115        };
3116        results.push(protocol::KeyVerificationResult {
3117            key: *key,
3118            present,
3119            paid,
3120        });
3121    }
3122
3123    send_replication_response(
3124        source,
3125        p2p_node,
3126        request_id,
3127        ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
3128        rr_message_id,
3129    )
3130    .await;
3131
3132    Ok(())
3133}
3134
3135async fn handle_fetch_request(
3136    source: &PeerId,
3137    request: &protocol::FetchRequest,
3138    storage: &Arc<LmdbStorage>,
3139    p2p_node: &Arc<P2PNode>,
3140    request_id: u64,
3141    rr_message_id: Option<&str>,
3142) -> Result<()> {
3143    let response = match storage.get(&request.key).await {
3144        Ok(Some(data)) => protocol::FetchResponse::Success {
3145            key: request.key,
3146            data,
3147        },
3148        Ok(None) => protocol::FetchResponse::NotFound { key: request.key },
3149        Err(e) => protocol::FetchResponse::Error {
3150            key: request.key,
3151            reason: format!("{e}"),
3152        },
3153    };
3154
3155    send_replication_response(
3156        source,
3157        p2p_node,
3158        request_id,
3159        ReplicationMessageBody::FetchResponse(response),
3160        rr_message_id,
3161    )
3162    .await;
3163
3164    Ok(())
3165}
3166
3167/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
3168/// the prune-confirmation audit, which reuses the same wire message): reply with
3169/// per-key possession digests.
3170async fn handle_audit_challenge_msg(
3171    source: &PeerId,
3172    challenge: &protocol::AuditChallenge,
3173    storage: &Arc<LmdbStorage>,
3174    p2p_node: &Arc<P2PNode>,
3175    is_bootstrapping: bool,
3176    request_id: u64,
3177    rr_message_id: Option<&str>,
3178) -> Result<()> {
3179    #[allow(clippy::cast_possible_truncation)]
3180    let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
3181    info!(
3182        "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
3183        challenge.keys.len(),
3184        is_bootstrapping,
3185        rr_message_id.is_some(),
3186    );
3187
3188    let response = audit::handle_audit_challenge(
3189        challenge,
3190        storage,
3191        p2p_node.peer_id(),
3192        is_bootstrapping,
3193        stored_chunks,
3194    )
3195    .await;
3196    let response_kind = audit_response_kind(&response);
3197
3198    let sent = send_replication_response_checked(
3199        source,
3200        p2p_node,
3201        request_id,
3202        ReplicationMessageBody::AuditResponse(response),
3203        rr_message_id,
3204    )
3205    .await;
3206    if sent {
3207        info!(
3208            "Audit challenge reply sent: kind=responsible response={} keys={} request_response={}",
3209            response_kind,
3210            challenge.keys.len(),
3211            rr_message_id.is_some(),
3212        );
3213    } else {
3214        warn!(
3215            "Audit challenge reply not sent: kind=responsible response={} keys={} request_response={}",
3216            response_kind,
3217            challenge.keys.len(),
3218            rr_message_id.is_some(),
3219        );
3220    }
3221
3222    Ok(())
3223}
3224
3225fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
3226    match response {
3227        protocol::AuditResponse::Digests { .. } => "digests",
3228        protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
3229        protocol::AuditResponse::Rejected { .. } => "rejected",
3230    }
3231}
3232
3233fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
3234    match response {
3235        protocol::SubtreeAuditResponse::Proof { .. } => "proof",
3236        protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
3237        protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
3238    }
3239}
3240
3241fn subtree_byte_response_kind(response: &protocol::SubtreeByteResponse) -> &'static str {
3242    match response {
3243        protocol::SubtreeByteResponse::Items { .. } => "items",
3244        protocol::SubtreeByteResponse::Bootstrapping { .. } => "bootstrapping",
3245        protocol::SubtreeByteResponse::Rejected { .. } => "rejected",
3246    }
3247}
3248
3249// ---------------------------------------------------------------------------
3250// Message sending helper
3251// ---------------------------------------------------------------------------
3252
3253/// Send a replication response message as a best-effort reply.
3254///
3255/// Encode and send failures are logged by the checked helper. Most response
3256/// paths do not need to branch on send success, so this wrapper keeps those
3257/// call sites explicit about their best-effort behavior.
3258async fn send_replication_response(
3259    peer: &PeerId,
3260    p2p_node: &Arc<P2PNode>,
3261    request_id: u64,
3262    body: ReplicationMessageBody,
3263    rr_message_id: Option<&str>,
3264) {
3265    let _ =
3266        send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id).await;
3267}
3268
3269/// Send a replication response message and report whether it was accepted.
3270///
3271/// Returns `true` after the message is encoded and accepted by the P2P send
3272/// path. Returns `false` after logging an encode or send failure. Repair-proof
3273/// recording uses this to avoid trusting hints that were not actually sent.
3274///
3275/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
3276/// request-response path so saorsa-core can route it back to the caller's
3277/// `send_request` future. Otherwise it is sent as a plain message.
3278async fn send_replication_response_checked(
3279    peer: &PeerId,
3280    p2p_node: &Arc<P2PNode>,
3281    request_id: u64,
3282    body: ReplicationMessageBody,
3283    rr_message_id: Option<&str>,
3284) -> bool {
3285    let msg = ReplicationMessage { request_id, body };
3286    let encoded = match msg.encode() {
3287        Ok(data) => data,
3288        Err(e) => {
3289            warn!("Failed to encode replication response: {e}");
3290            return false;
3291        }
3292    };
3293    // V2-684: per-peer served-bytes attribution for the heavy serve paths.
3294    // `FetchResponse` + `SubtreeByteResponse` carry ~99% of served bytes;
3295    // `NeighborSyncResponse` is included for completeness. Other response
3296    // variants (verification/audit/commitment) are intentionally excluded.
3297    if matches!(
3298        msg.body,
3299        ReplicationMessageBody::FetchResponse(_)
3300            | ReplicationMessageBody::SubtreeByteResponse(_)
3301            | ReplicationMessageBody::NeighborSyncResponse(_)
3302    ) {
3303        protocol::record_served(peer, encoded.len());
3304    }
3305    let result = if let Some(msg_id) = rr_message_id {
3306        p2p_node
3307            .send_response(peer, REPLICATION_PROTOCOL_ID, msg_id, encoded)
3308            .await
3309    } else {
3310        p2p_node
3311            .send_message(peer, REPLICATION_PROTOCOL_ID, encoded, &[])
3312            .await
3313    };
3314    if let Err(e) = result {
3315        debug!("Failed to send replication response to {peer}: {e}");
3316        return false;
3317    }
3318    true
3319}
3320
3321async fn record_sent_replica_hints(
3322    peer: &PeerId,
3323    hints: &[neighbor_sync::SentReplicaHint],
3324    repair_proofs: &Arc<RwLock<RepairProofs>>,
3325    sync_cycle_epoch: &Arc<RwLock<u64>>,
3326) {
3327    if hints.is_empty() {
3328        return;
3329    }
3330
3331    let hinted_at_epoch = *sync_cycle_epoch.read().await;
3332    let mut proofs = repair_proofs.write().await;
3333    for hint in hints {
3334        if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
3335            debug!(
3336                "Recorded repair hint proof for peer {peer} and key {}",
3337                hex::encode(hint.key)
3338            );
3339        }
3340    }
3341}
3342
3343// ---------------------------------------------------------------------------
3344// Neighbor sync round
3345// ---------------------------------------------------------------------------
3346
3347/// Run one neighbor sync round.
3348#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
3349async fn run_neighbor_sync_round(
3350    p2p_node: &Arc<P2PNode>,
3351    storage: &Arc<LmdbStorage>,
3352    paid_list: &Arc<PaidList>,
3353    queues: &Arc<RwLock<ReplicationQueues>>,
3354    config: &ReplicationConfig,
3355    sync_state: &Arc<RwLock<NeighborSyncState>>,
3356    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
3357    sync_cycle_epoch: &Arc<RwLock<u64>>,
3358    repair_proofs: &Arc<RwLock<RepairProofs>>,
3359    is_bootstrapping: &Arc<RwLock<bool>>,
3360    bootstrap_state: &Arc<RwLock<BootstrapState>>,
3361    commitment_state: &Arc<ResponderCommitmentState>,
3362    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
3363    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
3364    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
3365    gossip_audit: &GossipAuditTrigger,
3366) {
3367    let self_id = *p2p_node.peer_id();
3368    let bootstrapping = *is_bootstrapping.read().await;
3369
3370    // Check if cycle is complete; start new one if needed.
3371    // We check under a read lock, then release it before the expensive
3372    // prune pass and DHT snapshot so other tasks are not starved.
3373    let cycle_complete = sync_state.read().await.is_cycle_complete();
3374    if cycle_complete {
3375        // A completed local neighbor-sync cycle advances the epoch component
3376        // of repair-proof maturity. The per-key wall-clock minimum age is
3377        // checked when audits are selected.
3378        {
3379            let mut history = sync_history.write().await;
3380            for record in history.values_mut() {
3381                record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
3382            }
3383        }
3384        {
3385            let mut epoch = sync_cycle_epoch.write().await;
3386            *epoch = epoch.saturating_add(1);
3387        }
3388
3389        // Post-cycle pruning (Section 11) — runs without holding sync_state.
3390        // Prune candidacy is unconditional once the hysteresis elapses;
3391        // bootstrap state only defers the remote prune-confirmation audits
3392        // until bootstrap has drained.
3393        let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
3394        pruning::run_prune_pass_with_context(pruning::PrunePassContext {
3395            self_id: &self_id,
3396            storage,
3397            paid_list,
3398            p2p_node,
3399            config,
3400            sync_state,
3401            repair_proofs,
3402            allow_remote_prune_audits,
3403            commitment_state: Some(commitment_state),
3404        })
3405        .await;
3406
3407        // Take fresh close-neighbor snapshot (DHT query, no lock held).
3408        let neighbors =
3409            neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
3410                .await;
3411
3412        // Now re-acquire write lock and re-check before swapping cycle.
3413        let mut state = sync_state.write().await;
3414        if state.is_cycle_complete() {
3415            // Preserve cooldown and bootstrap-claim tracking across cycles.
3416            // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
3417            // would reset the abuse detection timer every cycle.
3418            let old_sync_times = std::mem::take(&mut state.last_sync_times);
3419            let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
3420            let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
3421            let old_prune_cursor = state.prune_cursor;
3422            *state = NeighborSyncState::new_cycle(neighbors);
3423            state.last_sync_times = old_sync_times;
3424            state.bootstrap_claims = old_bootstrap_claims;
3425            state.bootstrap_claim_history = old_bootstrap_claim_history;
3426            state.prune_cursor = old_prune_cursor;
3427        }
3428    }
3429
3430    // Select batch of peers.
3431    let batch = {
3432        let mut state = sync_state.write().await;
3433        neighbor_sync::select_sync_batch(
3434            &mut state,
3435            config.neighbor_sync_peer_count,
3436            config.neighbor_sync_cooldown,
3437        )
3438    };
3439
3440    if batch.is_empty() {
3441        return;
3442    }
3443
3444    debug!("Neighbor sync: syncing with {} peers", batch.len());
3445
3446    // Snapshot our current commitment once per round so all peers in
3447    // this batch see the same thing (gossip is the responder's attestation;
3448    // same value across the batch is fine and reduces RwLock churn). Atomically
3449    // snapshot + mark-gossiped so we stay answerable for exactly what we emit
3450    // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
3451    let my_commitment = commitment_state
3452        .current_for_gossip()
3453        .map(|b| b.commitment().clone());
3454
3455    let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
3456        &batch,
3457        storage,
3458        paid_list,
3459        p2p_node,
3460        config.close_group_size,
3461        config.paid_list_close_group_size,
3462    )
3463    .await;
3464
3465    // Sync with each peer in the batch.
3466    for peer in &batch {
3467        let hints = hints_by_peer.remove(peer).unwrap_or_default();
3468        let outcome = neighbor_sync::sync_with_peer_with_hints(
3469            peer,
3470            p2p_node,
3471            config,
3472            bootstrapping,
3473            hints,
3474            my_commitment.clone(),
3475        )
3476        .await;
3477
3478        if let Some(outcome) = outcome {
3479            handle_sync_response(
3480                &self_id,
3481                peer,
3482                &outcome.response,
3483                &outcome.sent_replica_hints,
3484                p2p_node,
3485                config,
3486                bootstrapping,
3487                bootstrap_state,
3488                storage,
3489                paid_list,
3490                queues,
3491                sync_state,
3492                sync_history,
3493                sync_cycle_epoch,
3494                repair_proofs,
3495                last_commitment_by_peer,
3496                ever_capable_peers,
3497                sig_verify_attempts,
3498                gossip_audit,
3499            )
3500            .await;
3501        } else {
3502            // Sync failed -- remove peer and try to fill slot.
3503            let replacement = {
3504                let mut state = sync_state.write().await;
3505                neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
3506            };
3507
3508            // Attempt sync with the replacement peer (if one was found).
3509            if let Some(replacement_peer) = replacement {
3510                let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
3511                    std::slice::from_ref(&replacement_peer),
3512                    storage,
3513                    paid_list,
3514                    p2p_node,
3515                    config.close_group_size,
3516                    config.paid_list_close_group_size,
3517                )
3518                .await;
3519                let hints = replacement_hints
3520                    .remove(&replacement_peer)
3521                    .unwrap_or_default();
3522                let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
3523                    &replacement_peer,
3524                    p2p_node,
3525                    config,
3526                    bootstrapping,
3527                    hints,
3528                    my_commitment.clone(),
3529                )
3530                .await;
3531
3532                if let Some(outcome) = replacement_outcome {
3533                    handle_sync_response(
3534                        &self_id,
3535                        &replacement_peer,
3536                        &outcome.response,
3537                        &outcome.sent_replica_hints,
3538                        p2p_node,
3539                        config,
3540                        bootstrapping,
3541                        bootstrap_state,
3542                        storage,
3543                        paid_list,
3544                        queues,
3545                        sync_state,
3546                        sync_history,
3547                        sync_cycle_epoch,
3548                        repair_proofs,
3549                        last_commitment_by_peer,
3550                        ever_capable_peers,
3551                        sig_verify_attempts,
3552                        gossip_audit,
3553                    )
3554                    .await;
3555                }
3556            }
3557        }
3558    }
3559}
3560
3561/// Process a successful neighbor sync response: record the sync, check for
3562/// bootstrap claim abuse, and admit inbound hints.
3563#[allow(clippy::too_many_arguments)]
3564async fn handle_sync_response(
3565    self_id: &PeerId,
3566    peer: &PeerId,
3567    resp: &NeighborSyncResponse,
3568    sent_replica_hints: &[neighbor_sync::SentReplicaHint],
3569    p2p_node: &Arc<P2PNode>,
3570    config: &ReplicationConfig,
3571    bootstrapping: bool,
3572    bootstrap_state: &Arc<RwLock<BootstrapState>>,
3573    storage: &Arc<LmdbStorage>,
3574    paid_list: &Arc<PaidList>,
3575    queues: &Arc<RwLock<ReplicationQueues>>,
3576    sync_state: &Arc<RwLock<NeighborSyncState>>,
3577    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
3578    sync_cycle_epoch: &Arc<RwLock<u64>>,
3579    repair_proofs: &Arc<RwLock<RepairProofs>>,
3580    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
3581    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
3582    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
3583    gossip_audit: &GossipAuditTrigger,
3584) {
3585    // Ingest the peer's commitment if they piggybacked one on the response.
3586    // Same verification as the request path (peer-id binding + signature);
3587    // forged commitments are dropped at the edge. A *changed* commitment here
3588    // is a gossip-audit trigger just like on the request path — so a peer that
3589    // only ever answers sync (never initiates) is still audited (ADR-0002).
3590    if let Some(target) = ingest_peer_commitment(
3591        peer,
3592        resp.commitment.as_ref(),
3593        p2p_node,
3594        last_commitment_by_peer,
3595        ever_capable_peers,
3596        sig_verify_attempts,
3597    )
3598    .await
3599    {
3600        maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
3601    }
3602
3603    // Record successful sync.
3604    {
3605        let mut state = sync_state.write().await;
3606        neighbor_sync::record_successful_sync(&mut state, peer);
3607    }
3608    {
3609        let mut history = sync_history.write().await;
3610        let record = history.entry(*peer).or_insert(PeerSyncRecord {
3611            last_sync: None,
3612            cycles_since_sync: 0,
3613        });
3614        record.last_sync = Some(Instant::now());
3615        record.cycles_since_sync = 0;
3616    }
3617
3618    // Process inbound hints from response (skip if peer is bootstrapping).
3619    if resp.bootstrapping {
3620        // Gap 6: BootstrapClaimAbuse grace period enforcement.
3621        // Separate state mutation from network I/O to avoid holding the
3622        // write lock across report_trust_event.
3623        let should_report = {
3624            let now = Instant::now();
3625            let mut state = sync_state.write().await;
3626            match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
3627                BootstrapClaimObservation::WithinGrace { .. } => false,
3628                BootstrapClaimObservation::PastGrace { first_seen } => {
3629                    warn!(
3630                        "Peer {peer} has been claiming bootstrap for {:?}, \
3631                         exceeding grace period of {:?} — reporting abuse",
3632                        now.duration_since(first_seen),
3633                        config.bootstrap_claim_grace_period,
3634                    );
3635                    true
3636                }
3637                BootstrapClaimObservation::Repeated { first_seen } => {
3638                    warn!(
3639                        "Peer {peer} repeated bootstrap claim after previously stopping; \
3640                         first claim was {:?} ago — reporting abuse",
3641                        now.duration_since(first_seen),
3642                    );
3643                    true
3644                }
3645            }
3646        };
3647        if should_report {
3648            p2p_node
3649                .report_trust_event(
3650                    peer,
3651                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
3652                )
3653                .await;
3654        }
3655    } else {
3656        // Peer is not claiming bootstrap; clear active claim while retaining
3657        // history so the peer cannot start a second grace window later.
3658        {
3659            let mut state = sync_state.write().await;
3660            state.clear_active_bootstrap_claim(peer);
3661        }
3662        record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
3663        let outcome = admit_and_queue_hints(
3664            self_id,
3665            peer,
3666            &resp.replica_hints,
3667            &resp.paid_hints,
3668            p2p_node,
3669            config,
3670            storage,
3671            paid_list,
3672            queues,
3673        )
3674        .await;
3675
3676        // Track discovered keys for bootstrap drain detection so that hints
3677        // admitted via regular neighbor sync are not missed. Capacity-
3678        // rejected hints keep this source on the "not yet drained" list
3679        // until its next sync replays them; a clean cycle clears it.
3680        if bootstrapping {
3681            if !outcome.discovered.is_empty() {
3682                bootstrap::track_discovered_keys(bootstrap_state, &outcome.discovered).await;
3683            }
3684            if outcome.capacity_rejected_count > 0 {
3685                bootstrap::note_capacity_rejected(bootstrap_state, *peer).await;
3686            } else {
3687                bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
3688            }
3689        }
3690    }
3691}
3692
3693/// Admit hints and queue them for verification, returning newly-discovered keys.
3694///
3695/// Shared by neighbor-sync request handling, response handling, and bootstrap
3696/// sync so that admission + queueing logic lives in one place.
3697#[allow(clippy::too_many_arguments)]
3698/// Outcome of [`admit_and_queue_hints`].
3699///
3700/// `capacity_rejected_count` is non-zero when one or more legitimately
3701/// admissible hints were dropped because `pending_verify`'s global or
3702/// per-source bound was hit. Callers that care about completeness
3703/// (bootstrap drain accounting) MUST NOT treat their work as complete while
3704/// this is > 0 — the source will need to re-hint after capacity frees up.
3705struct AdmissionOutcome {
3706    discovered: HashSet<XorName>,
3707    capacity_rejected_count: usize,
3708}
3709
3710#[allow(clippy::too_many_arguments)]
3711async fn admit_and_queue_hints(
3712    self_id: &PeerId,
3713    source_peer: &PeerId,
3714    replica_hints: &[XorName],
3715    paid_hints: &[XorName],
3716    p2p_node: &Arc<P2PNode>,
3717    config: &ReplicationConfig,
3718    storage: &Arc<LmdbStorage>,
3719    paid_list: &Arc<PaidList>,
3720    queues: &Arc<RwLock<ReplicationQueues>>,
3721) -> AdmissionOutcome {
3722    let pending_keys: HashSet<XorName> = {
3723        let q = queues.read().await;
3724        q.pending_keys().into_iter().collect()
3725    };
3726
3727    let admitted = admission::admit_hints(
3728        self_id,
3729        replica_hints,
3730        paid_hints,
3731        p2p_node,
3732        config,
3733        storage,
3734        paid_list,
3735        &pending_keys,
3736    )
3737    .await;
3738
3739    let mut discovered = HashSet::new();
3740    let mut capacity_rejected_count: usize = 0;
3741    let mut q = queues.write().await;
3742    let now = Instant::now();
3743
3744    for key in admitted.replica_keys {
3745        if !storage.exists(&key).unwrap_or(false) {
3746            let result = q.add_pending_verify(
3747                key,
3748                VerificationEntry {
3749                    state: VerificationState::PendingVerify,
3750                    pipeline: HintPipeline::Replica,
3751                    verified_sources: Vec::new(),
3752                    tried_sources: HashSet::new(),
3753                    created_at: now,
3754                    hint_sender: *source_peer,
3755                },
3756            );
3757            match result {
3758                crate::replication::scheduling::AdmissionResult::Admitted => {
3759                    discovered.insert(key);
3760                }
3761                crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
3762                crate::replication::scheduling::AdmissionResult::CapacityRejected => {
3763                    capacity_rejected_count += 1;
3764                }
3765            }
3766        }
3767    }
3768
3769    for key in admitted.paid_only_keys {
3770        let result = q.add_pending_verify(
3771            key,
3772            VerificationEntry {
3773                state: VerificationState::PendingVerify,
3774                pipeline: HintPipeline::PaidOnly,
3775                verified_sources: Vec::new(),
3776                tried_sources: HashSet::new(),
3777                created_at: now,
3778                hint_sender: *source_peer,
3779            },
3780        );
3781        match result {
3782            crate::replication::scheduling::AdmissionResult::Admitted => {
3783                discovered.insert(key);
3784            }
3785            crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
3786            crate::replication::scheduling::AdmissionResult::CapacityRejected => {
3787                capacity_rejected_count += 1;
3788            }
3789        }
3790    }
3791
3792    if capacity_rejected_count > 0 {
3793        debug!(
3794            "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
3795             rejected at queue capacity; source will need to re-hint after pending_verify drains"
3796        );
3797    }
3798
3799    AdmissionOutcome {
3800        discovered,
3801        capacity_rejected_count,
3802    }
3803}
3804
3805// ---------------------------------------------------------------------------
3806// Verification cycle
3807// ---------------------------------------------------------------------------
3808
3809/// Run one verification cycle: process pending keys through quorum checks.
3810#[allow(clippy::too_many_lines)]
3811async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
3812    let cycle_started = Instant::now();
3813    let VerificationCycleContext {
3814        p2p_node,
3815        paid_list,
3816        storage,
3817        queues,
3818        config,
3819        bootstrap_state,
3820        is_bootstrapping,
3821        bootstrap_complete_notify,
3822        last_commitment_by_peer,
3823        ever_capable_peers,
3824        recent_provers,
3825    } = ctx;
3826
3827    // Evict stale entries that have been pending too long (e.g. unreachable
3828    // verification targets during a network partition).
3829    {
3830        let mut q = queues.write().await;
3831        q.evict_stale(config::PENDING_VERIFY_MAX_AGE);
3832    }
3833
3834    let pending_keys = {
3835        let q = queues.read().await;
3836        q.pending_keys()
3837    };
3838
3839    if pending_keys.is_empty() {
3840        return;
3841    }
3842    let initial_pending_count = pending_keys.len();
3843
3844    let self_id = *p2p_node.peer_id();
3845
3846    // Step 1: Check local PaidForList for fast-path authorization (Section 9,
3847    // step 4).
3848    let mut local_paid_presence_probe_keys = Vec::new();
3849    let mut local_paid_paid_only_keys = Vec::new();
3850    let mut keys_needing_network = Vec::new();
3851    let mut terminal_keys: Vec<XorName> = Vec::new();
3852    {
3853        let mut q = queues.write().await;
3854        for key in &pending_keys {
3855            if paid_list.contains(key).unwrap_or(false) {
3856                if let Some(pipeline) =
3857                    q.set_pending_state(key, VerificationState::PaidListVerified)
3858                {
3859                    match pipeline {
3860                        HintPipeline::PaidOnly => {
3861                            // Paid-only + local paid state needs one more
3862                            // storage-admission check outside this lock: if we
3863                            // are also in the close group plus storage margin,
3864                            // the hint can repair a missing replica.
3865                            local_paid_paid_only_keys.push(*key);
3866                        }
3867                        HintPipeline::Replica => {
3868                            // Local paid-list membership authorizes the key.
3869                            // We still need a presence probe to discover fetch
3870                            // sources, but we must not require remote paid
3871                            // majority or presence quorum.
3872                            local_paid_presence_probe_keys.push(*key);
3873                        }
3874                    }
3875                }
3876            } else {
3877                keys_needing_network.push(*key);
3878            }
3879        }
3880    }
3881
3882    if !local_paid_paid_only_keys.is_empty() {
3883        let mut terminal_paid_only = Vec::new();
3884        for key in local_paid_paid_only_keys {
3885            if storage.exists(&key).unwrap_or(false) {
3886                terminal_paid_only.push(key);
3887            } else if admission::is_responsible(
3888                &self_id,
3889                &key,
3890                p2p_node,
3891                storage_admission_width(config.close_group_size),
3892            )
3893            .await
3894            {
3895                local_paid_presence_probe_keys.push(key);
3896            } else {
3897                terminal_paid_only.push(key);
3898            }
3899        }
3900
3901        if !terminal_paid_only.is_empty() {
3902            let mut q = queues.write().await;
3903            for key in terminal_paid_only {
3904                q.remove_pending(&key);
3905                terminal_keys.push(key);
3906            }
3907        }
3908    }
3909
3910    let local_paid_probe_count = local_paid_presence_probe_keys.len();
3911    let keys_needing_network_count = keys_needing_network.len();
3912
3913    // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
3914    // step 4, authorization succeeds immediately; run a presence-only probe
3915    // to find any holder we can fetch from.
3916    if !local_paid_presence_probe_keys.is_empty() {
3917        let targets = quorum::compute_presence_targets(
3918            &local_paid_presence_probe_keys,
3919            p2p_node,
3920            config,
3921            &self_id,
3922        )
3923        .await;
3924        let evidence = quorum::run_verification_round(
3925            &local_paid_presence_probe_keys,
3926            &targets,
3927            p2p_node,
3928            config,
3929        )
3930        .await;
3931
3932        let mut q = queues.write().await;
3933        for key in local_paid_presence_probe_keys {
3934            if storage.exists(&key).unwrap_or(false) {
3935                q.remove_pending(&key);
3936                terminal_keys.push(key);
3937                continue;
3938            }
3939            let sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
3940                quorum::present_sources_for_key(&key, ev, &targets)
3941            });
3942            if sources.is_empty() {
3943                // Terminal failure: remove pending and report. No fetch path.
3944                q.remove_pending(&key);
3945                warn!(
3946                    "Locally paid key {} has no responding holders (possible data loss)",
3947                    hex::encode(key)
3948                );
3949                terminal_keys.push(key);
3950            } else {
3951                let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
3952                // Atomic remove+enqueue: if fetch_queue is at capacity, the
3953                // pending entry is preserved and retried next cycle (no
3954                // silent drop of verified replica-repair work).
3955                let _ = q.promote_pending_to_fetch(key, distance, sources);
3956            }
3957        }
3958    }
3959
3960    // Steps 2-5: Network verification (skipped if all keys resolved locally).
3961    if !keys_needing_network.is_empty() {
3962        // Step 2: Compute targets and run network verification round.
3963        let targets =
3964            quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
3965                .await;
3966
3967        let evidence =
3968            quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
3969
3970        // Step 3: Evaluate results — collect outcomes without holding the write
3971        // lock across paid-list I/O.
3972        //
3973        // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
3974        // table and recent_provers cache up front so the synchronous
3975        // evaluate_key_evidence_with_holder_check predicate can consult
3976        // them without awaiting. The predicate downgrades a Present
3977        // claim to Unresolved unless the peer is credited for that key.
3978        // Snapshot per-peer commitment data. We need two views:
3979        //   - `commitment_by_peer_snapshot`: peers that currently have
3980        //     a verified commitment record on file (used to look up
3981        //     their current hash).
3982        //   - `capable_peer_snapshot`: the sticky "ever v12-capable"
3983        //     set. Sourced from a separate set rather than the
3984        //     commitment map so eviction (PeerRemoved cleanup, sybil
3985        //     cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
3986        //     a previously-v12 peer to "legacy" credit-unconditionally.
3987        //     Legacy / pre-v12 peers that have never sent a commitment
3988        //     remain absent from the set and are credited via the
3989        //     legacy path so mixed-version networks stay live.
3990        let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
3991            let map = last_commitment_by_peer.read().await;
3992            map.iter()
3993                // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
3994                // of every peer's ~5 KiB commitment.
3995                .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
3996                .collect()
3997        };
3998        let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
3999        // Take a full snapshot of recent_provers under the read lock,
4000        // then release. The cache is bounded (16/key × keys), so the
4001        // clone is cheap.
4002        let provers_snapshot = recent_provers.read().await.clone();
4003        // For the replica-fetch path, we need to know whether THIS
4004        // node already holds the key being verified. The v12 §6
4005        // holder-credit gate is meant to prevent uncredited Present
4006        // claims from contributing to paid-list / reward quorum for
4007        // keys we DO hold (and could audit ourselves). For keys we
4008        // are trying to FETCH (i.e. not in local storage), there is
4009        // no possible local audit credit, and gating the presence
4010        // quorum on credit would deadlock replica-repair in a
4011        // fully v12-capable close group.
4012        let mut locally_held: HashSet<XorName> = HashSet::new();
4013        for key in &keys_needing_network {
4014            if storage.exists(key).unwrap_or(false) {
4015                locally_held.insert(*key);
4016            }
4017        }
4018        let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
4019            if !locally_held.contains(key) {
4020                // Replica-fetch path: we don't hold this key, so we
4021                // cannot have collected audit credit for it. Trust
4022                // Present claims to drive fetch-source promotion;
4023                // chunk-PUT payment_verifier is the security backstop
4024                // when the bytes actually arrive.
4025                return true;
4026            }
4027            if !capable_peer_snapshot.contains(peer) {
4028                // Pre-v12 / legacy peer that has never gossiped a
4029                // commitment. The v12 §6 holder-eligibility check
4030                // doesn't apply: their Present evidence comes through
4031                // the legacy path and we credit it unconditionally
4032                // so a mixed-version network stays live during
4033                // transition.
4034                return true;
4035            }
4036            let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
4037                // Peer is commitment_capable (sticky) but currently
4038                // has no live commitment record on file (e.g. their
4039                // last gossip was evicted from the LRU cache, or it
4040                // failed verification). Withhold credit until they
4041                // re-prove storage under a fresh commitment.
4042                return false;
4043            };
4044            provers_snapshot.is_credited_holder(key, peer, hash)
4045        };
4046
4047        let mut evaluated: Vec<(XorName, KeyVerificationOutcome, HintPipeline)> = Vec::new();
4048        {
4049            let q = queues.read().await;
4050            for key in &keys_needing_network {
4051                let Some(ev) = evidence.get(key) else {
4052                    continue;
4053                };
4054                let Some(entry) = q.get_pending(key) else {
4055                    continue;
4056                };
4057                let outcome = quorum::evaluate_key_evidence_with_holder_check(
4058                    key,
4059                    ev,
4060                    &targets,
4061                    config,
4062                    holder_credit,
4063                );
4064                evaluated.push((*key, outcome, entry.pipeline));
4065            }
4066        } // read lock released
4067
4068        // Step 4: Insert verified keys into PaidForList (no lock held).
4069        let mut paid_insert_keys: Vec<XorName> = Vec::new();
4070        for (key, outcome, _) in &evaluated {
4071            if matches!(
4072                outcome,
4073                KeyVerificationOutcome::QuorumVerified { .. }
4074                    | KeyVerificationOutcome::PaidListVerified { .. }
4075            ) {
4076                paid_insert_keys.push(*key);
4077            }
4078        }
4079        for key in &paid_insert_keys {
4080            if let Err(e) = paid_list.insert(key).await {
4081                warn!("Failed to add verified key to PaidForList: {e}");
4082            }
4083        }
4084
4085        // Paid-only hints normally update PaidForList only. If this node is
4086        // also within the storage-admission group for the key, a verified
4087        // paid-only hint can safely repair a missing replica using sources
4088        // from the same verification round.
4089        let mut paid_only_fetch_keys: HashSet<XorName> = HashSet::new();
4090        for (key, outcome, pipeline) in &evaluated {
4091            if *pipeline == HintPipeline::PaidOnly
4092                && matches!(
4093                    outcome,
4094                    KeyVerificationOutcome::QuorumVerified { .. }
4095                        | KeyVerificationOutcome::PaidListVerified { .. }
4096                )
4097                && !storage.exists(key).unwrap_or(false)
4098                && admission::is_responsible(
4099                    &self_id,
4100                    key,
4101                    p2p_node,
4102                    storage_admission_width(config.close_group_size),
4103                )
4104                .await
4105            {
4106                paid_only_fetch_keys.insert(*key);
4107            }
4108        }
4109
4110        // Step 5: Update queues with the evaluated outcomes.
4111        let mut q = queues.write().await;
4112        for (key, outcome, pipeline) in evaluated {
4113            match outcome {
4114                KeyVerificationOutcome::QuorumVerified { sources }
4115                | KeyVerificationOutcome::PaidListVerified { sources } => {
4116                    let fetch_eligible =
4117                        pipeline == HintPipeline::Replica || paid_only_fetch_keys.contains(&key);
4118                    if fetch_eligible && !sources.is_empty() {
4119                        let distance =
4120                            crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
4121                        // Atomic remove+enqueue: on fetch_queue capacity miss
4122                        // the pending entry is preserved so this verified key
4123                        // is retried on the next cycle (no silent drop).
4124                        let _ = q.promote_pending_to_fetch(key, distance, sources);
4125                        // Not terminal — either moved to fetch queue, or
4126                        // retained as pending until queue drains.
4127                    } else if fetch_eligible && sources.is_empty() {
4128                        warn!(
4129                            "Verified storage-admitted key {} has no holders (possible data loss)",
4130                            hex::encode(key)
4131                        );
4132                        q.remove_pending(&key);
4133                        terminal_keys.push(key);
4134                    } else {
4135                        q.remove_pending(&key);
4136                        terminal_keys.push(key);
4137                    }
4138                }
4139                KeyVerificationOutcome::QuorumFailed
4140                | KeyVerificationOutcome::QuorumInconclusive => {
4141                    q.remove_pending(&key);
4142                    terminal_keys.push(key);
4143                }
4144            }
4145        }
4146    }
4147
4148    // Step 6: Remove terminal keys from bootstrap pending set and re-check
4149    // the drain condition.
4150    update_bootstrap_after_verification(
4151        &terminal_keys,
4152        bootstrap_state,
4153        queues,
4154        is_bootstrapping,
4155        bootstrap_complete_notify,
4156    )
4157    .await;
4158
4159    let (pending_after, fetch_after, in_flight_after) = {
4160        let q = queues.read().await;
4161        (
4162            q.pending_count(),
4163            q.fetch_queue_count(),
4164            q.in_flight_count(),
4165        )
4166    };
4167    let terminal_key_count = terminal_keys.len();
4168    let elapsed_ms = cycle_started.elapsed().as_millis();
4169
4170    if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
4171        info!(
4172            target: "ant_node::replication::verification",
4173            "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}",
4174        );
4175    } else {
4176        debug!(
4177            target: "ant_node::replication::verification",
4178            "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}",
4179        );
4180    }
4181}
4182
4183/// Post-verification bootstrap bookkeeping: remove terminal keys from the
4184/// bootstrap pending set and transition out of bootstrapping when drained.
4185async fn update_bootstrap_after_verification(
4186    terminal_keys: &[XorName],
4187    bootstrap_state: &Arc<RwLock<BootstrapState>>,
4188    queues: &Arc<RwLock<ReplicationQueues>>,
4189    is_bootstrapping: &Arc<RwLock<bool>>,
4190    bootstrap_complete_notify: &Arc<Notify>,
4191) {
4192    if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
4193        return;
4194    }
4195    {
4196        let mut bs = bootstrap_state.write().await;
4197        for key in terminal_keys {
4198            bs.remove_key(key);
4199        }
4200    }
4201    let q = queues.read().await;
4202    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
4203        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
4204    }
4205}
4206
4207/// Set `is_bootstrapping` to `false` and wake all waiters.
4208async fn complete_bootstrap(
4209    is_bootstrapping: &Arc<RwLock<bool>>,
4210    bootstrap_complete_notify: &Arc<Notify>,
4211) {
4212    *is_bootstrapping.write().await = false;
4213    bootstrap_complete_notify.notify_waiters();
4214    info!("Replication bootstrap complete");
4215}
4216
4217// ---------------------------------------------------------------------------
4218// Fetch types and single-fetch executor
4219// ---------------------------------------------------------------------------
4220
4221/// Result classification for a single fetch attempt.
4222enum FetchResult {
4223    /// Data fetched, integrity-checked, and stored successfully.
4224    Stored,
4225    /// Content-address integrity check failed — do not retry.
4226    IntegrityFailed,
4227    /// Source failed (network error or non-success response) — retryable.
4228    SourceFailed,
4229}
4230
4231/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
4232/// worker loop to update queue state.
4233struct FetchOutcome {
4234    key: XorName,
4235    result: FetchResult,
4236}
4237
4238#[allow(clippy::too_many_lines)]
4239/// Execute a single fetch request against `source` for `key`.
4240///
4241/// Handles encoding, network I/O, integrity checking, storage, and trust
4242/// event reporting.  Returns a [`FetchOutcome`] so the caller can update
4243/// queue state without holding any locks during the network round-trip.
4244async fn execute_single_fetch(
4245    p2p_node: Arc<P2PNode>,
4246    storage: Arc<LmdbStorage>,
4247    config: Arc<ReplicationConfig>,
4248    key: XorName,
4249    source: PeerId,
4250) -> FetchOutcome {
4251    let request = protocol::FetchRequest { key };
4252    let msg = ReplicationMessage {
4253        request_id: rand::thread_rng().gen::<u64>(),
4254        body: ReplicationMessageBody::FetchRequest(request),
4255    };
4256
4257    let encoded = match msg.encode() {
4258        Ok(data) => data,
4259        Err(e) => {
4260            warn!("Failed to encode fetch request: {e}");
4261            return FetchOutcome {
4262                key,
4263                result: FetchResult::SourceFailed,
4264            };
4265        }
4266    };
4267
4268    let result = p2p_node
4269        .send_request(
4270            &source,
4271            REPLICATION_PROTOCOL_ID,
4272            encoded,
4273            config.fetch_request_timeout,
4274        )
4275        .await;
4276
4277    match result {
4278        Ok(response) => {
4279            let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
4280                p2p_node
4281                    .report_trust_event(
4282                        &source,
4283                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4284                    )
4285                    .await;
4286                return FetchOutcome {
4287                    key,
4288                    result: FetchResult::SourceFailed,
4289                };
4290            };
4291
4292            match resp_msg.body {
4293                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
4294                    key: resp_key,
4295                    data,
4296                }) => {
4297                    // Validate the response key matches the requested key.
4298                    // A malicious peer could serve valid data for a different
4299                    // key, passing integrity checks while the requested key
4300                    // is falsely marked as fetched.
4301                    if resp_key != key {
4302                        warn!(
4303                            "Fetch response key mismatch: requested {}, got {}",
4304                            hex::encode(key),
4305                            hex::encode(resp_key)
4306                        );
4307                        p2p_node
4308                            .report_trust_event(
4309                                &source,
4310                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4311                            )
4312                            .await;
4313                        return FetchOutcome {
4314                            key,
4315                            result: FetchResult::IntegrityFailed,
4316                        };
4317                    }
4318
4319                    // Enforce chunk size invariant on fetched data.
4320                    // Checked before the content-address hash to avoid
4321                    // hashing up to 10 MiB of oversized junk data.
4322                    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
4323                        warn!(
4324                            "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
4325                            hex::encode(resp_key),
4326                            data.len(),
4327                            crate::ant_protocol::MAX_CHUNK_SIZE,
4328                        );
4329                        p2p_node
4330                            .report_trust_event(
4331                                &source,
4332                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4333                            )
4334                            .await;
4335                        return FetchOutcome {
4336                            key,
4337                            result: FetchResult::IntegrityFailed,
4338                        };
4339                    }
4340
4341                    // Content-address integrity check.
4342                    let computed = crate::client::compute_address(&data);
4343                    if computed != resp_key {
4344                        warn!(
4345                            "Fetched record integrity check failed: expected {}, got {}",
4346                            hex::encode(resp_key),
4347                            hex::encode(computed)
4348                        );
4349                        p2p_node
4350                            .report_trust_event(
4351                                &source,
4352                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4353                            )
4354                            .await;
4355                        return FetchOutcome {
4356                            key,
4357                            result: FetchResult::IntegrityFailed,
4358                        };
4359                    }
4360
4361                    if let Err(e) = storage.put(&resp_key, &data).await {
4362                        warn!(
4363                            "Failed to store fetched record {}: {e}",
4364                            hex::encode(resp_key)
4365                        );
4366                        return FetchOutcome {
4367                            key,
4368                            result: FetchResult::SourceFailed,
4369                        };
4370                    }
4371
4372                    FetchOutcome {
4373                        key,
4374                        result: FetchResult::Stored,
4375                    }
4376                }
4377                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::NotFound {
4378                    ..
4379                }) => {
4380                    // This peer was selected as a fetch source because it
4381                    // recently answered `Present` during verification. A
4382                    // subsequent NotFound is evidence of a stale/false claim
4383                    // or chunk wiping, so penalize lightly and try another
4384                    // verified source.
4385                    warn!(
4386                        "Fetch: verified source {source} returned NotFound for {}",
4387                        hex::encode(key)
4388                    );
4389                    p2p_node
4390                        .report_trust_event(
4391                            &source,
4392                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4393                        )
4394                        .await;
4395                    FetchOutcome {
4396                        key,
4397                        result: FetchResult::SourceFailed,
4398                    }
4399                }
4400                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Error {
4401                    reason,
4402                    ..
4403                }) => {
4404                    warn!(
4405                        "Fetch: peer {source} returned error for {}: {reason}",
4406                        hex::encode(key)
4407                    );
4408                    p2p_node
4409                        .report_trust_event(
4410                            &source,
4411                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4412                        )
4413                        .await;
4414                    FetchOutcome {
4415                        key,
4416                        result: FetchResult::SourceFailed,
4417                    }
4418                }
4419                _ => {
4420                    // Unexpected message type — treat as malformed.
4421                    p2p_node
4422                        .report_trust_event(
4423                            &source,
4424                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4425                        )
4426                        .await;
4427                    FetchOutcome {
4428                        key,
4429                        result: FetchResult::SourceFailed,
4430                    }
4431                }
4432            }
4433        }
4434        Err(e) => {
4435            debug!("Fetch request to {source} failed: {e}");
4436            // No ApplicationFailure here — P2PNode::send_request() already
4437            // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
4438            FetchOutcome {
4439                key,
4440                result: FetchResult::SourceFailed,
4441            }
4442        }
4443    }
4444}
4445
4446// ---------------------------------------------------------------------------
4447// Audit result handler
4448// ---------------------------------------------------------------------------
4449
4450/// Format the first confirmed-failed key as a 16-hex-char label.
4451///
4452/// Pairs with `challenged_peer` to form a stable cross-host correlation
4453/// handle in the audit-failure log line, e.g.
4454///
4455/// ```text
4456/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
4457/// ```
4458///
4459/// Falls back to `"0x"` when the list is empty so the log line never
4460/// contains a misleading default.
4461fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
4462    confirmed_failed_keys.first().map_or_else(
4463        || "0x".to_string(),
4464        |k| format!("0x{}", hex::encode(&k[..8])),
4465    )
4466}
4467
4468/// Execute the side effects for a subtree storage-commitment audit failure.
4469///
4470/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
4471/// legitimately time out on slow or loaded honest peers, so it never touches the
4472/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
4473/// failures still penalise immediately and revoke holder credit.
4474async fn handle_subtree_failed_audit(
4475    challenged_peer: &PeerId,
4476    confirmed_failed_key_count: usize,
4477    reason: &AuditFailureReason,
4478    p2p_node: &Arc<P2PNode>,
4479    sync_state: &Arc<RwLock<NeighborSyncState>>,
4480    recent_provers: &Arc<RwLock<RecentProvers>>,
4481) {
4482    if matches!(reason, AuditFailureReason::Timeout) {
4483        debug!(
4484            "Audit timeout for {challenged_peer} fully graced \
4485             (subtree audit does not evict on timeout)"
4486        );
4487        return;
4488    }
4489
4490    // The caller already logged the rich failure line with reason + per-category
4491    // summary; avoid a redundant second error log here.
4492    let _ = confirmed_failed_key_count;
4493    {
4494        let mut state = sync_state.write().await;
4495        state.clear_active_bootstrap_claim(challenged_peer);
4496    }
4497    {
4498        let mut provers_guard = recent_provers.write().await;
4499        apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
4500    }
4501    p2p_node
4502        .report_trust_event(
4503            challenged_peer,
4504            TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
4505        )
4506        .await;
4507}
4508
4509/// Handle audit result: log findings and emit trust events.
4510async fn handle_subtree_audit_result(
4511    result: &AuditTickResult,
4512    p2p_node: &Arc<P2PNode>,
4513    sync_state: &Arc<RwLock<NeighborSyncState>>,
4514    recent_provers: &Arc<RwLock<RecentProvers>>,
4515    config: &ReplicationConfig,
4516) {
4517    match result {
4518        AuditTickResult::Passed {
4519            challenged_peer,
4520            keys_checked,
4521        } => {
4522            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
4523            // Peer responded normally — clear the active bootstrap claim while
4524            // retaining history so a later claim is treated as repeated abuse.
4525            {
4526                let mut state = sync_state.write().await;
4527                state.clear_active_bootstrap_claim(challenged_peer);
4528            }
4529            p2p_node
4530                .report_trust_event(
4531                    challenged_peer,
4532                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
4533                )
4534                .await;
4535        }
4536        AuditTickResult::Failed { evidence } => {
4537            if let FailureEvidence::AuditFailure {
4538                challenged_peer,
4539                confirmed_failed_keys,
4540                summary,
4541                reason,
4542                ..
4543            } = evidence
4544            {
4545                // Rich diagnostics (from main's audit-failure logging) + the
4546                // first-failed-key correlation handle.
4547                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
4548                error!(
4549                    "Audit failure for {challenged_peer}: reason={reason:?}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
4550                    confirmed_failed_keys.len(),
4551                    summary.challenged_keys,
4552                    summary.absent_keys,
4553                    summary.digest_mismatch_keys,
4554                );
4555                // Route the side effects through the subtree-only failure path.
4556                // Responsible-chunk `AuditChallenge` handling intentionally uses
4557                // its own old immediate-penalty handler below.
4558                handle_subtree_failed_audit(
4559                    challenged_peer,
4560                    confirmed_failed_keys.len(),
4561                    reason,
4562                    p2p_node,
4563                    sync_state,
4564                    recent_provers,
4565                )
4566                .await;
4567            }
4568        }
4569        AuditTickResult::BootstrapClaim { peer } => {
4570            // Gap 6: BootstrapClaimAbuse grace period in audit path.
4571            // Separate state mutation from network I/O to avoid holding the
4572            // write lock across report_trust_event.
4573            let should_report = {
4574                let now = Instant::now();
4575                let mut state = sync_state.write().await;
4576                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
4577                {
4578                    BootstrapClaimObservation::WithinGrace { .. } => {
4579                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
4580                        false
4581                    }
4582                    BootstrapClaimObservation::PastGrace { first_seen } => {
4583                        warn!(
4584                            "Audit: peer {peer} claiming bootstrap past grace period \
4585                             ({:?} > {:?}), reporting abuse",
4586                            now.duration_since(first_seen),
4587                            config.bootstrap_claim_grace_period,
4588                        );
4589                        true
4590                    }
4591                    BootstrapClaimObservation::Repeated { first_seen } => {
4592                        warn!(
4593                            "Audit: peer {peer} repeated bootstrap claim after previously \
4594                             stopping; first claim was {:?} ago, reporting abuse",
4595                            now.duration_since(first_seen),
4596                        );
4597                        true
4598                    }
4599                }
4600            };
4601            if should_report {
4602                p2p_node
4603                    .report_trust_event(
4604                        peer,
4605                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4606                    )
4607                    .await;
4608            }
4609        }
4610        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
4611    }
4612}
4613
4614/// Whether a confirmed audit failure with this reason clears the peer's active
4615/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
4616/// bootstrapping); every confirmed storage-integrity reason does.
4617///
4618/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
4619/// the bootstrap claim but are still reported as audit failures, matching the
4620/// pre-ADR-0002 behaviour.
4621fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
4622    !matches!(reason, AuditFailureReason::Timeout)
4623}
4624
4625/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
4626/// events and manage bootstrap-claim state.
4627///
4628/// This is intentionally separate from the subtree audit result handler. A
4629/// responsible-chunk `AuditChallenge` `Failed` result reports
4630/// `ApplicationFailure` immediately for every reason, including `Timeout`,
4631/// restoring the pre-ADR-0002 behaviour.
4632async fn handle_audit_result(
4633    result: &AuditTickResult,
4634    p2p_node: &Arc<P2PNode>,
4635    sync_state: &Arc<RwLock<NeighborSyncState>>,
4636    config: &ReplicationConfig,
4637) {
4638    match result {
4639        AuditTickResult::Passed {
4640            challenged_peer,
4641            keys_checked,
4642        } => {
4643            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
4644            {
4645                let mut state = sync_state.write().await;
4646                state.clear_active_bootstrap_claim(challenged_peer);
4647            }
4648            p2p_node
4649                .report_trust_event(
4650                    challenged_peer,
4651                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
4652                )
4653                .await;
4654        }
4655        AuditTickResult::Failed { evidence } => {
4656            if let FailureEvidence::AuditFailure {
4657                challenged_peer,
4658                confirmed_failed_keys,
4659                summary,
4660                reason,
4661                ..
4662            } = evidence
4663            {
4664                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
4665                error!(
4666                    "Audit failure for {challenged_peer}: reason={reason:?}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
4667                    confirmed_failed_keys.len(),
4668                    summary.challenged_keys,
4669                    summary.absent_keys,
4670                    summary.digest_mismatch_keys,
4671                );
4672                if audit_failure_clears_bootstrap_claim(reason) {
4673                    let mut state = sync_state.write().await;
4674                    state.clear_active_bootstrap_claim(challenged_peer);
4675                } else {
4676                    debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
4677                }
4678                p2p_node
4679                    .report_trust_event(
4680                        challenged_peer,
4681                        TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
4682                    )
4683                    .await;
4684            }
4685        }
4686        AuditTickResult::BootstrapClaim { peer } => {
4687            let should_report = {
4688                let now = Instant::now();
4689                let mut state = sync_state.write().await;
4690                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
4691                {
4692                    BootstrapClaimObservation::WithinGrace { .. } => {
4693                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
4694                        false
4695                    }
4696                    BootstrapClaimObservation::PastGrace { first_seen } => {
4697                        warn!(
4698                            "Audit: peer {peer} claiming bootstrap past grace period \
4699                             ({:?} > {:?}), reporting abuse",
4700                            now.duration_since(first_seen),
4701                            config.bootstrap_claim_grace_period,
4702                        );
4703                        true
4704                    }
4705                    BootstrapClaimObservation::Repeated { first_seen } => {
4706                        warn!(
4707                            "Audit: peer {peer} repeated bootstrap claim after previously \
4708                             stopping; first claim was {:?} ago, reporting abuse",
4709                            now.duration_since(first_seen),
4710                        );
4711                        true
4712                    }
4713                }
4714            };
4715            if should_report {
4716                p2p_node
4717                    .report_trust_event(
4718                        peer,
4719                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4720                    )
4721                    .await;
4722            }
4723        }
4724        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
4725    }
4726}
4727
4728/// Whether a confirmed audit failure with this reason should revoke the
4729/// peer's `recent_provers` holder credit immediately (v12 §6).
4730///
4731/// `true` for any reason where the peer actually answered (or admitted
4732/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
4733/// bytes for committed key"), `MalformedResponse` — these prove the
4734/// peer no longer holds what it committed to, so it must not keep
4735/// holder credit for the proof TTL. `false` for `Timeout`: a single
4736/// dropped packet must not strip an honest peer; the 40-min TTL is the
4737/// deliberate liveness cushion there.
4738fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
4739    !matches!(reason, AuditFailureReason::Timeout)
4740}
4741
4742/// Apply the holder-credit revocation decision for a confirmed audit
4743/// failure. Pure over `RecentProvers` so the handler wiring is unit-
4744/// testable without a live `P2PNode`: the production `Failed` arm of
4745/// `handle_subtree_audit_result` calls exactly this.
4746fn apply_audit_failure_credit_revocation(
4747    provers: &mut RecentProvers,
4748    challenged_peer: &PeerId,
4749    reason: &AuditFailureReason,
4750) {
4751    if audit_failure_revokes_holder_credit(reason) {
4752        provers.forget_peer(challenged_peer);
4753    }
4754}
4755
4756// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
4757
4758// ---------------------------------------------------------------------------
4759// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
4760// ---------------------------------------------------------------------------
4761
4762/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
4763/// message handler passes one value instead of a long argument list; all
4764/// fields are cheap `Arc` clones.
4765#[derive(Clone)]
4766struct GossipAuditTrigger {
4767    p2p_node: Arc<P2PNode>,
4768    config: Arc<ReplicationConfig>,
4769    recent_provers: Arc<RwLock<RecentProvers>>,
4770    sync_state: Arc<RwLock<NeighborSyncState>>,
4771    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4772}
4773
4774/// What a gossip ingest yields for the audit trigger: the commitment hash to
4775/// pin and the `key_count` needed to size the response deadline from the actual
4776/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
4777/// or not) so a stable-keyset node stays auditable — not just on its first
4778/// commitment.
4779#[derive(Debug, Clone, Copy)]
4780struct AuditTarget {
4781    pin_hash: [u8; 32],
4782    key_count: u32,
4783}
4784
4785/// ADR-0004: a commitment that backed a payment, surfaced by the payment
4786/// verifier's cross-check so it can receive a **deterministic first audit**.
4787///
4788/// Sent from the verifier to the replication engine's first-audit drainer. The
4789/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
4790/// audits of the same peer revert to the gossip lottery), orders most-recently-
4791/// monetized first, and runs the same `run_subtree_audit` under the same
4792/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
4793#[derive(Debug, Clone, Copy)]
4794pub struct MonetizedPinEvent {
4795    /// The peer whose commitment backed the payment.
4796    pub peer: PeerId,
4797    /// The pinned commitment hash.
4798    pub pin: [u8; 32],
4799    /// The committed key count (sizes the audit deadline).
4800    pub key_count: u32,
4801    /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
4802    /// pin whose quote is older than the answerability window (ADR-0004 A1
4803    /// guardrail A): with grace removed, challenging an aged-out pin would
4804    /// false-convict, so a stale client-forwarded quote must not trigger an audit.
4805    pub quote_ts: SystemTime,
4806}
4807
4808/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
4809/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
4810/// stamps `now`), `false` if it was audited within
4811/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
4812/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
4813/// without a live node: a burst of gossips from one peer yields at most one
4814/// `true` per cooldown window.
4815fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
4816    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
4817    let known = match map.get(peer) {
4818        Some(&last) => {
4819            if now.saturating_duration_since(last) < cooldown {
4820                return false;
4821            }
4822            true
4823        }
4824        None => false,
4825    };
4826    // Bound the map under churn like its siblings (drop the oldest stamp) before
4827    // admitting a brand-new peer.
4828    if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
4829        if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
4830            map.remove(&victim);
4831        }
4832    }
4833    map.insert(*peer, now);
4834    true
4835}
4836
4837/// The gossip-audit launch decision in ONE place so the ordering is shared
4838/// between production and its test (ADR-0002 "occasional surprise exams").
4839///
4840/// Order matters and is the security-relevant property: the per-peer cooldown is
4841/// checked-and-stamped FIRST, THEN the probability lottery (`lottery_wins`) is
4842/// applied. If the lottery were sampled first, a gossip flood would re-roll it on
4843/// every message until one won, multiplying audits. Because the cooldown is
4844/// stamped before the lottery is consulted, a LOSING ticket still consumes the
4845/// window — so each peer gets at most one audit lottery per cooldown window
4846/// regardless of how often it gossips. Production calls this with
4847/// `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the test calls it with
4848/// a deterministic `lottery_wins`, so a reorder regression here fails the test.
4849fn audit_launch_decision(
4850    map: &mut HashMap<PeerId, Instant>,
4851    peer: &PeerId,
4852    now: Instant,
4853    lottery_wins: bool,
4854) -> bool {
4855    // Gate 1: cooldown check-and-stamp (consumes the window even on a loss).
4856    if !cooldown_allows_audit(map, peer, now) {
4857        return false;
4858    }
4859    // Gate 2: the probability lottery.
4860    lottery_wins
4861}
4862
4863/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
4864/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
4865/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
4866/// handling is never blocked on a network round-trip.
4867async fn maybe_trigger_gossip_audit(
4868    trigger: &GossipAuditTrigger,
4869    peer: &PeerId,
4870    target: AuditTarget,
4871) {
4872    // The launch decision (cooldown-then-lottery ordering) lives in the pure
4873    // `audit_launch_decision` so the ordering is shared with its test. Sample
4874    // the lottery here, then let the helper apply it AFTER the cooldown stamp.
4875    let now = Instant::now();
4876    let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
4877    {
4878        let mut map = trigger.cooldown.write().await;
4879        if !audit_launch_decision(&mut map, peer, now, lottery_wins) {
4880            return;
4881        }
4882    }
4883
4884    let trigger = trigger.clone();
4885    let peer = *peer;
4886    tokio::spawn(async move {
4887        let credit = storage_commitment_audit::AuditCredit {
4888            recent_provers: &trigger.recent_provers,
4889        };
4890        let result = storage_commitment_audit::run_subtree_audit(
4891            &trigger.p2p_node,
4892            &trigger.config,
4893            &peer,
4894            target.pin_hash,
4895            target.key_count,
4896            Some(&credit),
4897        )
4898        .await;
4899        handle_subtree_audit_result(
4900            &result,
4901            &trigger.p2p_node,
4902            &trigger.sync_state,
4903            &trigger.recent_provers,
4904            &trigger.config,
4905        )
4906        .await;
4907    });
4908}
4909
4910/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
4911///
4912/// Returns `true` if a signature verify is allowed now (and stamps the attempt
4913/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
4914/// of its last attempt. Holds one write lock across the decision so two
4915/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
4916/// caller's expensive verify so a slow/failed verify still rate-limits the next
4917/// message. Bounds the map under a flood of distinct peer ids.
4918async fn sig_verify_rate_limit_ok(
4919    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
4920    source: &PeerId,
4921    now: Instant,
4922) -> bool {
4923    let mut attempts = sig_verify_attempts.write().await;
4924    if let Some(&last) = attempts.get(source) {
4925        if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
4926            return false;
4927        }
4928    }
4929    if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
4930        if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
4931            attempts.remove(&victim);
4932        }
4933    }
4934    attempts.insert(*source, now);
4935    true
4936}
4937
4938/// Verify + store an inbound commitment from a gossip peer.
4939///
4940/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
4941/// the bootstrap-sync loop. Drops the commitment unless all five gates
4942/// pass:
4943///   1. `source` is in our DHT routing table (sybil/churn cap).
4944///   2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
4945///      binding to the authenticated transport peer).
4946///   3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
4947///      (the embedded pubkey actually belongs to the claimed identity —
4948///      saorsa-core derives `PeerId = BLAKE3(pubkey)`).
4949///   4. `verify_commitment_signature(commitment)` succeeds against the
4950///      embedded public key. The signed payload binds the pubkey, so an
4951///      adversary cannot swap the key while keeping the body.
4952///   5. The cache has room or this is an update for an existing entry
4953///      (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
4954///
4955/// On all-pass, the commitment is stored as the auditor's per-peer
4956/// "last known commitment" for use as `expected_commitment_hash` in
4957/// future audits.
4958///
4959/// Failures (no commitment / mismatched peer id / bad signature) are
4960/// silent drops — gossip is best-effort and a malformed commitment from
4961/// one peer should not affect anything else.
4962///
4963/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
4964/// or not its root changed), so the caller can run a probabilistic,
4965/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
4966/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
4967/// being auditable, so it cannot pass one audit and then delete data while
4968/// re-gossiping the same root forever. The cooldown + probability bound the
4969/// audit frequency. Returns `None` only if the commitment was dropped (failed a
4970/// gate) or there is nothing to pin.
4971///
4972/// Handle a capable peer gossiping `None` (a commitment downgrade).
4973///
4974/// A capable peer that previously gossiped a commitment but now gossips `None`
4975/// is trying to drop off the audit path. Within the answerability window we keep
4976/// the cached commitment pinned AND return it as an audit target so this gossip
4977/// still schedules a subtree audit against the peer's last known commitment — if
4978/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
4979/// the trigger MUST fire here or the downgrade is never re-challenged).
4980///
4981/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
4982/// honours for its own retired commitment: once that elapses since we last
4983/// received the peer's commitment, an honest peer has legitimately retired that
4984/// root (its responder side `retire_current`s and lets it age out) and can no
4985/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
4986/// failure, so we then forget the cached commitment (keeping the sticky
4987/// `commitment_capable` bit) and stop pinning it.
4988async fn handle_commitment_downgrade(
4989    source: &PeerId,
4990    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4991) -> Option<AuditTarget> {
4992    let now = Instant::now();
4993    let cached = {
4994        let map = last_commitment_by_peer.read().await;
4995        map.get(source).and_then(|rec| {
4996            if !rec.commitment_capable {
4997                return None;
4998            }
4999            let last = rec.last_commitment()?;
5000            let pin = rec.commitment_hash()?;
5001            let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
5002            Some((pin, last.key_count, fresh))
5003        })
5004    };
5005    match cached {
5006        Some((pin, key_count, true)) => {
5007            warn!(
5008                "ingest_peer_commitment: commitment-capable peer {source} sent None \
5009                 (downgrade attempt); auditing against its last cached commitment"
5010            );
5011            Some(AuditTarget {
5012                pin_hash: pin,
5013                key_count,
5014            })
5015        }
5016        Some((_, _, false)) => {
5017            // Cached commitment has aged past the answerability window — forget
5018            // it so we stop pinning a root the peer is no longer obliged to
5019            // answer. Keep `commitment_capable` (sticky). Re-check freshness
5020            // UNDER the write lock (compare-and-clear): a concurrent valid gossip
5021            // from this peer may have refreshed `received_at` in the gap between
5022            // our read and write locks; if so, leave its fresh commitment intact.
5023            if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
5024                let still_stale =
5025                    now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
5026                if still_stale {
5027                    rec.clear_commitment();
5028                    debug!(
5029                        "ingest_peer_commitment: capable peer {source} sent None and its cached \
5030                         commitment aged past the answerability TTL; forgetting it"
5031                    );
5032                }
5033            }
5034            None
5035        }
5036        None => None,
5037    }
5038}
5039
5040async fn ingest_peer_commitment(
5041    source: &PeerId,
5042    commitment: Option<&StorageCommitment>,
5043    p2p_node: &Arc<P2PNode>,
5044    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
5045    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
5046    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
5047) -> Option<AuditTarget> {
5048    let Some(c) = commitment else {
5049        return handle_commitment_downgrade(source, last_commitment_by_peer).await;
5050    };
5051    // RT-membership gate: only accept commitments from peers in our
5052    // routing table. Off-RT senders (sybils, drive-by relays) cannot
5053    // populate the cache, which closes the hole where a flood of
5054    // off-RT identities could fill the cap and evict honest
5055    // peers. The neighbor-sync request handler applies the same gate
5056    // before admitting inbound replication hints (see neighbor_sync.rs
5057    // `sender_in_rt`); we mirror that policy here for the commitment
5058    // piggyback.
5059    if !p2p_node.dht_manager().is_in_routing_table(source).await {
5060        debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
5061        return None;
5062    }
5063    // Peer-id binding: the commitment's claimed sender must match the
5064    // authenticated transport peer (`source`). Defeats relay/replay
5065    // and also pins which embedded public key we are about to verify
5066    // against — the verify itself trusts the embedded key, so the
5067    // peer-id binding is the link to a real identity.
5068    if &c.sender_peer_id != source.as_bytes() {
5069        warn!(
5070            "ingest_peer_commitment: sender_peer_id mismatch from {source} \
5071             (dropped, possible relay attempt)"
5072        );
5073        return None;
5074    }
5075    // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
5076    // BLAKE3(pubkey_bytes). Without this check, a responder could sign
5077    // with a throwaway key they own and lie about which identity it
5078    // belongs to (the embedded-key signature would verify trivially).
5079    let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
5080    if derived_peer_id != c.sender_peer_id {
5081        warn!(
5082            "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
5083             {source} (dropped, throwaway-key attack)"
5084        );
5085        return None;
5086    }
5087    // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
5088    // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
5089    // sybil/RT-membership-bypassing peer that flooded valid-looking
5090    // gossip would otherwise burn CPU on every message. The rate
5091    // limit is checked AFTER cheap structural gates (RT, peer-id
5092    // binding, pubkey-binding) and BEFORE the expensive sig verify.
5093    //
5094    // Tracked in `sig_verify_attempts` (separate from
5095    // last_commitment_by_peer) so EVERY attempt — successful or not —
5096    // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
5097    // would skip the cap for peers we've never successfully verified,
5098    // letting a flood of invalid-but-structurally-plausible gossips
5099    // burn CPU.
5100    let now = Instant::now();
5101    if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
5102        debug!(
5103            "ingest_peer_commitment: rate-limited sig verify from {source} \
5104             (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
5105        );
5106        return None;
5107    }
5108    // Signature verify, using the public key embedded in the commitment
5109    // itself. The pubkey is bound by the signature payload (see
5110    // commitment_signed_payload) so an adversary cannot keep the body
5111    // and swap the key to one they hold the secret for.
5112    if !crate::replication::commitment::verify_commitment_signature(c) {
5113        warn!(
5114            "ingest_peer_commitment: signature did not verify under embedded key for {source} \
5115             (dropped, forged commitment)"
5116        );
5117        return None;
5118    }
5119    // The new commitment's hash, used to store and to pin for the audit target.
5120    let new_hash = commitment_hash(c);
5121    let mut map = last_commitment_by_peer.write().await;
5122    // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
5123    // evict an arbitrary existing entry to make room. Updates for peers
5124    // already in the map are always accepted (they replace, not grow).
5125    if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
5126        // Drop one arbitrary entry. HashMap iter order is random which
5127        // is fine — over time PeerRemoved cleanup keeps the working set
5128        // anchored on the real RT membership; this cap only fires under
5129        // active flooding attempts.
5130        if let Some(victim) = map.keys().next().copied() {
5131            map.remove(&victim);
5132            warn!(
5133                "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
5134                 evicted {victim} to admit {source}"
5135            );
5136        }
5137    }
5138    // Preserve sticky commitment_capable across updates — once true,
5139    // always true. New entries start with capable = true (we just
5140    // verified a valid commitment from this peer).
5141    map.entry(*source)
5142        .and_modify(|r| {
5143            // set_commitment refreshes the cached hash (§13) alongside the
5144            // commitment + received_at so they never drift.
5145            r.set_commitment(c.clone(), now);
5146            r.last_sig_verify_at = now;
5147            r.commitment_capable = true; // sticky-redundant but explicit
5148        })
5149        .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
5150    drop(map);
5151    // Record the sticky "ever v12-capable" bit in a set independent of
5152    // `last_commitment_by_peer` (whose entries can be evicted by
5153    // `PeerRemoved` and the sybil cap). This is what the §3 audit
5154    // shield and the §6 holder-eligibility closure consult to decide
5155    // whether the peer is expected to speak v12.
5156    //
5157    // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
5158    // identity-rotation attacks: once full, new entries are refused.
5159    // Refusal degrades over-cap peers to the behaviour before this set
5160    // existed (treated as legacy on rejoin), which is not a security
5161    // regression and preserves the historic set stable.
5162    {
5163        let mut set = ever_capable_peers.write().await;
5164        if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
5165            set.insert(*source);
5166        } else {
5167            warn!(
5168                "ingest_peer_commitment: ever_capable_peers at cap \
5169                 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
5170            );
5171        }
5172    }
5173    // Return an audit target for EVERY valid stored commitment (changed or
5174    // not), so the caller's cooldown+probability-gated trigger keeps a
5175    // stable-keyset peer auditable over time (ADR-0002). Only a serialization
5176    // failure (new_hash == None, unreachable for a real commitment) yields None.
5177    new_hash.map(|pin_hash| AuditTarget {
5178        pin_hash,
5179        key_count: c.key_count,
5180    })
5181}
5182
5183// ---------------------------------------------------------------------------
5184// Storage-bound audit (v12) — responder commitment rotation
5185// ---------------------------------------------------------------------------
5186
5187/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
5188/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
5189/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
5190async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
5191    let bytes = match tokio::fs::read(path).await {
5192        Ok(b) => b,
5193        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
5194            debug!(
5195                "Commitment retention: no snapshot at {} (fresh start)",
5196                path.display()
5197            );
5198            return;
5199        }
5200        Err(e) => {
5201            warn!(
5202                "Commitment retention: failed to read {}: {e}",
5203                path.display()
5204            );
5205            return;
5206        }
5207    };
5208    if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
5209        state.restore(&persisted);
5210        info!(
5211            "Commitment retention: reloaded {} slot(s) from {}",
5212            state.retained_slot_count(),
5213            path.display()
5214        );
5215    } else {
5216        warn!(
5217            "Commitment retention: corrupt snapshot at {}; starting with empty retention",
5218            path.display()
5219        );
5220    }
5221}
5222
5223/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
5224/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
5225/// needless disk writes on idle nodes. On success updates `last` to the bytes
5226/// written; on a serialization/write error the existing on-disk snapshot is left
5227/// intact (never truncated).
5228async fn persist_retention_if_changed(
5229    state: &ResponderCommitmentState,
5230    path: &Path,
5231    last: &mut Option<Vec<u8>>,
5232) {
5233    let Some(bytes) = state.snapshot().to_bytes() else {
5234        warn!("Commitment retention: serialization failed; keeping previous snapshot");
5235        return;
5236    };
5237    if last.as_deref() == Some(bytes.as_slice()) {
5238        return;
5239    }
5240    if write_retention_atomic(path, bytes.clone()).await {
5241        *last = Some(bytes);
5242    }
5243}
5244
5245/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
5246/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
5247/// success. Only the retention-persist loop writes this path, so a fixed temp
5248/// name is safe.
5249async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
5250    let path = path.to_path_buf();
5251    let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
5252        let tmp = path.with_extension("tmp");
5253        std::fs::write(&tmp, &bytes)?;
5254        std::fs::File::open(&tmp)?.sync_all()?;
5255        std::fs::rename(&tmp, &path)?;
5256        // Fsync the directory so the rename (the durable-commit point) is not
5257        // lost on a crash right after it. An empty parent (relative filename)
5258        // means the current directory.
5259        let dir = path
5260            .parent()
5261            .filter(|p| !p.as_os_str().is_empty())
5262            .unwrap_or_else(|| Path::new("."));
5263        std::fs::File::open(dir)?.sync_all()?;
5264        Ok(())
5265    })
5266    .await;
5267    match res {
5268        Ok(Ok(())) => true,
5269        Ok(Err(e)) => {
5270            warn!("Commitment retention: persist failed: {e}");
5271            false
5272        }
5273        Err(e) => {
5274            warn!("Commitment retention: persist task join failed: {e}");
5275            false
5276        }
5277    }
5278}
5279
5280/// Read the current LMDB key set, build + sign a fresh
5281/// `StorageCommitment`, and rotate it into `state` as the new `current`.
5282/// The prior `current` is demoted to `previous`; the prior `previous` is
5283/// dropped (per `ResponderCommitmentState::rotate`).
5284///
5285/// For content-addressed chunks (Autonomi's chunk store), `address ==
5286/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
5287/// re-read each chunk's bytes to compute the leaf hash.
5288///
5289/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
5290/// rotate. The auditor side handles "no commitment for this peer" by
5291/// falling back to the legacy plain-digest audit path.
5292async fn rebuild_and_rotate_commitment(
5293    storage: &Arc<LmdbStorage>,
5294    identity: &Arc<NodeIdentity>,
5295    state: &Arc<ResponderCommitmentState>,
5296    p2p: &Arc<P2PNode>,
5297    config: &Arc<ReplicationConfig>,
5298) -> Result<()> {
5299    let stored_keys = storage
5300        .all_keys()
5301        .await
5302        .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
5303
5304    // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
5305    // everything currently on disk ("hold"). This is the half of the retention
5306    // contract that lets out-of-range chunks age out: a key that has left our
5307    // close group is excluded from the NEXT commitment, so once its last gossip
5308    // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
5309    // set, `ResponderCommitmentState::is_held` goes false,
5310    // and the pruner (which until then vetoes its deletion) reclaims it. Without
5311    // this filter the pruner's reprieve would keep re-committing stale keys
5312    // forever (the rebuild reads all_keys, so a retained-on-disk key would be
5313    // re-committed and re-gossiped every rotation — a permanent pin).
5314    let storage_empty = stored_keys.is_empty();
5315    let self_id = *p2p.peer_id();
5316    let mut keys = Vec::with_capacity(stored_keys.len());
5317    for k in stored_keys {
5318        if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
5319            keys.push(k);
5320        }
5321    }
5322
5323    if keys.is_empty() {
5324        if storage_empty {
5325            // Storage is genuinely empty — there is nothing to answer for, so
5326            // drop the previously advertised commitment immediately. Keeping it
5327            // would leave remote auditors pinning a hash we can never satisfy
5328            // again (the bytes are gone).
5329            if state.retained_slot_count() > 0 {
5330                debug!("Commitment rotation: storage empty, clearing retained slots");
5331                state.clear_all();
5332            }
5333            return Ok(());
5334        }
5335        // Bytes are still on disk but no key is currently in range. We must NOT
5336        // clear retention here: a peer may still be pinning a root we gossiped
5337        // moments ago and could demand its bytes in a round-2 challenge, which
5338        // we can still answer (the bytes are present). But we must STOP
5339        // advertising the stale commitment: retire it so `current()` returns
5340        // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
5341        // The retired slot then ages out by its gossip-answerability TTL while
5342        // remaining answerable for in-flight pins until then. Once it ages out,
5343        // `is_held` flips false and the pruner reclaims the now-uncommitted,
5344        // out-of-range chunks. (Calling `age_out` alone would leave `current()`
5345        // pointing at the stale root, which the gossip loop would keep
5346        // re-stamping — pinning its keys forever.)
5347        debug!(
5348            "Commitment rotation: no responsible keys to commit to; retiring current commitment \
5349             (stays answerable until its gossip TTL lapses, bytes still on disk)"
5350        );
5351        state.retire_current();
5352        return Ok(());
5353    }
5354
5355    // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
5356    // to more than the protocol limit; auditor would reject the
5357    // commitment otherwise).
5358    let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
5359    if keys.len() > cap {
5360        warn!(
5361            "Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
5362             truncating — investigate as this likely means a misconfiguration",
5363            keys.len(),
5364            cap
5365        );
5366    }
5367
5368    // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
5369    // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
5370    // full chunk re-read per rotation.
5371    //
5372    // Consequence to be precise about: because the leaf is `(key, key)`,
5373    // the Merkle root commits to the SET OF KEYS, not to the bytes. The
5374    // commitment therefore binds "which keys I claim to hold"; it does NOT
5375    // by itself prove byte possession. Byte possession is enforced by the
5376    // audit-verify path, which recomputes `bytes_hash == BLAKE3(local_bytes)`
5377    // and the per-key digest against the AUDITOR'S OWN local copy of the
5378    // bytes — so a responder that holds the key list but dropped the bytes
5379    // still fails (`missing bytes for committed key` / digest mismatch).
5380    // This is sound ONLY while keys are content addresses. If this module
5381    // is ever reused for non-content-addressed records (`bytes_hash != key`),
5382    // the `(k, k)` shortcut would let a byte-less node forge a valid root and
5383    // MUST be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
5384    let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
5385
5386    // No-op-rotation guard: compute just the Merkle root from `entries`
5387    // and compare against the currently-advertised commitment's root.
5388    // If they match, the key set is unchanged and a new rotation would
5389    // only swap a randomized ML-DSA signature for a fresh one — same
5390    // content, different commitment_hash. That invalidates every
5391    // outstanding `recent_provers` credit on this node across the
5392    // close group with no security benefit, breaking steady-state
5393    // quorum liveness on large nodes that can't re-audit every key
5394    // every rotation interval. Skip the rotation entirely when the
5395    // tree is unchanged.
5396    // Build the tree ONCE here (moving `entries`): it serves both the no-op
5397    // root check below and, if we proceed, the signed commitment via
5398    // `build_from_tree` (§11 — previously the tree was built here and AGAIN
5399    // inside `BuiltCommitment::build`).
5400    let candidate_tree = commitment::MerkleTree::build(entries)
5401        .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
5402    let candidate_root = candidate_tree.root();
5403    if let Some(current) = state.current() {
5404        if current.commitment().root == candidate_root {
5405            debug!(
5406                "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
5407                hex::encode(candidate_root)
5408            );
5409            // Even though we skip re-signing (to avoid invalidating holder
5410            // credit), retention must still advance on the wall clock: a
5411            // previously-gossiped commitment that holds a now-out-of-range key
5412            // must be able to age out of the answerability window even when the
5413            // committed key set is frozen here for many rotations. Without this,
5414            // the no-op guard would pin a stale slot — and its key — forever.
5415            state.age_out();
5416            return Ok(());
5417        }
5418    }
5419
5420    let sk_bytes = identity.secret_key_bytes().to_vec();
5421    let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
5422        .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
5423    let pk_bytes = identity.public_key().as_bytes().to_vec();
5424    let peer_id_bytes = *p2p.peer_id().as_bytes();
5425
5426    let built = commitment_state::BuiltCommitment::build_from_tree(
5427        candidate_tree,
5428        &peer_id_bytes,
5429        &sk,
5430        &pk_bytes,
5431    )
5432    .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
5433
5434    let hash = hex::encode(built.hash());
5435    let key_count = built.commitment().key_count;
5436    state.rotate(built);
5437    info!("Storage commitment rotated: hash={hash} key_count={key_count}");
5438    Ok(())
5439}
5440
5441#[cfg(test)]
5442#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
5443mod tests {
5444    use super::*;
5445
5446    fn test_peer(b: u8) -> PeerId {
5447        let mut bytes = [0u8; 32];
5448        bytes[0] = b;
5449        PeerId::from_bytes(bytes)
5450    }
5451
5452    fn test_key(b: u8) -> crate::ant_protocol::XorName {
5453        let mut k = [0u8; 32];
5454        k[0] = b;
5455        k
5456    }
5457
5458    #[tokio::test]
5459    async fn audit_responder_admission_reports_per_peer_cap_full() {
5460        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
5461        let inflight = Arc::new(RwLock::new(HashMap::new()));
5462        let peer = test_peer(0xA1);
5463
5464        let mut guards = Vec::new();
5465        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
5466            match admit_audit_responder(&semaphore, &inflight, &peer).await {
5467                Ok(guard) => guards.push(guard),
5468                Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
5469            }
5470        }
5471
5472        let Err(err) = admit_audit_responder(&semaphore, &inflight, &peer).await else {
5473            panic!("admission should fail once per-peer cap is full");
5474        };
5475        assert_eq!(err.reason, AuditResponderRejectReason::PerPeerCapFull);
5476        assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
5477        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
5478        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
5479
5480        drop(guards);
5481    }
5482
5483    #[tokio::test]
5484    async fn audit_responder_admission_reports_global_pool_full() {
5485        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
5486        let inflight = Arc::new(RwLock::new(HashMap::new()));
5487        let peer = test_peer(0xA2);
5488
5489        let mut held_global_permits = Vec::new();
5490        for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
5491            held_global_permits.push(
5492                Arc::clone(&semaphore)
5493                    .try_acquire_owned()
5494                    .expect("test should be able to exhaust the global pool"),
5495            );
5496        }
5497
5498        let Err(err) = admit_audit_responder(&semaphore, &inflight, &peer).await else {
5499            panic!("admission should fail once global pool is full");
5500        };
5501        assert_eq!(err.reason, AuditResponderRejectReason::GlobalPoolFull);
5502        assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
5503        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
5504        assert_eq!(err.peer_inflight, 0);
5505        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
5506
5507        drop(held_global_permits);
5508    }
5509
5510    #[test]
5511    fn first_audit_terminal_outcomes_are_stable() {
5512        let peer = test_peer(1);
5513        let passed = AuditTickResult::Passed {
5514            challenged_peer: peer,
5515            keys_checked: 1,
5516        };
5517        let timed_out = AuditTickResult::Failed {
5518            evidence: FailureEvidence::AuditFailure {
5519                challenge_id: 1,
5520                challenged_peer: peer,
5521                confirmed_failed_keys: vec![test_key(1)],
5522                summary: crate::replication::types::AuditFailureSummary::default(),
5523                reason: AuditFailureReason::Timeout,
5524            },
5525        };
5526
5527        assert_eq!(
5528            first_audit_terminal_outcome(&passed),
5529            FirstAuditTerminalOutcome::Passed
5530        );
5531        assert_eq!(
5532            first_audit_terminal_outcome(&timed_out),
5533            FirstAuditTerminalOutcome::Timeout
5534        );
5535        assert_eq!(
5536            first_audit_terminal_outcome(&AuditTickResult::Idle),
5537            FirstAuditTerminalOutcome::Idle
5538        );
5539        assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
5540        assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
5541        assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
5542        assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
5543        assert_eq!(
5544            FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
5545            "insufficient_keys"
5546        );
5547        assert_eq!(
5548            FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
5549            "bootstrap_claim"
5550        );
5551    }
5552
5553    #[test]
5554    fn first_audit_queue_exposes_coalescing_and_capacity_eviction() {
5555        let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
5556        let first = MonetizedPinEvent {
5557            peer: test_peer(1),
5558            pin: [1; 32],
5559            key_count: 1,
5560            quote_ts: SystemTime::now(),
5561        };
5562        let replacement = MonetizedPinEvent {
5563            pin: [2; 32],
5564            ..first
5565        };
5566        let other_peer = MonetizedPinEvent {
5567            peer: test_peer(2),
5568            pin: [3; 32],
5569            ..first
5570        };
5571
5572        assert_eq!(
5573            queue_first_audit_event(&mut pending, first),
5574            FirstAuditQueueOutcome::Queued
5575        );
5576        assert_eq!(
5577            queue_first_audit_event(&mut pending, replacement),
5578            FirstAuditQueueOutcome::Coalesced
5579        );
5580        assert_eq!(
5581            queue_first_audit_event(&mut pending, other_peer),
5582            FirstAuditQueueOutcome::CapacityEvicted {
5583                peer: first.peer,
5584                pin: replacement.pin,
5585            }
5586        );
5587        assert_eq!(pending.len(), 1);
5588        assert_eq!(
5589            pending.peek(&other_peer.peer).map(|event| event.pin),
5590            Some([3; 32])
5591        );
5592    }
5593
5594    #[test]
5595    fn fresh_offer_runs_store_admission_payment_checks() {
5596        let context = fresh_offer_payment_context();
5597        assert_eq!(context, VerificationContext::FreshReplication);
5598        // Fresh replication must keep verifying exactly like a direct client
5599        // PUT (store-strength cache, same live checks); the variant only
5600        // exists so price-floor telemetry can tell the two paths apart.
5601        assert!(context.is_store_admission());
5602    }
5603
5604    #[test]
5605    fn paid_notify_uses_paid_list_admission_payment_checks() {
5606        assert_eq!(
5607            paid_notify_payment_context(),
5608            VerificationContext::PaidListAdmission
5609        );
5610    }
5611
5612    /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
5613    /// signed quote inside the answerability window, fail-closed on BOTH ends so a
5614    /// stale or future/skewed client-forwarded quote cannot frame an honest node.
5615    #[test]
5616    fn monetized_quote_audit_window_fails_closed_both_ends() {
5617        let now = SystemTime::now();
5618        // Fresh (just quoted) and small future/past skew -> audited.
5619        assert!(quote_within_audit_window(now, now));
5620        assert!(quote_within_audit_window(
5621            now + Duration::from_secs(60),
5622            now
5623        ));
5624        assert!(quote_within_audit_window(
5625            now - Duration::from_secs(3600),
5626            now
5627        ));
5628        // Far future (badly-skewed / replayed) -> skipped.
5629        assert!(!quote_within_audit_window(
5630            now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_secs(60),
5631            now
5632        ));
5633        // Older than the window -> skipped (pin may have aged out).
5634        assert!(!quote_within_audit_window(
5635            now - GOSSIP_ANSWERABILITY_TTL,
5636            now
5637        ));
5638    }
5639
5640    #[test]
5641    fn audit_timeout_preserves_active_bootstrap_claim() {
5642        assert!(!audit_failure_clears_bootstrap_claim(
5643            &AuditFailureReason::Timeout
5644        ));
5645    }
5646
5647    fn strike_peer(b: u8) -> PeerId {
5648        let mut bytes = [0u8; 32];
5649        bytes[0] = b;
5650        PeerId::from_bytes(bytes)
5651    }
5652
5653    // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
5654    // cooldown must collapse a gossip flood into at most one audit per window.
5655
5656    #[test]
5657    fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
5658        let peer = strike_peer(1);
5659        let mut map: HashMap<PeerId, Instant> = HashMap::new();
5660        let t0 = Instant::now();
5661        // First gossip in the window passes; a burst of further gossips at the
5662        // same instant are all suppressed.
5663        assert!(cooldown_allows_audit(&mut map, &peer, t0));
5664        let mut passed = 1;
5665        for _ in 0..100 {
5666            if cooldown_allows_audit(&mut map, &peer, t0) {
5667                passed += 1;
5668            }
5669        }
5670        assert_eq!(
5671            passed, 1,
5672            "a flood at one instant must trigger exactly one audit"
5673        );
5674    }
5675
5676    // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
5677    // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
5678    // consumes the window. This is the property the isolated cooldown tests above
5679    // cannot see: they never sample the lottery, so a regression that reordered
5680    // the gates (sample probability first, only stamp the cooldown on a win)
5681    // would still pass them while breaking flood-resistance: a flood would then
5682    // re-roll the lottery on EVERY message until one won, multiplying audits.
5683    //
5684    // We model the exact production gate order (cooldown-then-lottery) with a
5685    // lottery driven by a fixed outcome instead of `gen_bool(..)`. The first
5686    // message LOSES the lottery; the remaining flood messages all WIN. With the
5687    // production order, the losing first ticket burns the window and every later
5688    // winner in the same window is blocked, so there are 0 audits this window. If
5689    // the gates were flipped, the second message's winning ticket would slip
5690    // through. The window only reopens after the cooldown elapses.
5691    //
5692    // FLIPS IF: the lottery is sampled before `cooldown_allows_audit` (a losing
5693    // ticket no longer consumes the window), re-enabling a flood-amplified audit
5694    // storm.
5695    #[test]
5696    fn losing_lottery_still_consumes_cooldown_window() {
5697        // Faithful re-implementation of the two gates in
5698        // `maybe_trigger_gossip_audit`, with the lottery outcome made
5699        // deterministic instead of `rand::thread_rng().gen_bool(..)`.
5700        // Calls the SHIPPED `audit_launch_decision` (the same function
5701        // `maybe_trigger_gossip_audit` uses), so a reorder of the two gates in
5702        // production fails this test — not a local reimplementation.
5703        let peer = strike_peer(3);
5704        let mut map: HashMap<PeerId, Instant> = HashMap::new();
5705        let t0 = Instant::now();
5706
5707        // First flooded message at t0 LOSES the lottery, but the cooldown is
5708        // stamped BEFORE the lottery is consulted, so the window is now consumed.
5709        assert!(
5710            !audit_launch_decision(&mut map, &peer, t0, false),
5711            "a losing ticket launches no audit"
5712        );
5713
5714        // 99 more flooded messages at the same instant would all WIN the lottery,
5715        // yet every one must be blocked by the cooldown the loser already stamped.
5716        // (If production sampled the lottery FIRST, these would each get a fresh
5717        // roll and audits would multiply — this assertion catches that reorder.)
5718        let mut audits = 0;
5719        for _ in 0..99 {
5720            if audit_launch_decision(&mut map, &peer, t0, true) {
5721                audits += 1;
5722            }
5723        }
5724        assert_eq!(
5725            audits, 0,
5726            "a losing first ticket must consume the window so no later flooded \
5727             message in the same window can audit"
5728        );
5729
5730        // The window only reopens after the cooldown elapses; the next winning
5731        // ticket then launches exactly one audit.
5732        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
5733        assert!(
5734            audit_launch_decision(&mut map, &peer, after, true),
5735            "after the cooldown a winning ticket audits again"
5736        );
5737    }
5738
5739    #[test]
5740    fn cooldown_lets_audit_through_after_the_window() {
5741        let peer = strike_peer(2);
5742        let mut map: HashMap<PeerId, Instant> = HashMap::new();
5743        let t0 = Instant::now();
5744        assert!(cooldown_allows_audit(&mut map, &peer, t0));
5745        // Within the window: suppressed.
5746        let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
5747        assert!(!cooldown_allows_audit(&mut map, &peer, within));
5748        // Past the window: allowed again.
5749        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
5750        assert!(cooldown_allows_audit(&mut map, &peer, after));
5751    }
5752
5753    #[test]
5754    fn cooldown_is_per_peer_independent() {
5755        let mut map: HashMap<PeerId, Instant> = HashMap::new();
5756        let t0 = Instant::now();
5757        // Different peers each get their own first-audit pass at the same instant.
5758        for i in 0..20u8 {
5759            assert!(
5760                cooldown_allows_audit(&mut map, &strike_peer(i), t0),
5761                "peer {i} should be auditable independently"
5762            );
5763        }
5764    }
5765
5766    #[test]
5767    fn audit_on_gossip_constants_match_adr() {
5768        // Tripwire on the ADR-locked tunables. The spot-check count sits at the
5769        // top of the auditor's 3..=5 band (the auditor clamps to that band, so
5770        // values above 5 would silently never be requested).
5771        assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
5772        assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
5773        assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
5774    }
5775
5776    // (d) A confirmed storage-integrity failure penalizes immediately and
5777    // revokes credit; it is not a timeout.
5778    #[test]
5779    fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
5780        assert!(audit_failure_clears_bootstrap_claim(
5781            &AuditFailureReason::DigestMismatch
5782        ));
5783        assert!(audit_failure_revokes_holder_credit(
5784            &AuditFailureReason::DigestMismatch
5785        ));
5786    }
5787
5788    /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
5789    /// uses: confirmed failures revoke credit, `Timeout` does not.
5790    #[test]
5791    fn confirmed_failures_revoke_credit_timeout_does_not() {
5792        for reason in [
5793            AuditFailureReason::MalformedResponse,
5794            AuditFailureReason::DigestMismatch,
5795            AuditFailureReason::KeyAbsent,
5796            AuditFailureReason::Rejected,
5797        ] {
5798            assert!(
5799                audit_failure_revokes_holder_credit(&reason),
5800                "confirmed failure {reason:?} must revoke holder credit"
5801            );
5802        }
5803        assert!(
5804            !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
5805            "Timeout must NOT revoke credit (single dropped packet != storage loss)"
5806        );
5807    }
5808
5809    /// Wiring test for the security fix: the helper the handler calls
5810    /// actually strips a credited peer on a confirmed failure
5811    /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
5812    /// Records genuine credit first so neither assertion is vacuous;
5813    /// this fails if `forget_peer` stops being called, or if the
5814    /// `Timeout` exclusion is dropped (both verified by mutation).
5815    #[test]
5816    fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
5817        let peer = test_peer(0xAB);
5818        let key = test_key(1);
5819        let hash = [0xCD; 32];
5820
5821        // Confirmed failure -> credit revoked.
5822        let mut provers = RecentProvers::new();
5823        provers.record_proof(key, peer, hash, Instant::now());
5824        assert!(
5825            provers.is_credited_holder(&key, &peer, &hash),
5826            "precondition: peer credited before failure"
5827        );
5828        apply_audit_failure_credit_revocation(
5829            &mut provers,
5830            &peer,
5831            &AuditFailureReason::DigestMismatch,
5832        );
5833        assert!(
5834            !provers.is_credited_holder(&key, &peer, &hash),
5835            "DigestMismatch must strip the peer's holder credit"
5836        );
5837
5838        // Timeout -> credit retained.
5839        let mut provers_timeout = RecentProvers::new();
5840        provers_timeout.record_proof(key, peer, hash, Instant::now());
5841        apply_audit_failure_credit_revocation(
5842            &mut provers_timeout,
5843            &peer,
5844            &AuditFailureReason::Timeout,
5845        );
5846        assert!(
5847            provers_timeout.is_credited_holder(&key, &peer, &hash),
5848            "Timeout must retain holder credit (deliberate liveness cushion)"
5849        );
5850    }
5851
5852    #[test]
5853    fn decoded_audit_failures_clear_active_bootstrap_claim() {
5854        for reason in [
5855            AuditFailureReason::MalformedResponse,
5856            AuditFailureReason::DigestMismatch,
5857            AuditFailureReason::KeyAbsent,
5858            AuditFailureReason::Rejected,
5859        ] {
5860            assert!(
5861                audit_failure_clears_bootstrap_claim(&reason),
5862                "decoded non-bootstrap failure {reason:?} should clear active claim"
5863            );
5864        }
5865    }
5866
5867    #[test]
5868    fn first_failed_key_label_truncates_to_16_hex_chars() {
5869        // The high-order 8 bytes of the XorName determine the label so an
5870        // operator can group audit-failures on the same chunk prefix.
5871        let mut key = [0u8; 32];
5872        key[0] = 0x18;
5873        key[7] = 0xff;
5874        // Low-order bytes (positions 8..32) are deliberately set to 0xAA
5875        // to verify they are NOT included in the label.
5876        for byte in &mut key[8..] {
5877            *byte = 0xAA;
5878        }
5879        let label = first_failed_key_label(&[key]);
5880        // Only the first 8 bytes are encoded, low-order bytes are dropped.
5881        assert_eq!(label, "0x18000000000000ff");
5882        assert_eq!(label.len(), "0x".len() + 16);
5883    }
5884
5885    #[test]
5886    fn first_failed_key_label_falls_back_when_empty() {
5887        // Should never happen in production (audit failure handling rejects
5888        // empty sets), but the formatter must still produce a valid label
5889        // so the log line doesn't contain a misleading default.
5890        assert_eq!(first_failed_key_label(&[]), "0x");
5891    }
5892
5893    #[test]
5894    fn first_failed_key_label_uses_first_key_only() {
5895        let first = [0x11u8; 32];
5896        let second = [0x22u8; 32];
5897        assert_eq!(
5898            first_failed_key_label(&[first, second]),
5899            format!("0x{}", hex::encode(&first[..8]))
5900        );
5901    }
5902}