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 verified_sources: Vec<PeerId>,
89 pub tried_sources: HashSet<PeerId>,
91 pub created_at: Instant,
93 pub next_verify_at: Instant,
96 pub hint_sources: HashSet<PeerId>,
99 pub replica_hint_sources: HashSet<PeerId>,
102}
103
104impl VerificationEntry {
105 #[must_use]
121 pub fn pipeline(&self) -> HintPipeline {
122 if self.replica_hint_sources.is_empty() {
123 HintPipeline::PaidOnly
124 } else {
125 HintPipeline::Replica
126 }
127 }
128}
129
130#[derive(Debug, Clone, Copy)]
147pub struct FetchOrder {
148 pub key: XorName,
150 pub distance: XorName,
152}
153
154impl Eq for FetchOrder {}
155
156impl PartialEq for FetchOrder {
157 fn eq(&self, other: &Self) -> bool {
158 self.distance == other.distance && self.key == other.key
159 }
160}
161
162impl Ord for FetchOrder {
163 fn cmp(&self, other: &Self) -> Ordering {
164 other
167 .distance
168 .cmp(&self.distance)
169 .then_with(|| self.key.cmp(&other.key))
170 }
171}
172
173impl PartialOrd for FetchOrder {
174 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
175 Some(self.cmp(other))
176 }
177}
178
179#[derive(Debug, Clone)]
186pub struct FetchPayload {
187 pub sources: Vec<PeerId>,
189 pub retry_verification: Option<VerificationEntry>,
192}
193
194#[derive(Debug, Clone)]
197pub struct FetchCandidate {
198 pub key: XorName,
200 pub distance: XorName,
202 pub sources: Vec<PeerId>,
204 pub retry_verification: Option<VerificationEntry>,
207}
208
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
215pub enum PresenceEvidence {
216 Present,
218 Absent,
220 Unresolved,
222}
223
224#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
226pub enum PaidListEvidence {
227 Confirmed,
229 NotFound,
231 Unresolved,
233}
234
235#[derive(Debug, Clone)]
238pub struct KeyVerificationEvidence {
239 pub presence: HashMap<PeerId, PresenceEvidence>,
241 pub paid_list: HashMap<PeerId, PaidListEvidence>,
243}
244
245#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
252pub struct AuditFailureSummary {
253 pub challenged_keys: usize,
255 pub failed_keys: usize,
257 pub absent_keys: usize,
259 pub digest_mismatch_keys: usize,
262}
263
264#[derive(Debug, Clone)]
266pub enum FailureEvidence {
267 ReplicationFailure {
269 peer: PeerId,
271 key: XorName,
273 },
274 AuditFailure {
276 challenge_id: u64,
278 challenged_peer: PeerId,
280 confirmed_failed_keys: Vec<XorName>,
282 summary: AuditFailureSummary,
284 reason: AuditFailureReason,
286 },
287 BootstrapClaimAbuse {
289 peer: PeerId,
291 first_seen: Instant,
293 },
294 QuoteCommitmentMismatch {
303 peer: PeerId,
305 pinned_commitment: [u8; 32],
308 quoted_key_count: u32,
310 committed_key_count: u32,
312 quote_artifact: Vec<u8>,
319 commitment: Box<crate::replication::commitment::StorageCommitment>,
325 },
326}
327
328#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
330pub enum AuditFailureReason {
331 Timeout,
333 MalformedResponse,
335 DigestMismatch,
337 KeyAbsent,
339 Rejected,
341}
342
343#[derive(Debug, Clone)]
349pub struct PeerSyncRecord {
350 pub last_sync: Option<Instant>,
352 pub cycles_since_sync: u32,
355}
356
357impl PeerSyncRecord {
358 #[must_use]
361 pub fn has_repair_opportunity(&self) -> bool {
362 self.last_sync.is_some() && self.cycles_since_sync >= 1
363 }
364}
365
366#[derive(Debug, Clone)]
372struct RepairProof {
373 hinted_at_epoch: u64,
375 hinted_at: Instant,
377}
378
379#[derive(Debug, Clone)]
382struct RepairProofEntry {
383 close_peers: HashSet<PeerId>,
385 peer_proofs: HashMap<PeerId, RepairProof>,
387}
388
389impl RepairProofEntry {
390 fn new(close_peers: HashSet<PeerId>) -> Self {
391 Self {
392 close_peers,
393 peer_proofs: HashMap::new(),
394 }
395 }
396}
397
398#[derive(Debug, Clone, Default)]
404pub struct RepairProofs {
405 proofs_by_key: HashMap<XorName, RepairProofEntry>,
407}
408
409impl RepairProofs {
410 #[must_use]
412 pub fn new() -> Self {
413 Self::default()
414 }
415
416 pub fn record_replica_hint_sent(
424 &mut self,
425 peer: PeerId,
426 key: XorName,
427 current_close_peers: &HashSet<PeerId>,
428 hinted_at_epoch: u64,
429 ) -> bool {
430 self.insert_replica_hint_sent(
431 peer,
432 key,
433 current_close_peers,
434 hinted_at_epoch,
435 Instant::now(),
436 )
437 }
438
439 #[cfg(any(test, feature = "test-utils"))]
446 pub fn record_replica_hint_sent_at(
447 &mut self,
448 peer: PeerId,
449 key: XorName,
450 current_close_peers: &HashSet<PeerId>,
451 hinted_at_epoch: u64,
452 hinted_at: Instant,
453 ) -> bool {
454 self.insert_replica_hint_sent(peer, key, current_close_peers, hinted_at_epoch, hinted_at)
455 }
456
457 fn insert_replica_hint_sent(
458 &mut self,
459 peer: PeerId,
460 key: XorName,
461 current_close_peers: &HashSet<PeerId>,
462 hinted_at_epoch: u64,
463 hinted_at: Instant,
464 ) -> bool {
465 self.reconcile_key_close_group(&key, current_close_peers);
466
467 if !current_close_peers.contains(&peer) {
468 return false;
469 }
470
471 let entry = self
472 .proofs_by_key
473 .entry(key)
474 .or_insert_with(|| RepairProofEntry::new(current_close_peers.clone()));
475
476 if entry.peer_proofs.contains_key(&peer) {
477 return false;
478 }
479
480 entry.peer_proofs.insert(
481 peer,
482 RepairProof {
483 hinted_at_epoch,
484 hinted_at,
485 },
486 );
487 true
488 }
489
490 pub fn has_mature_replica_hint(
497 &mut self,
498 peer: &PeerId,
499 key: &XorName,
500 current_close_peers: &HashSet<PeerId>,
501 current_epoch: u64,
502 now: Instant,
503 ) -> bool {
504 self.reconcile_key_close_group(key, current_close_peers);
505
506 self.proofs_by_key
507 .get(key)
508 .and_then(|entry| entry.peer_proofs.get(peer))
509 .is_some_and(|proof| {
510 proof.hinted_at_epoch < current_epoch
511 && now.saturating_duration_since(proof.hinted_at) >= REPAIR_HINT_MIN_AGE
512 })
513 }
514
515 pub fn remove_key(&mut self, key: &XorName) {
517 self.proofs_by_key.remove(key);
518 }
519
520 pub fn remove_peer(&mut self, peer: &PeerId) {
522 self.proofs_by_key.retain(|_, entry| {
523 entry.peer_proofs.remove(peer);
524 !entry.peer_proofs.is_empty()
525 });
526 }
527
528 fn reconcile_key_close_group(&mut self, key: &XorName, current_close_peers: &HashSet<PeerId>) {
529 let should_remove = if let Some(entry) = self.proofs_by_key.get_mut(key) {
530 if entry.close_peers == *current_close_peers {
531 return;
532 }
533
534 entry.close_peers.clone_from(current_close_peers);
535 entry
536 .peer_proofs
537 .retain(|peer, _| current_close_peers.contains(peer));
538 entry.peer_proofs.is_empty()
539 } else {
540 false
541 };
542
543 if should_remove {
544 self.proofs_by_key.remove(key);
545 }
546 }
547}
548
549#[derive(Debug, Clone, Copy, PartialEq, Eq)]
555pub enum BootstrapClaimObservation {
556 WithinGrace {
558 first_seen: Instant,
560 },
561 PastGrace {
563 first_seen: Instant,
565 },
566 Repeated {
568 first_seen: Instant,
570 },
571}
572
573#[derive(Debug)]
579pub struct NeighborSyncState {
580 pub priority_order: VecDeque<PeerId>,
587 pub order: Vec<PeerId>,
589 pub cursor: usize,
591 pub last_sync_times: HashMap<PeerId, Instant>,
593 pub bootstrap_claims: HashMap<PeerId, Instant>,
599 pub bootstrap_claim_history: HashMap<PeerId, Instant>,
607 pub prune_cursor: usize,
610}
611
612impl NeighborSyncState {
613 #[must_use]
615 pub fn new_cycle(close_neighbors: Vec<PeerId>) -> Self {
616 Self {
617 priority_order: VecDeque::new(),
618 order: close_neighbors,
619 cursor: 0,
620 last_sync_times: HashMap::new(),
621 bootstrap_claims: HashMap::new(),
622 bootstrap_claim_history: HashMap::new(),
623 prune_cursor: 0,
624 }
625 }
626
627 #[must_use]
634 pub fn observe_bootstrap_claim(
635 &mut self,
636 peer: PeerId,
637 now: Instant,
638 grace_period: Duration,
639 ) -> BootstrapClaimObservation {
640 if let Some(first_seen) = self.bootstrap_claims.get(&peer).copied() {
641 if now.duration_since(first_seen) > grace_period {
642 BootstrapClaimObservation::PastGrace { first_seen }
643 } else {
644 BootstrapClaimObservation::WithinGrace { first_seen }
645 }
646 } else if let Some(first_seen) = self.bootstrap_claim_history.get(&peer).copied() {
647 BootstrapClaimObservation::Repeated { first_seen }
648 } else {
649 self.bootstrap_claims.insert(peer, now);
650 self.bootstrap_claim_history.insert(peer, now);
651 BootstrapClaimObservation::WithinGrace { first_seen: now }
652 }
653 }
654
655 pub fn clear_active_bootstrap_claim(&mut self, peer: &PeerId) -> bool {
657 self.bootstrap_claims.remove(peer).is_some()
658 }
659
660 pub fn queue_priority_peers<I>(&mut self, peers: I) -> usize
665 where
666 I: IntoIterator<Item = PeerId>,
667 {
668 let mut queued = 0;
669 for peer in peers {
670 if self.priority_order.contains(&peer) {
671 continue;
672 }
673 self.priority_order.push_back(peer);
674 queued += 1;
675 }
676 queued
677 }
678
679 pub fn retain_sync_peers(&mut self, close_peers: &HashSet<PeerId>) -> usize {
684 let old_priority_len = self.priority_order.len();
685 self.priority_order
686 .retain(|peer| close_peers.contains(peer));
687
688 let old_order_len = self.order.len();
689 let old_cursor = self.cursor;
690 let mut retained_before_cursor = 0;
691 let mut retained_order = Vec::with_capacity(old_order_len);
692 for (idx, peer) in self.order.drain(..).enumerate() {
693 if close_peers.contains(&peer) {
694 if idx < old_cursor {
695 retained_before_cursor += 1;
696 }
697 retained_order.push(peer);
698 }
699 }
700
701 self.order = retained_order;
702 self.cursor = retained_before_cursor;
703
704 (old_priority_len - self.priority_order.len()) + (old_order_len - self.order.len())
705 }
706
707 pub fn remove_peer(&mut self, peer: &PeerId) -> bool {
709 let old_priority_len = self.priority_order.len();
710 self.priority_order.retain(|queued| queued != peer);
711
712 let old_order_len = self.order.len();
713 if let Some(pos) = self.order.iter().position(|queued| queued == peer) {
714 self.order.remove(pos);
715 if pos < self.cursor {
716 self.cursor = self.cursor.saturating_sub(1);
717 }
718 }
719
720 old_priority_len != self.priority_order.len() || old_order_len != self.order.len()
721 }
722
723 #[must_use]
725 pub fn is_cycle_complete(&self) -> bool {
726 self.priority_order.is_empty() && self.cursor >= self.order.len()
727 }
728
729 #[must_use]
736 pub fn has_priority_peers(&self) -> bool {
737 !self.priority_order.is_empty()
738 }
739}
740
741#[derive(Debug)]
747pub struct BootstrapState {
748 pub drained: bool,
750 pub pending_peer_requests: usize,
752 pub pending_keys: HashSet<XorName>,
755 pub capacity_rejected_sources: HashMap<PeerId, Instant>,
796}
797
798impl BootstrapState {
799 #[must_use]
801 pub fn new() -> Self {
802 Self {
803 drained: false,
804 pending_peer_requests: 0,
805 pending_keys: HashSet::new(),
806 capacity_rejected_sources: HashMap::new(),
807 }
808 }
809
810 pub fn note_capacity_rejected(&mut self, source: PeerId, now: Instant) -> bool {
821 let first = !self.capacity_rejected_sources.contains_key(&source);
822 self.capacity_rejected_sources.entry(source).or_insert(now);
823 first
824 }
825
826 #[must_use]
833 pub fn is_drained(&self) -> bool {
834 self.drained
835 }
836
837 pub fn remove_key(&mut self, key: &XorName) {
843 self.pending_keys.remove(key);
844 }
845}
846
847impl Default for BootstrapState {
848 fn default() -> Self {
849 Self::new()
850 }
851}
852
853#[cfg(test)]
858mod tests {
859 use super::*;
860
861 fn peer_id_from_byte(b: u8) -> PeerId {
863 let mut bytes = [0u8; 32];
864 bytes[0] = b;
865 PeerId::from_bytes(bytes)
866 }
867
868 fn mature_hint_times() -> (Instant, Instant) {
869 let hinted_at = Instant::now();
870 let now = hinted_at
871 .checked_add(REPAIR_HINT_MIN_AGE)
872 .unwrap_or(hinted_at);
873 (hinted_at, now)
874 }
875
876 #[test]
879 fn fetch_order_nearest_key_has_highest_priority() {
880 let near = FetchOrder {
881 key: [1u8; 32],
882 distance: [
883 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,
884 0, 0, 0, 0,
885 ],
886 };
887
888 let far = FetchOrder {
889 key: [2u8; 32],
890 distance: [
891 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,
892 0, 0, 0, 0, 0,
893 ],
894 };
895
896 assert!(near > far, "nearer candidate should compare greater");
899
900 let mut heap = std::collections::BinaryHeap::new();
901 heap.push(far);
902 heap.push(near);
903
904 assert_eq!(heap.len(), 2, "heap should contain both candidates");
905
906 let first = heap.pop();
907 assert!(first.is_some(), "first pop should succeed");
908 assert_eq!(
909 first.map(|c| c.key),
910 Some(near.key),
911 "nearest key should pop first"
912 );
913
914 let second = heap.pop();
915 assert!(second.is_some(), "second pop should succeed");
916 assert_eq!(
917 second.map(|c| c.key),
918 Some(far.key),
919 "farthest key should pop second"
920 );
921 }
922
923 #[test]
924 fn fetch_order_same_distance_and_key_is_equal() {
925 let a = FetchOrder {
926 key: [1u8; 32],
927 distance: [5u8; 32],
928 };
929
930 let b = FetchOrder {
931 key: [1u8; 32],
932 distance: [5u8; 32],
933 };
934
935 assert_eq!(
936 a.cmp(&b),
937 Ordering::Equal,
938 "same distance + same key should yield Equal"
939 );
940 assert_eq!(a, b, "PartialEq must agree with Ord");
941 }
942
943 #[test]
944 fn fetch_order_same_distance_different_key_is_deterministic() {
945 let a = FetchOrder {
946 key: [1u8; 32],
947 distance: [5u8; 32],
948 };
949
950 let b = FetchOrder {
951 key: [2u8; 32],
952 distance: [5u8; 32],
953 };
954
955 assert_ne!(
956 a.cmp(&b),
957 Ordering::Equal,
958 "same distance + different key must not be Equal"
959 );
960 assert_ne!(a, b, "PartialEq must agree with Ord");
961 }
962
963 #[test]
966 fn peer_sync_record_no_sync_yet() {
967 let record = PeerSyncRecord {
968 last_sync: None,
969 cycles_since_sync: 0,
970 };
971 assert!(
972 !record.has_repair_opportunity(),
973 "never-synced peer has no repair opportunity"
974 );
975 }
976
977 #[test]
978 fn peer_sync_record_synced_but_no_cycle() {
979 let record = PeerSyncRecord {
980 last_sync: Some(Instant::now()),
981 cycles_since_sync: 0,
982 };
983 assert!(
984 !record.has_repair_opportunity(),
985 "synced peer with zero subsequent cycles has no repair opportunity"
986 );
987 }
988
989 #[test]
990 fn peer_sync_record_synced_with_cycle() {
991 let record = PeerSyncRecord {
992 last_sync: Some(Instant::now()),
993 cycles_since_sync: 1,
994 };
995 assert!(
996 record.has_repair_opportunity(),
997 "synced peer with >= 1 cycle should have repair opportunity"
998 );
999 }
1000
1001 #[test]
1002 fn peer_sync_record_no_sync_many_cycles() {
1003 let record = PeerSyncRecord {
1004 last_sync: None,
1005 cycles_since_sync: 10,
1006 };
1007 assert!(
1008 !record.has_repair_opportunity(),
1009 "never-synced peer has no repair opportunity regardless of cycle count"
1010 );
1011 }
1012
1013 #[test]
1016 fn repair_proofs_record_sent_hint_for_close_peer() {
1017 const HINT_EPOCH: u64 = 7;
1018 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1019
1020 let key = [0xA1; 32];
1021 let peer = peer_id_from_byte(1);
1022 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1023 let mut proofs = RepairProofs::new();
1024 let (hinted_at, now) = mature_hint_times();
1025
1026 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1027
1028 assert!(
1029 proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1030 "old sent hint should make key auditable for that peer"
1031 );
1032 }
1033
1034 #[test]
1035 fn repair_proofs_reject_peer_outside_current_close_group() {
1036 const HINT_EPOCH: u64 = 7;
1037 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1038
1039 let key = [0xA2; 32];
1040 let peer = peer_id_from_byte(1);
1041 let close_peers = HashSet::from([peer_id_from_byte(2), peer_id_from_byte(3)]);
1042 let mut proofs = RepairProofs::new();
1043 let (hinted_at, now) = mature_hint_times();
1044
1045 assert!(!proofs.record_replica_hint_sent_at(
1046 peer,
1047 key,
1048 &close_peers,
1049 HINT_EPOCH,
1050 hinted_at,
1051 ));
1052
1053 assert!(
1054 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1055 "peers outside current close group must not get repair proof"
1056 );
1057 }
1058
1059 #[test]
1060 fn repair_proofs_require_later_epoch() {
1061 const HINT_EPOCH: u64 = 7;
1062 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1063
1064 let key = [0xA3; 32];
1065 let peer = peer_id_from_byte(1);
1066 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1067 let mut proofs = RepairProofs::new();
1068 let (hinted_at, now) = mature_hint_times();
1069
1070 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1071
1072 assert!(
1073 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, HINT_EPOCH, now),
1074 "same-cycle proof should not be audit-eligible"
1075 );
1076 assert!(
1077 proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1078 "old proof should mature after a later local sync-cycle epoch"
1079 );
1080 }
1081
1082 #[test]
1083 fn repair_proofs_require_min_hint_age() {
1084 const HINT_EPOCH: u64 = 7;
1085 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1086
1087 let key = [0xA8; 32];
1088 let peer = peer_id_from_byte(1);
1089 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1090 let mut proofs = RepairProofs::new();
1091 let hinted_at = Instant::now();
1092
1093 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at));
1094
1095 assert!(
1096 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, hinted_at),
1097 "fresh repair hints should not be audit-eligible"
1098 );
1099 assert!(
1100 proofs.has_mature_replica_hint(
1101 &peer,
1102 &key,
1103 &close_peers,
1104 CURRENT_EPOCH,
1105 hinted_at
1106 .checked_add(REPAIR_HINT_MIN_AGE)
1107 .unwrap_or(hinted_at),
1108 ),
1109 "repair hints should mature once they are at least the minimum age"
1110 );
1111 }
1112
1113 #[test]
1114 fn repair_proofs_repeated_hint_does_not_reset_maturity() {
1115 const HINT_EPOCH: u64 = 7;
1116 const REPEATED_HINT_EPOCH: u64 = HINT_EPOCH + 1;
1117
1118 let key = [0xA5; 32];
1119 let peer = peer_id_from_byte(1);
1120 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1121 let mut proofs = RepairProofs::new();
1122 let (hinted_at, now) = mature_hint_times();
1123
1124 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1125 assert!(
1126 !proofs.record_replica_hint_sent_at(peer, key, &close_peers, REPEATED_HINT_EPOCH, now),
1127 "duplicate hint in the same close group should keep existing proof"
1128 );
1129 assert!(
1130 proofs.has_mature_replica_hint(&peer, &key, &close_peers, REPEATED_HINT_EPOCH, now),
1131 "duplicate hint must not reset an already mature proof"
1132 );
1133 }
1134
1135 #[test]
1136 fn repair_proofs_retain_stable_peers_on_close_group_change() {
1137 const HINT_EPOCH: u64 = 7;
1138 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1139
1140 let key = [0xA7; 32];
1141 let stable_peer = peer_id_from_byte(1);
1142 let departing_peer = peer_id_from_byte(2);
1143 let retained_peer = peer_id_from_byte(3);
1144 let new_peer = peer_id_from_byte(4);
1145 let old_group = HashSet::from([stable_peer, departing_peer, retained_peer]);
1146 let changed_group = HashSet::from([stable_peer, retained_peer, new_peer]);
1147 let mut proofs = RepairProofs::new();
1148 let (hinted_at, now) = mature_hint_times();
1149
1150 assert!(proofs.record_replica_hint_sent_at(
1151 stable_peer,
1152 key,
1153 &old_group,
1154 HINT_EPOCH,
1155 hinted_at,
1156 ));
1157 assert!(proofs.record_replica_hint_sent_at(
1158 departing_peer,
1159 key,
1160 &old_group,
1161 HINT_EPOCH,
1162 hinted_at,
1163 ));
1164
1165 assert!(
1166 proofs.has_mature_replica_hint(&stable_peer, &key, &changed_group, CURRENT_EPOCH, now),
1167 "stable peers should keep mature repair proofs across unrelated close-group churn"
1168 );
1169 assert!(
1170 !proofs.has_mature_replica_hint(
1171 &departing_peer,
1172 &key,
1173 &changed_group,
1174 CURRENT_EPOCH,
1175 now,
1176 ),
1177 "peers that left the close group should lose repair proofs"
1178 );
1179 assert!(
1180 !proofs.has_mature_replica_hint(&new_peer, &key, &changed_group, CURRENT_EPOCH, now),
1181 "new close-group peers need their own repair hint before auditing"
1182 );
1183 }
1184
1185 #[test]
1186 fn repair_proofs_evicted_peer_reentry_requires_fresh_hint() {
1187 const FIRST_HINT_EPOCH: u64 = 7;
1188 const SECOND_HINT_EPOCH: u64 = FIRST_HINT_EPOCH + 1;
1189 const CURRENT_EPOCH: u64 = SECOND_HINT_EPOCH + 1;
1190
1191 let key = [0xA3; 32];
1192 let returning_peer = peer_id_from_byte(1);
1193 let new_peer = peer_id_from_byte(4);
1194 let old_group = HashSet::from([returning_peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1195 let changed_group = HashSet::from([new_peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1196 let mut proofs = RepairProofs::new();
1197 let (hinted_at, now) = mature_hint_times();
1198
1199 assert!(proofs.record_replica_hint_sent_at(
1200 returning_peer,
1201 key,
1202 &old_group,
1203 FIRST_HINT_EPOCH,
1204 hinted_at,
1205 ));
1206
1207 assert!(
1208 !proofs.has_mature_replica_hint(
1209 &new_peer,
1210 &key,
1211 &changed_group,
1212 SECOND_HINT_EPOCH,
1213 now
1214 ),
1215 "new close-group peer should not inherit another peer's repair proof"
1216 );
1217 assert!(
1218 !proofs.has_mature_replica_hint(&returning_peer, &key, &old_group, CURRENT_EPOCH, now),
1219 "a peer that re-enters must receive a fresh repair hint"
1220 );
1221
1222 assert!(proofs.record_replica_hint_sent_at(
1223 returning_peer,
1224 key,
1225 &old_group,
1226 SECOND_HINT_EPOCH,
1227 hinted_at,
1228 ));
1229 assert!(
1230 proofs.has_mature_replica_hint(&returning_peer, &key, &old_group, CURRENT_EPOCH, now),
1231 "fresh repair hint after re-entry should be eligible once mature"
1232 );
1233 }
1234
1235 #[test]
1236 fn repair_proofs_remove_peer_requires_fresh_hint_after_reentry() {
1237 const FIRST_HINT_EPOCH: u64 = 7;
1238 const SECOND_HINT_EPOCH: u64 = FIRST_HINT_EPOCH + 1;
1239 const CURRENT_EPOCH: u64 = SECOND_HINT_EPOCH + 1;
1240
1241 let key = [0xA6; 32];
1242 let peer = peer_id_from_byte(1);
1243 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1244 let mut proofs = RepairProofs::new();
1245 let (hinted_at, now) = mature_hint_times();
1246
1247 assert!(proofs.record_replica_hint_sent_at(
1248 peer,
1249 key,
1250 &close_peers,
1251 FIRST_HINT_EPOCH,
1252 hinted_at,
1253 ));
1254 proofs.remove_peer(&peer);
1255
1256 assert!(
1257 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1258 "routing-table removal should clear proof even if peer re-enters same close group"
1259 );
1260
1261 assert!(proofs.record_replica_hint_sent_at(
1262 peer,
1263 key,
1264 &close_peers,
1265 SECOND_HINT_EPOCH,
1266 hinted_at,
1267 ));
1268 assert!(
1269 proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1270 "fresh hint after re-entry should become eligible after a later epoch"
1271 );
1272 }
1273
1274 #[test]
1275 fn repair_proofs_remove_key_clears_all_peer_entries() {
1276 const HINT_EPOCH: u64 = 7;
1277 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1278
1279 let key = [0xA4; 32];
1280 let peer = peer_id_from_byte(1);
1281 let close_peers = HashSet::from([peer]);
1282 let mut proofs = RepairProofs::new();
1283 let (hinted_at, now) = mature_hint_times();
1284
1285 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1286 proofs.remove_key(&key);
1287
1288 assert!(
1289 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1290 "deleted local key should not retain repair proof entries"
1291 );
1292 }
1293
1294 #[test]
1297 fn neighbor_sync_empty_cycle_is_immediately_complete() {
1298 let state = NeighborSyncState::new_cycle(vec![]);
1299 assert!(
1300 state.is_cycle_complete(),
1301 "empty neighbor list means cycle is complete"
1302 );
1303 }
1304
1305 #[test]
1306 fn neighbor_sync_new_cycle_not_complete() {
1307 let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
1308 let state = NeighborSyncState::new_cycle(peers);
1309 assert!(
1310 !state.is_cycle_complete(),
1311 "fresh cycle with peers should not be complete"
1312 );
1313 }
1314
1315 #[test]
1316 fn neighbor_sync_cycle_completes_when_cursor_reaches_end() {
1317 let peers = vec![
1318 peer_id_from_byte(1),
1319 peer_id_from_byte(2),
1320 peer_id_from_byte(3),
1321 ];
1322 let mut state = NeighborSyncState::new_cycle(peers);
1323
1324 state.cursor = 2;
1326 assert!(
1327 !state.is_cycle_complete(),
1328 "cursor at len-1 should not be complete"
1329 );
1330
1331 state.cursor = 3;
1332 assert!(
1333 state.is_cycle_complete(),
1334 "cursor at len should be complete"
1335 );
1336 }
1337
1338 #[test]
1339 fn neighbor_sync_cursor_past_end_is_still_complete() {
1340 let peers = vec![peer_id_from_byte(1)];
1341 let mut state = NeighborSyncState::new_cycle(peers);
1342 state.cursor = 5;
1343 assert!(
1344 state.is_cycle_complete(),
1345 "cursor past end should still report complete"
1346 );
1347 }
1348
1349 #[test]
1350 fn neighbor_sync_priority_queue_blocks_cycle_completion() {
1351 let peer = peer_id_from_byte(2);
1352 let mut state = NeighborSyncState::new_cycle(Vec::new());
1353
1354 assert!(state.is_cycle_complete());
1355 assert_eq!(state.queue_priority_peers([peer]), 1);
1356 assert!(
1357 !state.is_cycle_complete(),
1358 "pending priority peers must sync before the cycle completes"
1359 );
1360 }
1361
1362 #[test]
1363 fn neighbor_sync_priority_queue_deduplicates_peers() {
1364 let peer = peer_id_from_byte(3);
1365 let mut state = NeighborSyncState::new_cycle(Vec::new());
1366
1367 assert_eq!(state.queue_priority_peers([peer, peer]), 1);
1368 assert_eq!(state.priority_order.len(), 1);
1369 }
1370
1371 #[test]
1372 fn neighbor_sync_has_priority_peers_tracks_queue_and_drain() {
1373 let first = peer_id_from_byte(6);
1379 let second = peer_id_from_byte(7);
1380 let mut state = NeighborSyncState::new_cycle(Vec::new());
1381 assert!(!state.has_priority_peers());
1382
1383 assert_eq!(state.queue_priority_peers([first, second]), 2);
1384 assert!(state.has_priority_peers());
1385
1386 assert!(state.remove_peer(&first));
1387 assert!(state.has_priority_peers(), "one entrant still pending");
1388
1389 assert!(state.remove_peer(&second));
1390 assert!(
1391 !state.has_priority_peers(),
1392 "drained queue must let the loop park"
1393 );
1394 }
1395
1396 #[test]
1397 fn neighbor_sync_remove_peer_clears_order_and_priority_queue() {
1398 let peer = peer_id_from_byte(4);
1399 let retained = peer_id_from_byte(5);
1400 let mut state = NeighborSyncState::new_cycle(vec![peer, retained]);
1401 assert_eq!(state.queue_priority_peers([peer]), 1);
1402 state.cursor = 1;
1403
1404 assert!(state.remove_peer(&peer));
1405
1406 assert!(!state.order.contains(&peer));
1407 assert!(!state.priority_order.contains(&peer));
1408 assert_eq!(state.order, vec![retained]);
1409 assert_eq!(state.cursor, 0);
1410 }
1411
1412 #[test]
1413 fn neighbor_sync_retain_sync_peers_prunes_only_departed_peers() {
1414 let already_scanned = peer_id_from_byte(1);
1415 let stable_scanned = peer_id_from_byte(2);
1416 let departed_priority = peer_id_from_byte(3);
1417 let stable_unscanned = peer_id_from_byte(4);
1418 let stable_priority = peer_id_from_byte(5);
1419 let mut state = NeighborSyncState::new_cycle(vec![
1420 already_scanned,
1421 stable_scanned,
1422 departed_priority,
1423 stable_unscanned,
1424 ]);
1425 assert_eq!(
1426 state.queue_priority_peers([departed_priority, stable_priority]),
1427 2
1428 );
1429 state.cursor = 2;
1430 let close_peers = HashSet::from([stable_scanned, stable_unscanned, stable_priority]);
1431
1432 let removed = state.retain_sync_peers(&close_peers);
1433
1434 assert_eq!(removed, 3);
1435 assert_eq!(state.order, vec![stable_scanned, stable_unscanned]);
1436 assert_eq!(
1437 state.priority_order.iter().copied().collect::<Vec<_>>(),
1438 vec![stable_priority]
1439 );
1440 assert_eq!(
1441 state.cursor, 1,
1442 "stable peer scanned before churn must not be selected again"
1443 );
1444 }
1445
1446 #[test]
1447 fn bootstrap_claim_history_prevents_second_grace_window() {
1448 let peer = peer_id_from_byte(9);
1449 let mut state = NeighborSyncState::new_cycle(vec![peer]);
1450 let first_seen = Instant::now();
1451 let grace = Duration::from_secs(60);
1452
1453 assert_eq!(
1454 state.observe_bootstrap_claim(peer, first_seen, grace),
1455 BootstrapClaimObservation::WithinGrace { first_seen }
1456 );
1457 assert!(state.clear_active_bootstrap_claim(&peer));
1458 assert!(!state.bootstrap_claims.contains_key(&peer));
1459 assert!(state.bootstrap_claim_history.contains_key(&peer));
1460
1461 assert_eq!(
1462 state.observe_bootstrap_claim(peer, first_seen + Duration::from_secs(1), grace),
1463 BootstrapClaimObservation::Repeated { first_seen }
1464 );
1465 assert!(
1466 !state.bootstrap_claims.contains_key(&peer),
1467 "repeated claims must not recreate an active grace window"
1468 );
1469 assert_eq!(
1470 state.observe_bootstrap_claim(peer, first_seen + Duration::from_secs(2), grace),
1471 BootstrapClaimObservation::Repeated { first_seen }
1472 );
1473 }
1474
1475 #[test]
1476 fn bootstrap_claim_active_window_reports_past_grace() {
1477 let peer = peer_id_from_byte(10);
1478 let mut state = NeighborSyncState::new_cycle(vec![peer]);
1479 let first_seen = Instant::now();
1480 let grace = Duration::from_secs(60);
1481
1482 let _ = state.observe_bootstrap_claim(peer, first_seen, grace);
1483
1484 assert_eq!(
1485 state.observe_bootstrap_claim(peer, first_seen + grace + Duration::from_secs(1), grace),
1486 BootstrapClaimObservation::PastGrace { first_seen }
1487 );
1488 }
1489
1490 #[test]
1493 fn bootstrap_state_initial_not_drained() {
1494 let state = BootstrapState::new();
1497 assert!(
1498 !state.is_drained(),
1499 "initial state must not be drained before bootstrap begins"
1500 );
1501 }
1502
1503 #[test]
1504 fn bootstrap_state_pending_requests_block_drain() {
1505 let mut state = BootstrapState::new();
1506 state.pending_peer_requests = 3;
1507 assert!(
1508 !state.is_drained(),
1509 "pending peer requests should block drain"
1510 );
1511 }
1512
1513 #[test]
1514 fn bootstrap_state_pending_keys_block_drain() {
1515 let mut state = BootstrapState::new();
1516 state.pending_keys.insert([42u8; 32]);
1517 assert!(!state.is_drained(), "pending keys should block drain");
1518 }
1519
1520 #[test]
1521 fn bootstrap_state_explicit_drained_overrides() {
1522 let mut state = BootstrapState::new();
1523 state.pending_peer_requests = 5;
1524 state.pending_keys.insert([99u8; 32]);
1525 state.drained = true;
1526 assert!(
1527 state.is_drained(),
1528 "explicit drained flag should override pending counts"
1529 );
1530 }
1531
1532 #[test]
1533 fn bootstrap_state_requires_explicit_drain() {
1534 let mut state = BootstrapState::new();
1535 state.pending_peer_requests = 2;
1536 state.pending_keys.insert([1u8; 32]);
1537
1538 state.pending_peer_requests = 0;
1540 state.pending_keys.clear();
1541
1542 assert!(
1543 !state.is_drained(),
1544 "clearing counters alone must not drain — requires check_bootstrap_drained"
1545 );
1546
1547 state.drained = true;
1549 assert!(state.is_drained(), "explicit flag should drain");
1550 }
1551
1552 #[test]
1553 fn bootstrap_state_default_matches_new() {
1554 let from_new = BootstrapState::new();
1555 let from_default = BootstrapState::default();
1556
1557 assert_eq!(from_new.drained, from_default.drained);
1558 assert_eq!(
1559 from_new.pending_peer_requests,
1560 from_default.pending_peer_requests
1561 );
1562 assert_eq!(from_new.pending_keys, from_default.pending_keys);
1563 }
1564
1565 #[test]
1570 fn bootstrap_drain_requires_empty_pending_keys() {
1571 let key_a: XorName = [0xA0; 32];
1572 let key_b: XorName = [0xB0; 32];
1573 let key_c: XorName = [0xC0; 32];
1574
1575 let mut state = BootstrapState::new();
1576 state.pending_peer_requests = 0; state.pending_keys = std::iter::once(key_a)
1578 .chain(std::iter::once(key_b))
1579 .chain(std::iter::once(key_c))
1580 .collect();
1581
1582 assert!(
1583 !state.is_drained(),
1584 "should NOT be drained while pending_keys still has entries"
1585 );
1586
1587 state.pending_keys.remove(&key_a);
1589 assert!(!state.is_drained(), "still not drained with 2 pending keys");
1590
1591 state.pending_keys.remove(&key_b);
1592 assert!(!state.is_drained(), "still not drained with 1 pending key");
1593
1594 state.pending_keys.remove(&key_c);
1595 assert!(
1596 !state.is_drained(),
1597 "removing all keys is necessary but not sufficient — needs explicit drain"
1598 );
1599
1600 state.drained = true;
1602 assert!(state.is_drained(), "explicit drain flag should finalize");
1603 }
1604
1605 #[test]
1608 fn verification_state_terminal_variants() {
1609 let terminal_states = [
1610 VerificationState::QuorumAbandoned,
1611 VerificationState::FetchAbandoned,
1612 VerificationState::Stored,
1613 VerificationState::Idle,
1614 ];
1615
1616 for (i, a) in terminal_states.iter().enumerate() {
1618 for (j, b) in terminal_states.iter().enumerate() {
1619 if i != j {
1620 assert_ne!(
1621 a, b,
1622 "terminal states at indices {i} and {j} must be distinct"
1623 );
1624 }
1625 }
1626 }
1627
1628 let non_terminal_states = [
1630 VerificationState::OfferReceived,
1631 VerificationState::PendingVerify,
1632 VerificationState::QuorumVerified,
1633 VerificationState::PaidListVerified,
1634 VerificationState::QueuedForFetch,
1635 VerificationState::Fetching,
1636 VerificationState::FetchRetryable,
1637 VerificationState::QuorumFailed,
1638 VerificationState::QuorumInconclusive,
1639 ];
1640
1641 for terminal in &terminal_states {
1642 for non_terminal in &non_terminal_states {
1643 assert_ne!(
1644 terminal, non_terminal,
1645 "terminal state {terminal:?} must not equal non-terminal state {non_terminal:?}"
1646 );
1647 }
1648 }
1649 }
1650
1651 #[test]
1654 fn repair_opportunity_requires_both_sync_and_cycle() {
1655 let synced_no_cycle = PeerSyncRecord {
1657 last_sync: Some(
1658 Instant::now()
1659 .checked_sub(std::time::Duration::from_secs(2))
1660 .unwrap_or_else(Instant::now),
1661 ),
1662 cycles_since_sync: 0,
1663 };
1664 assert!(
1665 !synced_no_cycle.has_repair_opportunity(),
1666 "synced with zero subsequent cycles should NOT have repair opportunity"
1667 );
1668
1669 let never_synced = PeerSyncRecord {
1671 last_sync: None,
1672 cycles_since_sync: 5,
1673 };
1674 assert!(
1675 !never_synced.has_repair_opportunity(),
1676 "never-synced peer should NOT have repair opportunity regardless of cycles"
1677 );
1678
1679 let ready = PeerSyncRecord {
1681 last_sync: Some(
1682 Instant::now()
1683 .checked_sub(std::time::Duration::from_secs(5))
1684 .unwrap_or_else(Instant::now),
1685 ),
1686 cycles_since_sync: 1,
1687 };
1688 assert!(
1689 ready.has_repair_opportunity(),
1690 "synced peer with >= 1 cycle SHOULD have repair opportunity"
1691 );
1692 }
1693}