Skip to main content

heika_block/
finalization.rs

1//! ファイナライズ。catbuffer の `finalization/`。
2//!
3//! 投票でファイナライズされたブロックを、ラウンド(エポックとポイント)、高さ、ハッシュで示す。
4//! 投票のメッセージは [`message`]、1つのラウンドの投票の数え方は [`round`]、メッセージを集めるのは
5//! [`aggregator`]、証明を投票者で確かめるのは [`proof`]。
6
7pub mod aggregator;
8pub mod message;
9pub mod proof;
10pub mod round;
11
12use core::fmt;
13
14use heika_core::hash::Hash256;
15
16/// ファイナライズの投票のラウンド。catbuffer の `FinalizationRound`。
17#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
18pub struct FinalizationRound {
19    pub epoch: u32,
20    pub point: u32,
21}
22
23/// ファイナライズされたブロック。catbuffer の `FinalizedBlockHeader`。
24#[derive(Clone, Copy, PartialEq, Eq, Debug)]
25pub struct FinalizedBlockHeader {
26    pub round: FinalizationRound,
27    pub height: u64,
28    pub hash: Hash256,
29}
30
31impl FinalizedBlockHeader {
32    /// ラウンド(エポック、ポイント)、高さ、ハッシュ。
33    pub const SIZE: usize = 4 + 4 + 8 + 32;
34
35    pub fn to_bytes(&self) -> [u8; Self::SIZE] {
36        let mut bytes = [0; Self::SIZE];
37        bytes[..4].copy_from_slice(&self.round.epoch.to_le_bytes());
38        bytes[4..8].copy_from_slice(&self.round.point.to_le_bytes());
39        bytes[8..16].copy_from_slice(&self.height.to_le_bytes());
40        bytes[16..].copy_from_slice(&self.hash.0);
41        bytes
42    }
43
44    pub fn from_bytes(bytes: &[u8]) -> Result<Self, InvalidFinalizedBlockHeaderSize> {
45        let bytes: &[u8; Self::SIZE] = bytes
46            .try_into()
47            .map_err(|_| InvalidFinalizedBlockHeaderSize(bytes.len()))?;
48        Ok(Self {
49            round: FinalizationRound {
50                epoch: u32::from_le_bytes(bytes[..4].try_into().expect("4 bytes")),
51                point: u32::from_le_bytes(bytes[4..8].try_into().expect("4 bytes")),
52            },
53            height: u64::from_le_bytes(bytes[8..16].try_into().expect("8 bytes")),
54            hash: Hash256(bytes[16..].try_into().expect("32 bytes")),
55        })
56    }
57}
58
59/// 長さが [`FinalizedBlockHeader::SIZE`] ではない。
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct InvalidFinalizedBlockHeaderSize(pub usize);
62
63impl fmt::Display for InvalidFinalizedBlockHeaderSize {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        write!(
66            f,
67            "ファイナライズされたブロックは {} バイトですが、{} バイトでした",
68            FinalizedBlockHeader::SIZE,
69            self.0
70        )
71    }
72}
73
74impl core::error::Error for InvalidFinalizedBlockHeaderSize {}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[test]
81    fn writes_the_round_height_and_hash_in_order() {
82        let header = FinalizedBlockHeader {
83            round: FinalizationRound {
84                epoch: 0x0102,
85                point: 3,
86            },
87            height: 0x0405,
88            hash: Hash256([6; 32]),
89        };
90        let bytes = header.to_bytes();
91        assert_eq!(
92            bytes[..16],
93            [2, 1, 0, 0, 3, 0, 0, 0, 5, 4, 0, 0, 0, 0, 0, 0]
94        );
95        assert_eq!(FinalizedBlockHeader::from_bytes(&bytes), Ok(header));
96        assert_eq!(
97            FinalizedBlockHeader::from_bytes(&bytes[..47]),
98            Err(InvalidFinalizedBlockHeaderSize(47))
99        );
100    }
101}