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