use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
pub type Hash = [u8; 32];
pub type NodeId = u64;
pub fn hash(data: &[u8]) -> Hash {
Sha256::digest(data).into()
}
pub fn hex(h: &Hash) -> String {
h.iter().map(|b| format!("{:02x}", b)).collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Role {
Proposer,
Validator,
Packer,
Normal,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Stage {
Idle,
PrePrepare,
Prepare,
Commit,
Reply,
Done,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Block {
pub round: u64,
pub prev_hash: Hash,
pub proposer: NodeId,
pub seed: u64,
pub data_hashes: Vec<Hash>,
}
impl Block {
pub fn new(round: u64, prev_hash: Hash, proposer: NodeId, seed: u64) -> Self {
Self {
round,
prev_hash,
proposer,
seed,
data_hashes: Vec::new(),
}
}
pub fn hash(&self) -> Hash {
let bytes = bincode::serialize(self).expect("block serialization failed");
hash(&bytes)
}
pub fn genesis() -> Self {
Self::new(0, [0u8; 32], 0, 0)
}
}