1use alloc::collections::BTreeMap;
16
17use heika_core::hash::Hash256;
18
19pub type Candidate = (u64, Hash256);
21
22#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
24pub struct Weights {
25 pub prevote: u64,
26 pub precommit: u64,
27}
28
29#[derive(Debug)]
31pub struct RoundContext {
32 total_weight: u64,
33 threshold: u64,
34 cumulative_precommit_weight: u64,
36 candidates: BTreeMap<(u64, [u8; 32]), Weights>,
38 parents: BTreeMap<Candidate, Option<Candidate>>,
40 pending_precommits: BTreeMap<Candidate, u64>,
42}
43
44impl RoundContext {
45 pub fn new(total_weight: u64, threshold: u64) -> Self {
47 Self {
48 total_weight,
49 threshold,
50 cumulative_precommit_weight: 0,
51 candidates: BTreeMap::new(),
52 parents: BTreeMap::new(),
53 pending_precommits: BTreeMap::new(),
54 }
55 }
56
57 pub fn len(&self) -> usize {
59 self.candidates.len()
60 }
61
62 pub fn is_empty(&self) -> bool {
63 self.candidates.is_empty()
64 }
65
66 pub fn weights(&self, candidate: Candidate) -> Weights {
68 self.candidates
69 .get(&(candidate.0, candidate.1.0))
70 .copied()
71 .unwrap_or_default()
72 }
73
74 pub fn best_prevote(&self) -> Option<Candidate> {
76 self.last_match(|_, weights| weights.prevote >= self.threshold)
77 }
78
79 pub fn best_precommit(&self) -> Option<Candidate> {
81 self.last_match(|_, weights| {
82 weights.prevote >= self.threshold && weights.precommit >= self.threshold
83 })
84 }
85
86 pub fn estimate(&self) -> Option<Candidate> {
88 self.estimate_below(self.best_prevote()?)
89 }
90
91 pub fn is_descendant(&self, parent: Candidate, child: Candidate) -> bool {
93 let mut current = self.parents.contains_key(&child).then_some(child);
94 while let Some(node) = current {
95 if node == parent {
96 return true;
97 }
98 current = self.parents[&node];
99 }
100 false
101 }
102
103 pub fn is_completable(&self) -> bool {
105 let Some(best_prevote) = self.best_prevote() else {
106 return false;
107 };
108 if self
110 .estimate_below(best_prevote)
111 .is_some_and(|estimate| estimate != best_prevote)
112 {
113 return true;
114 }
115 if self.can_reach_precommit_threshold(Weights::default()) {
117 return false;
118 }
119 !self
120 .candidates
121 .iter()
122 .rev()
123 .map(|(&(height, hash), weights)| ((height, Hash256(hash)), weights))
124 .any(|(candidate, weights)| {
125 candidate != best_prevote
126 && self.is_descendant(best_prevote, candidate)
127 && self.can_reach_precommit_threshold(*weights)
128 })
129 }
130
131 pub fn accept_prevote(&mut self, height: u64, hashes: &[Hash256], weight: u64) {
133 let mut parent = None;
134 for (index, hash) in hashes.iter().enumerate() {
135 let key = (height + index as u64, *hash);
136 self.parents.entry(key).or_insert(parent);
137 parent = Some(key);
138 }
139 for (index, hash) in hashes.iter().enumerate() {
140 let key = (height + index as u64, *hash);
141 let weights = self.candidates.entry((key.0, key.1.0)).or_default();
142 weights.prevote = weights.prevote.wrapping_add(weight);
143 if let Some(pending) = self.pending_precommits.remove(&key) {
144 self.add_precommit(key, pending);
145 }
146 }
147 }
148
149 pub fn accept_precommit(&mut self, height: u64, hash: Hash256, weight: u64) {
151 let key = (height, hash);
152 if self.parents.contains_key(&key) {
153 self.add_precommit(key, weight);
154 } else {
155 let pending = self.pending_precommits.entry(key).or_default();
156 *pending = pending.wrapping_add(weight);
157 }
158 }
159
160 fn add_precommit(&mut self, key: Candidate, weight: u64) {
162 let mut current = Some(key);
163 while let Some(node) = current {
164 let weights = self
165 .candidates
166 .get_mut(&(node.0, node.1.0))
167 .expect("木にあるブロックには prevote がある");
168 weights.precommit = weights.precommit.wrapping_add(weight);
169 current = self.parents[&node];
170 }
171 self.cumulative_precommit_weight = self.cumulative_precommit_weight.wrapping_add(weight);
172 }
173
174 fn can_reach_precommit_threshold(&self, weights: Weights) -> bool {
176 weights.precommit.wrapping_add(
177 self.total_weight
178 .wrapping_sub(self.cumulative_precommit_weight),
179 ) >= self.threshold
180 }
181
182 fn estimate_below(&self, best_prevote: Candidate) -> Option<Candidate> {
183 self.last_match(|candidate, weights| {
184 self.is_descendant(candidate, best_prevote)
185 && self.can_reach_precommit_threshold(*weights)
186 })
187 }
188
189 fn last_match(&self, predicate: impl Fn(Candidate, &Weights) -> bool) -> Option<Candidate> {
191 self.candidates
192 .iter()
193 .rev()
194 .map(|(&(height, hash), weights)| ((height, Hash256(hash)), weights))
195 .find(|(candidate, weights)| predicate(*candidate, weights))
196 .map(|(candidate, _)| candidate)
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203
204 fn branch(branch: u8, count: usize) -> Vec<Hash256> {
206 (0..count)
207 .map(|index| {
208 let mut hash = [branch; 32];
209 hash[0] = index as u8;
210 Hash256(hash)
211 })
212 .collect()
213 }
214
215 fn unknown() -> Hash256 {
216 Hash256([0xEE; 32])
217 }
218
219 fn weights(prevote: u64, precommit: u64) -> Weights {
220 Weights { prevote, precommit }
221 }
222
223 #[test]
224 fn starts_empty() {
225 let context = RoundContext::new(1000, 670);
226 assert!(context.is_empty());
227 assert_eq!(context.best_prevote(), None);
228 assert_eq!(context.best_precommit(), None);
229 assert_eq!(context.estimate(), None);
230 assert!(!context.is_completable());
231 }
232
233 fn two_prevoted_branches(count: usize) -> (RoundContext, Vec<Hash256>, Vec<Hash256>) {
235 let (first, second) = (branch(1, count), branch(2, count));
236 let mut context = RoundContext::new(1000, 670);
237 context.accept_prevote(7, &first, 669);
238 context.accept_prevote(7, &second, 100);
239 (context, first, second)
240 }
241
242 #[test]
243 fn finds_the_best_prevote_at_or_above_the_threshold() {
244 let (context, ..) = two_prevoted_branches(3);
245 assert_eq!(context.best_prevote(), None);
246
247 let (mut context, hashes, _) = two_prevoted_branches(3);
249 context.accept_prevote(7, &hashes[..2], 1);
250 assert_eq!(context.best_prevote(), Some((8, hashes[1])));
251 assert_eq!(context.best_precommit(), None);
252
253 let (mut context, hashes, _) = two_prevoted_branches(3);
255 context.accept_prevote(7, &hashes[..2], 31);
256 context.accept_prevote(7, &hashes[..1], 100);
257 assert_eq!(context.best_prevote(), Some((8, hashes[1])));
258 }
259
260 fn two_precommitted_branches() -> (RoundContext, Vec<Hash256>) {
262 let (mut context, first, second) = two_prevoted_branches(4);
263 context.accept_precommit(9, first[2], 669);
264 context.accept_precommit(9, second[2], 150);
265 (context, first)
266 }
267
268 #[test]
269 fn needs_both_prevotes_and_precommits_for_the_best_precommit() {
270 let (context, _) = two_precommitted_branches();
271 assert_eq!(context.best_precommit(), None);
272
273 let (mut context, hashes) = two_precommitted_branches();
275 context.accept_precommit(9, hashes[2], 100);
276 assert_eq!(context.best_precommit(), None);
277 assert_eq!(context.best_prevote(), None);
278
279 let (mut context, hashes) = two_precommitted_branches();
281 context.accept_prevote(7, &hashes, 100);
282 assert_eq!(context.best_precommit(), None);
283 assert_eq!(context.best_prevote(), Some((10, hashes[3])));
284
285 let (mut context, hashes) = two_precommitted_branches();
287 context.accept_prevote(7, &hashes[..3], 1);
288 context.accept_precommit(8, hashes[1], 1);
289 assert_eq!(context.best_precommit(), Some((8, hashes[1])));
290 assert_eq!(context.best_prevote(), Some((9, hashes[2])));
291
292 let (mut context, hashes) = two_precommitted_branches();
294 context.accept_prevote(7, &hashes[..3], 31);
295 context.accept_prevote(7, &hashes[..2], 100);
296 context.accept_precommit(8, hashes[1], 21);
297 context.accept_precommit(7, hashes[0], 100);
298 assert_eq!(context.best_precommit(), Some((8, hashes[1])));
299 assert_eq!(context.best_prevote(), Some((9, hashes[2])));
300 }
301
302 #[test]
303 fn ignores_precommits_for_unknown_blocks() {
304 let (mut context, hashes, _) = two_prevoted_branches(3);
305 context.accept_prevote(7, &hashes[..2], 100);
306 context.accept_precommit(9, unknown(), 750);
307 context.accept_precommit(9, Hash256([0xDD; 32]), 150);
308 assert_eq!(context.best_precommit(), None);
309 assert_eq!(context.best_prevote(), Some((8, hashes[1])));
310 }
311
312 fn forked() -> (RoundContext, Vec<Hash256>, Vec<Hash256>) {
320 let first = branch(1, 4);
321 let mut second = branch(2, 3);
322 second[0] = first[2];
323 let third = branch(3, 5);
324 let mut context = RoundContext::new(1000, 670);
325 context.accept_prevote(7, &first, 10);
326 context.accept_prevote(9, &second, 10);
327 context.accept_prevote(7, &third, 10);
328 (context, first, third)
329 }
330
331 #[test]
332 fn estimates_the_highest_block_that_can_still_be_precommitted() {
333 let (mut context, first, _) = forked();
335 context.accept_precommit(9, first[2], 700);
336 assert_eq!(context.estimate(), None);
337 assert!(!context.is_completable());
338
339 let (mut context, first, third) = forked();
341 context.accept_prevote(7, &first, 700);
342 context.accept_precommit(9, first[2], 350);
343 context.accept_precommit(9, third[2], 350);
344 assert_eq!(context.estimate(), None);
345 assert!(context.is_completable());
346
347 let (mut context, first, _) = forked();
349 context.accept_prevote(7, &first[..3], 700);
350 context.accept_precommit(9, first[2], 700);
351 assert_eq!(context.estimate(), Some((9, first[2])));
352 assert!(context.is_completable());
353
354 let (mut context, first, _) = forked();
356 context.accept_prevote(7, &first[..3], 700);
357 context.accept_precommit(9, first[2], 400);
358 assert_eq!(context.estimate(), Some((9, first[2])));
359 assert!(context.is_completable());
360
361 let (mut context, first, _) = forked();
363 context.accept_prevote(7, &first[..3], 700);
364 context.accept_precommit(8, first[1], 400);
365 assert_eq!(context.estimate(), Some((8, first[1])));
366 assert!(context.is_completable());
367
368 let (mut context, first, third) = forked();
370 context.accept_prevote(7, &first[..3], 700);
371 context.accept_precommit(9, first[2], 200);
372 context.accept_precommit(11, third[4], 200);
373 assert_eq!(context.estimate(), Some((9, first[2])));
374 assert!(context.is_completable());
375 }
376
377 #[test]
378 fn leaves_pending_precommits_out_of_the_estimate_until_their_prevote() {
379 let (mut context, first, _) = forked();
380 context.accept_prevote(7, &first[..3], 700);
381 context.accept_precommit(9, first[2], 400);
382 context.accept_precommit(10, unknown(), 500);
383 assert_eq!(context.estimate(), Some((9, first[2])));
384 assert!(context.is_completable());
385
386 context.accept_prevote(10, &[unknown()], 10);
388 assert_eq!(context.estimate(), None);
389 assert!(context.is_completable());
390 }
391
392 #[test]
393 fn follows_the_tree_for_descendants() {
394 let first = branch(1, 4);
398 let mut second = branch(2, 4);
399 second[0] = first[1];
400 second[1] = first[2];
401 let mut context = RoundContext::new(1000, 670);
402 context.accept_prevote(7, &first, 250);
403 context.accept_prevote(8, &second, 200);
404 assert!(!context.is_descendant((11, second[3]), (9, first[2])));
405 assert!(context.is_descendant((9, first[2]), (9, first[2])));
406 assert!(context.is_descendant((9, first[2]), (11, second[3])));
407 assert!(!context.is_descendant((9, first[0]), (11, second[3])));
408 assert!(!context.is_descendant((9, first[2]), (11, second[0])));
409 }
410
411 #[test]
412 fn completes_only_when_no_descendant_of_the_best_prevote_can_win() {
413 let (mut context, first, _) = forked();
415 context.accept_prevote(7, &first[..3], 700);
416 context.accept_precommit(9, first[2], 200);
417 assert!(!context.is_completable());
418 assert_eq!(context.estimate(), Some((9, first[2])));
419
420 let (mut context, first, third) = forked();
422 context.accept_prevote(7, &first[..3], 700);
423 context.accept_precommit(9, first[2], 200);
424 context.accept_precommit(9, third[2], 200);
425 assert!(context.is_completable());
426
427 let (mut context, first, _) = forked();
429 context.accept_prevote(7, &first[..3], 700);
430 context.accept_precommit(10, first[3], 400);
431 assert!(!context.is_completable());
432 assert_eq!(context.estimate(), Some((9, first[2])));
433
434 context.accept_precommit(10, unknown(), 500);
436 assert!(!context.is_completable());
437 context.accept_prevote(9, &[first[2], unknown()], 10);
438 assert!(context.is_completable());
439 assert_eq!(context.estimate(), Some((9, first[2])));
440 }
441
442 #[test]
443 fn adds_weights_along_overlapping_branches() {
444 let hashes = branch(1, 3);
445 let mut context = RoundContext::new(1000, 670);
446 context.accept_prevote(7, &hashes, 250);
447 assert_eq!(context.len(), 3);
448 assert_eq!(context.weights((8, hashes[1])), weights(250, 0));
449 assert_eq!(context.weights((11, hashes[0])), Weights::default());
450 assert_eq!(context.weights((8, unknown())), Weights::default());
451
452 let first = branch(1, 4);
456 let mut second = branch(2, 4);
457 second[0] = first[1];
458 second[1] = first[2];
459 for precommits_first in [false, true] {
460 let mut context = RoundContext::new(1000, 670);
461 let precommit = |context: &mut RoundContext| {
462 context.accept_precommit(10, first[3], 100);
463 context.accept_precommit(10, second[2], 150);
464 context.accept_precommit(8, first[1], 50);
465 };
466 if precommits_first {
467 precommit(&mut context);
468 assert!(context.is_empty());
469 }
470 context.accept_prevote(7, &first, 250);
471 context.accept_prevote(8, &second, 200);
472 if !precommits_first {
473 precommit(&mut context);
474 }
475 assert_eq!(context.len(), 6);
476 assert_eq!(context.weights((7, first[0])), weights(250, 300));
477 assert_eq!(context.weights((8, first[1])), weights(450, 300));
478 assert_eq!(context.weights((9, first[2])), weights(450, 250));
479 assert_eq!(context.weights((10, first[3])), weights(250, 100));
480 assert_eq!(context.weights((10, second[2])), weights(200, 150));
481 assert_eq!(context.weights((11, second[3])), weights(200, 0));
482 }
483 }
484
485 #[test]
486 fn adds_up_precommits_that_wait_for_the_same_block() {
487 let first = branch(1, 3);
488 let second = branch(2, 4);
489 let mut context = RoundContext::new(1000, 670);
490 context.accept_precommit(8, first[1], 75);
491 context.accept_precommit(8, first[1], 25);
492 context.accept_precommit(10, second[2], 110);
493 context.accept_precommit(10, second[2], 40);
494 context.accept_prevote(7, &first, 250);
495 context.accept_prevote(8, &second, 200);
496 assert_eq!(context.len(), 7);
497 assert_eq!(context.weights((7, first[0])), weights(250, 100));
498 assert_eq!(context.weights((8, first[1])), weights(250, 100));
499 assert_eq!(context.weights((9, first[2])), weights(250, 0));
500 assert_eq!(context.weights((8, second[0])), weights(200, 150));
501 assert_eq!(context.weights((10, second[2])), weights(200, 150));
502 assert_eq!(context.weights((11, second[3])), weights(200, 0));
503 }
504}