Skip to main content

ant_node/replication/
possession.rs

1//! Delayed possession verification for fresh replication (ADR-0003).
2//!
3//! After a node fresh-replicates a chunk, every close-group peer responsible
4//! for it is checked 5-15 minutes later for actual possession. The check is a
5//! single-key cryptographic
6//! [`AuditChallenge`]: the probed
7//! peer must return `BLAKE3(nonce ‖ peer_id ‖ key ‖ bytes)` computed over the
8//! chunk it claims to hold. It cannot produce that digest without the bytes, so
9//! — unlike a self-reported presence flag — a peer cannot escape the check by
10//! falsely asserting possession. A peer that holds the chunk earns nothing —
11//! storing what it was paid to store is the baseline expectation, not
12//! meritorious; a peer that returns the absent sentinel, or a digest that does
13//! not match the checker's canonical copy (cryptographic proof it lacks the
14//! bytes), is penalised at `AuditChallenge` severity. Delivery of the original
15//! push is irrelevant: a peer the push never reached is still checked and
16//! penalised if it lacks the chunk.
17//!
18//! A peer unreachable at check time is penalised immediately at audit severity,
19//! matching the responsible-chunk `AuditChallenge` path. A matching bootstrap
20//! claim uses the shared bootstrap-claim grace/abuse tracker; peer-side
21//! malformed, rejected, or mismatched responses are audit failures.
22
23use std::sync::Arc;
24use std::time::{Duration, Instant};
25
26use rand::Rng;
27use saorsa_core::identity::PeerId;
28use saorsa_core::{P2PNode, TrustEvent};
29use tokio::sync::RwLock;
30use tokio_util::sync::CancellationToken;
31
32use crate::ant_protocol::XorName;
33use crate::logging::{debug, info, warn};
34use crate::replication::audit_coordinator::AuditChallengeCoordinator;
35use crate::replication::audit_metrics::{self, AuditFailureClass, AuditType};
36use crate::replication::config::{
37    ReplicationConfig, AUDIT_FAILURE_TRUST_WEIGHT, REPLICATION_PROTOCOL_ID,
38};
39use crate::replication::protocol::{
40    compute_audit_digest, AuditChallenge, AuditResponse, ReplicationMessage,
41    ReplicationMessageBody, ABSENT_KEY_DIGEST,
42};
43use crate::replication::types::{BootstrapClaimObservation, NeighborSyncState};
44use crate::storage::ChunkStore;
45
46use super::REPLICATION_TRUST_WEIGHT;
47
48/// A possession probe challenges exactly one key, so the per-probe response
49/// budget is the audit-response timeout sized for a single chunk.
50const POSSESSION_PROBE_KEY_COUNT: usize = 1;
51
52pub(crate) fn possession_probe_response_timeout(config: &ReplicationConfig) -> Duration {
53    config.audit_response_timeout(POSSESSION_PROBE_KEY_COUNT)
54}
55
56/// A scheduled possession check for one freshly-replicated chunk.
57pub struct PossessionCheckEvent {
58    /// Content-address of the chunk.
59    pub key: XorName,
60    /// Close-group peers responsible for holding it (excludes self).
61    pub peers: Vec<PeerId>,
62}
63
64/// Verdict of cryptographically probing a single peer for possession of a chunk.
65#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
66enum ProbeOutcome {
67    /// Peer returned a digest proving it holds the chunk's bytes.
68    Present,
69    /// Peer failed the audit challenge: absent sentinel, digest mismatch,
70    /// rejection, mismatched challenge ID, wrong digest count, or malformed reply.
71    Failed(PossessionFailureReason),
72    /// No response. Penalised immediately at audit-failure severity; the class
73    /// is node-local observability only.
74    NoResponse(AuditFailureClass),
75    /// Peer returned a matching bootstrap claim. Graced only through the shared
76    /// bootstrap-claim tracker.
77    BootstrapClaim,
78    /// The probe could not be sent locally. Graced: no penalty.
79    Inconclusive,
80}
81
82/// Exact reason a responsive peer failed a possession proof check.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84enum PossessionFailureReason {
85    ResponseDecode,
86    UnexpectedResponseType,
87    DigestChallengeIdMismatch,
88    DigestCountMismatch,
89    AbsentKey,
90    DigestMismatch,
91    BootstrapChallengeIdMismatch,
92    Rejected,
93}
94
95#[cfg(any(feature = "logging", test))]
96impl PossessionFailureReason {
97    const fn as_str(self) -> &'static str {
98        match self {
99            Self::ResponseDecode => "response_decode",
100            Self::UnexpectedResponseType => "unexpected_response_type",
101            Self::DigestChallengeIdMismatch => "digest_challenge_id_mismatch",
102            Self::DigestCountMismatch => "digest_count_mismatch",
103            Self::AbsentKey => "absent_key",
104            Self::DigestMismatch => "digest_mismatch",
105            Self::BootstrapChallengeIdMismatch => "bootstrap_challenge_id_mismatch",
106            Self::Rejected => "rejected",
107        }
108    }
109}
110
111/// Pick a randomised delay in `[min, max]` to wait before a possession check
112/// runs. The bounds come from `ReplicationConfig` (defaulting to
113/// `POSSESSION_CHECK_DELAY_MIN`/`MAX`) so tests can shorten them.
114#[must_use]
115pub fn random_delay(min: Duration, max: Duration) -> Duration {
116    let to_millis = |d: Duration| u64::try_from(d.as_millis()).unwrap_or(u64::MAX);
117    let min_ms = to_millis(min);
118    let max_ms = to_millis(max);
119    if min_ms >= max_ms {
120        return min;
121    }
122    Duration::from_millis(rand::thread_rng().gen_range(min_ms..=max_ms))
123}
124
125/// Run the possession check for one chunk against every responsible peer.
126///
127/// Recomputes the expected audit digest from the checker's own canonical copy
128/// of `key`, so the check is meaningful only while the checker still holds the
129/// chunk — which it does immediately after accepting and fresh-replicating a
130/// PUT. If the checker no longer holds it (e.g. pruned), the check is moot and
131/// is skipped without penalising anyone.
132///
133/// A peer that fails to prove possession, including by timeout, is penalised at
134/// `AuditChallenge` severity immediately. A responsive peer is left unrewarded.
135#[allow(clippy::too_many_arguments)]
136pub(crate) async fn run_possession_check(
137    key: XorName,
138    peers: Vec<PeerId>,
139    p2p_node: &Arc<P2PNode>,
140    storage: &Arc<ChunkStore>,
141    config: &ReplicationConfig,
142    sync_state: &Arc<RwLock<NeighborSyncState>>,
143    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
144    shutdown: &CancellationToken,
145) {
146    let key_hex = hex::encode(key);
147
148    // Read our canonical copy once: the audit digest is recomputed from these
149    // bytes for every peer (hoisted out of the per-peer loop). If we no longer
150    // hold the chunk we cannot verify any peer's proof, and we are no longer a
151    // responsible checker for it — skip without penalising anyone. Read through
152    // the verifying path for the same reason: a local copy that no longer hashes
153    // to its key would fail every honest peer, so it is taken out of service by
154    // the read (replication repairs it) and the check is skipped.
155    let local_bytes = match storage.get(&key).await {
156        Ok(Some(bytes)) => bytes,
157        Ok(None) => {
158            debug!("Possession check: checker no longer holds {key_hex}; skipping");
159            return;
160        }
161        Err(e) => {
162            warn!("Possession check: failed to read local {key_hex}: {e}; skipping");
163            return;
164        }
165    };
166
167    // Single-key probe budget, matched to the audit response timeout's
168    // bandwidth-calibrated deadline (tight enough that a relay that must refetch
169    // the bytes blows it, generous for an honest local-disk read).
170    let probe_timeout = possession_probe_response_timeout(config);
171
172    for peer in peers {
173        if shutdown.is_cancelled() {
174            return;
175        }
176        match probe_once(
177            &key,
178            &local_bytes,
179            &peer,
180            p2p_node,
181            audit_challenge_coordinator,
182            probe_timeout,
183        )
184        .await
185        {
186            ProbeOutcome::Present => {
187                debug!("Possession check: {peer} proved possession of {key_hex}");
188                clear_possession_bootstrap_claim(&peer, sync_state).await;
189            }
190            ProbeOutcome::Failed(reason) => {
191                clear_possession_bootstrap_claim(&peer, sync_state).await;
192                report_possession_confirmed_failure(&peer, &key_hex, reason, p2p_node).await;
193            }
194            ProbeOutcome::NoResponse(class) => {
195                audit_metrics::record_audit_no_response(AuditType::Possession, class);
196                report_possession_audit_failure(&peer, &key_hex, class, p2p_node).await;
197            }
198            ProbeOutcome::BootstrapClaim => {
199                handle_possession_bootstrap_claim(&peer, &key_hex, p2p_node, config, sync_state)
200                    .await;
201            }
202            ProbeOutcome::Inconclusive => {
203                debug!(
204                    "Possession check: inconclusive probe of {peer} for {key_hex}; not penalised"
205                );
206            }
207        }
208    }
209}
210
211async fn clear_possession_bootstrap_claim(
212    peer: &PeerId,
213    sync_state: &Arc<RwLock<NeighborSyncState>>,
214) {
215    sync_state.write().await.clear_active_bootstrap_claim(peer);
216}
217
218async fn report_possession_confirmed_failure(
219    peer: &PeerId,
220    key_hex: &str,
221    failure_reason: PossessionFailureReason,
222    p2p_node: &Arc<P2PNode>,
223) {
224    warn!(
225        audit_type = AuditType::Possession.as_str(),
226        audit_failure_class = "confirmed",
227        possession_failure_reason = failure_reason.as_str(),
228        peer = %peer,
229        key = %key_hex,
230        trust_weight = AUDIT_FAILURE_TRUST_WEIGHT,
231        "Possession check: {peer} failed to prove possession for {key_hex} ({}); recorded at audit severity",
232        failure_reason.as_str()
233    );
234    crate::replication::config::penalise_unheld_close_group_chunk(
235        p2p_node,
236        peer,
237        AuditType::Possession.as_str(),
238        AUDIT_FAILURE_TRUST_WEIGHT,
239    )
240    .await;
241}
242
243async fn report_possession_audit_failure(
244    peer: &PeerId,
245    key_hex: &str,
246    failure_class: AuditFailureClass,
247    p2p_node: &Arc<P2PNode>,
248) {
249    warn!(
250        audit_type = AuditType::Possession.as_str(),
251        audit_failure_class = failure_class.as_str(),
252        peer = %peer,
253        key = %key_hex,
254        trust_weight = AUDIT_FAILURE_TRUST_WEIGHT,
255        "Possession check: {peer} {} for {key_hex}; recorded at audit severity",
256        failure_class.as_str()
257    );
258    crate::replication::config::penalise_unheld_close_group_chunk(
259        p2p_node,
260        peer,
261        AuditType::Possession.as_str(),
262        AUDIT_FAILURE_TRUST_WEIGHT,
263    )
264    .await;
265}
266
267async fn handle_possession_bootstrap_claim(
268    peer: &PeerId,
269    key_hex: &str,
270    p2p_node: &Arc<P2PNode>,
271    config: &ReplicationConfig,
272    sync_state: &Arc<RwLock<NeighborSyncState>>,
273) {
274    let (now, observation) = {
275        let now = Instant::now();
276        let mut state = sync_state.write().await;
277        (
278            now,
279            state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period),
280        )
281    };
282
283    match observation {
284        BootstrapClaimObservation::WithinGrace { .. } => {
285            debug!(
286                "Possession check: peer {peer} claims bootstrapping for {key_hex} \
287                 (within grace period)"
288            );
289        }
290        BootstrapClaimObservation::PastGrace { first_seen } => {
291            warn!(
292                "Possession check: peer {peer} claiming bootstrap for {key_hex} past grace period \
293                 ({:?} > {:?}), reporting abuse",
294                now.duration_since(first_seen),
295                config.bootstrap_claim_grace_period,
296            );
297            p2p_node
298                .report_trust_event(
299                    peer,
300                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
301                )
302                .await;
303        }
304        BootstrapClaimObservation::Repeated { first_seen } => {
305            warn!(
306                "Possession check: peer {peer} repeated bootstrap claim for {key_hex} after \
307                 previously stopping; first claim was {:?} ago, reporting abuse",
308                now.duration_since(first_seen),
309            );
310            p2p_node
311                .report_trust_event(
312                    peer,
313                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
314                )
315                .await;
316        }
317    }
318}
319
320/// Send one single-key cryptographic [`AuditChallenge`] and interpret the
321/// response. The peer proves possession by returning
322/// `compute_audit_digest(nonce, peer, key, bytes)`; absence is proven by the
323/// [`ABSENT_KEY_DIGEST`] sentinel or any digest that does not match the
324/// checker's canonical copy. A transport failure / deadline is a `Timeout`; a
325/// matching bootstrap response is a `BootstrapClaim`; a local encode failure is
326/// `Inconclusive`; peer-side malformed, rejected, or mismatched replies are
327/// `Failed`.
328#[allow(clippy::too_many_lines)]
329async fn probe_once(
330    key: &XorName,
331    local_bytes: &[u8],
332    peer: &PeerId,
333    p2p_node: &Arc<P2PNode>,
334    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
335    probe_timeout: Duration,
336) -> ProbeOutcome {
337    // Fresh nonce per probe so a stored digest cannot be replayed, and bind the
338    // challenge to this peer's identity so it cannot relay another node's proof.
339    let (nonce, challenge_id) = {
340        let mut rng = rand::thread_rng();
341        let nonce: [u8; 32] = rng.gen();
342        let challenge_id: u64 = rng.gen();
343        (nonce, challenge_id)
344    };
345    let challenge = AuditChallenge {
346        challenge_id,
347        nonce,
348        challenged_peer_id: *peer.as_bytes(),
349        keys: vec![*key],
350    };
351    let msg = ReplicationMessage {
352        request_id: challenge_id,
353        body: ReplicationMessageBody::AuditChallenge(challenge),
354    };
355    let Ok(encoded) = msg.encode() else {
356        warn!(
357            "Failed to encode possession challenge for {}",
358            hex::encode(key)
359        );
360        return ProbeOutcome::Inconclusive;
361    };
362
363    let Some(_slot) = audit_challenge_coordinator.acquire(*peer).await else {
364        warn!("Failed to acquire possession audit coordinator slot for {peer}");
365        return ProbeOutcome::Inconclusive;
366    };
367    info!(
368        target: "ant_node::replication::audit_requester",
369        event = "started",
370        audit_origin = AuditType::Possession.as_str(),
371        audit_round = "digest",
372        challenged_peer = %peer,
373        challenge_id,
374        work_items = 1,
375        timeout_ms = probe_timeout.as_millis(),
376        "Outbound audit request started"
377    );
378    let request_started = Instant::now();
379    let response = match p2p_node
380        .send_request(peer, REPLICATION_PROTOCOL_ID, encoded, probe_timeout)
381        .await
382    {
383        Ok(response) => {
384            info!(
385                target: "ant_node::replication::audit_requester",
386                event = "completed",
387                audit_origin = AuditType::Possession.as_str(),
388                audit_round = "digest",
389                challenged_peer = %peer,
390                challenge_id,
391                work_items = 1,
392                elapsed_ms = request_started.elapsed().as_millis(),
393                outcome = "response",
394                "Outbound audit request completed"
395            );
396            response
397        }
398        Err(e) => {
399            let error = e.to_string();
400            let (send_error_class, audit_failure_class) =
401                audit_metrics::classify_audit_send_error(&error);
402            warn!(
403                target: "ant_node::replication::audit_requester",
404                event = "completed",
405                audit_origin = AuditType::Possession.as_str(),
406                audit_round = "digest",
407                challenged_peer = %peer,
408                challenge_id,
409                work_items = 1,
410                elapsed_ms = request_started.elapsed().as_millis(),
411                outcome = "no_response",
412                audit_type = AuditType::Possession.as_str(),
413                audit_failure_class = audit_failure_class.as_str(),
414                send_error_class,
415                "Possession probe to {peer} got no response: {e}"
416            );
417            return ProbeOutcome::NoResponse(audit_failure_class);
418        }
419    };
420
421    let decoded = match ReplicationMessage::decode(&response.data) {
422        Ok(decoded) => decoded,
423        Err(e) => {
424            debug!("Failed to decode possession response from {peer}: {e}");
425            return ProbeOutcome::Failed(PossessionFailureReason::ResponseDecode);
426        }
427    };
428
429    let ReplicationMessageBody::AuditResponse(resp) = decoded.body else {
430        debug!("Unexpected possession response type from {peer}");
431        return ProbeOutcome::Failed(PossessionFailureReason::UnexpectedResponseType);
432    };
433
434    interpret_audit_response(
435        key,
436        local_bytes,
437        peer.as_bytes(),
438        &nonce,
439        challenge_id,
440        resp,
441    )
442}
443
444/// Classify an [`AuditResponse`] into a possession verdict. Pure (no I/O): the
445/// digest is verified against `local_bytes`, the checker's canonical copy.
446fn interpret_audit_response(
447    key: &XorName,
448    local_bytes: &[u8],
449    challenged_peer_id: &[u8; 32],
450    nonce: &[u8; 32],
451    challenge_id: u64,
452    response: AuditResponse,
453) -> ProbeOutcome {
454    match response {
455        AuditResponse::Digests {
456            challenge_id: resp_id,
457            digests,
458        } => {
459            if resp_id != challenge_id {
460                return ProbeOutcome::Failed(PossessionFailureReason::DigestChallengeIdMismatch);
461            }
462            if digests.len() != 1 {
463                return ProbeOutcome::Failed(PossessionFailureReason::DigestCountMismatch);
464            }
465            let received = digests[0];
466            if received == ABSENT_KEY_DIGEST {
467                return ProbeOutcome::Failed(PossessionFailureReason::AbsentKey);
468            }
469            let expected = compute_audit_digest(nonce, challenged_peer_id, key, local_bytes);
470            if received == expected {
471                ProbeOutcome::Present
472            } else {
473                // A non-sentinel digest that does not match our canonical bytes
474                // proves the peer cannot reproduce the content — treat as absent
475                // (matches the audit's DigestMismatch handling).
476                ProbeOutcome::Failed(PossessionFailureReason::DigestMismatch)
477            }
478        }
479        AuditResponse::Bootstrapping {
480            challenge_id: resp_id,
481        } => {
482            if resp_id == challenge_id {
483                ProbeOutcome::BootstrapClaim
484            } else {
485                ProbeOutcome::Failed(PossessionFailureReason::BootstrapChallengeIdMismatch)
486            }
487        }
488        AuditResponse::Rejected { .. } => ProbeOutcome::Failed(PossessionFailureReason::Rejected),
489    }
490}
491
492#[cfg(test)]
493mod tests {
494    use super::*;
495    use crate::replication::config::{POSSESSION_CHECK_DELAY_MAX, POSSESSION_CHECK_DELAY_MIN};
496
497    const PEER_ID: [u8; 32] = [0x42; 32];
498    const NONCE: [u8; 32] = [0x7a; 32];
499    const CHALLENGE_ID: u64 = 0xDEAD_BEEF;
500    const KEY: XorName = [0x11; 32];
501    const BYTES: &[u8] = b"possession-check payload";
502
503    fn digests_response(challenge_id: u64, digests: Vec<[u8; 32]>) -> AuditResponse {
504        AuditResponse::Digests {
505            challenge_id,
506            digests,
507        }
508    }
509
510    #[test]
511    fn possession_failure_reasons_have_stable_log_labels() {
512        let cases = [
513            (PossessionFailureReason::ResponseDecode, "response_decode"),
514            (
515                PossessionFailureReason::UnexpectedResponseType,
516                "unexpected_response_type",
517            ),
518            (
519                PossessionFailureReason::DigestChallengeIdMismatch,
520                "digest_challenge_id_mismatch",
521            ),
522            (
523                PossessionFailureReason::DigestCountMismatch,
524                "digest_count_mismatch",
525            ),
526            (PossessionFailureReason::AbsentKey, "absent_key"),
527            (PossessionFailureReason::DigestMismatch, "digest_mismatch"),
528            (
529                PossessionFailureReason::BootstrapChallengeIdMismatch,
530                "bootstrap_challenge_id_mismatch",
531            ),
532            (PossessionFailureReason::Rejected, "rejected"),
533        ];
534
535        for (reason, expected) in cases {
536            assert_eq!(reason.as_str(), expected);
537        }
538    }
539
540    #[test]
541    fn random_delay_is_within_bounds() {
542        for _ in 0..100 {
543            let d = random_delay(POSSESSION_CHECK_DELAY_MIN, POSSESSION_CHECK_DELAY_MAX);
544            assert!(d >= POSSESSION_CHECK_DELAY_MIN);
545            assert!(d <= POSSESSION_CHECK_DELAY_MAX);
546        }
547    }
548
549    #[test]
550    fn matching_digest_is_present() {
551        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
552        let verdict = interpret_audit_response(
553            &KEY,
554            BYTES,
555            &PEER_ID,
556            &NONCE,
557            CHALLENGE_ID,
558            digests_response(CHALLENGE_ID, vec![valid]),
559        );
560        assert_eq!(verdict, ProbeOutcome::Present);
561    }
562
563    #[test]
564    fn absent_sentinel_is_failed() {
565        let verdict = interpret_audit_response(
566            &KEY,
567            BYTES,
568            &PEER_ID,
569            &NONCE,
570            CHALLENGE_ID,
571            digests_response(CHALLENGE_ID, vec![ABSENT_KEY_DIGEST]),
572        );
573        assert_eq!(
574            verdict,
575            ProbeOutcome::Failed(PossessionFailureReason::AbsentKey)
576        );
577    }
578
579    #[test]
580    fn forged_digest_is_failed() {
581        // A peer that lacks the bytes cannot compute the right digest; whatever
582        // non-sentinel value it sends must not match our canonical copy.
583        let forged = [0x99; 32];
584        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
585        assert_ne!(forged, valid, "test fixture must use a wrong digest");
586        let verdict = interpret_audit_response(
587            &KEY,
588            BYTES,
589            &PEER_ID,
590            &NONCE,
591            CHALLENGE_ID,
592            digests_response(CHALLENGE_ID, vec![forged]),
593        );
594        assert_eq!(
595            verdict,
596            ProbeOutcome::Failed(PossessionFailureReason::DigestMismatch)
597        );
598    }
599
600    #[test]
601    fn mismatched_challenge_id_is_failed() {
602        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
603        let verdict = interpret_audit_response(
604            &KEY,
605            BYTES,
606            &PEER_ID,
607            &NONCE,
608            CHALLENGE_ID,
609            digests_response(CHALLENGE_ID.wrapping_add(1), vec![valid]),
610        );
611        assert_eq!(
612            verdict,
613            ProbeOutcome::Failed(PossessionFailureReason::DigestChallengeIdMismatch)
614        );
615    }
616
617    #[test]
618    fn wrong_arity_is_failed() {
619        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
620        let verdict = interpret_audit_response(
621            &KEY,
622            BYTES,
623            &PEER_ID,
624            &NONCE,
625            CHALLENGE_ID,
626            digests_response(CHALLENGE_ID, vec![valid, ABSENT_KEY_DIGEST]),
627        );
628        assert_eq!(
629            verdict,
630            ProbeOutcome::Failed(PossessionFailureReason::DigestCountMismatch)
631        );
632    }
633
634    #[test]
635    fn bootstrapping_is_bootstrap_claim() {
636        let verdict = interpret_audit_response(
637            &KEY,
638            BYTES,
639            &PEER_ID,
640            &NONCE,
641            CHALLENGE_ID,
642            AuditResponse::Bootstrapping {
643                challenge_id: CHALLENGE_ID,
644            },
645        );
646        assert_eq!(verdict, ProbeOutcome::BootstrapClaim);
647    }
648
649    #[test]
650    fn bootstrapping_with_wrong_challenge_id_is_failed() {
651        let verdict = interpret_audit_response(
652            &KEY,
653            BYTES,
654            &PEER_ID,
655            &NONCE,
656            CHALLENGE_ID,
657            AuditResponse::Bootstrapping {
658                challenge_id: CHALLENGE_ID.wrapping_add(1),
659            },
660        );
661        assert_eq!(
662            verdict,
663            ProbeOutcome::Failed(PossessionFailureReason::BootstrapChallengeIdMismatch)
664        );
665    }
666
667    #[tokio::test]
668    async fn possession_success_clears_active_bootstrap_claim_but_keeps_history() {
669        let peer = PeerId::from_bytes(PEER_ID);
670        let sync_state = Arc::new(RwLock::new(NeighborSyncState::new_cycle(Vec::new())));
671        {
672            let mut state = sync_state.write().await;
673            let now = Instant::now();
674            state.bootstrap_claims.insert(peer, now);
675            state.bootstrap_claim_history.insert(peer, now);
676        }
677
678        clear_possession_bootstrap_claim(&peer, &sync_state).await;
679
680        let state = sync_state.read().await;
681        assert!(!state.bootstrap_claims.contains_key(&peer));
682        assert!(state.bootstrap_claim_history.contains_key(&peer));
683    }
684
685    #[test]
686    fn rejected_is_failed() {
687        let verdict = interpret_audit_response(
688            &KEY,
689            BYTES,
690            &PEER_ID,
691            &NONCE,
692            CHALLENGE_ID,
693            AuditResponse::Rejected {
694                challenge_id: CHALLENGE_ID,
695                reason: "nope".to_string(),
696            },
697        );
698        assert_eq!(
699            verdict,
700            ProbeOutcome::Failed(PossessionFailureReason::Rejected)
701        );
702    }
703}