Skip to main content

heika_block/finalization/
aggregator.rs

1//! 投票のメッセージを集める。catapult の `chain::RoundMessageAggregator` と `chain::MultiRoundMessageAggregator`。
2//!
3//! [`RoundAggregator`] は1つのラウンドのメッセージを確かめて覚え、[`RoundContext`] で数える。
4//! [`MultiRoundAggregator`] は、最小から最大のラウンドまでの [`RoundAggregator`] を並べて持つ。最大のラウンドは
5//! 投票の段取り役が進め、最小のラウンドは、ファイナライズしたら前のエポックを捨てて進める。
6
7use alloc::collections::{BTreeMap, BTreeSet};
8use alloc::sync::Arc;
9use alloc::vec::Vec;
10
11use super::FinalizationRound;
12use super::message::FinalizationMessage;
13use super::proof::{MessageError, ProofParameters, VotingSet};
14use super::round::{Candidate, RoundContext};
15
16/// 足せたメッセージの段階
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum Added {
19    Prevote,
20    Precommit,
21}
22
23/// 1つのラウンドのメッセージ。catapult の `RoundMessageAggregator`
24#[derive(Debug)]
25pub struct RoundAggregator {
26    epoch: u32,
27    voters: Arc<VotingSet>,
28    parameters: ProofParameters,
29    /// 投票者を決めた高さ
30    voting_set_height: u64,
31    /// (投票者、prevote か)→(メッセージ、そのハッシュ)
32    messages: BTreeMap<([u8; 32], bool), (FinalizationMessage, [u8; 32])>,
33    round: RoundContext,
34}
35
36impl RoundAggregator {
37    /// エポック `epoch` のラウンド。投票者は `voters`
38    pub fn new(epoch: u32, voters: Arc<VotingSet>, parameters: ProofParameters) -> Self {
39        let total = voters.total();
40        // catapult は u64 のまま掛ける
41        let threshold = total.wrapping_mul(parameters.threshold) / parameters.size;
42        Self {
43            epoch,
44            voting_set_height: parameters.voting_set_end_height(epoch.saturating_sub(1).max(1)),
45            voters,
46            parameters,
47            messages: BTreeMap::new(),
48            round: RoundContext::new(total, threshold),
49        }
50    }
51
52    /// 覚えているメッセージの数
53    pub fn len(&self) -> usize {
54        self.messages.len()
55    }
56
57    pub fn is_empty(&self) -> bool {
58        self.messages.is_empty()
59    }
60
61    pub fn round(&self) -> &RoundContext {
62        &self.round
63    }
64
65    /// 覚えているメッセージ。投票者の鍵と段階の順
66    pub fn messages(&self) -> impl Iterator<Item = &FinalizationMessage> {
67        self.messages.values().map(|(message, _)| message)
68    }
69
70    /// 覚えているメッセージの短いハッシュ
71    pub fn short_hashes(&self) -> impl Iterator<Item = u32> {
72        self.messages
73            .values()
74            .map(|(_, hash)| u32::from_le_bytes(hash[..4].try_into().expect("4 bytes")))
75    }
76
77    /// 短いハッシュが `known` にないメッセージ。合わせて `max_size` バイトまで
78    pub fn unknown_messages(
79        &self,
80        known: &BTreeSet<u32>,
81        max_size: usize,
82    ) -> Vec<&FinalizationMessage> {
83        let mut size = 0;
84        let mut out = Vec::new();
85        for (message, hash) in self.messages.values() {
86            if known.contains(&u32::from_le_bytes(hash[..4].try_into().expect("4 bytes"))) {
87                continue;
88            }
89            size += message.size();
90            if size > max_size {
91                break;
92            }
93            out.push(message);
94        }
95        out
96    }
97
98    /// メッセージを確かめて足す。catapult の `RoundMessageAggregator::add` と同じ順で確かめる
99    pub fn add(&mut self, message: FinalizationMessage) -> Result<Added, MessageError> {
100        let count = message.hashes.len() as u64;
101        if count == 0 || count > self.parameters.max_hashes_per_point {
102            return Err(MessageError::InvalidHashes);
103        }
104        let last_height = message.last_height();
105        // 投票者を決めた高さ以降のハッシュを1つも含まないものは数えない
106        if self.voting_set_height > last_height {
107            return Err(MessageError::InvalidHeight);
108        }
109        if message.is_prevote {
110            let min = self
111                .parameters
112                .voting_set_end_height(message.round.epoch.saturating_sub(1).max(1));
113            let max = self.parameters.voting_set_end_height(message.round.epoch);
114            if message.height < min || last_height > max {
115                return Err(MessageError::InvalidHashes);
116            }
117        } else if count != 1 {
118            return Err(MessageError::InvalidHashes);
119        }
120
121        let key = (message.root_key(), message.is_prevote);
122        let hash = message.hash();
123        if let Some((_, existing)) = self.messages.get(&key) {
124            return Err(if *existing == hash {
125                MessageError::Redundant
126            } else {
127                MessageError::Conflicting
128            });
129        }
130        // catapult の `ProcessMessage`。予約と版は読んだときに確かめてある
131        let weight = self.voters.voters.get(&key.0).copied().unwrap_or(0);
132        if weight == 0 {
133            return Err(MessageError::Voter);
134        }
135        if !message.verify_signature() {
136            return Err(MessageError::Signature);
137        }
138        let added = if message.is_prevote {
139            self.round
140                .accept_prevote(message.height, &message.hashes, weight);
141            Added::Prevote
142        } else {
143            self.round
144                .accept_precommit(message.height, message.hashes[0], weight);
145            Added::Precommit
146        };
147        debug_assert_eq!(message.round.epoch, self.epoch);
148        self.messages.insert(key, (message, hash));
149        Ok(added)
150    }
151}
152
153/// ファイナライズできたブロックと、その証明にするメッセージ。catapult の `BestPrecommitDescriptor`
154#[derive(Debug)]
155pub struct BestPrecommit<'a> {
156    pub round: FinalizationRound,
157    pub target: Candidate,
158    pub messages: Vec<&'a FinalizationMessage>,
159}
160
161/// 足せなかったわけのうち、ラウンドごとの集計の前で弾いたもの
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163pub enum MultiRoundError {
164    /// 集めている範囲(最小から最大のラウンド)の外。catapult の `Failure_Invalid_Point`
165    Round,
166    /// そのエポックの投票者をまだ知らない
167    NoVotingSet,
168    Message(MessageError),
169}
170
171/// 最小から最大のラウンドまでのメッセージ。catapult の `MultiRoundMessageAggregator`
172#[derive(Debug)]
173pub struct MultiRoundAggregator {
174    parameters: ProofParameters,
175    /// 引かれたときに返すメッセージの、合わせた大きさの上限(`messageSynchronizationMaxResponseSize`)
176    max_response_size: usize,
177    min_round: FinalizationRound,
178    max_round: FinalizationRound,
179    /// 始めたときに最後にファイナライズしていたブロック。estimate がどのラウンドにもなければこれ
180    previous_finalized: Candidate,
181    voting_sets: BTreeMap<u32, Arc<VotingSet>>,
182    rounds: BTreeMap<FinalizationRound, RoundAggregator>,
183}
184
185impl MultiRoundAggregator {
186    /// 最後にファイナライズしたのが、ラウンド `round` のブロック `previous_finalized`。最小も最大も `round` から始める
187    pub fn new(
188        parameters: ProofParameters,
189        max_response_size: usize,
190        round: FinalizationRound,
191        previous_finalized: Candidate,
192    ) -> Self {
193        Self {
194            parameters,
195            max_response_size,
196            min_round: round,
197            max_round: round,
198            previous_finalized,
199            voting_sets: BTreeMap::new(),
200            rounds: BTreeMap::new(),
201        }
202    }
203
204    pub fn min_round(&self) -> FinalizationRound {
205        self.min_round
206    }
207
208    pub fn max_round(&self) -> FinalizationRound {
209        self.max_round
210    }
211
212    /// 持っているラウンドの数
213    pub fn len(&self) -> usize {
214        self.rounds.len()
215    }
216
217    pub fn is_empty(&self) -> bool {
218        self.rounds.is_empty()
219    }
220
221    /// エポック `epoch` の投票者を教える。そのエポックのメッセージは、教わるまで足せない
222    pub fn set_voting_set(&mut self, epoch: u32, voters: Arc<VotingSet>) {
223        self.voting_sets.insert(epoch, voters);
224    }
225
226    /// エポック `epoch` の投票者を知っているか
227    pub fn has_voting_set(&self, epoch: u32) -> bool {
228        self.voting_sets.contains_key(&epoch)
229    }
230
231    /// 集める範囲の最大を `round` にする。
232    ///
233    /// # Panics
234    ///
235    /// 最小より前にはできない(catapult も例外にする)
236    pub fn set_max_round(&mut self, round: FinalizationRound) {
237        assert!(
238            round >= self.min_round,
239            "集める範囲の最大を、最小より前にはできません"
240        );
241        self.max_round = round;
242    }
243
244    /// メッセージを足す。範囲の中なら、足せなくてもそのラウンドの集計は作る(catapult と同じ)
245    pub fn add(&mut self, message: FinalizationMessage) -> Result<Added, MultiRoundError> {
246        let round = message.round;
247        if round < self.min_round || round > self.max_round {
248            return Err(MultiRoundError::Round);
249        }
250        let aggregator = match self.rounds.entry(round) {
251            alloc::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
252            alloc::collections::btree_map::Entry::Vacant(entry) => {
253                let voters = self
254                    .voting_sets
255                    .get(&round.epoch)
256                    .ok_or(MultiRoundError::NoVotingSet)?;
257                entry.insert(RoundAggregator::new(
258                    round.epoch,
259                    voters.clone(),
260                    self.parameters,
261                ))
262            }
263        };
264        aggregator.add(message).map_err(MultiRoundError::Message)
265    }
266
267    /// ラウンド `round` の数え方。まだメッセージがなければ `None`
268    pub fn round(&self, round: FinalizationRound) -> Option<&RoundContext> {
269        self.rounds.get(&round).map(RoundAggregator::round)
270    }
271
272    /// `round` かそれより前のラウンドのうち、いちばん新しい estimate。catapult の `findEstimate`
273    pub fn find_estimate(&self, round: FinalizationRound) -> Candidate {
274        self.rounds
275            .range(..=round)
276            .rev()
277            .find_map(|(_, aggregator)| aggregator.round().estimate())
278            .unwrap_or(self.previous_finalized)
279    }
280
281    /// best precommit のある、いちばん新しいラウンド。証明にするメッセージは、そのラウンドの全部
282    /// (合わせて `max_response_size` まで)
283    pub fn best_precommit(&self) -> Option<BestPrecommit<'_>> {
284        self.rounds.iter().rev().find_map(|(round, aggregator)| {
285            aggregator
286                .round()
287                .best_precommit()
288                .map(|target| BestPrecommit {
289                    round: *round,
290                    target,
291                    messages: aggregator.unknown_messages(&BTreeSet::new(), self.max_response_size),
292                })
293        })
294    }
295
296    /// 持っているメッセージ全部の短いハッシュ
297    pub fn short_hashes(&self) -> Vec<u32> {
298        self.rounds
299            .values()
300            .flat_map(RoundAggregator::short_hashes)
301            .collect()
302    }
303
304    /// ラウンド `min` から `max` までのメッセージのうち、短いハッシュが `known` にないもの。合わせて
305    /// `max_response_size` バイトまで
306    pub fn unknown_messages(
307        &self,
308        min: FinalizationRound,
309        max: FinalizationRound,
310        known: &BTreeSet<u32>,
311    ) -> Vec<&FinalizationMessage> {
312        let mut size = 0;
313        let mut out = Vec::new();
314        for (round, aggregator) in &self.rounds {
315            if *round < min || *round > max {
316                continue;
317            }
318            for message in aggregator.unknown_messages(known, self.max_response_size) {
319                size += message.size();
320                if size > self.max_response_size {
321                    return out;
322                }
323                out.push(message);
324            }
325        }
326        out
327    }
328
329    /// エポック `epoch` より前のラウンドを捨て、最小をいちばん古く残ったラウンドにする(なければ最大)
330    pub fn prune(&mut self, epoch: u32) {
331        let keep = self
332            .rounds
333            .split_off(&FinalizationRound { epoch, point: 0 });
334        self.rounds = keep;
335        self.min_round = self.rounds.keys().next().copied().unwrap_or(self.max_round);
336        self.voting_sets.retain(|known, _| *known >= epoch);
337    }
338}
339
340#[cfg(test)]
341mod tests {
342    use heika_core::hash::Hash256;
343
344    use super::super::message::testing::{Voter, block_hash, chain};
345    use super::*;
346
347    /// エポックは 10 ブロック。エポック 3 の prevote は高さ 10〜20
348    const PARAMETERS: ProofParameters = ProofParameters {
349        voting_set_grouping: 10,
350        size: 10_000,
351        threshold: 6_700,
352        max_hashes_per_point: 256,
353    };
354
355    fn round(epoch: u32, point: u32) -> FinalizationRound {
356        FinalizationRound { epoch, point }
357    }
358
359    /// 重み 40、30、30 の3人。閾値は 67
360    fn voters() -> [Voter; 3] {
361        [Voter::new(1), Voter::new(2), Voter::new(3)]
362    }
363
364    fn voting_set(voters: &[Voter]) -> Arc<VotingSet> {
365        Arc::new(VotingSet {
366            voters: voters
367                .iter()
368                .zip([40, 30, 30])
369                .map(|(voter, weight)| (voter.key(), weight))
370                .collect(),
371        })
372    }
373
374    #[test]
375    fn checks_messages_in_the_order_catapult_does() {
376        let voters = voters();
377        let [a, b, ..] = &voters;
378        let mut aggregator = RoundAggregator::new(3, voting_set(&voters), PARAMETERS);
379        let at = round(3, 1);
380        assert_eq!(
381            aggregator.add(a.message(at, true, 10, Vec::new())),
382            Err(MessageError::InvalidHashes)
383        );
384        // 投票者を決めた高さ(10)より前で終わる
385        assert_eq!(
386            aggregator.add(a.message(at, false, 9, chain(9, 9))),
387            Err(MessageError::InvalidHeight)
388        );
389        // prevote はエポックの中(10〜20)
390        assert_eq!(
391            aggregator.add(a.message(at, true, 15, chain(15, 21))),
392            Err(MessageError::InvalidHashes)
393        );
394        assert_eq!(
395            aggregator.add(a.message(at, false, 15, chain(15, 16))),
396            Err(MessageError::InvalidHashes)
397        );
398        assert_eq!(
399            aggregator.add(Voter::new(9).message(at, true, 10, chain(10, 15))),
400            Err(MessageError::Voter)
401        );
402        let mut broken = b.message(at, true, 10, chain(10, 15));
403        broken.hashes[5] = block_hash(15, 1);
404        assert_eq!(aggregator.add(broken), Err(MessageError::Signature));
405        assert!(aggregator.is_empty());
406
407        let prevote = a.message(at, true, 10, chain(10, 15));
408        assert_eq!(aggregator.add(prevote.clone()), Ok(Added::Prevote));
409        assert_eq!(aggregator.add(prevote), Err(MessageError::Redundant));
410        assert_eq!(
411            aggregator.add(a.message(at, true, 10, chain(10, 14))),
412            Err(MessageError::Conflicting)
413        );
414        assert_eq!(
415            aggregator.add(a.message(at, false, 15, chain(15, 15))),
416            Ok(Added::Precommit)
417        );
418        assert_eq!(aggregator.len(), 2);
419        assert_eq!(
420            aggregator.round().weights((12, block_hash(12, 0))).prevote,
421            40
422        );
423    }
424
425    #[test]
426    fn finalizes_when_enough_weight_votes() {
427        let voters = voters();
428        let mut aggregator = RoundAggregator::new(3, voting_set(&voters), PARAMETERS);
429        let at = round(3, 1);
430        for voter in &voters[..2] {
431            aggregator
432                .add(voter.message(at, true, 10, chain(10, 15)))
433                .unwrap();
434        }
435        assert_eq!(
436            aggregator.round().best_prevote(),
437            Some((15, block_hash(15, 0)))
438        );
439        assert_eq!(aggregator.round().best_precommit(), None);
440        for voter in &voters[..2] {
441            aggregator
442                .add(voter.message(at, false, 14, chain(14, 14)))
443                .unwrap();
444        }
445        // 40 + 30 = 70 で閾値の 67 を超える
446        assert_eq!(
447            aggregator.round().best_precommit(),
448            Some((14, block_hash(14, 0)))
449        );
450    }
451
452    #[test]
453    fn hands_out_only_unknown_messages_up_to_the_size_limit() {
454        let voters = voters();
455        let mut aggregator = RoundAggregator::new(3, voting_set(&voters), PARAMETERS);
456        let messages: Vec<_> = voters
457            .iter()
458            .map(|voter| voter.message(round(3, 1), true, 10, chain(10, 15)))
459            .collect();
460        for message in &messages {
461            aggregator.add(message.clone()).unwrap();
462        }
463        let all = aggregator.unknown_messages(&BTreeSet::new(), usize::MAX);
464        assert_eq!(all.len(), 3);
465        let known: BTreeSet<u32> = [messages[0].short_hash()].into();
466        let unknown = aggregator.unknown_messages(&known, usize::MAX);
467        assert_eq!(unknown.len(), 2);
468        assert!(!unknown.contains(&&messages[0]));
469        // 1つ分と少しの大きさなら、1つだけ
470        let one = aggregator.unknown_messages(&BTreeSet::new(), messages[0].size() + 1);
471        assert_eq!(one.len(), 1);
472        let short: BTreeSet<u32> = aggregator.short_hashes().collect();
473        assert_eq!(
474            short,
475            messages
476                .iter()
477                .map(FinalizationMessage::short_hash)
478                .collect()
479        );
480    }
481
482    fn multi() -> MultiRoundAggregator {
483        let mut aggregator =
484            MultiRoundAggregator::new(PARAMETERS, usize::MAX, round(3, 1), (10, block_hash(10, 0)));
485        let voters = voters();
486        aggregator.set_voting_set(3, voting_set(&voters));
487        aggregator.set_voting_set(4, voting_set(&voters));
488        aggregator
489    }
490
491    #[test]
492    fn accepts_only_rounds_between_min_and_max() {
493        let [a, ..] = voters();
494        let mut aggregator = multi();
495        assert_eq!(
496            (aggregator.min_round(), aggregator.max_round()),
497            (round(3, 1), round(3, 1))
498        );
499        let prevote = |at| a.message(at, true, 10, chain(10, 15));
500        assert_eq!(
501            aggregator.add(prevote(round(3, 0))),
502            Err(MultiRoundError::Round)
503        );
504        assert_eq!(
505            aggregator.add(prevote(round(3, 2))),
506            Err(MultiRoundError::Round)
507        );
508        aggregator.set_max_round(round(3, 3));
509        assert_eq!(aggregator.add(prevote(round(3, 3))), Ok(Added::Prevote));
510        assert_eq!(aggregator.add(prevote(round(3, 1))), Ok(Added::Prevote));
511        // 足せなくても、そのラウンドの集計は作る
512        assert_eq!(
513            aggregator.add(a.message(round(3, 2), true, 10, Vec::new())),
514            Err(MultiRoundError::Message(MessageError::InvalidHashes))
515        );
516        assert_eq!(aggregator.len(), 3);
517        assert!(aggregator.round(round(3, 2)).unwrap().is_empty());
518        // 投票者を知らないエポック
519        aggregator.set_max_round(round(5, 1));
520        assert_eq!(
521            aggregator.add(a.message(round(5, 1), true, 40, chain(40, 41))),
522            Err(MultiRoundError::NoVotingSet)
523        );
524    }
525
526    #[test]
527    #[should_panic(expected = "最小より前")]
528    fn refuses_a_max_round_below_the_min() {
529        multi().set_max_round(round(3, 0));
530    }
531
532    #[test]
533    fn finds_the_estimate_and_best_precommit_in_the_newest_round_that_has_one() {
534        let voters = voters();
535        let mut aggregator = multi();
536        aggregator.set_max_round(round(3, 4));
537        assert_eq!(
538            aggregator.find_estimate(round(3, 4)),
539            (10, block_hash(10, 0))
540        );
541        assert!(aggregator.best_precommit().is_none());
542
543        // ラウンド 1 で高さ 14 が確定、ラウンド 2 は prevote だけ
544        for voter in &voters {
545            aggregator
546                .add(voter.message(round(3, 1), true, 10, chain(10, 15)))
547                .unwrap();
548            aggregator
549                .add(voter.message(round(3, 1), false, 14, chain(14, 14)))
550                .unwrap();
551            aggregator
552                .add(voter.message(round(3, 2), true, 14, chain(14, 18)))
553                .unwrap();
554        }
555        let best = aggregator.best_precommit().unwrap();
556        assert_eq!(
557            (best.round, best.target),
558            (round(3, 1), (14, block_hash(14, 0)))
559        );
560        assert_eq!(best.messages.len(), 6);
561        // ラウンド 2 は estimate が best prevote の 18。ラウンド 4 から見ても、いちばん新しいのはラウンド 2
562        assert_eq!(
563            aggregator.find_estimate(round(3, 4)),
564            (18, block_hash(18, 0))
565        );
566        assert_eq!(
567            aggregator.find_estimate(round(3, 1)),
568            (14, block_hash(14, 0))
569        );
570        assert_eq!(
571            aggregator.find_estimate(round(3, 0)),
572            (10, block_hash(10, 0))
573        );
574    }
575
576    #[test]
577    fn hands_out_unknown_messages_within_the_requested_rounds() {
578        let voters = voters();
579        let mut aggregator = multi();
580        aggregator.set_max_round(round(4, 2));
581        let mut messages = Vec::new();
582        for (at, height) in [(round(3, 1), 10), (round(3, 2), 12), (round(4, 1), 20)] {
583            for voter in &voters {
584                let message = voter.message(at, true, height, chain(height, height + 2));
585                aggregator.add(message.clone()).unwrap();
586                messages.push(message);
587            }
588        }
589        assert_eq!(aggregator.short_hashes().len(), 9);
590        let all = BTreeSet::new();
591        assert_eq!(
592            aggregator
593                .unknown_messages(round(3, 0), round(9, 0), &all)
594                .len(),
595            9
596        );
597        assert_eq!(
598            aggregator
599                .unknown_messages(round(3, 2), round(4, 1), &all)
600                .len(),
601            6
602        );
603        let known: BTreeSet<u32> = messages[..4]
604            .iter()
605            .map(FinalizationMessage::short_hash)
606            .collect();
607        assert_eq!(
608            aggregator
609                .unknown_messages(round(3, 0), round(9, 0), &known)
610                .len(),
611            5
612        );
613
614        let mut limited = MultiRoundAggregator::new(
615            PARAMETERS,
616            messages[0].size() * 2,
617            round(3, 1),
618            (10, Hash256([0; 32])),
619        );
620        limited.set_voting_set(3, voting_set(&voters));
621        limited.set_max_round(round(3, 2));
622        for message in &messages[..6] {
623            limited.add(message.clone()).unwrap();
624        }
625        assert_eq!(
626            limited
627                .unknown_messages(round(3, 0), round(9, 0), &all)
628                .len(),
629            2
630        );
631    }
632
633    #[test]
634    fn prunes_epochs_before_the_given_one() {
635        let voters = voters();
636        let mut aggregator = multi();
637        aggregator.prune(3);
638        assert_eq!(aggregator.min_round(), round(3, 1));
639
640        aggregator.set_max_round(round(4, 2));
641        for (at, height) in [(round(3, 1), 10), (round(3, 2), 12), (round(4, 1), 20)] {
642            aggregator
643                .add(voters[0].message(at, true, height, chain(height, height + 2)))
644                .unwrap();
645        }
646        aggregator.prune(3);
647        assert_eq!((aggregator.len(), aggregator.min_round()), (3, round(3, 1)));
648        aggregator.prune(4);
649        assert_eq!((aggregator.len(), aggregator.min_round()), (1, round(4, 1)));
650        assert!(!aggregator.has_voting_set(3));
651        assert!(aggregator.has_voting_set(4));
652        // 全部捨てると、最小は最大になる
653        aggregator.prune(5);
654        assert_eq!((aggregator.len(), aggregator.min_round()), (0, round(4, 2)));
655    }
656}