|
| 1 | +//! Kora block type using alloy types. |
| 2 | +
|
| 3 | +use alloy_consensus::Header; |
| 4 | +use alloy_primitives::{B256, keccak256}; |
| 5 | +use alloy_rlp::Encodable; |
| 6 | + |
| 7 | +/// Block type for Kora consensus. |
| 8 | +/// |
| 9 | +/// Uses alloy types directly for Ethereum compatibility. |
| 10 | +#[derive(Clone, Debug)] |
| 11 | +pub struct KoraBlock { |
| 12 | + /// Block header. |
| 13 | + pub header: Header, |
| 14 | + /// Transactions in the block (encoded). |
| 15 | + pub transactions: Vec<Vec<u8>>, |
| 16 | + /// Computed state root. |
| 17 | + pub state_root: B256, |
| 18 | +} |
| 19 | + |
| 20 | +impl KoraBlock { |
| 21 | + /// Create a new block. |
| 22 | + pub const fn new(header: Header, transactions: Vec<Vec<u8>>, state_root: B256) -> Self { |
| 23 | + Self { header, transactions, state_root } |
| 24 | + } |
| 25 | + |
| 26 | + /// Compute the block's hash from the header. |
| 27 | + pub fn hash(&self) -> B256 { |
| 28 | + let mut buf = Vec::new(); |
| 29 | + self.header.encode(&mut buf); |
| 30 | + keccak256(&buf) |
| 31 | + } |
| 32 | + |
| 33 | + /// Get the parent block's hash. |
| 34 | + pub const fn parent_hash(&self) -> B256 { |
| 35 | + self.header.parent_hash |
| 36 | + } |
| 37 | + |
| 38 | + /// Get the block height. |
| 39 | + pub const fn height(&self) -> u64 { |
| 40 | + self.header.number |
| 41 | + } |
| 42 | + |
| 43 | + /// Get the block timestamp. |
| 44 | + pub const fn timestamp(&self) -> u64 { |
| 45 | + self.header.timestamp |
| 46 | + } |
| 47 | + |
| 48 | + /// Get the number of transactions. |
| 49 | + pub const fn tx_count(&self) -> usize { |
| 50 | + self.transactions.len() |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +impl Default for KoraBlock { |
| 55 | + fn default() -> Self { |
| 56 | + Self { header: Header::default(), transactions: Vec::new(), state_root: B256::ZERO } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +#[cfg(test)] |
| 61 | +mod tests { |
| 62 | + use super::*; |
| 63 | + |
| 64 | + #[test] |
| 65 | + fn block_default() { |
| 66 | + let block = KoraBlock::default(); |
| 67 | + assert_eq!(block.height(), 0); |
| 68 | + assert_eq!(block.tx_count(), 0); |
| 69 | + assert_eq!(block.state_root, B256::ZERO); |
| 70 | + } |
| 71 | + |
| 72 | + #[test] |
| 73 | + fn block_hash_deterministic() { |
| 74 | + let block = KoraBlock::default(); |
| 75 | + let hash1 = block.hash(); |
| 76 | + let hash2 = block.hash(); |
| 77 | + assert_eq!(hash1, hash2); |
| 78 | + } |
| 79 | +} |
0 commit comments