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