types.rs
1 use std::collections::BTreeMap; 2 3 use serde::{Deserialize, Serialize}; 4 5 /// Unique identifier for a node in the network 6 pub type NodeId = u64; 7 8 /// Height of an event in the chain 9 pub type Height = u64; 10 11 /// The content of an event (could be any data) 12 pub type EventContent = u64; 13 14 /// An event in the consensus chain 15 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] 16 pub struct Event { 17 /// The creator of this event 18 pub creator: NodeId, 19 /// The height of this event in the chain 20 pub height: Height, 21 /// Hash of the previous event this one builds on 22 pub prev_hash: Option<String>, 23 /// Content of the event 24 pub content: EventContent, 25 /// Hash of this event (computed when created) 26 pub hash: String, 27 } 28 29 impl Event { 30 /// Create a new event 31 pub fn new( 32 creator: NodeId, 33 height: Height, 34 prev_hash: Option<String>, 35 content: EventContent, 36 ) -> Self { 37 let mut event = Self { 38 creator, 39 height, 40 prev_hash, 41 content, 42 hash: String::new(), 43 }; 44 // Simple hash computation for demonstration purposes 45 event.hash = event.compute_hash(); 46 event 47 } 48 49 /// Compute the hash of this event 50 fn compute_hash(&self) -> String { 51 use std::collections::hash_map::DefaultHasher; 52 use std::hash::{Hash, Hasher}; 53 54 let mut hasher = DefaultHasher::new(); 55 self.creator.hash(&mut hasher); 56 self.height.hash(&mut hasher); 57 if let Some(prev) = &self.prev_hash { 58 prev.hash(&mut hasher); 59 } 60 self.content.hash(&mut hasher); 61 format!("{:x}", hasher.finish()) 62 } 63 64 /// Validate that this event is correctly formed 65 pub fn is_valid(&self) -> bool { 66 self.hash == self.compute_hash() 67 } 68 } 69 70 /// The state of the consensus for a node 71 #[derive(Clone, Debug)] 72 pub struct ConsensusState { 73 /// The node's own ID 74 pub node_id: NodeId, 75 /// The chain of events, indexed by height 76 pub chain: BTreeMap<Height, Event>, 77 /// The maximum number of faulty nodes the system can tolerate 78 pub f: usize, 79 /// Total number of nodes in the system 80 pub n: usize, 81 /// The height of the last event this node has created 82 pub last_created_height: Option<Height>, 83 }