1use std::cmp::Ordering;
8use std::collections::{HashMap, HashSet, VecDeque};
9use std::time::{Duration, Instant};
10
11use serde::{Deserialize, Serialize};
12
13use crate::ant_protocol::XorName;
14use crate::replication::config::REPAIR_HINT_MIN_AGE;
15use saorsa_core::identity::PeerId;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum VerificationState {
28 OfferReceived,
30 PendingVerify,
32 QuorumVerified,
35 PaidListVerified,
38 QueuedForFetch,
40 Fetching,
42 Stored,
44 FetchRetryable,
46 FetchAbandoned,
48 QuorumFailed,
51 QuorumInconclusive,
53 QuorumAbandoned,
55 Idle,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
66pub enum HintPipeline {
67 Replica,
69 PaidOnly,
72}
73
74#[derive(Debug, Clone)]
83pub struct VerificationEntry {
84 pub state: VerificationState,
86 pub pipeline: HintPipeline,
88 pub verified_sources: Vec<PeerId>,
91 pub tried_sources: HashSet<PeerId>,
93 pub created_at: Instant,
95 pub hint_sender: PeerId,
97}
98
99#[derive(Debug, Clone)]
109pub struct FetchCandidate {
110 pub key: XorName,
112 pub distance: XorName,
114 pub sources: Vec<PeerId>,
116}
117
118impl Eq for FetchCandidate {}
119
120impl PartialEq for FetchCandidate {
121 fn eq(&self, other: &Self) -> bool {
122 self.distance == other.distance && self.key == other.key
123 }
124}
125
126impl Ord for FetchCandidate {
127 fn cmp(&self, other: &Self) -> Ordering {
128 other
131 .distance
132 .cmp(&self.distance)
133 .then_with(|| self.key.cmp(&other.key))
134 }
135}
136
137impl PartialOrd for FetchCandidate {
138 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
139 Some(self.cmp(other))
140 }
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
149pub enum PresenceEvidence {
150 Present,
152 Absent,
154 Unresolved,
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
160pub enum PaidListEvidence {
161 Confirmed,
163 NotFound,
165 Unresolved,
167}
168
169#[derive(Debug, Clone)]
172pub struct KeyVerificationEvidence {
173 pub presence: HashMap<PeerId, PresenceEvidence>,
175 pub paid_list: HashMap<PeerId, PaidListEvidence>,
177}
178
179#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
186pub struct AuditFailureSummary {
187 pub challenged_keys: usize,
189 pub failed_keys: usize,
191 pub absent_keys: usize,
193 pub digest_mismatch_keys: usize,
196}
197
198#[derive(Debug, Clone)]
200pub enum FailureEvidence {
201 ReplicationFailure {
203 peer: PeerId,
205 key: XorName,
207 },
208 AuditFailure {
210 challenge_id: u64,
212 challenged_peer: PeerId,
214 confirmed_failed_keys: Vec<XorName>,
216 summary: AuditFailureSummary,
218 reason: AuditFailureReason,
220 },
221 BootstrapClaimAbuse {
223 peer: PeerId,
225 first_seen: Instant,
227 },
228 QuoteCommitmentMismatch {
237 peer: PeerId,
239 pinned_commitment: [u8; 32],
242 quoted_key_count: u32,
244 committed_key_count: u32,
246 quote_artifact: Vec<u8>,
253 commitment: Box<crate::replication::commitment::StorageCommitment>,
259 },
260}
261
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
264pub enum AuditFailureReason {
265 Timeout,
267 MalformedResponse,
269 DigestMismatch,
271 KeyAbsent,
273 Rejected,
275}
276
277#[derive(Debug, Clone)]
283pub struct PeerSyncRecord {
284 pub last_sync: Option<Instant>,
286 pub cycles_since_sync: u32,
289}
290
291impl PeerSyncRecord {
292 #[must_use]
295 pub fn has_repair_opportunity(&self) -> bool {
296 self.last_sync.is_some() && self.cycles_since_sync >= 1
297 }
298}
299
300#[derive(Debug, Clone)]
306struct RepairProof {
307 hinted_at_epoch: u64,
309 hinted_at: Instant,
311}
312
313#[derive(Debug, Clone)]
316struct RepairProofEntry {
317 close_peers: HashSet<PeerId>,
319 peer_proofs: HashMap<PeerId, RepairProof>,
321}
322
323impl RepairProofEntry {
324 fn new(close_peers: HashSet<PeerId>) -> Self {
325 Self {
326 close_peers,
327 peer_proofs: HashMap::new(),
328 }
329 }
330}
331
332#[derive(Debug, Clone, Default)]
338pub struct RepairProofs {
339 proofs_by_key: HashMap<XorName, RepairProofEntry>,
341}
342
343impl RepairProofs {
344 #[must_use]
346 pub fn new() -> Self {
347 Self::default()
348 }
349
350 pub fn record_replica_hint_sent(
358 &mut self,
359 peer: PeerId,
360 key: XorName,
361 current_close_peers: &HashSet<PeerId>,
362 hinted_at_epoch: u64,
363 ) -> bool {
364 self.insert_replica_hint_sent(
365 peer,
366 key,
367 current_close_peers,
368 hinted_at_epoch,
369 Instant::now(),
370 )
371 }
372
373 #[cfg(any(test, feature = "test-utils"))]
380 pub fn record_replica_hint_sent_at(
381 &mut self,
382 peer: PeerId,
383 key: XorName,
384 current_close_peers: &HashSet<PeerId>,
385 hinted_at_epoch: u64,
386 hinted_at: Instant,
387 ) -> bool {
388 self.insert_replica_hint_sent(peer, key, current_close_peers, hinted_at_epoch, hinted_at)
389 }
390
391 fn insert_replica_hint_sent(
392 &mut self,
393 peer: PeerId,
394 key: XorName,
395 current_close_peers: &HashSet<PeerId>,
396 hinted_at_epoch: u64,
397 hinted_at: Instant,
398 ) -> bool {
399 self.reconcile_key_close_group(&key, current_close_peers);
400
401 if !current_close_peers.contains(&peer) {
402 return false;
403 }
404
405 let entry = self
406 .proofs_by_key
407 .entry(key)
408 .or_insert_with(|| RepairProofEntry::new(current_close_peers.clone()));
409
410 if entry.peer_proofs.contains_key(&peer) {
411 return false;
412 }
413
414 entry.peer_proofs.insert(
415 peer,
416 RepairProof {
417 hinted_at_epoch,
418 hinted_at,
419 },
420 );
421 true
422 }
423
424 pub fn has_mature_replica_hint(
431 &mut self,
432 peer: &PeerId,
433 key: &XorName,
434 current_close_peers: &HashSet<PeerId>,
435 current_epoch: u64,
436 now: Instant,
437 ) -> bool {
438 self.reconcile_key_close_group(key, current_close_peers);
439
440 self.proofs_by_key
441 .get(key)
442 .and_then(|entry| entry.peer_proofs.get(peer))
443 .is_some_and(|proof| {
444 proof.hinted_at_epoch < current_epoch
445 && now.saturating_duration_since(proof.hinted_at) >= REPAIR_HINT_MIN_AGE
446 })
447 }
448
449 pub fn remove_key(&mut self, key: &XorName) {
451 self.proofs_by_key.remove(key);
452 }
453
454 pub fn remove_peer(&mut self, peer: &PeerId) {
456 self.proofs_by_key.retain(|_, entry| {
457 entry.peer_proofs.remove(peer);
458 !entry.peer_proofs.is_empty()
459 });
460 }
461
462 fn reconcile_key_close_group(&mut self, key: &XorName, current_close_peers: &HashSet<PeerId>) {
463 let should_remove = if let Some(entry) = self.proofs_by_key.get_mut(key) {
464 if entry.close_peers == *current_close_peers {
465 return;
466 }
467
468 entry.close_peers.clone_from(current_close_peers);
469 entry
470 .peer_proofs
471 .retain(|peer, _| current_close_peers.contains(peer));
472 entry.peer_proofs.is_empty()
473 } else {
474 false
475 };
476
477 if should_remove {
478 self.proofs_by_key.remove(key);
479 }
480 }
481}
482
483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
489pub enum BootstrapClaimObservation {
490 WithinGrace {
492 first_seen: Instant,
494 },
495 PastGrace {
497 first_seen: Instant,
499 },
500 Repeated {
502 first_seen: Instant,
504 },
505}
506
507#[derive(Debug)]
513pub struct NeighborSyncState {
514 pub priority_order: VecDeque<PeerId>,
521 pub order: Vec<PeerId>,
523 pub cursor: usize,
525 pub last_sync_times: HashMap<PeerId, Instant>,
527 pub bootstrap_claims: HashMap<PeerId, Instant>,
533 pub bootstrap_claim_history: HashMap<PeerId, Instant>,
541 pub prune_cursor: usize,
544}
545
546impl NeighborSyncState {
547 #[must_use]
549 pub fn new_cycle(close_neighbors: Vec<PeerId>) -> Self {
550 Self {
551 priority_order: VecDeque::new(),
552 order: close_neighbors,
553 cursor: 0,
554 last_sync_times: HashMap::new(),
555 bootstrap_claims: HashMap::new(),
556 bootstrap_claim_history: HashMap::new(),
557 prune_cursor: 0,
558 }
559 }
560
561 #[must_use]
568 pub fn observe_bootstrap_claim(
569 &mut self,
570 peer: PeerId,
571 now: Instant,
572 grace_period: Duration,
573 ) -> BootstrapClaimObservation {
574 if let Some(first_seen) = self.bootstrap_claims.get(&peer).copied() {
575 if now.duration_since(first_seen) > grace_period {
576 BootstrapClaimObservation::PastGrace { first_seen }
577 } else {
578 BootstrapClaimObservation::WithinGrace { first_seen }
579 }
580 } else if let Some(first_seen) = self.bootstrap_claim_history.get(&peer).copied() {
581 BootstrapClaimObservation::Repeated { first_seen }
582 } else {
583 self.bootstrap_claims.insert(peer, now);
584 self.bootstrap_claim_history.insert(peer, now);
585 BootstrapClaimObservation::WithinGrace { first_seen: now }
586 }
587 }
588
589 pub fn clear_active_bootstrap_claim(&mut self, peer: &PeerId) -> bool {
591 self.bootstrap_claims.remove(peer).is_some()
592 }
593
594 pub fn queue_priority_peers<I>(&mut self, peers: I) -> usize
599 where
600 I: IntoIterator<Item = PeerId>,
601 {
602 let mut queued = 0;
603 for peer in peers {
604 if self.priority_order.contains(&peer) {
605 continue;
606 }
607 self.priority_order.push_back(peer);
608 queued += 1;
609 }
610 queued
611 }
612
613 pub fn retain_sync_peers(&mut self, close_peers: &HashSet<PeerId>) -> usize {
618 let old_priority_len = self.priority_order.len();
619 self.priority_order
620 .retain(|peer| close_peers.contains(peer));
621
622 let old_order_len = self.order.len();
623 let old_cursor = self.cursor;
624 let mut retained_before_cursor = 0;
625 let mut retained_order = Vec::with_capacity(old_order_len);
626 for (idx, peer) in self.order.drain(..).enumerate() {
627 if close_peers.contains(&peer) {
628 if idx < old_cursor {
629 retained_before_cursor += 1;
630 }
631 retained_order.push(peer);
632 }
633 }
634
635 self.order = retained_order;
636 self.cursor = retained_before_cursor;
637
638 (old_priority_len - self.priority_order.len()) + (old_order_len - self.order.len())
639 }
640
641 pub fn remove_peer(&mut self, peer: &PeerId) -> bool {
643 let old_priority_len = self.priority_order.len();
644 self.priority_order.retain(|queued| queued != peer);
645
646 let old_order_len = self.order.len();
647 if let Some(pos) = self.order.iter().position(|queued| queued == peer) {
648 self.order.remove(pos);
649 if pos < self.cursor {
650 self.cursor = self.cursor.saturating_sub(1);
651 }
652 }
653
654 old_priority_len != self.priority_order.len() || old_order_len != self.order.len()
655 }
656
657 #[must_use]
659 pub fn is_cycle_complete(&self) -> bool {
660 self.priority_order.is_empty() && self.cursor >= self.order.len()
661 }
662}
663
664#[derive(Debug)]
670pub struct BootstrapState {
671 pub drained: bool,
673 pub pending_peer_requests: usize,
675 pub pending_keys: HashSet<XorName>,
678 pub capacity_rejected_sources: HashSet<PeerId>,
689}
690
691impl BootstrapState {
692 #[must_use]
694 pub fn new() -> Self {
695 Self {
696 drained: false,
697 pending_peer_requests: 0,
698 pending_keys: HashSet::new(),
699 capacity_rejected_sources: HashSet::new(),
700 }
701 }
702
703 #[must_use]
710 pub fn is_drained(&self) -> bool {
711 self.drained
712 }
713
714 pub fn remove_key(&mut self, key: &XorName) {
720 self.pending_keys.remove(key);
721 }
722}
723
724impl Default for BootstrapState {
725 fn default() -> Self {
726 Self::new()
727 }
728}
729
730#[cfg(test)]
735mod tests {
736 use std::collections::BinaryHeap;
737
738 use super::*;
739
740 fn peer_id_from_byte(b: u8) -> PeerId {
742 let mut bytes = [0u8; 32];
743 bytes[0] = b;
744 PeerId::from_bytes(bytes)
745 }
746
747 fn mature_hint_times() -> (Instant, Instant) {
748 let hinted_at = Instant::now();
749 let now = hinted_at
750 .checked_add(REPAIR_HINT_MIN_AGE)
751 .unwrap_or(hinted_at);
752 (hinted_at, now)
753 }
754
755 #[test]
758 fn fetch_candidate_nearest_key_has_highest_priority() {
759 let near = FetchCandidate {
760 key: [1u8; 32],
761 distance: [
762 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
763 0, 0, 0, 0,
764 ],
765 sources: vec![peer_id_from_byte(1)],
766 };
767
768 let far = FetchCandidate {
769 key: [2u8; 32],
770 distance: [
771 0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
772 0, 0, 0, 0, 0,
773 ],
774 sources: vec![peer_id_from_byte(2)],
775 };
776
777 assert!(near > far, "nearer candidate should compare greater");
780
781 let mut heap = BinaryHeap::new();
782 heap.push(far.clone());
783 heap.push(near.clone());
784
785 assert_eq!(heap.len(), 2, "heap should contain both candidates");
786
787 let first = heap.pop();
788 assert!(first.is_some(), "first pop should succeed");
789 assert_eq!(
790 first.map(|c| c.key),
791 Some(near.key),
792 "nearest key should pop first"
793 );
794
795 let second = heap.pop();
796 assert!(second.is_some(), "second pop should succeed");
797 assert_eq!(
798 second.map(|c| c.key),
799 Some(far.key),
800 "farthest key should pop second"
801 );
802 }
803
804 #[test]
805 fn fetch_candidate_same_distance_and_key_is_equal() {
806 let a = FetchCandidate {
807 key: [1u8; 32],
808 distance: [5u8; 32],
809 sources: vec![],
810 };
811
812 let b = FetchCandidate {
813 key: [1u8; 32],
814 distance: [5u8; 32],
815 sources: vec![],
816 };
817
818 assert_eq!(
819 a.cmp(&b),
820 Ordering::Equal,
821 "same distance + same key should yield Equal"
822 );
823 assert_eq!(a, b, "PartialEq must agree with Ord");
824 }
825
826 #[test]
827 fn fetch_candidate_same_distance_different_key_is_deterministic() {
828 let a = FetchCandidate {
829 key: [1u8; 32],
830 distance: [5u8; 32],
831 sources: vec![],
832 };
833
834 let b = FetchCandidate {
835 key: [2u8; 32],
836 distance: [5u8; 32],
837 sources: vec![],
838 };
839
840 assert_ne!(
841 a.cmp(&b),
842 Ordering::Equal,
843 "same distance + different key must not be Equal"
844 );
845 assert_ne!(a, b, "PartialEq must agree with Ord");
846 }
847
848 #[test]
851 fn peer_sync_record_no_sync_yet() {
852 let record = PeerSyncRecord {
853 last_sync: None,
854 cycles_since_sync: 0,
855 };
856 assert!(
857 !record.has_repair_opportunity(),
858 "never-synced peer has no repair opportunity"
859 );
860 }
861
862 #[test]
863 fn peer_sync_record_synced_but_no_cycle() {
864 let record = PeerSyncRecord {
865 last_sync: Some(Instant::now()),
866 cycles_since_sync: 0,
867 };
868 assert!(
869 !record.has_repair_opportunity(),
870 "synced peer with zero subsequent cycles has no repair opportunity"
871 );
872 }
873
874 #[test]
875 fn peer_sync_record_synced_with_cycle() {
876 let record = PeerSyncRecord {
877 last_sync: Some(Instant::now()),
878 cycles_since_sync: 1,
879 };
880 assert!(
881 record.has_repair_opportunity(),
882 "synced peer with >= 1 cycle should have repair opportunity"
883 );
884 }
885
886 #[test]
887 fn peer_sync_record_no_sync_many_cycles() {
888 let record = PeerSyncRecord {
889 last_sync: None,
890 cycles_since_sync: 10,
891 };
892 assert!(
893 !record.has_repair_opportunity(),
894 "never-synced peer has no repair opportunity regardless of cycle count"
895 );
896 }
897
898 #[test]
901 fn repair_proofs_record_sent_hint_for_close_peer() {
902 const HINT_EPOCH: u64 = 7;
903 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
904
905 let key = [0xA1; 32];
906 let peer = peer_id_from_byte(1);
907 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
908 let mut proofs = RepairProofs::new();
909 let (hinted_at, now) = mature_hint_times();
910
911 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
912
913 assert!(
914 proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
915 "old sent hint should make key auditable for that peer"
916 );
917 }
918
919 #[test]
920 fn repair_proofs_reject_peer_outside_current_close_group() {
921 const HINT_EPOCH: u64 = 7;
922 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
923
924 let key = [0xA2; 32];
925 let peer = peer_id_from_byte(1);
926 let close_peers = HashSet::from([peer_id_from_byte(2), peer_id_from_byte(3)]);
927 let mut proofs = RepairProofs::new();
928 let (hinted_at, now) = mature_hint_times();
929
930 assert!(!proofs.record_replica_hint_sent_at(
931 peer,
932 key,
933 &close_peers,
934 HINT_EPOCH,
935 hinted_at,
936 ));
937
938 assert!(
939 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
940 "peers outside current close group must not get repair proof"
941 );
942 }
943
944 #[test]
945 fn repair_proofs_require_later_epoch() {
946 const HINT_EPOCH: u64 = 7;
947 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
948
949 let key = [0xA3; 32];
950 let peer = peer_id_from_byte(1);
951 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
952 let mut proofs = RepairProofs::new();
953 let (hinted_at, now) = mature_hint_times();
954
955 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
956
957 assert!(
958 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, HINT_EPOCH, now),
959 "same-cycle proof should not be audit-eligible"
960 );
961 assert!(
962 proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
963 "old proof should mature after a later local sync-cycle epoch"
964 );
965 }
966
967 #[test]
968 fn repair_proofs_require_min_hint_age() {
969 const HINT_EPOCH: u64 = 7;
970 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
971
972 let key = [0xA8; 32];
973 let peer = peer_id_from_byte(1);
974 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
975 let mut proofs = RepairProofs::new();
976 let hinted_at = Instant::now();
977
978 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at));
979
980 assert!(
981 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, hinted_at),
982 "fresh repair hints should not be audit-eligible"
983 );
984 assert!(
985 proofs.has_mature_replica_hint(
986 &peer,
987 &key,
988 &close_peers,
989 CURRENT_EPOCH,
990 hinted_at
991 .checked_add(REPAIR_HINT_MIN_AGE)
992 .unwrap_or(hinted_at),
993 ),
994 "repair hints should mature once they are at least the minimum age"
995 );
996 }
997
998 #[test]
999 fn repair_proofs_repeated_hint_does_not_reset_maturity() {
1000 const HINT_EPOCH: u64 = 7;
1001 const REPEATED_HINT_EPOCH: u64 = HINT_EPOCH + 1;
1002
1003 let key = [0xA5; 32];
1004 let peer = peer_id_from_byte(1);
1005 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1006 let mut proofs = RepairProofs::new();
1007 let (hinted_at, now) = mature_hint_times();
1008
1009 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1010 assert!(
1011 !proofs.record_replica_hint_sent_at(peer, key, &close_peers, REPEATED_HINT_EPOCH, now),
1012 "duplicate hint in the same close group should keep existing proof"
1013 );
1014 assert!(
1015 proofs.has_mature_replica_hint(&peer, &key, &close_peers, REPEATED_HINT_EPOCH, now),
1016 "duplicate hint must not reset an already mature proof"
1017 );
1018 }
1019
1020 #[test]
1021 fn repair_proofs_retain_stable_peers_on_close_group_change() {
1022 const HINT_EPOCH: u64 = 7;
1023 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1024
1025 let key = [0xA7; 32];
1026 let stable_peer = peer_id_from_byte(1);
1027 let departing_peer = peer_id_from_byte(2);
1028 let retained_peer = peer_id_from_byte(3);
1029 let new_peer = peer_id_from_byte(4);
1030 let old_group = HashSet::from([stable_peer, departing_peer, retained_peer]);
1031 let changed_group = HashSet::from([stable_peer, retained_peer, new_peer]);
1032 let mut proofs = RepairProofs::new();
1033 let (hinted_at, now) = mature_hint_times();
1034
1035 assert!(proofs.record_replica_hint_sent_at(
1036 stable_peer,
1037 key,
1038 &old_group,
1039 HINT_EPOCH,
1040 hinted_at,
1041 ));
1042 assert!(proofs.record_replica_hint_sent_at(
1043 departing_peer,
1044 key,
1045 &old_group,
1046 HINT_EPOCH,
1047 hinted_at,
1048 ));
1049
1050 assert!(
1051 proofs.has_mature_replica_hint(&stable_peer, &key, &changed_group, CURRENT_EPOCH, now),
1052 "stable peers should keep mature repair proofs across unrelated close-group churn"
1053 );
1054 assert!(
1055 !proofs.has_mature_replica_hint(
1056 &departing_peer,
1057 &key,
1058 &changed_group,
1059 CURRENT_EPOCH,
1060 now,
1061 ),
1062 "peers that left the close group should lose repair proofs"
1063 );
1064 assert!(
1065 !proofs.has_mature_replica_hint(&new_peer, &key, &changed_group, CURRENT_EPOCH, now),
1066 "new close-group peers need their own repair hint before auditing"
1067 );
1068 }
1069
1070 #[test]
1071 fn repair_proofs_evicted_peer_reentry_requires_fresh_hint() {
1072 const FIRST_HINT_EPOCH: u64 = 7;
1073 const SECOND_HINT_EPOCH: u64 = FIRST_HINT_EPOCH + 1;
1074 const CURRENT_EPOCH: u64 = SECOND_HINT_EPOCH + 1;
1075
1076 let key = [0xA3; 32];
1077 let returning_peer = peer_id_from_byte(1);
1078 let new_peer = peer_id_from_byte(4);
1079 let old_group = HashSet::from([returning_peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1080 let changed_group = HashSet::from([new_peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1081 let mut proofs = RepairProofs::new();
1082 let (hinted_at, now) = mature_hint_times();
1083
1084 assert!(proofs.record_replica_hint_sent_at(
1085 returning_peer,
1086 key,
1087 &old_group,
1088 FIRST_HINT_EPOCH,
1089 hinted_at,
1090 ));
1091
1092 assert!(
1093 !proofs.has_mature_replica_hint(
1094 &new_peer,
1095 &key,
1096 &changed_group,
1097 SECOND_HINT_EPOCH,
1098 now
1099 ),
1100 "new close-group peer should not inherit another peer's repair proof"
1101 );
1102 assert!(
1103 !proofs.has_mature_replica_hint(&returning_peer, &key, &old_group, CURRENT_EPOCH, now),
1104 "a peer that re-enters must receive a fresh repair hint"
1105 );
1106
1107 assert!(proofs.record_replica_hint_sent_at(
1108 returning_peer,
1109 key,
1110 &old_group,
1111 SECOND_HINT_EPOCH,
1112 hinted_at,
1113 ));
1114 assert!(
1115 proofs.has_mature_replica_hint(&returning_peer, &key, &old_group, CURRENT_EPOCH, now),
1116 "fresh repair hint after re-entry should be eligible once mature"
1117 );
1118 }
1119
1120 #[test]
1121 fn repair_proofs_remove_peer_requires_fresh_hint_after_reentry() {
1122 const FIRST_HINT_EPOCH: u64 = 7;
1123 const SECOND_HINT_EPOCH: u64 = FIRST_HINT_EPOCH + 1;
1124 const CURRENT_EPOCH: u64 = SECOND_HINT_EPOCH + 1;
1125
1126 let key = [0xA6; 32];
1127 let peer = peer_id_from_byte(1);
1128 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1129 let mut proofs = RepairProofs::new();
1130 let (hinted_at, now) = mature_hint_times();
1131
1132 assert!(proofs.record_replica_hint_sent_at(
1133 peer,
1134 key,
1135 &close_peers,
1136 FIRST_HINT_EPOCH,
1137 hinted_at,
1138 ));
1139 proofs.remove_peer(&peer);
1140
1141 assert!(
1142 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1143 "routing-table removal should clear proof even if peer re-enters same close group"
1144 );
1145
1146 assert!(proofs.record_replica_hint_sent_at(
1147 peer,
1148 key,
1149 &close_peers,
1150 SECOND_HINT_EPOCH,
1151 hinted_at,
1152 ));
1153 assert!(
1154 proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1155 "fresh hint after re-entry should become eligible after a later epoch"
1156 );
1157 }
1158
1159 #[test]
1160 fn repair_proofs_remove_key_clears_all_peer_entries() {
1161 const HINT_EPOCH: u64 = 7;
1162 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1163
1164 let key = [0xA4; 32];
1165 let peer = peer_id_from_byte(1);
1166 let close_peers = HashSet::from([peer]);
1167 let mut proofs = RepairProofs::new();
1168 let (hinted_at, now) = mature_hint_times();
1169
1170 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1171 proofs.remove_key(&key);
1172
1173 assert!(
1174 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1175 "deleted local key should not retain repair proof entries"
1176 );
1177 }
1178
1179 #[test]
1182 fn neighbor_sync_empty_cycle_is_immediately_complete() {
1183 let state = NeighborSyncState::new_cycle(vec![]);
1184 assert!(
1185 state.is_cycle_complete(),
1186 "empty neighbor list means cycle is complete"
1187 );
1188 }
1189
1190 #[test]
1191 fn neighbor_sync_new_cycle_not_complete() {
1192 let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
1193 let state = NeighborSyncState::new_cycle(peers);
1194 assert!(
1195 !state.is_cycle_complete(),
1196 "fresh cycle with peers should not be complete"
1197 );
1198 }
1199
1200 #[test]
1201 fn neighbor_sync_cycle_completes_when_cursor_reaches_end() {
1202 let peers = vec![
1203 peer_id_from_byte(1),
1204 peer_id_from_byte(2),
1205 peer_id_from_byte(3),
1206 ];
1207 let mut state = NeighborSyncState::new_cycle(peers);
1208
1209 state.cursor = 2;
1211 assert!(
1212 !state.is_cycle_complete(),
1213 "cursor at len-1 should not be complete"
1214 );
1215
1216 state.cursor = 3;
1217 assert!(
1218 state.is_cycle_complete(),
1219 "cursor at len should be complete"
1220 );
1221 }
1222
1223 #[test]
1224 fn neighbor_sync_cursor_past_end_is_still_complete() {
1225 let peers = vec![peer_id_from_byte(1)];
1226 let mut state = NeighborSyncState::new_cycle(peers);
1227 state.cursor = 5;
1228 assert!(
1229 state.is_cycle_complete(),
1230 "cursor past end should still report complete"
1231 );
1232 }
1233
1234 #[test]
1235 fn neighbor_sync_priority_queue_blocks_cycle_completion() {
1236 let peer = peer_id_from_byte(2);
1237 let mut state = NeighborSyncState::new_cycle(Vec::new());
1238
1239 assert!(state.is_cycle_complete());
1240 assert_eq!(state.queue_priority_peers([peer]), 1);
1241 assert!(
1242 !state.is_cycle_complete(),
1243 "pending priority peers must sync before the cycle completes"
1244 );
1245 }
1246
1247 #[test]
1248 fn neighbor_sync_priority_queue_deduplicates_peers() {
1249 let peer = peer_id_from_byte(3);
1250 let mut state = NeighborSyncState::new_cycle(Vec::new());
1251
1252 assert_eq!(state.queue_priority_peers([peer, peer]), 1);
1253 assert_eq!(state.priority_order.len(), 1);
1254 }
1255
1256 #[test]
1257 fn neighbor_sync_remove_peer_clears_order_and_priority_queue() {
1258 let peer = peer_id_from_byte(4);
1259 let retained = peer_id_from_byte(5);
1260 let mut state = NeighborSyncState::new_cycle(vec![peer, retained]);
1261 assert_eq!(state.queue_priority_peers([peer]), 1);
1262 state.cursor = 1;
1263
1264 assert!(state.remove_peer(&peer));
1265
1266 assert!(!state.order.contains(&peer));
1267 assert!(!state.priority_order.contains(&peer));
1268 assert_eq!(state.order, vec![retained]);
1269 assert_eq!(state.cursor, 0);
1270 }
1271
1272 #[test]
1273 fn neighbor_sync_retain_sync_peers_prunes_only_departed_peers() {
1274 let already_scanned = peer_id_from_byte(1);
1275 let stable_scanned = peer_id_from_byte(2);
1276 let departed_priority = peer_id_from_byte(3);
1277 let stable_unscanned = peer_id_from_byte(4);
1278 let stable_priority = peer_id_from_byte(5);
1279 let mut state = NeighborSyncState::new_cycle(vec![
1280 already_scanned,
1281 stable_scanned,
1282 departed_priority,
1283 stable_unscanned,
1284 ]);
1285 assert_eq!(
1286 state.queue_priority_peers([departed_priority, stable_priority]),
1287 2
1288 );
1289 state.cursor = 2;
1290 let close_peers = HashSet::from([stable_scanned, stable_unscanned, stable_priority]);
1291
1292 let removed = state.retain_sync_peers(&close_peers);
1293
1294 assert_eq!(removed, 3);
1295 assert_eq!(state.order, vec![stable_scanned, stable_unscanned]);
1296 assert_eq!(
1297 state.priority_order.iter().copied().collect::<Vec<_>>(),
1298 vec![stable_priority]
1299 );
1300 assert_eq!(
1301 state.cursor, 1,
1302 "stable peer scanned before churn must not be selected again"
1303 );
1304 }
1305
1306 #[test]
1307 fn bootstrap_claim_history_prevents_second_grace_window() {
1308 let peer = peer_id_from_byte(9);
1309 let mut state = NeighborSyncState::new_cycle(vec![peer]);
1310 let first_seen = Instant::now();
1311 let grace = Duration::from_secs(60);
1312
1313 assert_eq!(
1314 state.observe_bootstrap_claim(peer, first_seen, grace),
1315 BootstrapClaimObservation::WithinGrace { first_seen }
1316 );
1317 assert!(state.clear_active_bootstrap_claim(&peer));
1318 assert!(!state.bootstrap_claims.contains_key(&peer));
1319 assert!(state.bootstrap_claim_history.contains_key(&peer));
1320
1321 assert_eq!(
1322 state.observe_bootstrap_claim(peer, first_seen + Duration::from_secs(1), grace),
1323 BootstrapClaimObservation::Repeated { first_seen }
1324 );
1325 assert!(
1326 !state.bootstrap_claims.contains_key(&peer),
1327 "repeated claims must not recreate an active grace window"
1328 );
1329 assert_eq!(
1330 state.observe_bootstrap_claim(peer, first_seen + Duration::from_secs(2), grace),
1331 BootstrapClaimObservation::Repeated { first_seen }
1332 );
1333 }
1334
1335 #[test]
1336 fn bootstrap_claim_active_window_reports_past_grace() {
1337 let peer = peer_id_from_byte(10);
1338 let mut state = NeighborSyncState::new_cycle(vec![peer]);
1339 let first_seen = Instant::now();
1340 let grace = Duration::from_secs(60);
1341
1342 let _ = state.observe_bootstrap_claim(peer, first_seen, grace);
1343
1344 assert_eq!(
1345 state.observe_bootstrap_claim(peer, first_seen + grace + Duration::from_secs(1), grace),
1346 BootstrapClaimObservation::PastGrace { first_seen }
1347 );
1348 }
1349
1350 #[test]
1353 fn bootstrap_state_initial_not_drained() {
1354 let state = BootstrapState::new();
1357 assert!(
1358 !state.is_drained(),
1359 "initial state must not be drained before bootstrap begins"
1360 );
1361 }
1362
1363 #[test]
1364 fn bootstrap_state_pending_requests_block_drain() {
1365 let mut state = BootstrapState::new();
1366 state.pending_peer_requests = 3;
1367 assert!(
1368 !state.is_drained(),
1369 "pending peer requests should block drain"
1370 );
1371 }
1372
1373 #[test]
1374 fn bootstrap_state_pending_keys_block_drain() {
1375 let mut state = BootstrapState::new();
1376 state.pending_keys.insert([42u8; 32]);
1377 assert!(!state.is_drained(), "pending keys should block drain");
1378 }
1379
1380 #[test]
1381 fn bootstrap_state_explicit_drained_overrides() {
1382 let mut state = BootstrapState::new();
1383 state.pending_peer_requests = 5;
1384 state.pending_keys.insert([99u8; 32]);
1385 state.drained = true;
1386 assert!(
1387 state.is_drained(),
1388 "explicit drained flag should override pending counts"
1389 );
1390 }
1391
1392 #[test]
1393 fn bootstrap_state_requires_explicit_drain() {
1394 let mut state = BootstrapState::new();
1395 state.pending_peer_requests = 2;
1396 state.pending_keys.insert([1u8; 32]);
1397
1398 state.pending_peer_requests = 0;
1400 state.pending_keys.clear();
1401
1402 assert!(
1403 !state.is_drained(),
1404 "clearing counters alone must not drain — requires check_bootstrap_drained"
1405 );
1406
1407 state.drained = true;
1409 assert!(state.is_drained(), "explicit flag should drain");
1410 }
1411
1412 #[test]
1413 fn bootstrap_state_default_matches_new() {
1414 let from_new = BootstrapState::new();
1415 let from_default = BootstrapState::default();
1416
1417 assert_eq!(from_new.drained, from_default.drained);
1418 assert_eq!(
1419 from_new.pending_peer_requests,
1420 from_default.pending_peer_requests
1421 );
1422 assert_eq!(from_new.pending_keys, from_default.pending_keys);
1423 }
1424
1425 #[test]
1430 fn bootstrap_drain_requires_empty_pending_keys() {
1431 let key_a: XorName = [0xA0; 32];
1432 let key_b: XorName = [0xB0; 32];
1433 let key_c: XorName = [0xC0; 32];
1434
1435 let mut state = BootstrapState::new();
1436 state.pending_peer_requests = 0; state.pending_keys = std::iter::once(key_a)
1438 .chain(std::iter::once(key_b))
1439 .chain(std::iter::once(key_c))
1440 .collect();
1441
1442 assert!(
1443 !state.is_drained(),
1444 "should NOT be drained while pending_keys still has entries"
1445 );
1446
1447 state.pending_keys.remove(&key_a);
1449 assert!(!state.is_drained(), "still not drained with 2 pending keys");
1450
1451 state.pending_keys.remove(&key_b);
1452 assert!(!state.is_drained(), "still not drained with 1 pending key");
1453
1454 state.pending_keys.remove(&key_c);
1455 assert!(
1456 !state.is_drained(),
1457 "removing all keys is necessary but not sufficient — needs explicit drain"
1458 );
1459
1460 state.drained = true;
1462 assert!(state.is_drained(), "explicit drain flag should finalize");
1463 }
1464
1465 #[test]
1468 fn verification_state_terminal_variants() {
1469 let terminal_states = [
1470 VerificationState::QuorumAbandoned,
1471 VerificationState::FetchAbandoned,
1472 VerificationState::Stored,
1473 VerificationState::Idle,
1474 ];
1475
1476 for (i, a) in terminal_states.iter().enumerate() {
1478 for (j, b) in terminal_states.iter().enumerate() {
1479 if i != j {
1480 assert_ne!(
1481 a, b,
1482 "terminal states at indices {i} and {j} must be distinct"
1483 );
1484 }
1485 }
1486 }
1487
1488 let non_terminal_states = [
1490 VerificationState::OfferReceived,
1491 VerificationState::PendingVerify,
1492 VerificationState::QuorumVerified,
1493 VerificationState::PaidListVerified,
1494 VerificationState::QueuedForFetch,
1495 VerificationState::Fetching,
1496 VerificationState::FetchRetryable,
1497 VerificationState::QuorumFailed,
1498 VerificationState::QuorumInconclusive,
1499 ];
1500
1501 for terminal in &terminal_states {
1502 for non_terminal in &non_terminal_states {
1503 assert_ne!(
1504 terminal, non_terminal,
1505 "terminal state {terminal:?} must not equal non-terminal state {non_terminal:?}"
1506 );
1507 }
1508 }
1509 }
1510
1511 #[test]
1514 fn repair_opportunity_requires_both_sync_and_cycle() {
1515 let synced_no_cycle = PeerSyncRecord {
1517 last_sync: Some(
1518 Instant::now()
1519 .checked_sub(std::time::Duration::from_secs(2))
1520 .unwrap_or_else(Instant::now),
1521 ),
1522 cycles_since_sync: 0,
1523 };
1524 assert!(
1525 !synced_no_cycle.has_repair_opportunity(),
1526 "synced with zero subsequent cycles should NOT have repair opportunity"
1527 );
1528
1529 let never_synced = PeerSyncRecord {
1531 last_sync: None,
1532 cycles_since_sync: 5,
1533 };
1534 assert!(
1535 !never_synced.has_repair_opportunity(),
1536 "never-synced peer should NOT have repair opportunity regardless of cycles"
1537 );
1538
1539 let ready = PeerSyncRecord {
1541 last_sync: Some(
1542 Instant::now()
1543 .checked_sub(std::time::Duration::from_secs(5))
1544 .unwrap_or_else(Instant::now),
1545 ),
1546 cycles_since_sync: 1,
1547 };
1548 assert!(
1549 ready.has_repair_opportunity(),
1550 "synced peer with >= 1 cycle SHOULD have repair opportunity"
1551 );
1552 }
1553}