1use heika_block::finalization::FinalizationRound;
11use heika_block::finalization::aggregator::MultiRoundAggregator;
12use heika_block::finalization::message::FinalizationMessage;
13use heika_block::finalization::round::Candidate;
14
15use crate::stage::StageAdvancer;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub struct VotingStatus {
20 pub round: FinalizationRound,
21 pub sent_prevote: bool,
22 pub sent_precommit: bool,
23}
24
25impl VotingStatus {
26 pub fn at(round: FinalizationRound) -> Self {
28 Self {
29 round,
30 sent_prevote: false,
31 sent_precommit: false,
32 }
33 }
34
35 pub fn to_bytes(&self) -> [u8; 10] {
37 let mut out = [0; 10];
38 out[..4].copy_from_slice(&self.round.epoch.to_le_bytes());
39 out[4..8].copy_from_slice(&self.round.point.to_le_bytes());
40 out[8] = u8::from(self.sent_prevote);
41 out[9] = u8::from(self.sent_precommit);
42 out
43 }
44
45 pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
46 let bytes: &[u8; 10] = bytes.try_into().ok()?;
47 Some(Self {
48 round: FinalizationRound {
49 epoch: u32::from_le_bytes(bytes[..4].try_into().expect("4 bytes")),
50 point: u32::from_le_bytes(bytes[4..8].try_into().expect("4 bytes")),
51 },
52 sent_prevote: bytes[8] != 0,
53 sent_precommit: bytes[9] != 0,
54 })
55 }
56}
57
58pub trait MessageFactory {
60 fn prevote(&mut self, round: FinalizationRound) -> Option<FinalizationMessage>;
61 fn precommit(
62 &mut self,
63 round: FinalizationRound,
64 target: Candidate,
65 ) -> Option<FinalizationMessage>;
66}
67
68#[derive(Clone, Copy, Debug, Default)]
70pub struct NoVotes;
71
72impl MessageFactory for NoVotes {
73 fn prevote(&mut self, _: FinalizationRound) -> Option<FinalizationMessage> {
74 None
75 }
76
77 fn precommit(&mut self, _: FinalizationRound, _: Candidate) -> Option<FinalizationMessage> {
78 None
79 }
80}
81
82#[derive(Debug)]
84pub struct Orchestrator {
85 status: VotingStatus,
86 step_duration: u64,
87 advancer: Option<StageAdvancer>,
88}
89
90impl Orchestrator {
91 pub fn new(status: VotingStatus, step_duration: u64) -> Self {
93 Self {
94 status,
95 step_duration,
96 advancer: None,
97 }
98 }
99
100 pub fn status(&self) -> VotingStatus {
101 self.status
102 }
103
104 pub fn set_epoch(&mut self, epoch: u32) {
110 assert!(
111 epoch >= self.status.round.epoch,
112 "エポックは戻せません({} → {epoch})",
113 self.status.round.epoch
114 );
115 if epoch == self.status.round.epoch {
116 return;
117 }
118 self.status = VotingStatus::at(FinalizationRound { epoch, point: 1 });
119 self.advancer = None;
120 }
121
122 pub fn poll(
125 &mut self,
126 time: u64,
127 aggregator: &MultiRoundAggregator,
128 factory: &mut dyn MessageFactory,
129 eligible: &dyn Fn(&FinalizationMessage) -> bool,
130 ) -> Vec<FinalizationMessage> {
131 let mut sent = Vec::new();
132 let advancer = *self
133 .advancer
134 .get_or_insert_with(|| StageAdvancer::new(self.status.round, time, self.step_duration));
135 if !self.status.sent_prevote && advancer.can_send_prevote(time, aggregator) {
136 sent.extend(factory.prevote(self.status.round).filter(|m| eligible(m)));
137 self.status.sent_prevote = true;
138 }
139 if !self.status.sent_precommit
140 && let Some(target) = advancer.can_send_precommit(time, aggregator)
141 {
142 sent.extend(
143 factory
144 .precommit(self.status.round, target)
145 .filter(|m| eligible(m)),
146 );
147 self.status.sent_precommit = true;
148 }
149 if self.status.sent_precommit && advancer.can_start_next_round(aggregator) {
150 let next = FinalizationRound {
151 epoch: self.status.round.epoch,
152 point: self.status.round.point + 1,
153 };
154 self.status = VotingStatus::at(next);
155 self.advancer = Some(StageAdvancer::new(next, time, self.step_duration));
156 }
157 sent
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use heika_block::finalization::round::Candidate;
164
165 use super::*;
166 use crate::stage::tests::{ROUND, STEP, aggregator, block_hash, chain, vote};
167
168 #[derive(Default)]
170 struct Voter {
171 prevotes: Vec<FinalizationRound>,
172 precommits: Vec<(FinalizationRound, Candidate)>,
173 }
174
175 impl MessageFactory for Voter {
176 fn prevote(&mut self, round: FinalizationRound) -> Option<FinalizationMessage> {
177 self.prevotes.push(round);
178 Some(vote(1, round, true, 10, &chain(10, 14)))
179 }
180
181 fn precommit(
182 &mut self,
183 round: FinalizationRound,
184 target: Candidate,
185 ) -> Option<FinalizationMessage> {
186 self.precommits.push((round, target));
187 Some(vote(1, round, false, target.0, &[target.1]))
188 }
189 }
190
191 fn everyone(round: FinalizationRound) -> Vec<FinalizationMessage> {
192 (1..=3)
193 .flat_map(|seed| {
194 [
195 vote(seed, round, true, 10, &chain(10, 14)),
196 vote(seed, round, false, 14, &chain(14, 14)),
197 ]
198 })
199 .collect()
200 }
201
202 #[test]
203 fn sends_each_stage_once_and_moves_to_the_next_point() {
204 let mut aggregator = aggregator();
205 let mut orchestrator = Orchestrator::new(VotingStatus::at(ROUND), STEP);
206 let mut voter = Voter::default();
207 let anyone = |_: &FinalizationMessage| true;
208
209 assert!(
211 orchestrator
212 .poll(0, &aggregator, &mut voter, &anyone)
213 .is_empty()
214 );
215 let sent = orchestrator.poll(STEP, &aggregator, &mut voter, &anyone);
217 assert_eq!(sent.len(), 1);
218 assert!(sent[0].is_prevote);
219 assert!(
220 orchestrator
221 .poll(STEP, &aggregator, &mut voter, &anyone)
222 .is_empty()
223 );
224 assert_eq!(voter.prevotes, [ROUND]);
225
226 for message in everyone(ROUND) {
228 let _ = aggregator.add(message);
229 }
230 let sent = orchestrator.poll(STEP + 1, &aggregator, &mut voter, &anyone);
231 assert_eq!(sent.len(), 1);
232 assert_eq!(voter.precommits, [(ROUND, (14, block_hash(14, 0)))]);
233 let next = FinalizationRound { epoch: 3, point: 3 };
234 assert_eq!(orchestrator.status(), VotingStatus::at(next));
235 }
236
237 #[test]
238 fn moves_on_without_keys() {
239 let mut aggregator = aggregator();
240 for message in everyone(ROUND) {
241 aggregator.add(message).unwrap();
242 }
243 let mut orchestrator = Orchestrator::new(VotingStatus::at(ROUND), STEP);
244 assert!(
246 orchestrator
247 .poll(0, &aggregator, &mut NoVotes, &|_| true)
248 .is_empty()
249 );
250 assert_eq!(
251 orchestrator.status(),
252 VotingStatus::at(FinalizationRound { epoch: 3, point: 3 })
253 );
254 }
255
256 #[test]
257 fn drops_messages_from_ineligible_keys_but_still_moves_on() {
258 let mut aggregator = aggregator();
259 for message in everyone(ROUND) {
260 aggregator.add(message).unwrap();
261 }
262 let mut orchestrator = Orchestrator::new(VotingStatus::at(ROUND), STEP);
263 let mut voter = Voter::default();
264 assert!(
265 orchestrator
266 .poll(0, &aggregator, &mut voter, &|_| false)
267 .is_empty()
268 );
269 assert_eq!(voter.prevotes.len(), 1);
270 assert_eq!(voter.precommits.len(), 1);
271 assert_eq!(orchestrator.status().round.point, 3);
272 }
273
274 #[test]
275 fn keeps_what_was_sent_before_a_restart() {
276 let mut aggregator = aggregator();
277 let status = VotingStatus {
278 round: ROUND,
279 sent_prevote: true,
280 sent_precommit: false,
281 };
282 let mut orchestrator = Orchestrator::new(status, STEP);
283 let mut voter = Voter::default();
284 for message in everyone(ROUND) {
285 aggregator.add(message).unwrap();
286 }
287 orchestrator.poll(0, &aggregator, &mut voter, &|_| true);
288 assert!(voter.prevotes.is_empty());
289 assert_eq!(voter.precommits.len(), 1);
290 }
291
292 #[test]
293 fn moves_to_a_later_epoch_only() {
294 let mut orchestrator = Orchestrator::new(VotingStatus::at(ROUND), STEP);
295 orchestrator.set_epoch(3);
296 assert_eq!(orchestrator.status(), VotingStatus::at(ROUND));
297 orchestrator.set_epoch(5);
298 assert_eq!(
299 orchestrator.status(),
300 VotingStatus::at(FinalizationRound { epoch: 5, point: 1 })
301 );
302 let result = std::panic::catch_unwind(move || orchestrator.set_epoch(4));
303 assert!(result.is_err());
304 }
305
306 #[test]
307 fn writes_the_voting_status_like_catapult() {
308 let status = VotingStatus {
309 round: FinalizationRound {
310 epoch: 0x0102,
311 point: 7,
312 },
313 sent_prevote: true,
314 sent_precommit: false,
315 };
316 assert_eq!(status.to_bytes(), [2, 1, 0, 0, 7, 0, 0, 0, 1, 0]);
317 assert_eq!(VotingStatus::from_bytes(&status.to_bytes()), Some(status));
318 assert_eq!(VotingStatus::from_bytes(&[0; 9]), None);
319 }
320}