state.rs 16 KB

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