Skip to main content

heika_finalization/
epoch.rs

1//! エポックの切り替えと、集まったメッセージからの確定。catapult の `FinalizationOrchestratorService` の
2//! `calculateEpochStatus` と、`CreateFinalizer`。
3
4use heika_block::finalization::FinalizedBlockHeader;
5use heika_block::finalization::aggregator::MultiRoundAggregator;
6use heika_block::finalization::proof::build_proof;
7use heika_core::hash::Hash256;
8
9/// 段取り役のエポックをどうするか
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum EpochStatus {
12    /// 今のエポックのまま進める
13    Continue,
14    /// エポックの最後のブロックが確定したが、手元のチェーンがまだそこに届いていないか、違うブロックを持っている。
15    /// 追いつくまで投票しない
16    Wait,
17    /// このエポックに移る
18    Advance(u32),
19}
20
21/// 段取り役がエポック `epoch` にいて、最後の確定が `finalized` のときにどうするか。`local_hash_at` は手元の
22/// チェーンのその高さのブロックのハッシュ(まだなければ `None`)
23pub fn epoch_status(
24    epoch: u32,
25    finalized: &FinalizedBlockHeader,
26    voting_set_grouping: u64,
27    local_hash_at: impl FnOnce(u64) -> Option<Hash256>,
28) -> EpochStatus {
29    let ahead = finalized.round.epoch > epoch;
30    let epoch_end = match epoch {
31        0 | 1 => 1,
32        epoch => (u64::from(epoch) - 1) * voting_set_grouping,
33    };
34    if !ahead && finalized.height != epoch_end {
35        return EpochStatus::Continue;
36    }
37    if local_hash_at(finalized.height) != Some(finalized.hash) {
38        return EpochStatus::Wait;
39    }
40    EpochStatus::Advance(finalized.round.epoch + 1)
41}
42
43/// 集まったメッセージで確定したブロックと、その証明
44#[derive(Clone, Debug, PartialEq, Eq)]
45pub struct Finalized {
46    pub header: FinalizedBlockHeader,
47    pub proof: Vec<u8>,
48}
49
50/// best precommit があり、その高さが最後の確定(`finalized_height`)と違えば、確定して証明を組む。確定したら、
51/// そのひとつ前のエポックまでのメッセージを捨てる(catapult の `CreateFinalizer`)
52pub fn finalize(aggregator: &mut MultiRoundAggregator, finalized_height: u64) -> Option<Finalized> {
53    let best = aggregator.best_precommit()?;
54    if best.target.0 == finalized_height {
55        return None;
56    }
57    let header = FinalizedBlockHeader {
58        round: best.round,
59        height: best.target.0,
60        hash: best.target.1,
61    };
62    let proof = build_proof(&header, best.messages);
63    aggregator.prune(header.round.epoch.saturating_sub(1));
64    Some(Finalized { header, proof })
65}
66
67#[cfg(test)]
68mod tests {
69    use heika_block::finalization::FinalizationRound;
70    use heika_block::finalization::proof::verify_proof;
71
72    use super::*;
73    use crate::stage::tests::{PARAMETERS, ROUND, aggregator, block_hash, chain, vote, voting_set};
74
75    fn finalized(epoch: u32, height: u64) -> FinalizedBlockHeader {
76        FinalizedBlockHeader {
77            round: FinalizationRound { epoch, point: 5 },
78            height,
79            hash: block_hash(height, 0),
80        }
81    }
82
83    #[test]
84    fn moves_to_the_next_epoch_once_its_last_block_is_finalized_locally() {
85        let local = |height| Some(block_hash(height, 0));
86        // エポック 3 は高さ 20 で終わる(グループは 10)
87        assert_eq!(
88            epoch_status(3, &finalized(3, 15), 10, local),
89            EpochStatus::Continue
90        );
91        assert_eq!(
92            epoch_status(3, &finalized(3, 20), 10, local),
93            EpochStatus::Advance(4)
94        );
95        // 手元が届いていない、違うブロックを持っている
96        assert_eq!(
97            epoch_status(3, &finalized(3, 20), 10, |_| None),
98            EpochStatus::Wait
99        );
100        assert_eq!(
101            epoch_status(3, &finalized(3, 20), 10, |height| Some(block_hash(
102                height, 1
103            ))),
104            EpochStatus::Wait
105        );
106        // 確定がもっと先のエポックにある(追いついたあと)
107        assert_eq!(
108            epoch_status(3, &finalized(6, 52), 10, local),
109            EpochStatus::Advance(7)
110        );
111    }
112
113    #[test]
114    fn finalizes_the_best_precommit_once() {
115        let mut aggregator = aggregator();
116        assert_eq!(finalize(&mut aggregator, 10), None);
117        for seed in 1..=3 {
118            aggregator
119                .add(vote(seed, ROUND, true, 10, &chain(10, 14)))
120                .unwrap();
121            aggregator
122                .add(vote(seed, ROUND, false, 14, &chain(14, 14)))
123                .unwrap();
124        }
125        let done = finalize(&mut aggregator, 10).unwrap();
126        assert_eq!(done.header.round, ROUND);
127        assert_eq!(done.header.height, 14);
128        assert_eq!(
129            verify_proof(&done.proof, 3, &voting_set(), &PARAMETERS),
130            Ok(done.header)
131        );
132        // 同じ高さはもう確定しない
133        assert_eq!(finalize(&mut aggregator, 14), None);
134        // 前のエポック(2)までを捨てるので、エポック 3 は残る
135        assert_eq!(aggregator.len(), 1);
136    }
137}