state.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. use chrono::{NaiveDateTime, Utc};
  2. use serde::{Deserialize, Serialize};
  3. use std::{
  4. collections::hash_map::DefaultHasher,
  5. hash::{Hash, Hasher},
  6. path::PathBuf,
  7. time::Duration,
  8. };
  9. use super::{
  10. block::Block,
  11. blockchain::Blockchain,
  12. util::{get_current_time, load, save, Timestamp},
  13. vote::Vote,
  14. };
  15. use darkfi::{
  16. crypto::{
  17. keypair::{PublicKey, SecretKey},
  18. schnorr::{SchnorrPublic, SchnorrSecret},
  19. },
  20. Result,
  21. };
  22. use rand::rngs::OsRng;
  23. /// This struct represents the state of a consensus node.
  24. /// Each node is numbered and has a secret-public keys pair, to sign messages.
  25. /// Nodes hold a set of Blockchains(some of which are not notarized)
  26. /// and a set of unconfirmed pending transactions.
  27. #[derive(Deserialize, Serialize)]
  28. pub struct State {
  29. pub id: u64,
  30. pub genesis_time: Timestamp,
  31. pub secret_key: SecretKey,
  32. pub public_key: PublicKey,
  33. pub canonical_blockchain: Blockchain,
  34. pub node_blockchains: Vec<Blockchain>,
  35. pub unconfirmed_txs: Vec<String>,
  36. }
  37. impl State {
  38. pub fn new(id: u64, genesis_time: Timestamp, init_block: Block) -> State {
  39. // TODO: clock sync
  40. let secret = SecretKey::random(&mut OsRng);
  41. State {
  42. id,
  43. genesis_time,
  44. secret_key: secret,
  45. public_key: PublicKey::from_secret(secret),
  46. canonical_blockchain: Blockchain::new(init_block),
  47. node_blockchains: Vec::new(),
  48. unconfirmed_txs: Vec::new(),
  49. }
  50. }
  51. /// Node retreives a transaction and append it to the unconfirmed transactions list.
  52. /// Additional validity rules must be defined by the protocol for transactions.
  53. pub fn append_tx(&mut self, tx: String) {
  54. self.unconfirmed_txs.push(tx);
  55. }
  56. /// Node calculates seconds until next epoch starting time.
  57. /// Epochs duration is configured using the delta value.
  58. pub fn get_seconds_until_next_epoch_start(&self) -> Duration {
  59. let delta = 10;
  60. let start_time = NaiveDateTime::from_timestamp(self.genesis_time.0, 0);
  61. let current_epoch = self.get_current_epoch() + 1;
  62. let next_epoch_start_timestamp =
  63. (current_epoch * (2 * delta)) + (start_time.timestamp() as u64);
  64. let next_epoch_start =
  65. NaiveDateTime::from_timestamp(next_epoch_start_timestamp.try_into().unwrap(), 0);
  66. let current_time = NaiveDateTime::from_timestamp(Utc::now().timestamp(), 0);
  67. let diff = next_epoch_start - current_time;
  68. Duration::new(diff.num_seconds().try_into().unwrap(), 0)
  69. }
  70. /// Node calculates current epoch, based on elapsed time from the genesis block.
  71. /// Epochs duration is configured using the delta value.
  72. pub fn get_current_epoch(&self) -> u64 {
  73. let delta = 10;
  74. self.genesis_time.clone().elapsed() / (2 * delta)
  75. }
  76. /// Node finds epochs leader, using a simple hash method.
  77. /// Leader calculation is based on how many nodes are participating in the network.
  78. pub fn get_epoch_leader(&self, nodes_count: u64) -> u64 {
  79. let epoch = self.get_current_epoch();
  80. let mut hasher = DefaultHasher::new();
  81. epoch.hash(&mut hasher);
  82. hasher.finish() % nodes_count
  83. }
  84. /// Node checks if they are the current epoch leader.
  85. pub fn check_if_epoch_leader(&self, nodes_count: u64) -> bool {
  86. let leader = self.get_epoch_leader(nodes_count);
  87. self.id == leader
  88. }
  89. /// Node generates a block proposal(mapped as Vote) for the current epoch,
  90. /// containing all uncorfirmed transactions.
  91. /// Block extends the longest notarized blockchain the node holds.
  92. pub fn propose_block(&self) -> Option<Vote> {
  93. let epoch = self.get_current_epoch();
  94. let longest_notarized_chain = self.find_longest_notarized_chain();
  95. let mut hasher = DefaultHasher::new();
  96. longest_notarized_chain.blocks.last().unwrap().hash(&mut hasher);
  97. let unproposed_txs = self.get_unproposed_txs();
  98. let proposed_block = Block::new(
  99. hasher.finish().to_string(),
  100. epoch,
  101. unproposed_txs,
  102. String::from("proof"),
  103. String::from("r"),
  104. String::from("s"),
  105. );
  106. let signed_block = self.secret_key.sign(&proposed_block.signature_encode());
  107. Some(Vote::new(signed_block, proposed_block, self.id))
  108. }
  109. /// Node retrieves all unconfiremd transactions not proposed in previous blocks.
  110. pub fn get_unproposed_txs(&self) -> Vec<String> {
  111. let mut unproposed_txs = self.unconfirmed_txs.clone();
  112. for blockchain in &self.node_blockchains {
  113. for block in &blockchain.blocks {
  114. for tx in &block.txs {
  115. if let Some(pos) = unproposed_txs.iter().position(|txs| *txs == *tx) {
  116. unproposed_txs.remove(pos);
  117. }
  118. }
  119. }
  120. }
  121. unproposed_txs
  122. }
  123. /// Finds the longest fully notarized blockchain the node holds.
  124. pub fn find_longest_notarized_chain(&self) -> &Blockchain {
  125. let mut longest_notarized_chain = &self.canonical_blockchain;
  126. let mut length = 0;
  127. for blockchain in &self.node_blockchains {
  128. if blockchain.is_notarized() && blockchain.blocks.len() > length {
  129. length = blockchain.blocks.len();
  130. longest_notarized_chain = &blockchain;
  131. }
  132. }
  133. &longest_notarized_chain
  134. }
  135. /// Node receives the proposed block(mapped as Vote), verifies its sender(epoch leader),
  136. /// and proceeds with voting on it.
  137. pub fn receive_proposed_block(
  138. &mut self,
  139. leader_public_key: &PublicKey,
  140. proposed_block_vote: &Vote,
  141. nodes_count: u64,
  142. ) -> Option<Vote> {
  143. assert!(self.get_epoch_leader(nodes_count) == proposed_block_vote.id);
  144. assert!(leader_public_key
  145. .verify(&proposed_block_vote.block.signature_encode(), &proposed_block_vote.vote));
  146. self.vote_block(&proposed_block_vote.block)
  147. }
  148. /// Given a block, node finds which blockchain it extends.
  149. /// If block extends the canonical blockchain, a new fork blockchain is created.
  150. /// Node votes on the block, only if it extends the longest notarized chain it has seen.
  151. pub fn vote_block(&mut self, block: &Block) -> Option<Vote> {
  152. let index = self.find_extended_blockchain_index(block);
  153. let blockchain = if index == -1 {
  154. let blockchain = Blockchain::new(block.clone());
  155. self.node_blockchains.push(blockchain);
  156. self.node_blockchains.last().unwrap()
  157. } else {
  158. self.node_blockchains[index as usize].add_block(&block);
  159. &self.node_blockchains[index as usize]
  160. };
  161. if self.extends_notarized_blockchain(blockchain) {
  162. let block_copy = block.clone();
  163. let signed_block = self.secret_key.sign(&block_copy.signature_encode());
  164. return Some(Vote::new(signed_block, block_copy, self.id))
  165. }
  166. None
  167. }
  168. /// Node verifies if provided blockchain is notarized excluding the last block.
  169. pub fn extends_notarized_blockchain(&self, blockchain: &Blockchain) -> bool {
  170. for block in &blockchain.blocks[..(blockchain.blocks.len() - 1)] {
  171. if !block.metadata.sm.notarized {
  172. return false
  173. }
  174. }
  175. true
  176. }
  177. /// Given a block, node finds the index of the blockchain it extends.
  178. pub fn find_extended_blockchain_index(&self, block: &Block) -> i64 {
  179. let mut hasher = DefaultHasher::new();
  180. for (index, blockchain) in self.node_blockchains.iter().enumerate() {
  181. let last_block = blockchain.blocks.last().unwrap();
  182. last_block.hash(&mut hasher);
  183. if block.st == hasher.finish().to_string() && block.sl > last_block.sl {
  184. return index as i64
  185. }
  186. }
  187. let last_block = self.canonical_blockchain.blocks.last().unwrap();
  188. last_block.hash(&mut hasher);
  189. if block.st != hasher.finish().to_string() || block.sl <= last_block.sl {
  190. panic!("Proposed block doesn't extend any known chains.");
  191. }
  192. -1
  193. }
  194. /// Node receives a vote for a block.
  195. /// First, sender is verified using their public key.
  196. /// Block is searched in nodes blockchains.
  197. /// If the vote wasn't received before, it is appended to block votes list.
  198. /// When a node sees 2n/3 votes for a block it notarizes it.
  199. /// When a block gets notarized, the transactions it contains are removed from
  200. /// nodes unconfirmed transactions list.
  201. /// Finally, we check if the notarization of the block can finalize parent blocks
  202. /// in its blockchain.
  203. pub fn receive_vote(&mut self, node_public_key: &PublicKey, vote: &Vote, nodes_count: usize) {
  204. assert!(node_public_key.verify(&vote.block.signature_encode(), &vote.vote));
  205. let vote_block = self.find_block(&vote.block);
  206. if vote_block == None {
  207. panic!("Received vote for unknown block.");
  208. }
  209. let (unwrapped_vote_block, blockchain_index) = vote_block.unwrap();
  210. if !unwrapped_vote_block.metadata.sm.votes.contains(vote) {
  211. unwrapped_vote_block.metadata.sm.votes.push(vote.clone());
  212. }
  213. if !unwrapped_vote_block.metadata.sm.notarized &&
  214. unwrapped_vote_block.metadata.sm.votes.len() > (2 * nodes_count / 3)
  215. {
  216. unwrapped_vote_block.metadata.sm.notarized = true;
  217. self.check_blockchain_finalization(blockchain_index);
  218. }
  219. }
  220. /// Node searches it the blockchains it holds for provided block.
  221. pub fn find_block(&mut self, vote_block: &Block) -> Option<(&mut Block, i64)> {
  222. for (index, blockchain) in &mut self.node_blockchains.iter_mut().enumerate() {
  223. for block in blockchain.blocks.iter_mut().rev() {
  224. if vote_block == block {
  225. return Some((block, index as i64))
  226. }
  227. }
  228. }
  229. for block in &mut self.canonical_blockchain.blocks.iter_mut().rev() {
  230. if vote_block == block {
  231. return Some((block, -1))
  232. }
  233. }
  234. None
  235. }
  236. /// Node checks if the index blockchain can be finalized.
  237. /// Consensus finalization logic: If node has observed the notarization of 3 consecutive
  238. /// blocks in a fork chain, it finalizes (appends to canonical blockchain) all blocks up to the middle block.
  239. /// When fork chain blocks are finalized, rest fork chains not starting by those blocks are removed.
  240. pub fn check_blockchain_finalization(&mut self, blockchain_index: i64) {
  241. let blockchain = if blockchain_index == -1 {
  242. &mut self.canonical_blockchain
  243. } else {
  244. &mut self.node_blockchains[blockchain_index as usize]
  245. };
  246. let blockchain_len = blockchain.blocks.len();
  247. if blockchain_len > 2 {
  248. let mut consecutive_notarized = 0;
  249. for block in &blockchain.blocks {
  250. if block.metadata.sm.notarized {
  251. consecutive_notarized = consecutive_notarized + 1;
  252. } else {
  253. break
  254. }
  255. }
  256. if consecutive_notarized > 2 {
  257. let mut finalized_blocks = Vec::new();
  258. for block in &mut blockchain.blocks[..(consecutive_notarized - 1)] {
  259. block.metadata.sm.finalized = true;
  260. finalized_blocks.push(block.clone());
  261. for tx in block.txs.clone() {
  262. if let Some(pos) = self.unconfirmed_txs.iter().position(|txs| *txs == tx) {
  263. self.unconfirmed_txs.remove(pos);
  264. }
  265. }
  266. }
  267. blockchain.blocks.drain(0..(consecutive_notarized - 1));
  268. for block in &finalized_blocks {
  269. self.canonical_blockchain.blocks.push(block.clone());
  270. }
  271. let mut hasher = DefaultHasher::new();
  272. let last_finalized_block = self.canonical_blockchain.blocks.last().unwrap();
  273. last_finalized_block.hash(&mut hasher);
  274. let last_finalized_block_hash = hasher.finish().to_string();
  275. let mut dropped_blockchains = Vec::new();
  276. for (index, blockchain) in self.node_blockchains.iter().enumerate() {
  277. let first_block = blockchain.blocks.first().unwrap();
  278. if first_block.st != last_finalized_block_hash ||
  279. first_block.sl <= last_finalized_block.sl
  280. {
  281. dropped_blockchains.push(index);
  282. }
  283. }
  284. for index in dropped_blockchains {
  285. self.node_blockchains.remove(index);
  286. }
  287. }
  288. }
  289. }
  290. /// Util function to save the current node state to provided file path.
  291. pub fn save(&self, path: &PathBuf) -> Result<()> {
  292. save::<Self>(path, self)
  293. }
  294. /// Util function to load current node state by the provided file path.
  295. // If file is not found, node state is reset.
  296. pub fn load_or_create(id: u64, path: &PathBuf) -> Result<Self> {
  297. match load::<Self>(path) {
  298. Ok(state) => Ok(state),
  299. Err(_) => return Self::reset(id, path),
  300. }
  301. }
  302. /// Util function to load the current node state by the provided file path.
  303. pub fn load_current_state(id: u64, path: &PathBuf) -> Result<State> {
  304. let state = Self::load_or_create(id, path)?;
  305. Ok(state)
  306. }
  307. /// Util function to reset node state.
  308. pub fn reset(id: u64, path: &PathBuf) -> Result<State> {
  309. // Genesis block is generated.
  310. let mut genesis_block = Block::new(
  311. String::from("⊥"),
  312. 0,
  313. vec![],
  314. String::from("proof"),
  315. String::from("r"),
  316. String::from("s"),
  317. );
  318. genesis_block.metadata.sm.notarized = true;
  319. genesis_block.metadata.sm.finalized = true;
  320. let genesis_time = get_current_time();
  321. let state = Self::new(id, genesis_time, genesis_block.clone());
  322. state.save(path)?;
  323. return Ok(state)
  324. }
  325. }