state.rs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use darkfi_sdk::{
  19. blockchain::Slot,
  20. crypto::MerkleTree,
  21. pasta::{group::ff::PrimeField, pallas},
  22. };
  23. use darkfi_serial::{deserialize, serialize, SerialDecodable, SerialEncodable};
  24. use log::info;
  25. use rand::{thread_rng, Rng};
  26. use super::{
  27. constants,
  28. lead_coin::{LeadCoin, LeadCoinSecrets},
  29. utils::fbig2base,
  30. Block, BlockProposal, Float10,
  31. };
  32. use crate::{
  33. blockchain::Blockchain,
  34. impl_p2p_message,
  35. net::Message,
  36. tx::Transaction,
  37. util::time::{TimeKeeper, Timestamp},
  38. wallet::WalletPtr,
  39. Error, Result,
  40. };
  41. use std::{
  42. fs::File,
  43. io::{prelude::*, BufWriter},
  44. };
  45. /// This struct represents the information required by the consensus algorithm
  46. pub struct ConsensusState {
  47. /// Wallet interface
  48. pub wallet: WalletPtr,
  49. /// Canonical (finalized) blockchain
  50. pub blockchain: Blockchain,
  51. /// Network bootstrap timestamp
  52. pub bootstrap_ts: Timestamp,
  53. /// Helper structure to calculate time related operations
  54. pub time_keeper: TimeKeeper,
  55. /// Genesis block hash
  56. pub genesis_block: blake3::Hash,
  57. /// Total sum of initial staking coins
  58. pub initial_distribution: u64,
  59. /// Flag to enable single-node mode
  60. pub single_node: bool,
  61. /// Slot the network was bootstrapped
  62. pub bootstrap_slot: u64,
  63. /// Participating start slot
  64. pub participating: Option<u64>,
  65. /// Node is able to propose proposals
  66. pub proposing: bool,
  67. /// Last slot node check for finalization
  68. pub checked_finalization: u64,
  69. /// Fork chains containing block proposals
  70. pub forks: Vec<Fork>,
  71. /// Current epoch
  72. pub epoch: u64,
  73. /// Hot/live slots
  74. pub slots: Vec<Slot>,
  75. /// Last slot leaders count
  76. pub previous_leaders: u64,
  77. /// Controller output history
  78. pub f_history: Vec<Float10>,
  79. /// Controller proportional error history
  80. pub err_history: Vec<Float10>,
  81. // TODO: Aren't these already in db after finalization?
  82. /// Canonical competing coins
  83. pub coins: Vec<LeadCoin>,
  84. /// Canonical coin commitments tree
  85. pub coins_tree: MerkleTree,
  86. /// Canonical seen nullifiers from proposals
  87. pub nullifiers: Vec<pallas::Base>,
  88. }
  89. impl ConsensusState {
  90. pub fn new(
  91. wallet: WalletPtr,
  92. blockchain: Blockchain,
  93. bootstrap_ts: Timestamp,
  94. genesis_ts: Timestamp,
  95. genesis_data: blake3::Hash,
  96. initial_distribution: u64,
  97. single_node: bool,
  98. ) -> Self {
  99. let genesis_block = Block::genesis_block(genesis_ts, genesis_data).blockhash();
  100. let time_keeper =
  101. TimeKeeper::new(genesis_ts, constants::EPOCH_LENGTH as u64, constants::SLOT_TIME, 0);
  102. Self {
  103. wallet,
  104. blockchain,
  105. bootstrap_ts,
  106. time_keeper,
  107. genesis_block,
  108. initial_distribution,
  109. single_node,
  110. bootstrap_slot: 0,
  111. participating: None,
  112. proposing: false,
  113. checked_finalization: 0,
  114. forks: vec![],
  115. epoch: 0,
  116. slots: vec![],
  117. previous_leaders: 0,
  118. f_history: vec![constants::FLOAT10_ZERO.clone()],
  119. err_history: vec![constants::FLOAT10_ZERO.clone(), constants::FLOAT10_ZERO.clone()],
  120. coins: vec![],
  121. coins_tree: MerkleTree::new(constants::EPOCH_LENGTH * 100),
  122. nullifiers: vec![],
  123. }
  124. }
  125. /// Finds the last slot a proposal or block was generated.
  126. pub fn last_slot(&self) -> Result<u64> {
  127. let mut slot = 0;
  128. for chain in &self.forks {
  129. for state_checkpoint in &chain.sequence {
  130. if state_checkpoint.proposal.block.header.slot > slot {
  131. slot = state_checkpoint.proposal.block.header.slot;
  132. }
  133. }
  134. }
  135. // We return here in case proposals exist,
  136. // so we don't query the sled database.
  137. if slot > 0 {
  138. return Ok(slot)
  139. }
  140. let (last_slot, _) = self.blockchain.last()?;
  141. Ok(last_slot)
  142. }
  143. /// Set participating slot to next.
  144. pub fn set_participating(&mut self) -> Result<()> {
  145. self.participating = Some(self.time_keeper.current_slot() + 1);
  146. Ok(())
  147. }
  148. /// Generate current slot
  149. fn generate_slot(
  150. &mut self,
  151. fork_hashes: Vec<blake3::Hash>,
  152. fork_previous_hashes: Vec<blake3::Hash>,
  153. sigma1: pallas::Base,
  154. sigma2: pallas::Base,
  155. ) {
  156. let id = self.time_keeper.current_slot();
  157. let previous_eta = self.get_previous_eta();
  158. let slot = Slot { id, previous_eta, fork_hashes, fork_previous_hashes, sigma1, sigma2 };
  159. info!(target: "consensus::state", "generate_slot: {:?}", slot);
  160. self.slots.push(slot);
  161. }
  162. // Initialize node lead coins and set current epoch and eta.
  163. pub async fn init_coins(&mut self) -> Result<()> {
  164. self.epoch = self.time_keeper.current_epoch();
  165. self.coins = self.create_coins().await?;
  166. self.update_forks_checkpoints();
  167. Ok(())
  168. }
  169. /// Check if new epoch has started and generate slot.
  170. /// Returns flag to signify if epoch has changed.
  171. pub async fn epoch_changed(
  172. &mut self,
  173. fork_hashes: Vec<blake3::Hash>,
  174. fork_previous_hashes: Vec<blake3::Hash>,
  175. sigma1: pallas::Base,
  176. sigma2: pallas::Base,
  177. ) -> Result<bool> {
  178. self.generate_slot(fork_hashes, fork_previous_hashes, sigma1, sigma2);
  179. let epoch = self.time_keeper.current_epoch();
  180. if epoch <= self.epoch {
  181. return Ok(false)
  182. }
  183. self.epoch = epoch;
  184. Ok(true)
  185. }
  186. /// Return 2-term target approximation sigma coefficients.
  187. pub fn sigmas(&mut self) -> (pallas::Base, pallas::Base) {
  188. let f = self.win_inv_prob_with_full_stake();
  189. let total_stake = self.total_stake();
  190. let total_sigma = Float10::try_from(total_stake).unwrap();
  191. self.calc_sigmas(f, total_sigma)
  192. }
  193. fn calc_sigmas(&self, f: Float10, total_sigma: Float10) -> (pallas::Base, pallas::Base) {
  194. info!(target: "consensus::state", "sigmas(): f: {}", f);
  195. info!(target: "consensus::state", "sigmas(): total network stake: {:}", total_sigma);
  196. let one = constants::FLOAT10_ONE.clone();
  197. let neg_one = constants::FLOAT10_NEG_ONE.clone();
  198. let two = constants::FLOAT10_TWO.clone();
  199. let field_p = Float10::try_from(constants::P).unwrap();
  200. let x = one - f;
  201. let c = x.ln();
  202. let neg_c = neg_one * c;
  203. let sigma1_fbig = neg_c.clone() /
  204. (total_sigma.clone() + constants::FLOAT10_EPSILON.clone()) *
  205. field_p.clone();
  206. info!(target: "consensus::state", "sigma1_fbig: {:}", sigma1_fbig);
  207. let sigma1 = fbig2base(sigma1_fbig);
  208. let sigma2_fbig = (neg_c / (total_sigma + constants::FLOAT10_EPSILON.clone()))
  209. .powf(two.clone()) *
  210. (field_p / two);
  211. info!(target: "consensus::state", "sigma2_fbig: {:}", sigma2_fbig);
  212. let sigma2 = fbig2base(sigma2_fbig);
  213. (sigma1, sigma2)
  214. }
  215. /// Generate coins for provided sigmas.
  216. /// NOTE: The strategy here is having a single competing coin per slot.
  217. // TODO: DRK coin need to be burned, and consensus coin to be minted.
  218. async fn create_coins(&mut self) -> Result<Vec<LeadCoin>> {
  219. // TODO: cleanup LeadCoinSecrets, no need to keep a vector
  220. let (seeds, epoch_secrets) = {
  221. let mut rng = thread_rng();
  222. let mut seeds: Vec<u64> = Vec::with_capacity(constants::EPOCH_LENGTH);
  223. for _ in 0..constants::EPOCH_LENGTH {
  224. seeds.push(rng.gen());
  225. }
  226. (seeds, LeadCoinSecrets::generate())
  227. };
  228. // LeadCoin matrix containing node competing coins.
  229. let mut coins: Vec<LeadCoin> = Vec::with_capacity(constants::EPOCH_LENGTH);
  230. // Retrieve coin from wallet
  231. // NOTE: In future this will be retrieved from the money contract.
  232. // Execute the query and see if we find any rows
  233. let query_str = format!("SELECT * FROM {}", constants::CONSENSUS_COIN_TABLE);
  234. let wallet_conn = self.wallet.conn.lock().await;
  235. let mut stmt = wallet_conn.prepare(&query_str)?;
  236. let coin = stmt.query_row((), |row| {
  237. let bytes: Vec<u8> = row.get(constants::CONSENSUS_COIN_COL)?;
  238. let coin = deserialize(&bytes).unwrap();
  239. Ok(coin)
  240. });
  241. stmt.finalize()?;
  242. let coin = match coin {
  243. Ok(c) => c,
  244. Err(_) => {
  245. // If no records are found, we generate a new coin and save it to the database
  246. info!(target: "consensus::state", "create_coins(): No LeadCoin was found in DB, generating new one...");
  247. // Temporarily, we compete with fixed stake.
  248. // This stake should be based on how many nodes we want to run, and they all
  249. // must sum to initial distribution total coins.
  250. //let stake = self.initial_distribution;
  251. let c = LeadCoin::new(
  252. 0,
  253. self.time_keeper.current_slot(),
  254. epoch_secrets.secret_keys[0].inner(),
  255. epoch_secrets.merkle_roots[0],
  256. 0,
  257. epoch_secrets.merkle_paths[0].clone(),
  258. pallas::Base::from(seeds[0]),
  259. &mut self.coins_tree,
  260. );
  261. let query_str = format!(
  262. "INSERT INTO {} ({}) VALUES (?1);",
  263. constants::CONSENSUS_COIN_TABLE,
  264. constants::CONSENSUS_COIN_COL
  265. );
  266. let mut stmt = wallet_conn.prepare(&query_str)?;
  267. stmt.execute([serialize(&c)])?;
  268. c
  269. }
  270. };
  271. info!(target: "consensus::state", "create_coins(): Will use LeadCoin with value: {}", coin.value);
  272. coins.push(coin);
  273. Ok(coins)
  274. }
  275. /// Leadership reward, assuming constant reward
  276. /// TODO (res) implement reward mechanism with accord to DRK,DARK token-economics
  277. fn reward(&self) -> u64 {
  278. constants::REWARD
  279. }
  280. /// Auxillary function to calculate total slot rewards.
  281. fn slot_rewards(&self) -> u64 {
  282. // Retrieve existing blocks excluding genesis
  283. let blocks = (self.blockchain.len() as u64) - 1;
  284. // Retrieve longest fork length, to include those proposals in the calculation
  285. let max_fork_length = self.longest_chain_length() as u64;
  286. // Calculate rewarded slots
  287. let rewarded_slots = blocks + max_fork_length;
  288. rewarded_slots * self.reward()
  289. }
  290. /// Network total stake, assuming constant reward.
  291. /// Only used for fine-tuning. At genesis epoch first slot, of absolute index 0,
  292. /// if no stake was distributed, the total stake would be 0.
  293. /// To avoid division by zero, we asume total stake at first division is GENESIS_TOTAL_STAKE(1).
  294. fn total_stake(&self) -> u64 {
  295. let total_stake = self.slot_rewards() + self.initial_distribution;
  296. if total_stake == 0 {
  297. return constants::GENESIS_TOTAL_STAKE
  298. }
  299. total_stake
  300. }
  301. fn f_err(&mut self) -> Float10 {
  302. info!(target: "consensus::state", "Previous leaders: {}", self.previous_leaders);
  303. // Write counter to file
  304. let mut count_str: String = self.previous_leaders.to_string();
  305. count_str.push(',');
  306. let f =
  307. File::options().append(true).create(true).open(constants::LEADER_HISTORY_LOG).unwrap();
  308. {
  309. let mut writer = BufWriter::new(f);
  310. let _ = writer.write(&count_str.into_bytes()).unwrap();
  311. }
  312. // Calculate feedback
  313. let feedback = Float10::try_from(self.previous_leaders as i64).unwrap();
  314. // Reset previous leaders counter
  315. self.previous_leaders = 0;
  316. let target = constants::FLOAT10_ONE.clone();
  317. target - feedback
  318. }
  319. fn discrete_pid(&mut self) -> Float10 {
  320. let k1 = constants::KP.clone() + constants::KI.clone() + constants::KD.clone();
  321. let k2 = constants::FLOAT10_NEG_ONE.clone() * constants::KP.clone() +
  322. constants::FLOAT10_NEG_TWO.clone() * constants::KD.clone();
  323. let k3 = constants::KD.clone();
  324. let f_len = self.f_history.len();
  325. let err = self.f_err();
  326. let err_len = self.err_history.len();
  327. let ret = self.f_history[f_len - 1].clone() +
  328. k1.clone() * err.clone() +
  329. k2.clone() * self.err_history[err_len - 1].clone() +
  330. k3.clone() * self.err_history[err_len - 2].clone();
  331. info!(target: "consensus::state", "pid::f-1: {:}", self.f_history[f_len - 1].clone());
  332. info!(target: "consensus::state", "pid::err: {:}", err);
  333. info!(target: "consensus::state", "pid::err-1: {}", self.err_history[err_len - 1].clone());
  334. info!(target: "consensus::state", "pid::err-2: {}", self.err_history[err_len - 2].clone());
  335. info!(target: "consensus::state", "pid::k1: {}", k1);
  336. info!(target: "consensus::state", "pid::k2: {}", k2);
  337. info!(target: "consensus::state", "pid::k3: {}", k3);
  338. self.err_history.push(err);
  339. ret
  340. }
  341. /// the probability inverse of winnig lottery having all the stake
  342. /// returns f
  343. fn win_inv_prob_with_full_stake(&mut self) -> Float10 {
  344. let mut f = self.discrete_pid();
  345. if f <= constants::FLOAT10_ZERO.clone() {
  346. f = constants::MIN_F.clone()
  347. } else if f >= constants::FLOAT10_ONE.clone() {
  348. f = constants::MAX_F.clone()
  349. }
  350. // log f history
  351. let file =
  352. File::options().append(true).create(true).open(constants::F_HISTORY_LOG).unwrap();
  353. {
  354. let mut f_history = format!("{:}", f);
  355. f_history.push(',');
  356. let mut writer = BufWriter::new(file);
  357. let _ = writer.write(&f_history.into_bytes()).unwrap();
  358. }
  359. self.f_history.push(f.clone());
  360. f
  361. }
  362. /// Check that the participant/stakeholder coins win the slot lottery.
  363. /// If the stakeholder has multiple competing winning coins, only the highest value
  364. /// coin is selected, since the stakeholder can't give more than one proof per block/slot.
  365. /// * 'sigma1', 'sigma2': slot sigmas
  366. /// Returns: (check: bool, idx: usize) where idx is the winning coin's index
  367. pub fn is_slot_leader(
  368. &mut self,
  369. sigma1: pallas::Base,
  370. sigma2: pallas::Base,
  371. ) -> (bool, i64, usize) {
  372. // Check if node can produce proposals
  373. if !self.proposing {
  374. return (false, 0, 0)
  375. }
  376. let fork_index = self.longest_chain_index();
  377. let competing_coins = if fork_index == -1 {
  378. self.coins.clone()
  379. } else {
  380. self.forks[fork_index as usize].sequence.last().unwrap().coins.clone()
  381. };
  382. // If on single-node mode, node always proposes by extending the
  383. // single fork it holds.
  384. if self.single_node {
  385. return (true, fork_index, 0)
  386. }
  387. let mut won = false;
  388. let mut highest_stake = 0;
  389. let mut highest_stake_idx = 0;
  390. let total_stake = self.total_stake();
  391. for (winning_idx, coin) in competing_coins.iter().enumerate() {
  392. info!(target: "consensus::state", "is_slot_leader: coin stake: {:?}", coin.value);
  393. info!(target: "consensus::state", "is_slot_leader: total stake: {}", total_stake);
  394. info!(target: "consensus::state", "is_slot_leader: relative stake: {}", (coin.value as f64) / total_stake as f64);
  395. let first_winning = coin.is_leader(
  396. sigma1,
  397. sigma2,
  398. self.get_previous_eta(),
  399. pallas::Base::from(self.time_keeper.current_slot()),
  400. );
  401. if first_winning && !won {
  402. highest_stake_idx = winning_idx;
  403. }
  404. won |= first_winning;
  405. if won && coin.value > highest_stake {
  406. highest_stake = coin.value;
  407. highest_stake_idx = winning_idx;
  408. }
  409. }
  410. (won, fork_index, highest_stake_idx)
  411. }
  412. /// Finds the longest forkchain the node holds and
  413. /// returns its index.
  414. pub fn longest_chain_index(&self) -> i64 {
  415. let mut length = 0;
  416. let mut index = -1;
  417. if !self.forks.is_empty() {
  418. for (i, chain) in self.forks.iter().enumerate() {
  419. if chain.sequence.len() > length {
  420. length = chain.sequence.len();
  421. index = i as i64;
  422. }
  423. }
  424. }
  425. index
  426. }
  427. /// Finds the length of longest fork chain the node holds.
  428. pub fn longest_chain_length(&self) -> usize {
  429. let mut max = 0;
  430. for fork in &self.forks {
  431. if fork.sequence.len() > max {
  432. max = fork.sequence.len();
  433. }
  434. }
  435. max
  436. }
  437. /// Given a proposal, find the index of the fork chain it extends.
  438. pub fn find_extended_chain_index(&mut self, proposal: &BlockProposal) -> Result<i64> {
  439. // We iterate through all forks to find which fork to extend
  440. let mut chain_index = -1;
  441. let mut state_checkpoint_index = 0;
  442. for (c_index, chain) in self.forks.iter().enumerate() {
  443. // Traverse sequence in reverse
  444. for (sc_index, state_checkpoint) in chain.sequence.iter().enumerate().rev() {
  445. if proposal.block.header.previous == state_checkpoint.proposal.hash {
  446. chain_index = c_index as i64;
  447. state_checkpoint_index = sc_index;
  448. break
  449. }
  450. }
  451. if chain_index != -1 {
  452. break
  453. }
  454. }
  455. // If no fork was found, we check with canonical
  456. if chain_index == -1 {
  457. let (last_slot, last_block) = self.blockchain.last()?;
  458. if proposal.block.header.previous != last_block ||
  459. proposal.block.header.slot <= last_slot
  460. {
  461. info!(target: "consensus::state", "find_extended_chain_index(): Proposal doesn't extend any known chain");
  462. return Ok(-2)
  463. }
  464. // Proposal extends canonical chain
  465. return Ok(-1)
  466. }
  467. // Found fork chain
  468. let chain = &self.forks[chain_index as usize];
  469. // Proposal extends fork at last proposal
  470. if state_checkpoint_index == (chain.sequence.len() - 1) {
  471. return Ok(chain_index)
  472. }
  473. info!(target: "consensus::state", "find_extended_chain_index(): Proposal to fork a forkchain was received.");
  474. let mut chain = self.forks[chain_index as usize].clone();
  475. // We keep all proposals until the one it extends
  476. chain.sequence.drain((state_checkpoint_index + 1)..);
  477. self.forks.push(chain);
  478. Ok(self.forks.len() as i64 - 1)
  479. }
  480. /// Search the chains we're holding for the given proposal.
  481. pub fn proposal_exists(&self, input_proposal: &blake3::Hash) -> bool {
  482. for chain in self.forks.iter() {
  483. for state_checkpoint in chain.sequence.iter().rev() {
  484. if input_proposal == &state_checkpoint.proposal.hash {
  485. return true
  486. }
  487. }
  488. }
  489. false
  490. }
  491. /// Utility function to extract leader selection lottery randomness(eta),
  492. /// defined as the hash of the last block, converted to pallas base.
  493. pub fn get_previous_eta(&self) -> pallas::Base {
  494. let (_, hash) = self.blockchain.last().unwrap();
  495. let mut bytes: [u8; 32] = *hash.as_bytes();
  496. // Read first 254 bits
  497. bytes[30] = 0;
  498. bytes[31] = 0;
  499. pallas::Base::from_repr(bytes).unwrap()
  500. }
  501. /// Auxillary function to retrieve slot of provided slot UID.
  502. pub fn get_slot(&self, id: u64) -> Result<Slot> {
  503. // Check hot/live slotz
  504. for slot in self.slots.iter().rev() {
  505. if slot.id == id {
  506. return Ok(slot.clone())
  507. }
  508. }
  509. // Check if slot is finalized
  510. if let Ok(slots) = self.blockchain.get_slots_by_id(&[id]) {
  511. if !slots.is_empty() {
  512. if let Some(known_slot) = &slots[0] {
  513. return Ok(known_slot.clone())
  514. }
  515. }
  516. }
  517. Err(Error::SlotNotFound(id))
  518. }
  519. /// Auxillary function to check if node has seen current or previous slots.
  520. /// This check ensures that either the slots exist in memory or node has seen the finalization of these slots.
  521. pub fn slots_is_empty(&self) -> bool {
  522. let current_slot = self.time_keeper.current_slot();
  523. if self.get_slot(current_slot).is_ok() {
  524. return false
  525. }
  526. let previous_slot = current_slot - 1;
  527. self.get_slot(previous_slot).is_err()
  528. }
  529. /// Auxillary function to update all fork state checkpoints to nodes coins current canonical states.
  530. /// Note: This function should only be invoked once on nodes' coins creation.
  531. pub fn update_forks_checkpoints(&mut self) {
  532. for fork in &mut self.forks {
  533. for state_checkpoint in &mut fork.sequence {
  534. state_checkpoint.coins = self.coins.clone();
  535. state_checkpoint.coins_tree = self.coins_tree.clone();
  536. }
  537. }
  538. }
  539. /// Retrieve current forks last proposal hashes and their previous
  540. /// hashes. If node holds no fork, retrieve last canonical hash.
  541. pub fn fork_hashes(&self) -> (Vec<blake3::Hash>, Vec<blake3::Hash>) {
  542. let mut hashes = vec![];
  543. let mut previous_hashes = vec![];
  544. for fork in &self.forks {
  545. let proposal = &fork.sequence.last().unwrap().proposal;
  546. hashes.push(proposal.hash);
  547. previous_hashes.push(proposal.block.header.previous);
  548. }
  549. if hashes.is_empty() {
  550. hashes.push(self.genesis_block);
  551. previous_hashes.push(self.genesis_block);
  552. }
  553. (hashes, previous_hashes)
  554. }
  555. /// Auxiliary structure to reset consensus state for a resync
  556. pub fn reset(&mut self) {
  557. self.participating = None;
  558. self.proposing = false;
  559. self.forks = vec![];
  560. self.slots = vec![];
  561. self.previous_leaders = 0;
  562. self.f_history = vec![constants::FLOAT10_ZERO.clone()];
  563. self.err_history = vec![constants::FLOAT10_ZERO.clone(), constants::FLOAT10_ZERO.clone()];
  564. self.nullifiers = vec![];
  565. }
  566. }
  567. /// Auxiliary structure used for consensus syncing.
  568. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  569. pub struct ConsensusRequest {}
  570. impl_p2p_message!(ConsensusRequest, "consensusrequest");
  571. /// Auxiliary structure used for consensus syncing.
  572. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  573. pub struct ConsensusResponse {
  574. /// Slot the network was bootstrapped
  575. pub bootstrap_slot: u64,
  576. /// Current slot
  577. pub current_slot: u64,
  578. /// Hot/live data used by the consensus algorithm
  579. pub forks: Vec<ForkInfo>,
  580. /// Pending transactions
  581. pub pending_txs: Vec<Transaction>,
  582. /// Hot/live slots
  583. pub slots: Vec<Slot>,
  584. // TODO: When Float10 supports encoding/decoding this should be
  585. // replaced by directly using Vec<Float10>
  586. /// Controller output history
  587. pub f_history: Vec<String>,
  588. /// Controller proportional error history
  589. pub err_history: Vec<String>,
  590. /// Seen nullifiers from proposals
  591. pub nullifiers: Vec<pallas::Base>,
  592. }
  593. impl_p2p_message!(ConsensusResponse, "consensusresponse");
  594. /// Auxiliary structure used for consensus syncing.
  595. #[derive(Debug, SerialEncodable, SerialDecodable)]
  596. pub struct ConsensusSyncRequest {}
  597. impl_p2p_message!(ConsensusSyncRequest, "consensussyncrequest");
  598. /// Auxiliary structure used for consensus syncing.
  599. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  600. pub struct ConsensusSyncResponse {
  601. /// Node known bootstrap slot
  602. pub bootstrap_slot: u64,
  603. /// Node is able to propose proposals
  604. pub proposing: bool,
  605. /// Node has hot/live slots
  606. pub is_empty: bool,
  607. }
  608. impl_p2p_message!(ConsensusSyncResponse, "consensussyncresponse");
  609. impl_p2p_message!(Slot, "slot");
  610. /// Auxiliary structure used for slots syncing
  611. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  612. pub struct SlotRequest {
  613. /// Slot UID
  614. pub slot: u64,
  615. }
  616. impl_p2p_message!(SlotRequest, "slotrequest");
  617. /// Auxiliary structure used for slots syncing
  618. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  619. pub struct SlotResponse {
  620. /// Response blocks.
  621. pub slots: Vec<Slot>,
  622. }
  623. impl_p2p_message!(SlotResponse, "slotresponse");
  624. /// Auxiliary structure used to keep track of consensus state checkpoints.
  625. #[derive(Debug, Clone)]
  626. pub struct StateCheckpoint {
  627. /// Block proposal
  628. pub proposal: BlockProposal,
  629. /// Node competing coins current state
  630. pub coins: Vec<LeadCoin>,
  631. /// Coin commitments tree current state
  632. pub coins_tree: MerkleTree,
  633. /// Seen nullifiers from proposals current state
  634. pub nullifiers: Vec<pallas::Base>,
  635. }
  636. impl StateCheckpoint {
  637. pub fn new(
  638. proposal: BlockProposal,
  639. coins: Vec<LeadCoin>,
  640. coins_tree: MerkleTree,
  641. nullifiers: Vec<pallas::Base>,
  642. ) -> Self {
  643. Self { proposal, coins, coins_tree, nullifiers }
  644. }
  645. }
  646. /// Auxiliary structure used for forked consensus state checkpoints syncing
  647. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  648. pub struct StateCheckpointInfo {
  649. /// Block proposal
  650. pub proposal: BlockProposal,
  651. /// Seen nullifiers from proposals current state
  652. pub nullifiers: Vec<pallas::Base>,
  653. }
  654. impl From<StateCheckpoint> for StateCheckpointInfo {
  655. fn from(state_checkpoint: StateCheckpoint) -> Self {
  656. Self { proposal: state_checkpoint.proposal, nullifiers: state_checkpoint.nullifiers }
  657. }
  658. }
  659. impl From<StateCheckpointInfo> for StateCheckpoint {
  660. fn from(state_checkpoint_info: StateCheckpointInfo) -> Self {
  661. Self {
  662. proposal: state_checkpoint_info.proposal,
  663. coins: vec![],
  664. coins_tree: MerkleTree::new(constants::EPOCH_LENGTH * 100),
  665. nullifiers: state_checkpoint_info.nullifiers,
  666. }
  667. }
  668. }
  669. /// This struct represents a sequence of consensus state checkpoints.
  670. #[derive(Debug, Clone)]
  671. pub struct Fork {
  672. pub genesis_block: blake3::Hash,
  673. pub sequence: Vec<StateCheckpoint>,
  674. }
  675. impl Fork {
  676. pub fn new(genesis_block: blake3::Hash, initial_state_checkpoint: StateCheckpoint) -> Self {
  677. Self { genesis_block, sequence: vec![initial_state_checkpoint] }
  678. }
  679. /// Insertion of a valid state checkpoint.
  680. pub fn add(&mut self, state_checkpoint: &StateCheckpoint) {
  681. if self.check_state_checkpoint(state_checkpoint, self.sequence.last().unwrap()) {
  682. self.sequence.push(state_checkpoint.clone());
  683. }
  684. }
  685. /// A fork chain is considered valid when every state checkpoint is valid,
  686. /// based on the `check_state_checkpoint` function
  687. pub fn check_chain(&self) -> bool {
  688. for (index, state_checkpoint) in self.sequence[1..].iter().enumerate() {
  689. if !self.check_state_checkpoint(state_checkpoint, &self.sequence[index]) {
  690. return false
  691. }
  692. }
  693. true
  694. }
  695. /// A state checkpoint is considered valid when its proposal parent hash is equal to the
  696. /// hash of the previous checkpoint's proposal and their slots are incremental,
  697. /// excluding the genesis block proposal.
  698. pub fn check_state_checkpoint(
  699. &self,
  700. state_checkpoint: &StateCheckpoint,
  701. previous: &StateCheckpoint,
  702. ) -> bool {
  703. if state_checkpoint.proposal.block.header.previous == self.genesis_block {
  704. info!(target: "consensus::state", "check_checkpoint(): Genesis block proposal provided.");
  705. return false
  706. }
  707. if state_checkpoint.proposal.block.header.previous != previous.proposal.hash ||
  708. state_checkpoint.proposal.block.header.slot <= previous.proposal.block.header.slot
  709. {
  710. info!(target: "consensus::state", "check_checkpoint(): Provided state checkpoint proposal is invalid.");
  711. return false
  712. }
  713. // TODO: validate rest checkpoint info(like nullifiers)
  714. true
  715. }
  716. }
  717. /// Auxiliary structure used for forks syncing
  718. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  719. pub struct ForkInfo {
  720. pub genesis_block: blake3::Hash,
  721. pub sequence: Vec<StateCheckpointInfo>,
  722. }
  723. impl From<Fork> for ForkInfo {
  724. fn from(fork: Fork) -> Self {
  725. let mut sequence = vec![];
  726. for state_checkpoint in fork.sequence {
  727. sequence.push(state_checkpoint.into());
  728. }
  729. Self { genesis_block: fork.genesis_block, sequence }
  730. }
  731. }
  732. impl From<ForkInfo> for Fork {
  733. fn from(fork_info: ForkInfo) -> Self {
  734. let mut sequence = vec![];
  735. for checkpoint in fork_info.sequence {
  736. sequence.push(checkpoint.into());
  737. }
  738. Self { genesis_block: fork_info.genesis_block, sequence }
  739. }
  740. }
  741. #[cfg(test)]
  742. mod tests {
  743. use crate::{
  744. consensus::{
  745. state::{Blockchain, ConsensusState},
  746. utils::fbig2base,
  747. Float10, TESTNET_BOOTSTRAP_TIMESTAMP, TESTNET_GENESIS_HASH_BYTES,
  748. TESTNET_GENESIS_TIMESTAMP, TESTNET_INITIAL_DISTRIBUTION,
  749. },
  750. wallet::WalletDb,
  751. Result,
  752. };
  753. #[async_std::test]
  754. async fn calc_sigmas_test() -> Result<()> {
  755. // Generate dummy state
  756. let wallet = WalletDb::new(None, "foo").await?;
  757. let sled_db = sled::Config::new().temporary(true).open()?;
  758. let blockchain = Blockchain::new(&sled_db)?;
  759. let state = ConsensusState::new(
  760. wallet,
  761. blockchain,
  762. *TESTNET_BOOTSTRAP_TIMESTAMP,
  763. *TESTNET_GENESIS_TIMESTAMP,
  764. *TESTNET_GENESIS_HASH_BYTES,
  765. *TESTNET_INITIAL_DISTRIBUTION,
  766. true,
  767. );
  768. let precision_diff = Float10::try_from(
  769. "10000000000000000000000000000000000000000000000000000000000000000000000000",
  770. )
  771. .unwrap();
  772. let precision_diff_base = fbig2base(precision_diff);
  773. let f = Float10::try_from("0.01").unwrap();
  774. let total_stake = Float10::try_from("100").unwrap();
  775. let (sigma1, sigma2) = state.calc_sigmas(f, total_stake);
  776. let sigma1_rhs = Float10::try_from(
  777. "2909373465034095801035568917399197865646520818579502832252119592405565440",
  778. )
  779. .unwrap();
  780. let sigma1_rhs_base = fbig2base(sigma1_rhs);
  781. let sigma2_rhs = Float10::try_from(
  782. "9137556389643100714432609642916129738741963230846798778430644027392",
  783. )
  784. .unwrap();
  785. let sigma2_rhs_base = fbig2base(sigma2_rhs);
  786. let sigma1_delta = if sigma1_rhs_base > sigma1 {
  787. sigma1_rhs_base - sigma1
  788. } else {
  789. sigma1 - sigma1_rhs_base
  790. };
  791. let sigma2_delta = if sigma2_rhs_base > sigma2 {
  792. sigma2_rhs_base - sigma2
  793. } else {
  794. sigma2 - sigma2_rhs_base
  795. };
  796. //note! test cases were generated by low precision python scripts.
  797. //https://github.com/ertosns/lotterysim/blob/master/pallas_unittests.csv
  798. assert!(sigma1_delta < precision_diff_base);
  799. assert!(sigma2_delta < precision_diff_base);
  800. Ok(())
  801. }
  802. }