node.rs 12 KB

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