state.rs 34 KB

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