1use serde::{Deserialize, Serialize};
2use sha2::{Digest, Sha256};
3
4pub type Hash = [u8; 32];
5pub type NodeId = u64;
6
7pub fn hash(data: &[u8]) -> Hash {
8 Sha256::digest(data).into()
9}
10
11pub fn hex(h: &Hash) -> String {
12 h.iter().map(|b| format!("{:02x}", b)).collect()
13}
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
16pub enum Role {
17 Proposer,
18 Validator,
19 Packer,
20 Normal,
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
24pub enum Stage {
25 Idle,
26 PrePrepare,
27 Prepare,
28 Commit,
29 Reply,
30 Done,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct Block {
35 pub round: u64,
36 pub prev_hash: Hash,
37 pub proposer: NodeId,
38 pub seed: u64,
39 pub data_hashes: Vec<Hash>,
40}
41
42impl Block {
43 pub fn new(round: u64, prev_hash: Hash, proposer: NodeId, seed: u64) -> Self {
44 Self {
45 round,
46 prev_hash,
47 proposer,
48 seed,
49 data_hashes: Vec::new(),
50 }
51 }
52
53 pub fn hash(&self) -> Hash {
54 let bytes = bincode::serialize(self).expect("block serialization failed");
55 hash(&bytes)
56 }
57
58 pub fn genesis() -> Self {
59 Self::new(0, [0u8; 32], 0, 0)
60 }
61}