heika_finalization/
prevote.rs1use heika_block::finalization::FinalizationRound;
7
8use crate::Settings;
9
10pub fn prevote_range(
13 round: FinalizationRound,
14 finalized_height: u64,
15 chain_height: u64,
16 settings: &Settings,
17) -> (u64, u64) {
18 let multiple = settings.prevote_blocks_multiple;
19 let mut max_height = if chain_height >= multiple {
20 chain_height - multiple
21 } else {
22 chain_height
23 };
24 let epoch_end = match round.epoch {
25 0 | 1 => 1,
26 epoch => (u64::from(epoch) - 1) * settings.voting_set_grouping,
27 };
28 max_height = max_height.min(epoch_end);
29 let clamped = round_down(max_height, multiple);
30 let mut count = if clamped > finalized_height {
31 clamped - finalized_height + 1
32 } else {
33 1
34 };
35 if count > settings.max_hashes_per_point {
36 count -= round_up(count - settings.max_hashes_per_point, multiple);
37 }
38 (finalized_height, count)
39}
40
41fn round_down(value: u64, multiple: u64) -> u64 {
43 if value.is_multiple_of(multiple) {
44 value
45 } else {
46 value / multiple * multiple
47 }
48}
49
50fn round_up(value: u64, multiple: u64) -> u64 {
52 if value.is_multiple_of(multiple) {
53 value
54 } else {
55 (value / multiple + 1) * multiple
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 const SETTINGS: Settings = Settings {
64 step_duration: 1000,
65 prevote_blocks_multiple: 4,
66 max_hashes_per_point: 16,
67 voting_set_grouping: 100,
68 };
69 const ROUND: FinalizationRound = FinalizationRound { epoch: 3, point: 1 };
71
72 #[test]
73 fn votes_up_to_a_multiple_below_the_tip() {
74 assert_eq!(prevote_range(ROUND, 140, 150, &SETTINGS), (140, 5));
76 assert_eq!(prevote_range(ROUND, 140, 148, &SETTINGS), (140, 5));
78 }
79
80 #[test]
81 fn votes_only_the_finalized_block_when_the_chain_is_not_ahead() {
82 assert_eq!(prevote_range(ROUND, 140, 143, &SETTINGS), (140, 1));
83 assert_eq!(prevote_range(ROUND, 140, 140, &SETTINGS), (140, 1));
84 assert_eq!(prevote_range(ROUND, 1, 3, &SETTINGS), (1, 1));
86 }
87
88 #[test]
89 fn stops_at_the_end_of_the_epoch() {
90 assert_eq!(prevote_range(ROUND, 196, 300, &SETTINGS), (196, 5));
91 }
92
93 #[test]
94 fn trims_to_the_limit_by_multiples() {
95 assert_eq!(prevote_range(ROUND, 100, 150, &SETTINGS), (100, 13));
97 }
98}