Skip to main content

ant_node/replication/
audit.rs

1//! Storage audit protocol (Section 15).
2//!
3//! Challenge-response for claimed holders. Anti-outsourcing protection.
4
5use std::collections::{HashMap, HashSet};
6use std::sync::Arc;
7use std::time::Instant;
8
9use crate::logging::{debug, enabled, info, warn};
10use rand::seq::SliceRandom;
11use rand::Rng;
12
13use crate::ant_protocol::XorName;
14use crate::replication::audit_coordinator::AuditChallengeCoordinator;
15use crate::replication::audit_metrics::{self, AuditFailureClass, AuditType};
16use crate::replication::config::{ReplicationConfig, REPLICATION_PROTOCOL_ID};
17use crate::replication::protocol::{
18    compute_audit_digest, AuditChallenge, AuditResponse, ReplicationMessage,
19    ReplicationMessageBody, ABSENT_KEY_DIGEST,
20};
21use crate::replication::types::{
22    AuditFailureReason, AuditFailureSummary, FailureEvidence, PeerSyncRecord, RepairProofs,
23};
24use crate::storage::ChunkStore;
25use saorsa_core::identity::PeerId;
26use saorsa_core::P2PNode;
27use tokio::sync::RwLock;
28
29// Test-only imports. Kept here rather than inside `mod tests` so every `use` in
30// this file lives at the top, and `#[cfg(test)]`-gated so non-test builds do
31// not carry them.
32#[cfg(test)]
33use crate::replication::config::REPAIR_HINT_MIN_AGE;
34#[cfg(test)]
35use crate::replication::types::{BootstrapClaimObservation, NeighborSyncState};
36#[cfg(test)]
37use crate::storage::ChunkStoreConfig;
38#[cfg(test)]
39use tempfile::TempDir;
40
41// ---------------------------------------------------------------------------
42// Audit tick result
43// ---------------------------------------------------------------------------
44
45/// Result of an audit tick.
46#[derive(Debug)]
47pub enum AuditTickResult {
48    /// Audit completed successfully (all digests matched).
49    Passed {
50        /// The peer that was challenged.
51        challenged_peer: PeerId,
52        /// Number of keys verified.
53        keys_checked: usize,
54    },
55    /// Audit found failures (after responsibility confirmation).
56    Failed {
57        /// Evidence of the failure for trust engine.
58        evidence: FailureEvidence,
59        /// Node-local no-response class for metrics/logs. This is deliberately
60        /// kept out of [`FailureEvidence`] so no serialized evidence format or
61        /// wire protocol changes.
62        no_response_class: Option<&'static str>,
63    },
64    /// Audit target claimed bootstrapping.
65    BootstrapClaim {
66        /// The peer claiming bootstrap status.
67        peer: PeerId,
68    },
69    /// No eligible peers for audit this tick.
70    Idle,
71    /// Audit skipped (not enough local keys).
72    InsufficientKeys,
73}
74
75/// Format the first challenged key as a short stable correlation label.
76fn first_challenged_key_label(keys: &[XorName]) -> String {
77    keys.first().map_or_else(
78        || "0x".to_string(),
79        |k| format!("0x{}", hex::encode(&k[..8])),
80    )
81}
82
83/// Best-effort coarse class for the transport/request error returned by
84/// `P2PNode::send_request`.
85///
86/// The current core networking layer can wrap request deadline timeouts inside
87/// display strings, so this deliberately remains a bounded heuristic for logs
88/// rather than protocol/trust semantics.
89fn classify_audit_send_error(error: &str) -> (&'static str, AuditFailureClass) {
90    audit_metrics::classify_audit_send_error(error)
91}
92
93pub(crate) fn responsible_audit_response_timeout(
94    config: &ReplicationConfig,
95    key_count: usize,
96) -> std::time::Duration {
97    config.audit_response_timeout(key_count)
98}
99
100// ---------------------------------------------------------------------------
101// Main audit tick
102// ---------------------------------------------------------------------------
103
104/// Execute one repair-proof-gated audit tick.
105///
106/// This is the production path used by the replication engine. Direct
107/// callers that have not adopted repair proofs remain conservative and do not
108/// audit peers for unproven keys.
109#[allow(
110    clippy::implicit_hasher,
111    clippy::too_many_arguments,
112    clippy::too_many_lines
113)]
114pub async fn audit_tick_with_repair_proofs(
115    p2p_node: &Arc<P2PNode>,
116    storage: &Arc<ChunkStore>,
117    config: &ReplicationConfig,
118    sync_history: &HashMap<PeerId, PeerSyncRecord>,
119    repair_proofs: &Arc<RwLock<RepairProofs>>,
120    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
121    current_sync_epoch: u64,
122    is_bootstrapping: bool,
123) -> AuditTickResult {
124    // Invariant 19: never audit while still bootstrapping.
125    if is_bootstrapping {
126        return AuditTickResult::Idle;
127    }
128
129    let dht = p2p_node.dht_manager();
130
131    // Step 2: Select one eligible peer (has RepairOpportunity) at random.
132    // Peers with active bootstrap claims remain eligible. A follow-up audit is
133    // how we observe a continued claim and apply past-grace abuse handling.
134    let eligible_peers = eligible_audit_peers(sync_history);
135
136    if eligible_peers.is_empty() {
137        return AuditTickResult::Idle;
138    }
139
140    let (challenged_peer, nonce, challenge_id) = {
141        let mut rng = rand::thread_rng();
142        let selected = match eligible_peers.choose(&mut rng) {
143            Some(p) => *p,
144            None => return AuditTickResult::Idle,
145        };
146        let n: [u8; 32] = rng.gen();
147        let c: u64 = rng.gen();
148        (selected, n, c)
149    };
150
151    // Step 3: Sample keys from local store and keep those the peer is
152    // responsible for (appears in the close group via local RT lookup).
153    let all_keys = match storage.all_keys().await {
154        Ok(keys) => keys,
155        Err(e) => {
156            warn!("Audit: failed to read local keys: {e}");
157            return AuditTickResult::Idle;
158        }
159    };
160
161    if all_keys.is_empty() {
162        return AuditTickResult::Idle;
163    }
164
165    let sample_count = ReplicationConfig::responsible_audit_key_limit(all_keys.len());
166    let sampled_keys: Vec<XorName> = {
167        let mut rng = rand::thread_rng();
168        all_keys
169            .choose_multiple(&mut rng, sample_count)
170            .copied()
171            .collect()
172    };
173
174    // Step 4: Filter to keys where the chosen peer is in the close group and
175    // this node has proof that it already sent the peer a repair hint for the
176    // specific key.
177    let mut sampled_key_groups = Vec::new();
178    for key in &sampled_keys {
179        let closest = dht
180            .find_closest_nodes_local_with_self(key, config.close_group_size)
181            .await;
182        let close_peers: HashSet<PeerId> = closest.iter().map(|node| node.peer_id).collect();
183        if close_peers.contains(&challenged_peer) {
184            sampled_key_groups.push((*key, close_peers));
185        }
186    }
187
188    let peer_keys = {
189        let mut proofs = repair_proofs.write().await;
190        let now = Instant::now();
191        mature_audit_keys_for_peer(
192            &challenged_peer,
193            sampled_key_groups,
194            &mut proofs,
195            current_sync_epoch,
196            now,
197        )
198    };
199
200    if peer_keys.is_empty() {
201        return AuditTickResult::Idle;
202    }
203
204    // peer_keys is naturally bounded by audit_sample_count (sqrt-scaled),
205    // so no explicit truncation needed.
206
207    // Step 6: Send challenge.
208
209    let challenge = AuditChallenge {
210        challenge_id,
211        nonce,
212        challenged_peer_id: *challenged_peer.as_bytes(),
213        keys: peer_keys.clone(),
214    };
215
216    let msg = ReplicationMessage {
217        request_id: challenge_id,
218        body: ReplicationMessageBody::AuditChallenge(challenge),
219    };
220
221    let encoded = match msg.encode() {
222        Ok(data) => data,
223        Err(e) => {
224            warn!("Audit: failed to encode challenge: {e}");
225            return AuditTickResult::Idle;
226        }
227    };
228
229    let Some(_slot) = audit_challenge_coordinator.acquire(challenged_peer).await else {
230        warn!("Audit: failed to acquire outbound audit coordinator slot for {challenged_peer}");
231        return AuditTickResult::Idle;
232    };
233    let encoded_len = encoded.len();
234    let audit_timeout = responsible_audit_response_timeout(config, peer_keys.len());
235    info!(
236        target: "ant_node::replication::audit_requester",
237        event = "started",
238        audit_origin = AuditType::ResponsibleChunk.as_str(),
239        audit_round = "digest",
240        challenged_peer = %challenged_peer,
241        challenge_id,
242        work_items = peer_keys.len(),
243        timeout_ms = audit_timeout.as_millis(),
244        "Outbound audit request started"
245    );
246    let audit_started = Instant::now();
247    let response = match p2p_node
248        .send_request(
249            &challenged_peer,
250            REPLICATION_PROTOCOL_ID,
251            encoded,
252            audit_timeout,
253        )
254        .await
255    {
256        Ok(resp) => {
257            info!(
258                target: "ant_node::replication::audit_requester",
259                event = "completed",
260                audit_origin = AuditType::ResponsibleChunk.as_str(),
261                audit_round = "digest",
262                challenged_peer = %challenged_peer,
263                challenge_id,
264                work_items = peer_keys.len(),
265                elapsed_ms = audit_started.elapsed().as_millis(),
266                outcome = "response",
267                "Outbound audit request completed"
268            );
269            resp
270        }
271        Err(e) => {
272            let send_error = e.to_string();
273            let (send_error_class, audit_failure_class) = classify_audit_send_error(&send_error);
274            audit_metrics::record_audit_no_response(
275                AuditType::ResponsibleChunk,
276                audit_failure_class,
277            );
278            if enabled!(crate::logging::Level::WARN) {
279                let elapsed = audit_started.elapsed();
280                let first_key = first_challenged_key_label(&peer_keys);
281                warn!(
282                    target: "ant_node::replication::audit_requester",
283                    event = "completed",
284                    audit_origin = AuditType::ResponsibleChunk.as_str(),
285                    audit_round = "digest",
286                    outcome = "no_response",
287                    audit_type = AuditType::ResponsibleChunk.as_str(),
288                    audit_phase = "challenge_send",
289                    audit_outcome = "send_request_failed",
290                    audit_failure_class = audit_failure_class.as_str(),
291                    challenged_peer = %challenged_peer,
292                    challenge_id,
293                    key_count = peer_keys.len(),
294                    timeout_ms = audit_timeout.as_millis(),
295                    elapsed_ms = elapsed.as_millis(),
296                    first_key = %first_key,
297                    encoded_len,
298                    send_error_class,
299                    "Audit challenge send_request failed: audit_type=responsible_chunk, audit_phase=challenge_send, audit_outcome=send_request_failed, audit_failure_class={}, challenged_peer={challenged_peer}, challenge_id={challenge_id}, key_count={}, timeout_ms={}, elapsed_ms={}, first_key={first_key}, encoded_len={encoded_len}, send_error_class={send_error_class}",
300                    audit_failure_class.as_str(),
301                    peer_keys.len(),
302                    audit_timeout.as_millis(),
303                    elapsed.as_millis(),
304                );
305            }
306            debug!(
307                challenged_peer = %challenged_peer,
308                challenge_id,
309                send_error = %e,
310                audit_failure_class = audit_failure_class.as_str(),
311                "Audit challenge raw send_request error"
312            );
313            // No-response verdicts still use the existing Timeout evidence
314            // reason; the class is node-local observability only.
315            return handle_audit_timeout(
316                &challenged_peer,
317                challenge_id,
318                &peer_keys,
319                audit_failure_class,
320                p2p_node,
321                config,
322            )
323            .await;
324        }
325    };
326
327    // Step 7: Parse response.
328    let resp_msg = match ReplicationMessage::decode(&response.data) {
329        Ok(m) => m,
330        Err(e) => {
331            warn!("Audit: failed to decode response from {challenged_peer}: {e}");
332            return handle_audit_failure(
333                &challenged_peer,
334                challenge_id,
335                &peer_keys,
336                AuditFailureReason::MalformedResponse,
337                p2p_node,
338                config,
339            )
340            .await;
341        }
342    };
343
344    match resp_msg.body {
345        ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
346            challenge_id: resp_id,
347        }) => {
348            if resp_id != challenge_id {
349                warn!("Audit: challenge ID mismatch on Bootstrapping from {challenged_peer}");
350                return handle_audit_failure(
351                    &challenged_peer,
352                    challenge_id,
353                    &peer_keys,
354                    AuditFailureReason::MalformedResponse,
355                    p2p_node,
356                    config,
357                )
358                .await;
359            }
360            // Step 7b: Bootstrapping claim.
361            AuditTickResult::BootstrapClaim {
362                peer: challenged_peer,
363            }
364        }
365        ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
366            challenge_id: resp_id,
367            digests,
368        }) => {
369            if resp_id != challenge_id {
370                warn!("Audit: challenge ID mismatch from {challenged_peer}");
371                return handle_audit_failure(
372                    &challenged_peer,
373                    challenge_id,
374                    &peer_keys,
375                    AuditFailureReason::MalformedResponse,
376                    p2p_node,
377                    config,
378                )
379                .await;
380            }
381            verify_digests(
382                &challenged_peer,
383                challenge_id,
384                &nonce,
385                &peer_keys,
386                &digests,
387                storage,
388                p2p_node,
389                config,
390            )
391            .await
392        }
393        ReplicationMessageBody::AuditResponse(AuditResponse::Rejected {
394            challenge_id: resp_id,
395            reason,
396        }) => {
397            if resp_id != challenge_id {
398                warn!("Audit: challenge ID mismatch on Rejected from {challenged_peer}");
399                return handle_audit_failure(
400                    &challenged_peer,
401                    challenge_id,
402                    &peer_keys,
403                    AuditFailureReason::MalformedResponse,
404                    p2p_node,
405                    config,
406                )
407                .await;
408            }
409            warn!("Audit: challenge rejected by {challenged_peer}: {reason}");
410            handle_audit_failure(
411                &challenged_peer,
412                challenge_id,
413                &peer_keys,
414                AuditFailureReason::Rejected,
415                p2p_node,
416                config,
417            )
418            .await
419        }
420        _ => {
421            warn!("Audit: unexpected response type from {challenged_peer}");
422            handle_audit_failure(
423                &challenged_peer,
424                challenge_id,
425                &peer_keys,
426                AuditFailureReason::MalformedResponse,
427                p2p_node,
428                config,
429            )
430            .await
431        }
432    }
433}
434
435fn eligible_audit_peers(sync_history: &HashMap<PeerId, PeerSyncRecord>) -> Vec<PeerId> {
436    sync_history
437        .iter()
438        .filter(|(_, record)| record.has_repair_opportunity())
439        .map(|(peer, _)| *peer)
440        .collect()
441}
442
443fn mature_audit_keys_for_peer(
444    challenged_peer: &PeerId,
445    sampled_key_groups: Vec<(XorName, HashSet<PeerId>)>,
446    repair_proofs: &mut RepairProofs,
447    current_sync_epoch: u64,
448    now: Instant,
449) -> Vec<XorName> {
450    sampled_key_groups
451        .into_iter()
452        .filter_map(|(key, close_peers)| {
453            repair_proofs
454                .has_mature_replica_hint(
455                    challenged_peer,
456                    &key,
457                    &close_peers,
458                    current_sync_epoch,
459                    now,
460                )
461                .then_some(key)
462        })
463        .collect()
464}
465
466#[derive(Debug, Clone, Copy, PartialEq, Eq)]
467enum AuditKeyFailureKind {
468    Absent,
469    DigestMismatch,
470    Unclassified,
471}
472
473#[derive(Debug, Clone, Copy, PartialEq, Eq)]
474struct AuditKeyFailure {
475    key: XorName,
476    kind: AuditKeyFailureKind,
477}
478
479impl AuditKeyFailure {
480    fn absent(key: XorName) -> Self {
481        Self {
482            key,
483            kind: AuditKeyFailureKind::Absent,
484        }
485    }
486
487    fn digest_mismatch(key: XorName) -> Self {
488        Self {
489            key,
490            kind: AuditKeyFailureKind::DigestMismatch,
491        }
492    }
493
494    fn unclassified(key: XorName) -> Self {
495        Self {
496            key,
497            kind: AuditKeyFailureKind::Unclassified,
498        }
499    }
500}
501
502fn build_audit_failure_summary(
503    challenged_key_count: usize,
504    confirmed_failures: &[AuditKeyFailure],
505) -> AuditFailureSummary {
506    let mut summary = AuditFailureSummary {
507        challenged_keys: challenged_key_count,
508        failed_keys: confirmed_failures.len(),
509        ..AuditFailureSummary::default()
510    };
511
512    for failure in confirmed_failures {
513        match failure.kind {
514            AuditKeyFailureKind::Absent => summary.absent_keys += 1,
515            AuditKeyFailureKind::DigestMismatch => summary.digest_mismatch_keys += 1,
516            AuditKeyFailureKind::Unclassified => {}
517        }
518    }
519
520    summary
521}
522
523fn audit_digest_failure_reason(confirmed_failures: &[AuditKeyFailure]) -> AuditFailureReason {
524    if confirmed_failures
525        .iter()
526        .all(|failure| failure.kind == AuditKeyFailureKind::Absent)
527    {
528        AuditFailureReason::KeyAbsent
529    } else {
530        AuditFailureReason::DigestMismatch
531    }
532}
533
534// ---------------------------------------------------------------------------
535// Digest verification
536// ---------------------------------------------------------------------------
537
538/// Verify per-key digests from audit response (Step 8).
539#[allow(clippy::too_many_arguments)]
540async fn verify_digests(
541    challenged_peer: &PeerId,
542    challenge_id: u64,
543    nonce: &[u8; 32],
544    keys: &[XorName],
545    digests: &[[u8; 32]],
546    storage: &Arc<ChunkStore>,
547    p2p_node: &Arc<P2PNode>,
548    config: &ReplicationConfig,
549) -> AuditTickResult {
550    // Requirement: response must have exactly one digest per key.
551    if digests.len() != keys.len() {
552        warn!(
553            "Audit: malformed response from {challenged_peer}: {} digests for {} keys",
554            digests.len(),
555            keys.len()
556        );
557        return handle_audit_failure(
558            challenged_peer,
559            challenge_id,
560            keys,
561            AuditFailureReason::MalformedResponse,
562            p2p_node,
563            config,
564        )
565        .await;
566    }
567
568    let challenged_peer_bytes = challenged_peer.as_bytes();
569    let mut failed_keys = Vec::new();
570
571    for (i, key) in keys.iter().enumerate() {
572        let received_digest = &digests[i];
573
574        // Check for absent sentinel.
575        if *received_digest == ABSENT_KEY_DIGEST {
576            failed_keys.push(AuditKeyFailure::absent(*key));
577            continue;
578        }
579
580        // Recompute expected digest from local copy.
581        let local_bytes = match storage.get_raw(key).await {
582            Ok(Some(bytes)) => bytes,
583            Ok(None) => {
584                // We should hold this key (we sampled it), but it's gone.
585                warn!(
586                    "Audit: local key {} disappeared during audit",
587                    hex::encode(key)
588                );
589                continue;
590            }
591            Err(e) => {
592                warn!("Audit: failed to read local key {}: {e}", hex::encode(key));
593                continue;
594            }
595        };
596
597        let expected = compute_audit_digest(nonce, challenged_peer_bytes, key, &local_bytes);
598        if *received_digest != expected {
599            failed_keys.push(AuditKeyFailure::digest_mismatch(*key));
600        }
601    }
602
603    if failed_keys.is_empty() {
604        info!(
605            "Audit: peer {challenged_peer} passed (all {} keys verified)",
606            keys.len()
607        );
608        return AuditTickResult::Passed {
609            challenged_peer: *challenged_peer,
610            keys_checked: keys.len(),
611        };
612    }
613
614    // Step 9: Responsibility confirmation for failed keys.
615    handle_classified_audit_failure(
616        challenged_peer,
617        challenge_id,
618        &failed_keys,
619        AuditFailureReason::DigestMismatch,
620        keys.len(),
621        None,
622        p2p_node,
623        config,
624    )
625    .await
626}
627
628// ---------------------------------------------------------------------------
629// Failure handling with responsibility confirmation
630// ---------------------------------------------------------------------------
631
632/// Handle audit failure: confirm responsibility before emitting evidence (Step 9).
633async fn handle_audit_failure(
634    challenged_peer: &PeerId,
635    challenge_id: u64,
636    failed_keys: &[XorName],
637    reason: AuditFailureReason,
638    p2p_node: &Arc<P2PNode>,
639    config: &ReplicationConfig,
640) -> AuditTickResult {
641    let failures = failed_keys
642        .iter()
643        .copied()
644        .map(AuditKeyFailure::unclassified)
645        .collect::<Vec<_>>();
646    handle_classified_audit_failure(
647        challenged_peer,
648        challenge_id,
649        &failures,
650        reason,
651        failed_keys.len(),
652        None,
653        p2p_node,
654        config,
655    )
656    .await
657}
658
659#[allow(clippy::too_many_arguments)]
660async fn handle_classified_audit_failure(
661    challenged_peer: &PeerId,
662    challenge_id: u64,
663    failed_keys: &[AuditKeyFailure],
664    reason: AuditFailureReason,
665    challenged_key_count: usize,
666    no_response_class: Option<&'static str>,
667    p2p_node: &Arc<P2PNode>,
668    config: &ReplicationConfig,
669) -> AuditTickResult {
670    let dht = p2p_node.dht_manager();
671    let mut confirmed_failures = Vec::new();
672
673    // Step 9a-b: Fresh local RT lookup for each failed key.
674    for failure in failed_keys {
675        let closest = dht
676            .find_closest_nodes_local_with_self(&failure.key, config.close_group_size)
677            .await;
678        if closest.iter().any(|n| n.peer_id == *challenged_peer) {
679            confirmed_failures.push(*failure);
680        } else {
681            debug!(
682                "Audit: peer {challenged_peer} not responsible for {} (removed from failure set)",
683                hex::encode(failure.key)
684            );
685        }
686    }
687
688    // Step 9c: Empty confirmed set -> peer is no longer responsible for any
689    // of the failed keys (topology churn). This is NOT a pass — the peer did
690    // not prove it stores the data. Return Idle to avoid granting unearned
691    // positive trust.
692    if confirmed_failures.is_empty() {
693        info!("Audit: all failures for {challenged_peer} cleared by responsibility confirmation");
694        return AuditTickResult::Idle;
695    }
696
697    let summary = build_audit_failure_summary(challenged_key_count, &confirmed_failures);
698    let reason = if reason == AuditFailureReason::DigestMismatch {
699        audit_digest_failure_reason(&confirmed_failures)
700    } else {
701        reason
702    };
703    let confirmed_failed_keys = confirmed_failures
704        .iter()
705        .map(|failure| failure.key)
706        .collect();
707
708    // Step 9d: Non-empty confirmed set -> emit evidence.
709    let evidence = FailureEvidence::AuditFailure {
710        challenge_id,
711        challenged_peer: *challenged_peer,
712        confirmed_failed_keys,
713        summary,
714        reason,
715    };
716
717    AuditTickResult::Failed {
718        evidence,
719        no_response_class,
720    }
721}
722
723/// Handle audit timeout (no response received).
724async fn handle_audit_timeout(
725    challenged_peer: &PeerId,
726    challenge_id: u64,
727    keys: &[XorName],
728    no_response_class: AuditFailureClass,
729    p2p_node: &Arc<P2PNode>,
730    config: &ReplicationConfig,
731) -> AuditTickResult {
732    let failures = keys
733        .iter()
734        .copied()
735        .map(AuditKeyFailure::unclassified)
736        .collect::<Vec<_>>();
737    handle_classified_audit_failure(
738        challenged_peer,
739        challenge_id,
740        &failures,
741        AuditFailureReason::Timeout,
742        keys.len(),
743        Some(no_response_class.as_str()),
744        p2p_node,
745        config,
746    )
747    .await
748}
749
750// ---------------------------------------------------------------------------
751// Responder-side handler
752// ---------------------------------------------------------------------------
753
754/// Handle an incoming audit challenge (responder side).
755///
756/// Validates that the challenge targets this node, computes per-key digests,
757/// and returns the response.  Rejects challenges where
758/// `challenged_peer_id` does not match `self_peer_id` to prevent an oracle
759/// attack where a malicious challenger forges digests for a different peer.
760pub async fn handle_audit_challenge(
761    challenge: &AuditChallenge,
762    storage: &ChunkStore,
763    self_peer_id: &PeerId,
764    is_bootstrapping: bool,
765    stored_chunks: usize,
766) -> AuditResponse {
767    if is_bootstrapping {
768        return AuditResponse::Bootstrapping {
769            challenge_id: challenge.challenge_id,
770        };
771    }
772
773    if challenge.challenged_peer_id != *self_peer_id.as_bytes() {
774        warn!(
775            "Audit challenge targeted wrong peer: expected {}, got {}",
776            hex::encode(self_peer_id.as_bytes()),
777            hex::encode(challenge.challenged_peer_id),
778        );
779        return AuditResponse::Rejected {
780            challenge_id: challenge.challenge_id,
781            reason: "challenged_peer_id does not match this node".to_string(),
782        };
783    }
784
785    let max_keys = ReplicationConfig::max_incoming_audit_keys(stored_chunks);
786    if challenge.keys.len() > max_keys {
787        warn!(
788            "Audit challenge rejected: {} keys exceeds dynamic limit of {max_keys} \
789             (stored_chunks={stored_chunks})",
790            challenge.keys.len(),
791        );
792        return AuditResponse::Rejected {
793            challenge_id: challenge.challenge_id,
794            reason: format!(
795                "challenge contains {} keys, limit is {max_keys}",
796                challenge.keys.len()
797            ),
798        };
799    }
800
801    let mut digests = Vec::with_capacity(challenge.keys.len());
802
803    for key in &challenge.keys {
804        match storage.get_raw(key).await {
805            Ok(Some(data)) => {
806                let digest = compute_audit_digest(
807                    &challenge.nonce,
808                    &challenge.challenged_peer_id,
809                    key,
810                    &data,
811                );
812                digests.push(digest);
813            }
814            Ok(None) => {
815                digests.push(ABSENT_KEY_DIGEST);
816            }
817            Err(e) => {
818                warn!(
819                    "Audit responder: failed to read key {}: {e}",
820                    hex::encode(key)
821                );
822                digests.push(ABSENT_KEY_DIGEST);
823            }
824        }
825    }
826
827    AuditResponse::Digests {
828        challenge_id: challenge.challenge_id,
829        digests,
830    }
831}
832
833// ---------------------------------------------------------------------------
834// Tests
835// ---------------------------------------------------------------------------
836
837#[cfg(test)]
838#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
839mod tests {
840    use super::*;
841
842    /// Simulated stored chunk count for tests. Large enough that the dynamic
843    /// incoming audit limit (`2 * sqrt(N)`) never rejects small test challenges.
844    const TEST_STORED_CHUNKS: usize = 1_000_000;
845
846    #[test]
847    fn first_challenged_key_label_truncates_to_16_hex_chars() {
848        let mut key = [0u8; 32];
849        key[0] = 0xAB;
850        key[7] = 0xCD;
851        key[8] = 0xEF;
852
853        assert_eq!(first_challenged_key_label(&[key]), "0xab000000000000cd");
854    }
855
856    #[test]
857    fn first_challenged_key_label_falls_back_when_empty() {
858        assert_eq!(first_challenged_key_label(&[]), "0x");
859    }
860
861    #[test]
862    fn classify_audit_send_error_uses_bounded_classes() {
863        assert_eq!(
864            classify_audit_send_error("request to peer timed out after 10s"),
865            ("response_timeout", AuditFailureClass::Timeout)
866        );
867        assert_eq!(
868            classify_audit_send_error("peer not found in active channels"),
869            ("peer_unavailable", AuditFailureClass::Unreachable)
870        );
871        assert_eq!(
872            classify_audit_send_error("dial failed for all candidate addresses"),
873            ("connection_failed", AuditFailureClass::Unreachable)
874        );
875        assert_eq!(
876            classify_audit_send_error("response receiver dropped before delivery"),
877            ("connection_closed", AuditFailureClass::Unreachable)
878        );
879        assert_eq!(
880            classify_audit_send_error("transport stream error"),
881            ("transport_error", AuditFailureClass::Unreachable)
882        );
883        assert_eq!(
884            classify_audit_send_error("operation timed out after 10s"),
885            ("transport_timeout", AuditFailureClass::Unreachable)
886        );
887        assert_eq!(
888            classify_audit_send_error("unexpected error"),
889            ("other", AuditFailureClass::Unreachable)
890        );
891    }
892
893    /// Create a test `ChunkStore` backed by a temp directory.
894    async fn create_test_storage() -> (ChunkStore, TempDir) {
895        let temp_dir = TempDir::new().expect("create temp dir");
896        let config = ChunkStoreConfig {
897            root_dir: temp_dir.path().to_path_buf(),
898            verify_on_read: false,
899            max_map_size: 0,
900            disk_reserve: 0,
901            ..ChunkStoreConfig::test_default()
902        };
903        let storage = ChunkStore::new(config).await.expect("create storage");
904        (storage, temp_dir)
905    }
906
907    /// Build a challenge with the given parameters.
908    fn make_challenge(
909        challenge_id: u64,
910        nonce: [u8; 32],
911        peer_id: [u8; 32],
912        keys: Vec<XorName>,
913    ) -> AuditChallenge {
914        AuditChallenge {
915            challenge_id,
916            nonce,
917            challenged_peer_id: peer_id,
918            keys,
919        }
920    }
921
922    /// Build a `PeerId` matching the raw bytes used in a challenge.
923    fn peer_id_from_bytes(bytes: [u8; 32]) -> PeerId {
924        PeerId::from_bytes(bytes)
925    }
926
927    // -- handle_audit_challenge: present keys ---------------------------------
928
929    #[tokio::test]
930    async fn handle_challenge_present_keys_returns_correct_digests() {
931        let (storage, _temp) = create_test_storage().await;
932
933        // Store two chunks.
934        let content_a = b"chunk alpha";
935        let addr_a = ChunkStore::compute_address(content_a);
936        storage.put(&addr_a, content_a).await.expect("put a");
937
938        let content_b = b"chunk beta";
939        let addr_b = ChunkStore::compute_address(content_b);
940        storage.put(&addr_b, content_b).await.expect("put b");
941
942        let nonce = [0xAA; 32];
943        let peer_id = [0xBB; 32];
944        let challenge = make_challenge(42, nonce, peer_id, vec![addr_a, addr_b]);
945        let self_id = peer_id_from_bytes(peer_id);
946
947        let response =
948            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
949
950        match response {
951            AuditResponse::Digests {
952                challenge_id,
953                digests,
954            } => {
955                assert_eq!(challenge_id, 42);
956                assert_eq!(digests.len(), 2);
957
958                let expected_a = compute_audit_digest(&nonce, &peer_id, &addr_a, content_a);
959                let expected_b = compute_audit_digest(&nonce, &peer_id, &addr_b, content_b);
960                assert_eq!(digests[0], expected_a);
961                assert_eq!(digests[1], expected_b);
962            }
963            AuditResponse::Bootstrapping { .. } => {
964                panic!("expected Digests, got Bootstrapping");
965            }
966            AuditResponse::Rejected { .. } => {
967                panic!("Unexpected Rejected response");
968            }
969        }
970    }
971
972    // -- handle_audit_challenge: absent keys ----------------------------------
973
974    #[tokio::test]
975    async fn handle_challenge_absent_keys_returns_sentinel() {
976        let (storage, _temp) = create_test_storage().await;
977
978        let absent_key = [0xFF; 32];
979        let nonce = [0x11; 32];
980        let peer_id = [0x22; 32];
981        let challenge = make_challenge(99, nonce, peer_id, vec![absent_key]);
982        let self_id = peer_id_from_bytes(peer_id);
983
984        let response =
985            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
986
987        match response {
988            AuditResponse::Digests {
989                challenge_id,
990                digests,
991            } => {
992                assert_eq!(challenge_id, 99);
993                assert_eq!(digests.len(), 1);
994                assert_eq!(
995                    digests[0], ABSENT_KEY_DIGEST,
996                    "absent key should produce sentinel digest"
997                );
998            }
999            AuditResponse::Bootstrapping { .. } => {
1000                panic!("expected Digests, got Bootstrapping");
1001            }
1002            AuditResponse::Rejected { .. } => {
1003                panic!("Unexpected Rejected response");
1004            }
1005        }
1006    }
1007
1008    // -- handle_audit_challenge: mixed present and absent ---------------------
1009
1010    #[tokio::test]
1011    async fn handle_challenge_mixed_present_and_absent() {
1012        let (storage, _temp) = create_test_storage().await;
1013
1014        let content = b"present chunk";
1015        let addr_present = ChunkStore::compute_address(content);
1016        storage.put(&addr_present, content).await.expect("put");
1017
1018        let addr_absent = [0xDE; 32];
1019        let nonce = [0x33; 32];
1020        let peer_id = [0x44; 32];
1021        let challenge = make_challenge(7, nonce, peer_id, vec![addr_present, addr_absent]);
1022        let self_id = peer_id_from_bytes(peer_id);
1023
1024        let response =
1025            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1026
1027        match response {
1028            AuditResponse::Digests { digests, .. } => {
1029                assert_eq!(digests.len(), 2);
1030
1031                let expected_present =
1032                    compute_audit_digest(&nonce, &peer_id, &addr_present, content);
1033                assert_eq!(digests[0], expected_present);
1034                assert_eq!(
1035                    digests[1], ABSENT_KEY_DIGEST,
1036                    "absent key should be sentinel"
1037                );
1038            }
1039            AuditResponse::Bootstrapping { .. } => {
1040                panic!("expected Digests, got Bootstrapping");
1041            }
1042            AuditResponse::Rejected { .. } => {
1043                panic!("Unexpected Rejected response");
1044            }
1045        }
1046    }
1047
1048    // -- handle_audit_challenge: bootstrapping --------------------------------
1049
1050    #[tokio::test]
1051    async fn handle_challenge_bootstrapping_returns_bootstrapping_response() {
1052        let (storage, _temp) = create_test_storage().await;
1053
1054        let challenge = make_challenge(55, [0x00; 32], [0x01; 32], vec![[0x02; 32]]);
1055        let self_id = peer_id_from_bytes([0x01; 32]);
1056
1057        let response =
1058            handle_audit_challenge(&challenge, &storage, &self_id, true, TEST_STORED_CHUNKS).await;
1059
1060        match response {
1061            AuditResponse::Bootstrapping { challenge_id } => {
1062                assert_eq!(challenge_id, 55);
1063            }
1064            AuditResponse::Digests { .. } => {
1065                panic!("expected Bootstrapping, got Digests");
1066            }
1067            AuditResponse::Rejected { .. } => {
1068                panic!("Unexpected Rejected response");
1069            }
1070        }
1071    }
1072
1073    // -- handle_audit_challenge: empty key list -------------------------------
1074
1075    #[tokio::test]
1076    async fn handle_challenge_empty_keys_returns_empty_digests() {
1077        let (storage, _temp) = create_test_storage().await;
1078
1079        let challenge = make_challenge(100, [0x10; 32], [0x20; 32], vec![]);
1080        let self_id = peer_id_from_bytes([0x20; 32]);
1081
1082        let response =
1083            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1084
1085        match response {
1086            AuditResponse::Digests {
1087                challenge_id,
1088                digests,
1089            } => {
1090                assert_eq!(challenge_id, 100);
1091                assert!(
1092                    digests.is_empty(),
1093                    "empty key list should yield empty digests"
1094                );
1095            }
1096            AuditResponse::Bootstrapping { .. } => {
1097                panic!("expected Digests, got Bootstrapping");
1098            }
1099            AuditResponse::Rejected { .. } => {
1100                panic!("Unexpected Rejected response");
1101            }
1102        }
1103    }
1104
1105    // -- Digest verification: matching ----------------------------------------
1106
1107    #[test]
1108    fn digest_verification_matching() {
1109        let nonce = [0x01; 32];
1110        let peer_id = [0x02; 32];
1111        let key: XorName = [0x03; 32];
1112        let data = b"correct data";
1113
1114        let expected = compute_audit_digest(&nonce, &peer_id, &key, data);
1115        let recomputed = compute_audit_digest(&nonce, &peer_id, &key, data);
1116
1117        assert_eq!(
1118            expected, recomputed,
1119            "same inputs must produce identical digests"
1120        );
1121        assert_ne!(
1122            expected, ABSENT_KEY_DIGEST,
1123            "real digest must not be sentinel"
1124        );
1125    }
1126
1127    // -- Digest verification: mismatching -------------------------------------
1128
1129    #[test]
1130    fn digest_verification_mismatching_data() {
1131        let nonce = [0x01; 32];
1132        let peer_id = [0x02; 32];
1133        let key: XorName = [0x03; 32];
1134
1135        let digest_a = compute_audit_digest(&nonce, &peer_id, &key, b"data version A");
1136        let digest_b = compute_audit_digest(&nonce, &peer_id, &key, b"data version B");
1137
1138        assert_ne!(
1139            digest_a, digest_b,
1140            "different data must produce different digests"
1141        );
1142    }
1143
1144    #[test]
1145    fn digest_verification_mismatching_nonce() {
1146        let peer_id = [0x02; 32];
1147        let key: XorName = [0x03; 32];
1148        let data = b"same data";
1149
1150        let digest_a = compute_audit_digest(&[0x01; 32], &peer_id, &key, data);
1151        let digest_b = compute_audit_digest(&[0xFF; 32], &peer_id, &key, data);
1152
1153        assert_ne!(
1154            digest_a, digest_b,
1155            "different nonces must produce different digests"
1156        );
1157    }
1158
1159    #[test]
1160    fn digest_verification_mismatching_peer() {
1161        let nonce = [0x01; 32];
1162        let key: XorName = [0x03; 32];
1163        let data = b"same data";
1164
1165        let digest_a = compute_audit_digest(&nonce, &[0x02; 32], &key, data);
1166        let digest_b = compute_audit_digest(&nonce, &[0xFE; 32], &key, data);
1167
1168        assert_ne!(
1169            digest_a, digest_b,
1170            "different peers must produce different digests"
1171        );
1172    }
1173
1174    #[test]
1175    fn digest_verification_mismatching_key() {
1176        let nonce = [0x01; 32];
1177        let peer_id = [0x02; 32];
1178        let data = b"same data";
1179
1180        let digest_a = compute_audit_digest(&nonce, &peer_id, &[0x03; 32], data);
1181        let digest_b = compute_audit_digest(&nonce, &peer_id, &[0xFC; 32], data);
1182
1183        assert_ne!(
1184            digest_a, digest_b,
1185            "different keys must produce different digests"
1186        );
1187    }
1188
1189    // -- Absent sentinel is all zeros -----------------------------------------
1190
1191    #[test]
1192    fn absent_sentinel_is_all_zeros() {
1193        assert_eq!(ABSENT_KEY_DIGEST, [0u8; 32], "sentinel must be all zeros");
1194    }
1195
1196    // -- Bootstrapping skips digest computation even with stored keys ---------
1197
1198    #[tokio::test]
1199    async fn bootstrapping_skips_digest_computation() {
1200        let (storage, _temp) = create_test_storage().await;
1201
1202        let content = b"stored but bootstrapping";
1203        let addr = ChunkStore::compute_address(content);
1204        storage.put(&addr, content).await.expect("put");
1205
1206        let challenge = make_challenge(200, [0xCC; 32], [0xDD; 32], vec![addr]);
1207        let self_id = peer_id_from_bytes([0xDD; 32]);
1208
1209        let response =
1210            handle_audit_challenge(&challenge, &storage, &self_id, true, TEST_STORED_CHUNKS).await;
1211
1212        assert!(
1213            matches!(response, AuditResponse::Bootstrapping { challenge_id: 200 }),
1214            "bootstrapping node must not compute digests"
1215        );
1216    }
1217
1218    // -- Scenario 19/53: Partial failure with mixed responsibility ----------------
1219
1220    #[tokio::test]
1221    async fn scenario_19_partial_failure_mixed_responsibility() {
1222        // Three keys challenged: K1 matches, K2 mismatches, K3 absent.
1223        // After responsibility confirmation, only K2 is confirmed responsible.
1224        // AuditFailure emitted for {K2} only.
1225        // Test handle_audit_challenge with mixed results, then verify
1226        // the digest logic manually.
1227
1228        let (storage, _temp) = create_test_storage().await;
1229        let nonce = [0x42u8; 32];
1230        let peer_id = [0xAA; 32];
1231
1232        // Store K1 and K2, but NOT K3
1233        let content_k1 = b"key one data";
1234        let addr_k1 = ChunkStore::compute_address(content_k1);
1235        storage.put(&addr_k1, content_k1).await.unwrap();
1236
1237        let content_k2 = b"key two data";
1238        let addr_k2 = ChunkStore::compute_address(content_k2);
1239        storage.put(&addr_k2, content_k2).await.unwrap();
1240
1241        let addr_k3 = [0xFF; 32]; // Not stored
1242
1243        let challenge = AuditChallenge {
1244            challenge_id: 100,
1245            nonce,
1246            challenged_peer_id: peer_id,
1247            keys: vec![addr_k1, addr_k2, addr_k3],
1248        };
1249        let self_id = peer_id_from_bytes(peer_id);
1250
1251        let response =
1252            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1253
1254        match response {
1255            AuditResponse::Digests { digests, .. } => {
1256                assert_eq!(digests.len(), 3);
1257
1258                // K1 should have correct digest
1259                let expected_k1 = compute_audit_digest(&nonce, &peer_id, &addr_k1, content_k1);
1260                assert_eq!(digests[0], expected_k1);
1261
1262                // K2 should have correct digest
1263                let expected_k2 = compute_audit_digest(&nonce, &peer_id, &addr_k2, content_k2);
1264                assert_eq!(digests[1], expected_k2);
1265
1266                // K3 absent -> sentinel
1267                assert_eq!(digests[2], ABSENT_KEY_DIGEST);
1268            }
1269            AuditResponse::Bootstrapping { .. } => panic!("Expected Digests response"),
1270            AuditResponse::Rejected { .. } => panic!("Unexpected Rejected response"),
1271        }
1272    }
1273
1274    // -- Scenario 54: All digests pass -------------------------------------------
1275
1276    #[tokio::test]
1277    async fn scenario_54_all_digests_pass() {
1278        // All challenged keys present and digests match.
1279        // Multiple keys to strengthen coverage beyond existing two-key tests.
1280        let (storage, _temp) = create_test_storage().await;
1281        let nonce = [0x10; 32];
1282        let peer_id = [0x20; 32];
1283
1284        let c1 = b"chunk alpha";
1285        let c2 = b"chunk beta";
1286        let c3 = b"chunk gamma";
1287        let a1 = ChunkStore::compute_address(c1);
1288        let a2 = ChunkStore::compute_address(c2);
1289        let a3 = ChunkStore::compute_address(c3);
1290        storage.put(&a1, c1).await.unwrap();
1291        storage.put(&a2, c2).await.unwrap();
1292        storage.put(&a3, c3).await.unwrap();
1293
1294        let challenge = AuditChallenge {
1295            challenge_id: 200,
1296            nonce,
1297            challenged_peer_id: peer_id,
1298            keys: vec![a1, a2, a3],
1299        };
1300        let self_id = peer_id_from_bytes(peer_id);
1301
1302        let response =
1303            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1304        match response {
1305            AuditResponse::Digests { digests, .. } => {
1306                assert_eq!(digests.len(), 3);
1307                for (i, (addr, content)) in [(a1, &c1[..]), (a2, &c2[..]), (a3, &c3[..])]
1308                    .iter()
1309                    .enumerate()
1310                {
1311                    let expected = compute_audit_digest(&nonce, &peer_id, addr, content);
1312                    assert_eq!(digests[i], expected, "Key {i} digest should match");
1313                }
1314            }
1315            AuditResponse::Bootstrapping { .. } => panic!("Expected Digests"),
1316            AuditResponse::Rejected { .. } => panic!("Unexpected Rejected response"),
1317        }
1318    }
1319
1320    // -- Scenario 55: Empty failure set means no evidence -------------------------
1321
1322    /// Scenario 55: Peer challenged on {K1, K2}. Both digests mismatch.
1323    /// Responsibility confirmation shows the peer is NOT responsible for
1324    /// either key. The confirmed failure set is empty — no `AuditFailure`
1325    /// evidence is emitted.
1326    ///
1327    /// Full `verify_digests` requires a live `P2PNode` for network lookups.
1328    /// This test exercises the deterministic sub-steps:
1329    ///   (1) Digest comparison identifies K1 and K2 as mismatches.
1330    ///   (2) Responsibility confirmation removes both keys.
1331    ///   (3) Empty confirmed failure set means no evidence.
1332    #[tokio::test]
1333    async fn scenario_55_no_confirmed_responsibility_no_evidence() {
1334        let (storage, _temp) = create_test_storage().await;
1335        let nonce = [0x55; 32];
1336        let peer_id = [0x55; 32];
1337
1338        // Store K1 and K2 on the challenger (for expected digest computation).
1339        let c1 = b"scenario 55 key one";
1340        let c2 = b"scenario 55 key two";
1341        let k1 = ChunkStore::compute_address(c1);
1342        let k2 = ChunkStore::compute_address(c2);
1343        storage.put(&k1, c1).await.expect("put k1");
1344        storage.put(&k2, c2).await.expect("put k2");
1345
1346        // Challenger computes expected digests.
1347        let expected_d1 = compute_audit_digest(&nonce, &peer_id, &k1, c1);
1348        let expected_d2 = compute_audit_digest(&nonce, &peer_id, &k2, c2);
1349
1350        // Simulate peer returning WRONG digests for both keys.
1351        let wrong_d1 = compute_audit_digest(&nonce, &peer_id, &k1, b"corrupted k1");
1352        let wrong_d2 = compute_audit_digest(&nonce, &peer_id, &k2, b"corrupted k2");
1353        assert_ne!(wrong_d1, expected_d1, "K1 digest should mismatch");
1354        assert_ne!(wrong_d2, expected_d2, "K2 digest should mismatch");
1355
1356        // Step 1: Identify failed keys via digest comparison.
1357        let keys = [k1, k2];
1358        let expected = [expected_d1, expected_d2];
1359        let received = [wrong_d1, wrong_d2];
1360
1361        let mut failed_keys = Vec::new();
1362        for i in 0..keys.len() {
1363            if received[i] != expected[i] {
1364                failed_keys.push(keys[i]);
1365            }
1366        }
1367        assert_eq!(
1368            failed_keys.len(),
1369            2,
1370            "Both keys should be identified as digest mismatches"
1371        );
1372
1373        // Step 2: Responsibility confirmation — peer is NOT responsible for
1374        // either key (simulated by filtering them all out).
1375        let confirmed_responsible_keys: Vec<XorName> = Vec::new();
1376        let confirmed_failures: Vec<XorName> = failed_keys
1377            .into_iter()
1378            .filter(|k| confirmed_responsible_keys.contains(k))
1379            .collect();
1380
1381        // Step 3: Empty confirmed failure set → no AuditFailure evidence.
1382        assert!(
1383            confirmed_failures.is_empty(),
1384            "With no confirmed responsibility, failure set must be empty — \
1385             no AuditFailure evidence should be emitted"
1386        );
1387
1388        // Verify that constructing evidence with empty keys results in a
1389        // no-penalty outcome (the caller checks is_empty before emitting).
1390        let peer = PeerId::from_bytes(peer_id);
1391        let evidence = FailureEvidence::AuditFailure {
1392            challenge_id: 5500,
1393            challenged_peer: peer,
1394            confirmed_failed_keys: confirmed_failures,
1395            summary: AuditFailureSummary::default(),
1396            reason: AuditFailureReason::DigestMismatch,
1397        };
1398        if let FailureEvidence::AuditFailure {
1399            confirmed_failed_keys,
1400            ..
1401        } = evidence
1402        {
1403            assert!(
1404                confirmed_failed_keys.is_empty(),
1405                "Evidence with empty failure set should not trigger a trust penalty"
1406            );
1407        }
1408    }
1409
1410    // -- Scenario 56: RepairOpportunity filters never-synced peers ----------------
1411
1412    #[test]
1413    fn scenario_56_repair_opportunity_filters_never_synced() {
1414        // PeerSyncRecord with last_sync=None should not pass
1415        // has_repair_opportunity().
1416
1417        let never_synced = PeerSyncRecord {
1418            last_sync: None,
1419            cycles_since_sync: 5,
1420        };
1421        assert!(!never_synced.has_repair_opportunity());
1422
1423        let synced_no_cycle = PeerSyncRecord {
1424            last_sync: Some(Instant::now()),
1425            cycles_since_sync: 0,
1426        };
1427        assert!(!synced_no_cycle.has_repair_opportunity());
1428
1429        let synced_with_cycle = PeerSyncRecord {
1430            last_sync: Some(Instant::now()),
1431            cycles_since_sync: 1,
1432        };
1433        assert!(synced_with_cycle.has_repair_opportunity());
1434    }
1435
1436    #[test]
1437    fn expired_bootstrap_claim_does_not_remove_peer_from_audit_eligibility() {
1438        let peer = peer_id_from_bytes([0x57; 32]);
1439        let mut sync_history = HashMap::new();
1440        sync_history.insert(
1441            peer,
1442            PeerSyncRecord {
1443                last_sync: Some(Instant::now()),
1444                cycles_since_sync: 1,
1445            },
1446        );
1447
1448        let mut bootstrap_claims = HashMap::new();
1449        let first_seen = Instant::now()
1450            .checked_sub(
1451                crate::replication::config::BOOTSTRAP_CLAIM_GRACE_PERIOD
1452                    + std::time::Duration::from_secs(1),
1453            )
1454            .unwrap_or_else(Instant::now);
1455        bootstrap_claims.insert(peer, first_seen);
1456
1457        let eligible = eligible_audit_peers(&sync_history);
1458
1459        assert!(bootstrap_claims.contains_key(&peer));
1460        assert!(
1461            eligible.contains(&peer),
1462            "continued bootstrap claims must remain auditable so past-grace abuse can be observed"
1463        );
1464    }
1465
1466    #[test]
1467    fn audit_failure_summary_counts_confirmed_absent_and_mismatch_keys() {
1468        let absent_key = [0xA1; 32];
1469        let mismatch_key = [0xB2; 32];
1470        let confirmed = vec![
1471            AuditKeyFailure::absent(absent_key),
1472            AuditKeyFailure::digest_mismatch(mismatch_key),
1473        ];
1474
1475        let summary = build_audit_failure_summary(5, &confirmed);
1476
1477        assert_eq!(summary.challenged_keys, 5);
1478        assert_eq!(summary.failed_keys, 2);
1479        assert_eq!(summary.absent_keys, 1);
1480        assert_eq!(summary.digest_mismatch_keys, 1);
1481    }
1482
1483    #[test]
1484    fn audit_failure_summary_leaves_unclassified_rejections_out_of_absent_mismatch_counts() {
1485        let rejected_key = [0xC3; 32];
1486        let confirmed = vec![AuditKeyFailure::unclassified(rejected_key)];
1487
1488        let summary = build_audit_failure_summary(3, &confirmed);
1489
1490        assert_eq!(summary.challenged_keys, 3);
1491        assert_eq!(summary.failed_keys, 1);
1492        assert_eq!(summary.absent_keys, 0);
1493        assert_eq!(summary.digest_mismatch_keys, 0);
1494    }
1495
1496    #[test]
1497    fn audit_digest_failure_reason_is_key_absent_when_all_confirmed_failures_are_absent() {
1498        let failures = vec![AuditKeyFailure::absent([0xD4; 32])];
1499
1500        assert_eq!(
1501            audit_digest_failure_reason(&failures),
1502            AuditFailureReason::KeyAbsent
1503        );
1504    }
1505
1506    #[test]
1507    fn audit_digest_failure_reason_is_digest_mismatch_for_mixed_failures() {
1508        let failures = vec![
1509            AuditKeyFailure::absent([0xD5; 32]),
1510            AuditKeyFailure::digest_mismatch([0xE6; 32]),
1511        ];
1512
1513        assert_eq!(
1514            audit_digest_failure_reason(&failures),
1515            AuditFailureReason::DigestMismatch
1516        );
1517    }
1518
1519    #[test]
1520    fn audit_key_filter_retains_stable_proofs_and_rejects_evicted_peers() {
1521        const HINT_EPOCH: u64 = 7;
1522        const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1523        const CHALLENGED_PEER_BYTE: u8 = 0xA1;
1524        const OTHER_PEER_BYTE: u8 = 0xA2;
1525        const NEW_PEER_BYTE: u8 = 0xA3;
1526        const MATURE_KEY_BYTE: u8 = 0xB1;
1527        const SAME_EPOCH_KEY_BYTE: u8 = 0xB2;
1528        const MISSING_PROOF_KEY_BYTE: u8 = 0xB3;
1529        const STABLE_CHURN_KEY_BYTE: u8 = 0xB4;
1530        const EVICTED_KEY_BYTE: u8 = 0xB5;
1531        const FRESH_HINT_KEY_BYTE: u8 = 0xB6;
1532        const XOR_NAME_LEN: usize = 32;
1533
1534        let challenged_peer = peer_id_from_bytes([CHALLENGED_PEER_BYTE; XOR_NAME_LEN]);
1535        let other_peer = peer_id_from_bytes([OTHER_PEER_BYTE; XOR_NAME_LEN]);
1536        let new_peer = peer_id_from_bytes([NEW_PEER_BYTE; XOR_NAME_LEN]);
1537        let mature_key = [MATURE_KEY_BYTE; XOR_NAME_LEN];
1538        let same_epoch_key = [SAME_EPOCH_KEY_BYTE; XOR_NAME_LEN];
1539        let missing_proof_key = [MISSING_PROOF_KEY_BYTE; XOR_NAME_LEN];
1540        let stable_churn_key = [STABLE_CHURN_KEY_BYTE; XOR_NAME_LEN];
1541        let evicted_key = [EVICTED_KEY_BYTE; XOR_NAME_LEN];
1542        let fresh_hint_key = [FRESH_HINT_KEY_BYTE; XOR_NAME_LEN];
1543        let close_group = HashSet::from([challenged_peer, other_peer]);
1544        let changed_close_group = HashSet::from([challenged_peer, new_peer]);
1545        let evicted_close_group = HashSet::from([other_peer, new_peer]);
1546        let mut repair_proofs = RepairProofs::new();
1547        let mature_hinted_at = Instant::now();
1548        let now = mature_hinted_at
1549            .checked_add(REPAIR_HINT_MIN_AGE)
1550            .unwrap_or(mature_hinted_at);
1551
1552        assert!(repair_proofs.record_replica_hint_sent_at(
1553            challenged_peer,
1554            mature_key,
1555            &close_group,
1556            HINT_EPOCH,
1557            mature_hinted_at,
1558        ));
1559        assert!(repair_proofs.record_replica_hint_sent_at(
1560            challenged_peer,
1561            same_epoch_key,
1562            &close_group,
1563            CURRENT_EPOCH,
1564            mature_hinted_at,
1565        ));
1566        assert!(repair_proofs.record_replica_hint_sent_at(
1567            challenged_peer,
1568            stable_churn_key,
1569            &close_group,
1570            HINT_EPOCH,
1571            mature_hinted_at,
1572        ));
1573        assert!(repair_proofs.record_replica_hint_sent_at(
1574            challenged_peer,
1575            evicted_key,
1576            &close_group,
1577            HINT_EPOCH,
1578            mature_hinted_at,
1579        ));
1580        assert!(repair_proofs.record_replica_hint_sent_at(
1581            challenged_peer,
1582            fresh_hint_key,
1583            &close_group,
1584            HINT_EPOCH,
1585            now,
1586        ));
1587
1588        let sampled_key_groups = vec![
1589            (mature_key, close_group.clone()),
1590            (same_epoch_key, close_group.clone()),
1591            (missing_proof_key, close_group.clone()),
1592            (stable_churn_key, changed_close_group),
1593            (evicted_key, evicted_close_group),
1594            (fresh_hint_key, close_group.clone()),
1595        ];
1596        let peer_keys = mature_audit_keys_for_peer(
1597            &challenged_peer,
1598            sampled_key_groups,
1599            &mut repair_proofs,
1600            CURRENT_EPOCH,
1601            now,
1602        );
1603
1604        assert_eq!(
1605            peer_keys,
1606            vec![mature_key, stable_churn_key],
1607            "mature proofs for stable close-group peers should become audit keys, while same-epoch, fresh, missing, and evicted-peer proofs should not"
1608        );
1609    }
1610
1611    // -- Audit response must match key count --------------------------------------
1612
1613    #[tokio::test]
1614    async fn audit_response_must_match_key_count() {
1615        // Section 15: "A response is invalid if it has fewer or more entries
1616        // than challenged keys."
1617        // Verify handle_audit_challenge always produces exactly N digests for
1618        // N keys, including edge cases.
1619
1620        let (storage, _temp) = create_test_storage().await;
1621        let nonce = [0x50; 32];
1622        let peer_id = [0x60; 32];
1623
1624        // Store a single chunk
1625        let content = b"single chunk";
1626        let addr = ChunkStore::compute_address(content);
1627        storage.put(&addr, content).await.unwrap();
1628
1629        // Challenge with 1 stored + 4 absent = 5 keys total
1630        let absent_keys: Vec<XorName> = (1..=4u8).map(|i| [i; 32]).collect();
1631        let mut keys = vec![addr];
1632        keys.extend_from_slice(&absent_keys);
1633
1634        let key_count = keys.len();
1635        let challenge = make_challenge(300, nonce, peer_id, keys);
1636        let self_id = peer_id_from_bytes(peer_id);
1637
1638        let response =
1639            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1640        match response {
1641            AuditResponse::Digests { digests, .. } => {
1642                assert_eq!(
1643                    digests.len(),
1644                    key_count,
1645                    "must produce exactly one digest per challenged key"
1646                );
1647            }
1648            AuditResponse::Bootstrapping { .. } => panic!("Expected Digests"),
1649            AuditResponse::Rejected { .. } => panic!("Unexpected Rejected response"),
1650        }
1651    }
1652
1653    // -- Audit digest uses full record bytes --------------------------------------
1654
1655    #[test]
1656    fn audit_digest_uses_full_record_bytes() {
1657        // Verify digest changes when record content changes.
1658        let nonce = [1u8; 32];
1659        let peer = [2u8; 32];
1660        let key = [3u8; 32];
1661
1662        let d1 = compute_audit_digest(&nonce, &peer, &key, b"data version 1");
1663        let d2 = compute_audit_digest(&nonce, &peer, &key, b"data version 2");
1664        assert_ne!(
1665            d1, d2,
1666            "Different record bytes must produce different digests"
1667        );
1668    }
1669
1670    // -- Scenario 29: Audit start gate ------------------------------------------
1671
1672    /// Scenario 29: `handle_audit_challenge` returns `Bootstrapping` when the
1673    /// node is still bootstrapping — audit digests are never computed, and no
1674    /// `AuditFailure` evidence is emitted by the caller.
1675    ///
1676    /// This is the responder-side gate.  The challenger-side gate is enforced
1677    /// by `audit_tick`'s `is_bootstrapping` guard (Invariant 19) and by
1678    /// `check_bootstrap_drained()` in the engine loop; this test confirms the
1679    /// complementary responder behavior.
1680    #[tokio::test]
1681    async fn scenario_29_audit_start_gate_during_bootstrap() {
1682        let (storage, _temp) = create_test_storage().await;
1683
1684        // Store data so there *would* be work to audit.
1685        let content = b"should not be audited during bootstrap";
1686        let addr = ChunkStore::compute_address(content);
1687        storage.put(&addr, content).await.expect("put");
1688
1689        let challenge = make_challenge(2900, [0x29; 32], [0x29; 32], vec![addr]);
1690        let self_id = peer_id_from_bytes([0x29; 32]);
1691
1692        // Responder is bootstrapping → Bootstrapping response, NOT Digests.
1693        let response =
1694            handle_audit_challenge(&challenge, &storage, &self_id, true, TEST_STORED_CHUNKS).await;
1695        assert!(
1696            matches!(
1697                response,
1698                AuditResponse::Bootstrapping { challenge_id: 2900 }
1699            ),
1700            "bootstrapping node must not compute digests — audit start gate"
1701        );
1702
1703        // Responder is NOT bootstrapping → normal Digests.
1704        let response =
1705            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1706        assert!(
1707            matches!(response, AuditResponse::Digests { .. }),
1708            "drained node should compute digests normally"
1709        );
1710    }
1711
1712    // -- Scenario 30: Audit peer selection from sampled keys --------------------
1713
1714    /// Scenario 30: Key sampling uses dynamic sqrt-based batch sizing and
1715    /// `RepairOpportunity` filtering excludes never-synced peers.
1716    ///
1717    /// Full `audit_tick` requires a live network.  This test verifies the two
1718    /// deterministic sub-steps the function relies on:
1719    ///   (a) `audit_sample_count` scales with `sqrt(total_keys)`.
1720    ///   (b) `PeerSyncRecord::has_repair_opportunity` gates peer eligibility.
1721    #[test]
1722    fn scenario_30_audit_peer_selection_from_sampled_keys() {
1723        // (a) Dynamic sample count scales with sqrt(total_keys).
1724        assert_eq!(
1725            ReplicationConfig::audit_sample_count(100),
1726            10,
1727            "sample count should scale with sqrt(total_keys)"
1728        );
1729
1730        assert_eq!(ReplicationConfig::audit_sample_count(3), 1, "sqrt(3) = 1");
1731
1732        assert_eq!(
1733            ReplicationConfig::audit_sample_count(10_000),
1734            100,
1735            "sqrt(10000) = 100"
1736        );
1737
1738        // (b) Peer eligibility via RepairOpportunity.
1739        // Never synced → not eligible.
1740        let never = PeerSyncRecord {
1741            last_sync: None,
1742            cycles_since_sync: 10,
1743        };
1744        assert!(!never.has_repair_opportunity());
1745
1746        // Synced but zero subsequent cycles → not eligible.
1747        let too_soon = PeerSyncRecord {
1748            last_sync: Some(Instant::now()),
1749            cycles_since_sync: 0,
1750        };
1751        assert!(!too_soon.has_repair_opportunity());
1752
1753        // Synced with ≥1 cycle → eligible.
1754        let eligible = PeerSyncRecord {
1755            last_sync: Some(Instant::now()),
1756            cycles_since_sync: 2,
1757        };
1758        assert!(eligible.has_repair_opportunity());
1759    }
1760
1761    // -- Scenario 32: Dynamic challenge size ------------------------------------
1762
1763    /// Scenario 32: Challenge key count equals `|PeerKeySet(challenged_peer)|`,
1764    /// which is dynamic per round.  If no eligible peer remains after filtering,
1765    /// the tick is idle.
1766    ///
1767    /// Verified via `handle_audit_challenge`: the response digest count always
1768    /// equals the number of keys in the challenge.
1769    #[tokio::test]
1770    async fn scenario_32_dynamic_challenge_size() {
1771        let (storage, _temp) = create_test_storage().await;
1772
1773        // Store varying numbers of chunks.
1774        let mut addrs = Vec::new();
1775        for i in 0u8..5 {
1776            let content = format!("dynamic challenge key {i}");
1777            let addr = ChunkStore::compute_address(content.as_bytes());
1778            storage.put(&addr, content.as_bytes()).await.expect("put");
1779            addrs.push(addr);
1780        }
1781
1782        let nonce = [0x32; 32];
1783        let peer_id = [0x32; 32];
1784        let self_id = peer_id_from_bytes(peer_id);
1785
1786        // Challenge with 1 key.
1787        let challenge1 = make_challenge(3201, nonce, peer_id, vec![addrs[0]]);
1788        let resp1 =
1789            handle_audit_challenge(&challenge1, &storage, &self_id, false, TEST_STORED_CHUNKS)
1790                .await;
1791        if let AuditResponse::Digests { digests, .. } = resp1 {
1792            assert_eq!(digests.len(), 1, "|PeerKeySet| = 1 → 1 digest");
1793        }
1794
1795        // Challenge with 3 keys.
1796        let challenge3 = make_challenge(3203, nonce, peer_id, addrs[0..3].to_vec());
1797        let resp3 =
1798            handle_audit_challenge(&challenge3, &storage, &self_id, false, TEST_STORED_CHUNKS)
1799                .await;
1800        if let AuditResponse::Digests { digests, .. } = resp3 {
1801            assert_eq!(digests.len(), 3, "|PeerKeySet| = 3 → 3 digests");
1802        }
1803
1804        // Challenge with all 5 keys.
1805        let challenge5 = make_challenge(3205, nonce, peer_id, addrs.clone());
1806        let resp5 =
1807            handle_audit_challenge(&challenge5, &storage, &self_id, false, TEST_STORED_CHUNKS)
1808                .await;
1809        if let AuditResponse::Digests { digests, .. } = resp5 {
1810            assert_eq!(digests.len(), 5, "|PeerKeySet| = 5 → 5 digests");
1811        }
1812
1813        // Challenge with 0 keys (idle equivalent — no work).
1814        let challenge0 = make_challenge(3200, nonce, peer_id, vec![]);
1815        let resp0 =
1816            handle_audit_challenge(&challenge0, &storage, &self_id, false, TEST_STORED_CHUNKS)
1817                .await;
1818        if let AuditResponse::Digests { digests, .. } = resp0 {
1819            assert!(digests.is_empty(), "|PeerKeySet| = 0 → 0 digests (idle)");
1820        }
1821    }
1822
1823    // -- Scenario 47: Bootstrap claim grace period (audit) ----------------------
1824
1825    /// Scenario 47: Challenged peer responds with bootstrapping claim during
1826    /// audit.  `handle_audit_challenge` returns `Bootstrapping`; caller records
1827    /// `BootstrapClaimFirstSeen`.  No `AuditFailure` evidence is emitted.
1828    #[tokio::test]
1829    async fn scenario_47_bootstrap_claim_grace_period_audit() {
1830        let (storage, _temp) = create_test_storage().await;
1831
1832        // Store data so there is an auditable key.
1833        let content = b"bootstrap grace test";
1834        let addr = ChunkStore::compute_address(content);
1835        storage.put(&addr, content).await.expect("put");
1836
1837        let challenge = make_challenge(4700, [0x47; 32], [0x47; 32], vec![addr]);
1838        let self_id = peer_id_from_bytes([0x47; 32]);
1839
1840        // Bootstrapping peer → Bootstrapping response (grace period start).
1841        let response =
1842            handle_audit_challenge(&challenge, &storage, &self_id, true, TEST_STORED_CHUNKS).await;
1843        let challenge_id = match response {
1844            AuditResponse::Bootstrapping { challenge_id } => challenge_id,
1845            AuditResponse::Digests { .. } => {
1846                panic!("Expected Bootstrapping response during grace period")
1847            }
1848            AuditResponse::Rejected { .. } => {
1849                panic!("Unexpected Rejected response")
1850            }
1851        };
1852        assert_eq!(challenge_id, 4700);
1853
1854        // Caller records BootstrapClaimFirstSeen — verify the types support it.
1855        let peer = PeerId::from_bytes([0x47; 32]);
1856        let mut state = NeighborSyncState::new_cycle(vec![peer]);
1857        let now = Instant::now();
1858        let observed = state.observe_bootstrap_claim(
1859            peer,
1860            now,
1861            crate::replication::config::BOOTSTRAP_CLAIM_GRACE_PERIOD,
1862        );
1863
1864        assert_eq!(
1865            observed,
1866            BootstrapClaimObservation::WithinGrace { first_seen: now }
1867        );
1868        assert!(
1869            state.bootstrap_claims.contains_key(&peer),
1870            "BootstrapClaimFirstSeen should be recorded after grace-period claim"
1871        );
1872        assert!(
1873            state.bootstrap_claim_history.contains_key(&peer),
1874            "Bootstrap claim history should remember that the grace window was used"
1875        );
1876    }
1877
1878    // -- Scenario 53: Audit partial per-key failure with mixed responsibility ---
1879
1880    /// Scenario 53: P challenged on {K1, K2, K3}.  K1 matches, K2 and K3
1881    /// mismatch.  Responsibility confirmation: P is responsible for K2 but
1882    /// not K3.  `AuditFailure` emitted for {K2} only.
1883    ///
1884    /// Full `verify_digests` + `handle_audit_failure` requires a `P2PNode` for
1885    /// network lookups.  This test verifies the conceptual steps:
1886    ///   (1) Digest comparison correctly identifies K2 and K3 as failures.
1887    ///   (2) `FailureEvidence::AuditFailure` carries only confirmed keys.
1888    #[tokio::test]
1889    async fn scenario_53_partial_failure_mixed_responsibility() {
1890        let (storage, _temp) = create_test_storage().await;
1891        let nonce = [0x53; 32];
1892        let peer_id = [0x53; 32];
1893
1894        // Store K1, K2, K3.
1895        let c1 = b"scenario 53 key one";
1896        let c2 = b"scenario 53 key two";
1897        let c3 = b"scenario 53 key three";
1898        let k1 = ChunkStore::compute_address(c1);
1899        let k2 = ChunkStore::compute_address(c2);
1900        let k3 = ChunkStore::compute_address(c3);
1901        storage.put(&k1, c1).await.expect("put k1");
1902        storage.put(&k2, c2).await.expect("put k2");
1903        storage.put(&k3, c3).await.expect("put k3");
1904
1905        // Correct digests from challenger's local store.
1906        let d1_expected = compute_audit_digest(&nonce, &peer_id, &k1, c1);
1907        let d2_expected = compute_audit_digest(&nonce, &peer_id, &k2, c2);
1908        let d3_expected = compute_audit_digest(&nonce, &peer_id, &k3, c3);
1909
1910        // Simulate peer response: K1 matches, K2 wrong data, K3 wrong data.
1911        let d2_wrong = compute_audit_digest(&nonce, &peer_id, &k2, b"tampered k2");
1912        let d3_wrong = compute_audit_digest(&nonce, &peer_id, &k3, b"tampered k3");
1913
1914        assert_eq!(d1_expected, d1_expected, "K1 should match");
1915        assert_ne!(d2_wrong, d2_expected, "K2 should mismatch");
1916        assert_ne!(d3_wrong, d3_expected, "K3 should mismatch");
1917
1918        // Step 1: Identify failed keys (digest comparison).
1919        let digests = [d1_expected, d2_wrong, d3_wrong];
1920        let keys = [k1, k2, k3];
1921        let contents: [&[u8]; 3] = [c1, c2, c3];
1922
1923        let mut failed_keys = Vec::new();
1924        for (i, key) in keys.iter().enumerate() {
1925            if digests[i] == ABSENT_KEY_DIGEST {
1926                failed_keys.push(*key);
1927                continue;
1928            }
1929            let expected = compute_audit_digest(&nonce, &peer_id, key, contents[i]);
1930            if digests[i] != expected {
1931                failed_keys.push(*key);
1932            }
1933        }
1934
1935        assert_eq!(failed_keys.len(), 2, "K2 and K3 should be in failure set");
1936        assert!(failed_keys.contains(&k2));
1937        assert!(failed_keys.contains(&k3));
1938        assert!(!failed_keys.contains(&k1), "K1 passed digest check");
1939
1940        // Step 2: Responsibility confirmation removes K3 (not responsible).
1941        // Simulate: P is in closest peers for K2 but not K3.
1942        let responsible_for_k2 = true;
1943        let responsible_for_k3 = false;
1944        let mut confirmed = Vec::new();
1945        for key in &failed_keys {
1946            let is_responsible = if *key == k2 {
1947                responsible_for_k2
1948            } else {
1949                responsible_for_k3
1950            };
1951            if is_responsible {
1952                confirmed.push(*key);
1953            }
1954        }
1955
1956        assert_eq!(confirmed, vec![k2], "Only K2 should be in confirmed set");
1957
1958        // Step 3: Construct evidence for confirmed failures only.
1959        let challenged_peer = PeerId::from_bytes(peer_id);
1960        let evidence = FailureEvidence::AuditFailure {
1961            challenge_id: 5300,
1962            challenged_peer,
1963            confirmed_failed_keys: confirmed,
1964            summary: AuditFailureSummary::default(),
1965            reason: AuditFailureReason::DigestMismatch,
1966        };
1967
1968        match evidence {
1969            FailureEvidence::AuditFailure {
1970                confirmed_failed_keys,
1971                ..
1972            } => {
1973                assert_eq!(
1974                    confirmed_failed_keys.len(),
1975                    1,
1976                    "Only K2 should generate evidence"
1977                );
1978                assert_eq!(confirmed_failed_keys[0], k2);
1979            }
1980            _ => panic!("Expected AuditFailure evidence"),
1981        }
1982    }
1983}