fork.rs (3186B)
1 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 2 pub(super) struct ForkPoint { 3 pub(super) common_ancestor_height: u64, 4 } 5 6 #[derive(Clone, Debug, Eq, PartialEq)] 7 pub(super) struct FinalityCheckpoint { 8 pub(super) height: u64, 9 pub(super) hash: String, 10 } 11 12 impl ForkPoint { 13 pub(super) fn first_diverging_height(self) -> u64 { 14 self.common_ancestor_height + 1 15 } 16 } 17 18 #[derive(Clone, Debug, Eq, PartialEq)] 19 pub(super) struct LeaderScore { 20 pub(super) finalizer_mode_rank: u8, 21 pub(super) finalizer_rank: u32, 22 pub(super) proof_rank: String, 23 } 24 25 impl Ord for LeaderScore { 26 fn cmp(&self, other: &Self) -> std::cmp::Ordering { 27 self.finalizer_mode_rank 28 .cmp(&other.finalizer_mode_rank) 29 .then_with(|| self.finalizer_rank.cmp(&other.finalizer_rank)) 30 .then_with(|| self.proof_rank.cmp(&other.proof_rank)) 31 } 32 } 33 34 impl PartialOrd for LeaderScore { 35 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { 36 Some(self.cmp(other)) 37 } 38 } 39 40 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 41 pub(super) enum ForkQuality { 42 LocalBetter, 43 RemoteBetter, 44 Equal, 45 } 46 47 impl From<std::cmp::Ordering> for ForkQuality { 48 fn from(ordering: std::cmp::Ordering) -> Self { 49 match ordering { 50 std::cmp::Ordering::Less => Self::LocalBetter, 51 std::cmp::Ordering::Equal => Self::Equal, 52 std::cmp::Ordering::Greater => Self::RemoteBetter, 53 } 54 } 55 } 56 57 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 58 pub(super) enum ForkChoice { 59 KeepLocal, 60 SwitchToCandidate, 61 } 62 63 #[cfg(test)] 64 mod tests { 65 use super::{ForkPoint, ForkQuality, LeaderScore}; 66 67 #[test] 68 fn fork_point_reports_first_diverging_height() { 69 assert_eq!( 70 ForkPoint { 71 common_ancestor_height: 41 72 } 73 .first_diverging_height(), 74 42 75 ); 76 } 77 78 #[test] 79 fn leader_score_orders_by_mode_rank_then_finalizer_rank_then_proof_rank() { 80 let base = LeaderScore { 81 finalizer_mode_rank: 0, 82 finalizer_rank: 0, 83 proof_rank: "b".to_string(), 84 }; 85 86 assert!( 87 base < LeaderScore { 88 finalizer_mode_rank: 1, 89 finalizer_rank: 0, 90 proof_rank: "a".to_string(), 91 } 92 ); 93 assert!( 94 base < LeaderScore { 95 finalizer_mode_rank: 0, 96 finalizer_rank: 1, 97 proof_rank: "a".to_string(), 98 } 99 ); 100 assert!( 101 base > LeaderScore { 102 finalizer_mode_rank: 0, 103 finalizer_rank: 0, 104 proof_rank: "a".to_string(), 105 } 106 ); 107 } 108 109 #[test] 110 fn fork_quality_maps_ordering_without_inversion() { 111 assert_eq!( 112 ForkQuality::from(std::cmp::Ordering::Less), 113 ForkQuality::LocalBetter 114 ); 115 assert_eq!( 116 ForkQuality::from(std::cmp::Ordering::Equal), 117 ForkQuality::Equal 118 ); 119 assert_eq!( 120 ForkQuality::from(std::cmp::Ordering::Greater), 121 ForkQuality::RemoteBetter 122 ); 123 } 124 }