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    p2p_node
235        .report_trust_event(
236            peer,
237            TrustEvent::ApplicationFailure(AUDIT_FAILURE_TRUST_WEIGHT),
238        )
239        .await;
240}
241
242async fn report_possession_audit_failure(
243    peer: &PeerId,
244    key_hex: &str,
245    failure_class: AuditFailureClass,
246    p2p_node: &Arc<P2PNode>,
247) {
248    warn!(
249        audit_type = AuditType::Possession.as_str(),
250        audit_failure_class = failure_class.as_str(),
251        peer = %peer,
252        key = %key_hex,
253        trust_weight = AUDIT_FAILURE_TRUST_WEIGHT,
254        "Possession check: {peer} {} for {key_hex}; recorded at audit severity",
255        failure_class.as_str()
256    );
257    p2p_node
258        .report_trust_event(
259            peer,
260            TrustEvent::ApplicationFailure(AUDIT_FAILURE_TRUST_WEIGHT),
261        )
262        .await;
263}
264
265async fn handle_possession_bootstrap_claim(
266    peer: &PeerId,
267    key_hex: &str,
268    p2p_node: &Arc<P2PNode>,
269    config: &ReplicationConfig,
270    sync_state: &Arc<RwLock<NeighborSyncState>>,
271) {
272    let (now, observation) = {
273        let now = Instant::now();
274        let mut state = sync_state.write().await;
275        (
276            now,
277            state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period),
278        )
279    };
280
281    match observation {
282        BootstrapClaimObservation::WithinGrace { .. } => {
283            debug!(
284                "Possession check: peer {peer} claims bootstrapping for {key_hex} \
285                 (within grace period)"
286            );
287        }
288        BootstrapClaimObservation::PastGrace { first_seen } => {
289            warn!(
290                "Possession check: peer {peer} claiming bootstrap for {key_hex} past grace period \
291                 ({:?} > {:?}), reporting abuse",
292                now.duration_since(first_seen),
293                config.bootstrap_claim_grace_period,
294            );
295            p2p_node
296                .report_trust_event(
297                    peer,
298                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
299                )
300                .await;
301        }
302        BootstrapClaimObservation::Repeated { first_seen } => {
303            warn!(
304                "Possession check: peer {peer} repeated bootstrap claim for {key_hex} after \
305                 previously stopping; first claim was {:?} ago, reporting abuse",
306                now.duration_since(first_seen),
307            );
308            p2p_node
309                .report_trust_event(
310                    peer,
311                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
312                )
313                .await;
314        }
315    }
316}
317
318/// Send one single-key cryptographic [`AuditChallenge`] and interpret the
319/// response. The peer proves possession by returning
320/// `compute_audit_digest(nonce, peer, key, bytes)`; absence is proven by the
321/// [`ABSENT_KEY_DIGEST`] sentinel or any digest that does not match the
322/// checker's canonical copy. A transport failure / deadline is a `Timeout`; a
323/// matching bootstrap response is a `BootstrapClaim`; a local encode failure is
324/// `Inconclusive`; peer-side malformed, rejected, or mismatched replies are
325/// `Failed`.
326#[allow(clippy::too_many_lines)]
327async fn probe_once(
328    key: &XorName,
329    local_bytes: &[u8],
330    peer: &PeerId,
331    p2p_node: &Arc<P2PNode>,
332    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
333    probe_timeout: Duration,
334) -> ProbeOutcome {
335    // Fresh nonce per probe so a stored digest cannot be replayed, and bind the
336    // challenge to this peer's identity so it cannot relay another node's proof.
337    let (nonce, challenge_id) = {
338        let mut rng = rand::thread_rng();
339        let nonce: [u8; 32] = rng.gen();
340        let challenge_id: u64 = rng.gen();
341        (nonce, challenge_id)
342    };
343    let challenge = AuditChallenge {
344        challenge_id,
345        nonce,
346        challenged_peer_id: *peer.as_bytes(),
347        keys: vec![*key],
348    };
349    let msg = ReplicationMessage {
350        request_id: challenge_id,
351        body: ReplicationMessageBody::AuditChallenge(challenge),
352    };
353    let Ok(encoded) = msg.encode() else {
354        warn!(
355            "Failed to encode possession challenge for {}",
356            hex::encode(key)
357        );
358        return ProbeOutcome::Inconclusive;
359    };
360
361    let Some(_slot) = audit_challenge_coordinator.acquire(*peer).await else {
362        warn!("Failed to acquire possession audit coordinator slot for {peer}");
363        return ProbeOutcome::Inconclusive;
364    };
365    info!(
366        target: "ant_node::replication::audit_requester",
367        event = "started",
368        audit_origin = AuditType::Possession.as_str(),
369        audit_round = "digest",
370        challenged_peer = %peer,
371        challenge_id,
372        work_items = 1,
373        timeout_ms = probe_timeout.as_millis(),
374        "Outbound audit request started"
375    );
376    let request_started = Instant::now();
377    let response = match p2p_node
378        .send_request(peer, REPLICATION_PROTOCOL_ID, encoded, probe_timeout)
379        .await
380    {
381        Ok(response) => {
382            info!(
383                target: "ant_node::replication::audit_requester",
384                event = "completed",
385                audit_origin = AuditType::Possession.as_str(),
386                audit_round = "digest",
387                challenged_peer = %peer,
388                challenge_id,
389                work_items = 1,
390                elapsed_ms = request_started.elapsed().as_millis(),
391                outcome = "response",
392                "Outbound audit request completed"
393            );
394            response
395        }
396        Err(e) => {
397            let error = e.to_string();
398            let (send_error_class, audit_failure_class) =
399                audit_metrics::classify_audit_send_error(&error);
400            warn!(
401                target: "ant_node::replication::audit_requester",
402                event = "completed",
403                audit_origin = AuditType::Possession.as_str(),
404                audit_round = "digest",
405                challenged_peer = %peer,
406                challenge_id,
407                work_items = 1,
408                elapsed_ms = request_started.elapsed().as_millis(),
409                outcome = "no_response",
410                audit_type = AuditType::Possession.as_str(),
411                audit_failure_class = audit_failure_class.as_str(),
412                send_error_class,
413                "Possession probe to {peer} got no response: {e}"
414            );
415            return ProbeOutcome::NoResponse(audit_failure_class);
416        }
417    };
418
419    let decoded = match ReplicationMessage::decode(&response.data) {
420        Ok(decoded) => decoded,
421        Err(e) => {
422            debug!("Failed to decode possession response from {peer}: {e}");
423            return ProbeOutcome::Failed(PossessionFailureReason::ResponseDecode);
424        }
425    };
426
427    let ReplicationMessageBody::AuditResponse(resp) = decoded.body else {
428        debug!("Unexpected possession response type from {peer}");
429        return ProbeOutcome::Failed(PossessionFailureReason::UnexpectedResponseType);
430    };
431
432    interpret_audit_response(
433        key,
434        local_bytes,
435        peer.as_bytes(),
436        &nonce,
437        challenge_id,
438        resp,
439    )
440}
441
442/// Classify an [`AuditResponse`] into a possession verdict. Pure (no I/O): the
443/// digest is verified against `local_bytes`, the checker's canonical copy.
444fn interpret_audit_response(
445    key: &XorName,
446    local_bytes: &[u8],
447    challenged_peer_id: &[u8; 32],
448    nonce: &[u8; 32],
449    challenge_id: u64,
450    response: AuditResponse,
451) -> ProbeOutcome {
452    match response {
453        AuditResponse::Digests {
454            challenge_id: resp_id,
455            digests,
456        } => {
457            if resp_id != challenge_id {
458                return ProbeOutcome::Failed(PossessionFailureReason::DigestChallengeIdMismatch);
459            }
460            if digests.len() != 1 {
461                return ProbeOutcome::Failed(PossessionFailureReason::DigestCountMismatch);
462            }
463            let received = digests[0];
464            if received == ABSENT_KEY_DIGEST {
465                return ProbeOutcome::Failed(PossessionFailureReason::AbsentKey);
466            }
467            let expected = compute_audit_digest(nonce, challenged_peer_id, key, local_bytes);
468            if received == expected {
469                ProbeOutcome::Present
470            } else {
471                // A non-sentinel digest that does not match our canonical bytes
472                // proves the peer cannot reproduce the content — treat as absent
473                // (matches the audit's DigestMismatch handling).
474                ProbeOutcome::Failed(PossessionFailureReason::DigestMismatch)
475            }
476        }
477        AuditResponse::Bootstrapping {
478            challenge_id: resp_id,
479        } => {
480            if resp_id == challenge_id {
481                ProbeOutcome::BootstrapClaim
482            } else {
483                ProbeOutcome::Failed(PossessionFailureReason::BootstrapChallengeIdMismatch)
484            }
485        }
486        AuditResponse::Rejected { .. } => ProbeOutcome::Failed(PossessionFailureReason::Rejected),
487    }
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493    use crate::replication::config::{POSSESSION_CHECK_DELAY_MAX, POSSESSION_CHECK_DELAY_MIN};
494
495    const PEER_ID: [u8; 32] = [0x42; 32];
496    const NONCE: [u8; 32] = [0x7a; 32];
497    const CHALLENGE_ID: u64 = 0xDEAD_BEEF;
498    const KEY: XorName = [0x11; 32];
499    const BYTES: &[u8] = b"possession-check payload";
500
501    fn digests_response(challenge_id: u64, digests: Vec<[u8; 32]>) -> AuditResponse {
502        AuditResponse::Digests {
503            challenge_id,
504            digests,
505        }
506    }
507
508    #[test]
509    fn possession_failure_reasons_have_stable_log_labels() {
510        let cases = [
511            (PossessionFailureReason::ResponseDecode, "response_decode"),
512            (
513                PossessionFailureReason::UnexpectedResponseType,
514                "unexpected_response_type",
515            ),
516            (
517                PossessionFailureReason::DigestChallengeIdMismatch,
518                "digest_challenge_id_mismatch",
519            ),
520            (
521                PossessionFailureReason::DigestCountMismatch,
522                "digest_count_mismatch",
523            ),
524            (PossessionFailureReason::AbsentKey, "absent_key"),
525            (PossessionFailureReason::DigestMismatch, "digest_mismatch"),
526            (
527                PossessionFailureReason::BootstrapChallengeIdMismatch,
528                "bootstrap_challenge_id_mismatch",
529            ),
530            (PossessionFailureReason::Rejected, "rejected"),
531        ];
532
533        for (reason, expected) in cases {
534            assert_eq!(reason.as_str(), expected);
535        }
536    }
537
538    #[test]
539    fn random_delay_is_within_bounds() {
540        for _ in 0..100 {
541            let d = random_delay(POSSESSION_CHECK_DELAY_MIN, POSSESSION_CHECK_DELAY_MAX);
542            assert!(d >= POSSESSION_CHECK_DELAY_MIN);
543            assert!(d <= POSSESSION_CHECK_DELAY_MAX);
544        }
545    }
546
547    #[test]
548    fn matching_digest_is_present() {
549        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
550        let verdict = interpret_audit_response(
551            &KEY,
552            BYTES,
553            &PEER_ID,
554            &NONCE,
555            CHALLENGE_ID,
556            digests_response(CHALLENGE_ID, vec![valid]),
557        );
558        assert_eq!(verdict, ProbeOutcome::Present);
559    }
560
561    #[test]
562    fn absent_sentinel_is_failed() {
563        let verdict = interpret_audit_response(
564            &KEY,
565            BYTES,
566            &PEER_ID,
567            &NONCE,
568            CHALLENGE_ID,
569            digests_response(CHALLENGE_ID, vec![ABSENT_KEY_DIGEST]),
570        );
571        assert_eq!(
572            verdict,
573            ProbeOutcome::Failed(PossessionFailureReason::AbsentKey)
574        );
575    }
576
577    #[test]
578    fn forged_digest_is_failed() {
579        // A peer that lacks the bytes cannot compute the right digest; whatever
580        // non-sentinel value it sends must not match our canonical copy.
581        let forged = [0x99; 32];
582        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
583        assert_ne!(forged, valid, "test fixture must use a wrong digest");
584        let verdict = interpret_audit_response(
585            &KEY,
586            BYTES,
587            &PEER_ID,
588            &NONCE,
589            CHALLENGE_ID,
590            digests_response(CHALLENGE_ID, vec![forged]),
591        );
592        assert_eq!(
593            verdict,
594            ProbeOutcome::Failed(PossessionFailureReason::DigestMismatch)
595        );
596    }
597
598    #[test]
599    fn mismatched_challenge_id_is_failed() {
600        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
601        let verdict = interpret_audit_response(
602            &KEY,
603            BYTES,
604            &PEER_ID,
605            &NONCE,
606            CHALLENGE_ID,
607            digests_response(CHALLENGE_ID.wrapping_add(1), vec![valid]),
608        );
609        assert_eq!(
610            verdict,
611            ProbeOutcome::Failed(PossessionFailureReason::DigestChallengeIdMismatch)
612        );
613    }
614
615    #[test]
616    fn wrong_arity_is_failed() {
617        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
618        let verdict = interpret_audit_response(
619            &KEY,
620            BYTES,
621            &PEER_ID,
622            &NONCE,
623            CHALLENGE_ID,
624            digests_response(CHALLENGE_ID, vec![valid, ABSENT_KEY_DIGEST]),
625        );
626        assert_eq!(
627            verdict,
628            ProbeOutcome::Failed(PossessionFailureReason::DigestCountMismatch)
629        );
630    }
631
632    #[test]
633    fn bootstrapping_is_bootstrap_claim() {
634        let verdict = interpret_audit_response(
635            &KEY,
636            BYTES,
637            &PEER_ID,
638            &NONCE,
639            CHALLENGE_ID,
640            AuditResponse::Bootstrapping {
641                challenge_id: CHALLENGE_ID,
642            },
643        );
644        assert_eq!(verdict, ProbeOutcome::BootstrapClaim);
645    }
646
647    #[test]
648    fn bootstrapping_with_wrong_challenge_id_is_failed() {
649        let verdict = interpret_audit_response(
650            &KEY,
651            BYTES,
652            &PEER_ID,
653            &NONCE,
654            CHALLENGE_ID,
655            AuditResponse::Bootstrapping {
656                challenge_id: CHALLENGE_ID.wrapping_add(1),
657            },
658        );
659        assert_eq!(
660            verdict,
661            ProbeOutcome::Failed(PossessionFailureReason::BootstrapChallengeIdMismatch)
662        );
663    }
664
665    #[tokio::test]
666    async fn possession_success_clears_active_bootstrap_claim_but_keeps_history() {
667        let peer = PeerId::from_bytes(PEER_ID);
668        let sync_state = Arc::new(RwLock::new(NeighborSyncState::new_cycle(Vec::new())));
669        {
670            let mut state = sync_state.write().await;
671            let now = Instant::now();
672            state.bootstrap_claims.insert(peer, now);
673            state.bootstrap_claim_history.insert(peer, now);
674        }
675
676        clear_possession_bootstrap_claim(&peer, &sync_state).await;
677
678        let state = sync_state.read().await;
679        assert!(!state.bootstrap_claims.contains_key(&peer));
680        assert!(state.bootstrap_claim_history.contains_key(&peer));
681    }
682
683    #[test]
684    fn rejected_is_failed() {
685        let verdict = interpret_audit_response(
686            &KEY,
687            BYTES,
688            &PEER_ID,
689            &NONCE,
690            CHALLENGE_ID,
691            AuditResponse::Rejected {
692                challenge_id: CHALLENGE_ID,
693                reason: "nope".to_string(),
694            },
695        );
696        assert_eq!(
697            verdict,
698            ProbeOutcome::Failed(PossessionFailureReason::Rejected)
699        );
700    }
701}