node.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. use chrono::Utc;
  2. use std::{
  3. collections::hash_map::DefaultHasher,
  4. hash::{Hash, Hasher},
  5. };
  6. use super::{block::Block, blockchain::Blockchain, vote::Vote};
  7. /// This struct represents a protocol node.
  8. /// Each node is numbered and has a secret-public keys pair, to sign messages.
  9. /// Nodes hold a set of Blockchains(some of which are not notarized)
  10. /// and a set of unconfirmed pending transactions.
  11. #[derive(Debug)]
  12. pub struct Node {
  13. pub id: u64,
  14. pub genesis_time: i64,
  15. pub password: String,
  16. pub private_key: String,
  17. pub public_key: String,
  18. pub canonical_blockchain: Blockchain,
  19. pub node_blockchains: Vec<Blockchain>,
  20. pub unconfirmed_transactions: Vec<String>,
  21. }
  22. impl Node {
  23. pub fn new(id: u64, genesis_time: i64, password: String, init_block: Block) -> Node {
  24. // TODO: add keypair generation, clock sync
  25. Node {
  26. id,
  27. genesis_time,
  28. password,
  29. private_key: String::from("private_key"),
  30. public_key: String::from("public_key"),
  31. canonical_blockchain: Blockchain::new(init_block),
  32. node_blockchains: Vec::new(),
  33. unconfirmed_transactions: Vec::new(),
  34. }
  35. }
  36. /// A nodes output is the finalized (canonical) blockchain they hold.
  37. pub fn output(&self) -> &Blockchain {
  38. &self.canonical_blockchain
  39. }
  40. /// Node retreives a transaction and append it to the unconfirmed transactions list.
  41. /// Additional validity rules must be defined by the protocol for its blockchain data structure.
  42. pub fn receive_transaction(&mut self, transaction: String) {
  43. self.unconfirmed_transactions.push(transaction);
  44. }
  45. /// Node broadcast a transaction to provided nodes list.
  46. pub fn broadcast_transaction(&mut self, nodes: Vec<&mut Node>, transaction: String) {
  47. for node in nodes {
  48. node.receive_transaction(transaction.clone())
  49. }
  50. }
  51. /// Node calculates current epoch, based on elapsed time from the genesis block.
  52. /// Epochs duration is configured using the delta value.
  53. pub fn get_current_epoch(&self) -> i64 {
  54. let delta = 2;
  55. let current_time = Utc::now().timestamp();
  56. ((current_time - self.genesis_time) % (2 * delta)) + 1
  57. }
  58. /// Node finds epochs leader, using a simple hash method.
  59. /// Leader calculation is based on how many nodes are participating in the network.
  60. pub fn get_epoch_leader(&self, nodes_count: u64) -> u64 {
  61. let epoch = self.get_current_epoch();
  62. let mut hasher = DefaultHasher::new();
  63. epoch.hash(&mut hasher);
  64. hasher.finish() % nodes_count
  65. }
  66. /// Node checks if they are the current epoch leader.
  67. pub fn check_if_epoch_leader(&self, nodes_count: u64) -> bool {
  68. let leader = self.get_epoch_leader(nodes_count);
  69. self.id == leader
  70. }
  71. /// Node generates a block for the current, containing all uncorfirmed transactions.
  72. /// Block extends the longest notarized blockchain the node holds.
  73. pub fn propose_block(&self) -> Block {
  74. let epoch = self.get_current_epoch();
  75. let longest_notarized_chain = self.find_longest_notarized_chain();
  76. let mut hasher = DefaultHasher::new();
  77. longest_notarized_chain.blocks.last().unwrap().hash(&mut hasher);
  78. let proposed_block =
  79. Block::new(hasher.finish().to_string(), epoch, self.unconfirmed_transactions.clone());
  80. // TODO: add block signing.
  81. proposed_block
  82. }
  83. /// Node receives the proposed block, verifies its sender(epoch leader), and proceeds with voting on it.
  84. pub fn receive_proposed_block(&mut self, proposed_block: &Block) -> Option<Vote> {
  85. // TODO: verify leader keys.
  86. self.vote_block(proposed_block)
  87. }
  88. /// Given a block, node finds which blockchain it extends.
  89. /// If block extends the canonical blockchain, a new fork blockchain is created.
  90. /// Node votes on the block, only if it extends the longest notarized chain it has seen.
  91. pub fn vote_block(&mut self, block: &Block) -> Option<Vote> {
  92. let index = self.find_extended_blockchain_index(block);
  93. let blockchain = if index == -1 {
  94. let blockchain = Blockchain::new(block.clone());
  95. self.node_blockchains.push(blockchain);
  96. self.node_blockchains.last().unwrap()
  97. } else {
  98. self.node_blockchains[index as usize].add_block(&block);
  99. &self.node_blockchains[index as usize]
  100. };
  101. if self.extends_notarized_blockchain(blockchain) {
  102. // TODO: add block signing.
  103. return Some(Vote::new(String::from("signed_block"), block.clone(), self.id))
  104. }
  105. None
  106. }
  107. /// Node verifies if provided blockchain is notarized excluding the last block.
  108. pub fn extends_notarized_blockchain(&self, blockchain: &Blockchain) -> bool {
  109. for block in &blockchain.blocks[..(blockchain.blocks.len() - 1)] {
  110. if !block.notarized {
  111. return false
  112. }
  113. }
  114. true
  115. }
  116. /// Given a block, node finds the index of the blockchain it extends.
  117. pub fn find_extended_blockchain_index(&self, block: &Block) -> i64 {
  118. let mut hasher = DefaultHasher::new();
  119. for (index, blockchain) in self.node_blockchains.iter().enumerate() {
  120. blockchain.blocks.last().unwrap().hash(&mut hasher);
  121. if block.h == hasher.finish().to_string() &&
  122. block.e > blockchain.blocks.last().unwrap().e
  123. {
  124. return index as i64
  125. }
  126. }
  127. self.canonical_blockchain.blocks.last().unwrap().hash(&mut hasher);
  128. if block.h != hasher.finish().to_string() ||
  129. block.e <= self.canonical_blockchain.blocks.last().unwrap().e
  130. {
  131. panic!("Proposed block doesn't extend any known chains.");
  132. }
  133. -1
  134. }
  135. /// Finds the longest fully notarized blockchain the node holds.
  136. pub fn find_longest_notarized_chain(&self) -> &Blockchain {
  137. let mut longest_notarized_chain = &self.canonical_blockchain;
  138. let mut length = 0;
  139. for blockchain in &self.node_blockchains {
  140. if blockchain.is_notarized() && blockchain.blocks.len() > length {
  141. length = blockchain.blocks.len();
  142. longest_notarized_chain = &blockchain;
  143. }
  144. }
  145. &longest_notarized_chain
  146. }
  147. /// Node receives a vote for a block.
  148. /// First, sender is verified using their public key.
  149. /// Block is searched in nodes blockchains.
  150. /// If the vote wasn't received before, it is appended to block votes list.
  151. /// When a node sees 2n/3 votes for a block it notarizes it.
  152. /// When a block gets notarized, the transactions it contains are removed from
  153. /// nodes unconfirmed transactions list.
  154. /// Finally, we check if the notarization of the block can finalize parent blocks
  155. /// in its blockchain.
  156. pub fn receive_vote(&mut self, vote: &Vote, nodes_count: usize) -> Option<Vote> {
  157. // TODO: verify vote signature.
  158. let vote_block = self.find_block(&vote.block);
  159. if vote_block == None {
  160. return self.vote_block(&vote.block)
  161. }
  162. let (unwrapped_vote_block, blockchain_index) = vote_block.unwrap();
  163. if !unwrapped_vote_block.votes.contains(vote) {
  164. unwrapped_vote_block.votes.push(vote.clone());
  165. }
  166. if !unwrapped_vote_block.notarized &&
  167. unwrapped_vote_block.votes.len() > (2 * nodes_count / 3)
  168. {
  169. unwrapped_vote_block.notarized = true;
  170. for transaction in unwrapped_vote_block.txs.clone() {
  171. let txs_clone = transaction.clone();
  172. if let Some(pos) =
  173. self.unconfirmed_transactions.iter().position(|txs| *txs == txs_clone)
  174. {
  175. self.unconfirmed_transactions.remove(pos);
  176. }
  177. }
  178. self.check_blockchain_finalization(blockchain_index);
  179. }
  180. None
  181. }
  182. /// Node searches it the blockchains it holds for provided block.
  183. pub fn find_block(&mut self, vote_block: &Block) -> Option<(&mut Block, i64)> {
  184. for (index, blockchain) in &mut self.node_blockchains.iter_mut().enumerate() {
  185. for block in blockchain.blocks.iter_mut().rev() {
  186. if vote_block == block {
  187. return Some((block, index as i64))
  188. }
  189. }
  190. }
  191. for block in &mut self.canonical_blockchain.blocks.iter_mut().rev() {
  192. if vote_block == block {
  193. return Some((block, -1))
  194. }
  195. }
  196. None
  197. }
  198. /// Node checks if the index blockchain can be finalized.
  199. /// Consensus finalization logic: If node has observed the notarization of 3 consecutive
  200. /// blocks in a fork chain, it finalizes (appends to canonical blockchain) all blocks up to the middle block.
  201. /// When fork chain blocks are finalized, rest fork chains not starting by those blocks are removed.
  202. pub fn check_blockchain_finalization(&mut self, blockchain_index: i64) {
  203. let blockchain = if blockchain_index == -1 {
  204. &mut self.canonical_blockchain
  205. } else {
  206. &mut self.node_blockchains[blockchain_index as usize]
  207. };
  208. let blockchain_len = blockchain.blocks.len();
  209. if blockchain_len > 2 {
  210. let mut consecutive_notarized = 0;
  211. for block in &blockchain.blocks {
  212. if block.notarized {
  213. consecutive_notarized = consecutive_notarized + 1;
  214. } else {
  215. break
  216. }
  217. }
  218. if consecutive_notarized > 2 {
  219. let mut finalized_blocks = Vec::new();
  220. for block in &mut blockchain.blocks[..(consecutive_notarized - 1)] {
  221. block.finalized = true;
  222. finalized_blocks.push(block.clone());
  223. }
  224. blockchain.blocks.drain(0..(consecutive_notarized - 1));
  225. for block in &finalized_blocks {
  226. self.canonical_blockchain.blocks.push(block.clone());
  227. }
  228. let mut hasher = DefaultHasher::new();
  229. let last_finalized_block = self.canonical_blockchain.blocks.last().unwrap();
  230. last_finalized_block.hash(&mut hasher);
  231. let last_finalized_block_hash = hasher.finish().to_string();
  232. let mut dropped_blockchains = Vec::new();
  233. for (index, blockchain) in self.node_blockchains.iter().enumerate() {
  234. let first_block = blockchain.blocks.first().unwrap();
  235. if first_block.h != last_finalized_block_hash ||
  236. first_block.e <= last_finalized_block.e
  237. {
  238. dropped_blockchains.push(index);
  239. }
  240. }
  241. for index in dropped_blockchains {
  242. self.node_blockchains.remove(index);
  243. }
  244. }
  245. }
  246. }
  247. }