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