1use heika_block::finalization::FinalizationRound;
9use heika_block::finalization::aggregator::MultiRoundAggregator;
10use heika_block::finalization::round::{Candidate, RoundContext};
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub struct StageAdvancer {
15 round: FinalizationRound,
16 start: u64,
18 step_duration: u64,
19}
20
21impl StageAdvancer {
22 pub fn new(round: FinalizationRound, start: u64, step_duration: u64) -> Self {
24 Self {
25 round,
26 start,
27 step_duration,
28 }
29 }
30
31 pub fn round(&self) -> FinalizationRound {
32 self.round
33 }
34
35 pub fn can_send_prevote(&self, time: u64, aggregator: &MultiRoundAggregator) -> bool {
37 self.is_elapsed(time, 1)
38 || self
39 .current(aggregator)
40 .is_some_and(RoundContext::is_completable)
41 }
42
43 pub fn can_send_precommit(
45 &self,
46 time: u64,
47 aggregator: &MultiRoundAggregator,
48 ) -> Option<Candidate> {
49 let round = self.current(aggregator)?;
50 let best_prevote = round.best_prevote()?;
51 let previous = FinalizationRound {
53 epoch: self.round.epoch,
54 point: self.round.point.wrapping_sub(1),
55 };
56 let estimate = aggregator.find_estimate(previous);
57 if !round.is_descendant(estimate, best_prevote) {
58 return None;
59 }
60 (self.is_elapsed(time, 2) || round.is_completable()).then_some(best_prevote)
61 }
62
63 pub fn can_start_next_round(&self, aggregator: &MultiRoundAggregator) -> bool {
65 self.current(aggregator)
66 .is_some_and(RoundContext::is_completable)
67 }
68
69 fn current<'a>(&self, aggregator: &'a MultiRoundAggregator) -> Option<&'a RoundContext> {
70 aggregator.round(self.round)
71 }
72
73 fn is_elapsed(&self, time: u64, steps: u64) -> bool {
74 time >= self.start + steps * self.step_duration
75 }
76}
77
78#[cfg(test)]
79pub(crate) mod tests {
80 use std::sync::Arc;
81
82 use heika_block::finalization::message::FinalizationMessage;
83 use heika_block::finalization::proof::{ProofParameters, VotingSet};
84 use heika_core::hash::Hash256;
85 use heika_core::key::{PrivateKey, PublicKey};
86
87 use super::*;
88
89 pub const PARAMETERS: ProofParameters = ProofParameters {
90 voting_set_grouping: 10,
91 size: 10_000,
92 threshold: 6_700,
93 max_hashes_per_point: 256,
94 };
95 pub const STEP: u64 = 1000;
96 pub const ROUND: FinalizationRound = FinalizationRound { epoch: 3, point: 2 };
97
98 pub fn block_hash(height: u64, fork: u8) -> Hash256 {
100 let mut hash = [fork; 32];
101 hash[..8].copy_from_slice(&height.to_le_bytes());
102 Hash256(hash)
103 }
104
105 pub fn keys(seed: u8) -> (PrivateKey, PrivateKey) {
107 (
108 PrivateKey::from_bytes(&[seed; 32]),
109 PrivateKey::from_bytes(&[seed ^ 0x80; 32]),
110 )
111 }
112
113 pub fn vote(
115 seed: u8,
116 round: FinalizationRound,
117 is_prevote: bool,
118 height: u64,
119 hashes: &[Hash256],
120 ) -> FinalizationMessage {
121 let (root, bottom) = keys(seed);
122 let bottom_public = PublicKey::from_private_key(&bottom).0;
123 let mut signed = Vec::new();
124 signed.extend_from_slice(&1u32.to_le_bytes());
125 signed.extend_from_slice(&(hashes.len() as u32).to_le_bytes());
126 signed.extend_from_slice(&round.epoch.to_le_bytes());
127 signed.extend_from_slice(&((round.point << 1) | u32::from(!is_prevote)).to_le_bytes());
128 signed.extend_from_slice(&height.to_le_bytes());
129 for hash in hashes {
130 signed.extend_from_slice(&hash.0);
131 }
132 let mut bytes = Vec::new();
133 bytes.extend_from_slice(&((200 + signed.len()) as u32).to_le_bytes());
134 bytes.extend_from_slice(&0u32.to_le_bytes());
135 bytes.extend_from_slice(&PublicKey::from_private_key(&root).0);
136 let epoch = u64::from(round.epoch).to_le_bytes();
137 bytes.extend_from_slice(&root.sign(&[&bottom_public, &epoch]).0);
138 bytes.extend_from_slice(&bottom_public);
139 bytes.extend_from_slice(&bottom.sign(&[&signed]).0);
140 bytes.extend_from_slice(&signed);
141 FinalizationMessage::from_bytes(&bytes).unwrap()
142 }
143
144 pub fn voting_set() -> Arc<VotingSet> {
146 Arc::new(VotingSet {
147 voters: [1, 2, 3]
148 .into_iter()
149 .zip([40, 30, 30])
150 .map(|(seed, weight)| (PublicKey::from_private_key(&keys(seed).0).0, weight))
151 .collect(),
152 })
153 }
154
155 pub fn aggregator() -> MultiRoundAggregator {
157 let mut aggregator = MultiRoundAggregator::new(
158 PARAMETERS,
159 usize::MAX,
160 FinalizationRound { epoch: 3, point: 1 },
161 (10, block_hash(10, 0)),
162 );
163 aggregator.set_voting_set(3, voting_set());
164 aggregator.set_max_round(ROUND);
165 aggregator
166 }
167
168 pub fn chain(from: u64, through: u64) -> Vec<Hash256> {
169 (from..=through).map(|at| block_hash(at, 0)).collect()
170 }
171
172 fn advancer() -> StageAdvancer {
173 StageAdvancer::new(ROUND, 5000, STEP)
174 }
175
176 #[test]
177 fn waits_at_the_start_of_a_round() {
178 let aggregator = aggregator();
179 let advancer = advancer();
180 assert!(!advancer.can_send_prevote(5000, &aggregator));
181 assert_eq!(advancer.can_send_precommit(5000, &aggregator), None);
182 assert!(!advancer.can_start_next_round(&aggregator));
183 }
184
185 #[test]
186 fn sends_a_prevote_after_one_step_or_when_completable() {
187 let mut aggregator = aggregator();
188 let advancer = advancer();
189 assert!(!advancer.can_send_prevote(5999, &aggregator));
190 assert!(advancer.can_send_prevote(6000, &aggregator));
191
192 for seed in 1..=3 {
194 aggregator
195 .add(vote(seed, ROUND, true, 10, &chain(10, 14)))
196 .unwrap();
197 }
198 assert!(!advancer.can_send_prevote(5000, &aggregator));
199 for seed in 1..=3 {
200 aggregator
201 .add(vote(seed, ROUND, false, 14, &chain(14, 14)))
202 .unwrap();
203 }
204 assert!(advancer.can_send_prevote(5000, &aggregator));
205 assert!(advancer.can_start_next_round(&aggregator));
206 }
207
208 #[test]
209 fn sends_a_precommit_only_for_a_descendant_of_the_previous_estimate() {
210 let mut aggregator = aggregator();
211 let advancer = advancer();
212 assert_eq!(advancer.can_send_precommit(7000, &aggregator), None);
214 aggregator
215 .add(vote(1, ROUND, true, 10, &chain(10, 14)))
216 .unwrap();
217 assert_eq!(advancer.can_send_precommit(7000, &aggregator), None);
218
219 for seed in 2..=3 {
221 aggregator
222 .add(vote(seed, ROUND, true, 10, &chain(10, 14)))
223 .unwrap();
224 }
225 assert_eq!(advancer.can_send_precommit(6999, &aggregator), None);
226 assert_eq!(
227 advancer.can_send_precommit(7000, &aggregator),
228 Some((14, block_hash(14, 0)))
229 );
230 assert!(!advancer.can_start_next_round(&aggregator));
231
232 let mut forked = MultiRoundAggregator::new(
234 PARAMETERS,
235 usize::MAX,
236 FinalizationRound { epoch: 3, point: 1 },
237 (10, block_hash(10, 1)),
238 );
239 forked.set_voting_set(3, voting_set());
240 forked.set_max_round(ROUND);
241 for seed in 1..=3 {
242 forked
243 .add(vote(seed, ROUND, true, 10, &chain(10, 14)))
244 .unwrap();
245 }
246 assert_eq!(advancer.can_send_precommit(9000, &forked), None);
247 }
248
249 #[test]
250 fn sends_a_precommit_before_two_steps_when_completable() {
251 let mut aggregator = aggregator();
252 let advancer = advancer();
253 for seed in 1..=3 {
254 aggregator
255 .add(vote(seed, ROUND, true, 10, &chain(10, 14)))
256 .unwrap();
257 aggregator
258 .add(vote(seed, ROUND, false, 14, &chain(14, 14)))
259 .unwrap();
260 }
261 assert_eq!(
262 advancer.can_send_precommit(5000, &aggregator),
263 Some((14, block_hash(14, 0)))
264 );
265 }
266}