state.rs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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 std::time::Duration;
  19. use chrono::{NaiveDateTime, Utc};
  20. use darkfi_sdk::{
  21. crypto::{constants::MERKLE_DEPTH, MerkleNode},
  22. incrementalmerkletree::bridgetree::BridgeTree,
  23. pasta::{group::ff::PrimeField, pallas},
  24. };
  25. use darkfi_serial::{SerialDecodable, SerialEncodable};
  26. use log::info;
  27. use rand::{thread_rng, Rng};
  28. use super::{
  29. constants,
  30. leadcoin::{LeadCoin, LeadCoinSecrets},
  31. utils::fbig2base,
  32. Block, BlockProposal, Float10,
  33. };
  34. use crate::{blockchain::Blockchain, net, tx::Transaction, util::time::Timestamp, Error, Result};
  35. use std::io::{prelude::*, BufWriter};
  36. use std::fs::File;
  37. /// This struct represents the information required by the consensus algorithm
  38. pub struct ConsensusState {
  39. /// Canonical (finalized) blockchain
  40. pub blockchain: Blockchain,
  41. /// Network bootstrap timestamp
  42. pub bootstrap_ts: Timestamp,
  43. /// Genesis block creation timestamp
  44. pub genesis_ts: Timestamp,
  45. /// Genesis block hash
  46. pub genesis_block: blake3::Hash,
  47. /// Total sum of initial staking coins
  48. pub initial_distribution: u64,
  49. /// Slot the network was bootstrapped
  50. pub bootstrap_slot: u64,
  51. /// Participating start slot
  52. pub participating: Option<u64>,
  53. /// Node is able to propose proposals
  54. pub proposing: bool,
  55. /// Last slot node check for finalization
  56. pub checked_finalization: u64,
  57. /// Slots offset since genesis,
  58. pub offset: Option<u64>,
  59. /// Fork chains containing block proposals
  60. pub forks: Vec<Fork>,
  61. /// Current epoch
  62. pub epoch: u64,
  63. /// Current epoch eta
  64. pub epoch_eta: pallas::Base,
  65. /// Hot/live slot checkpoints
  66. pub slot_checkpoints: Vec<SlotCheckpoint>,
  67. /// Leaders count history
  68. pub leaders_history: Vec<u64>,
  69. /// controller output history
  70. pub f_history: Vec<Float10>,
  71. /// controller proportional error history
  72. pub err_history: Vec<Float10>,
  73. // TODO: Aren't these already in db after finalization?
  74. /// Canonical competing coins
  75. pub coins: Vec<LeadCoin>,
  76. /// Canonical coin commitments tree
  77. pub coins_tree: BridgeTree<MerkleNode, MERKLE_DEPTH>,
  78. /// Canonical seen nullifiers from proposals
  79. pub nullifiers: Vec<pallas::Base>,
  80. }
  81. impl ConsensusState {
  82. pub fn new(
  83. blockchain: Blockchain,
  84. bootstrap_ts: Timestamp,
  85. genesis_ts: Timestamp,
  86. genesis_data: blake3::Hash,
  87. initial_distribution: u64,
  88. ) -> Result<Self> {
  89. let genesis_block = Block::genesis_block(genesis_ts, genesis_data).blockhash();
  90. Ok(Self {
  91. blockchain,
  92. bootstrap_ts,
  93. genesis_ts,
  94. genesis_block,
  95. initial_distribution,
  96. bootstrap_slot: 0,
  97. participating: None,
  98. proposing: false,
  99. checked_finalization: 0,
  100. offset: None,
  101. forks: vec![],
  102. epoch: 0,
  103. epoch_eta: pallas::Base::zero(),
  104. slot_checkpoints: vec![],
  105. leaders_history: vec![0],
  106. f_history: vec![constants::FLOAT10_ZERO.clone()],
  107. err_history: vec![constants::FLOAT10_ZERO.clone(),
  108. constants::FLOAT10_ZERO.clone()],
  109. coins: vec![],
  110. coins_tree: BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(constants::EPOCH_LENGTH * 100),
  111. nullifiers: vec![],
  112. })
  113. }
  114. /// Calculates current epoch.
  115. pub fn current_epoch(&self) -> u64 {
  116. self.slot_epoch(self.current_slot())
  117. }
  118. /// Calculates the epoch of the provided slot.
  119. /// Epoch duration is configured using the `EPOCH_LENGTH` value.
  120. pub fn slot_epoch(&self, slot: u64) -> u64 {
  121. slot / constants::EPOCH_LENGTH as u64
  122. }
  123. /// Calculates current slot, based on elapsed time from the genesis block.
  124. /// Slot duration is configured using the `SLOT_TIME` constant.
  125. pub fn current_slot(&self) -> u64 {
  126. self.genesis_ts.elapsed() / constants::SLOT_TIME
  127. }
  128. /// Calculates the relative number of the provided slot.
  129. pub fn relative_slot(&self, slot: u64) -> u64 {
  130. slot % constants::EPOCH_LENGTH as u64
  131. }
  132. /// Finds the last slot a proposal or block was generated.
  133. pub fn last_slot(&self) -> Result<u64> {
  134. let mut slot = 0;
  135. for chain in &self.forks {
  136. for state_checkpoint in &chain.sequence {
  137. if state_checkpoint.proposal.block.header.slot > slot {
  138. slot = state_checkpoint.proposal.block.header.slot;
  139. }
  140. }
  141. }
  142. // We return here in case proposals exist,
  143. // so we don't query the sled database.
  144. if slot > 0 {
  145. return Ok(slot)
  146. }
  147. let (last_slot, _) = self.blockchain.last()?;
  148. Ok(last_slot)
  149. }
  150. /// Calculates seconds until next Nth slot starting time.
  151. /// Slots duration is configured using the SLOT_TIME constant.
  152. pub fn next_n_slot_start(&self, n: u64) -> Duration {
  153. assert!(n > 0);
  154. let start_time = NaiveDateTime::from_timestamp_opt(self.genesis_ts.0, 0).unwrap();
  155. let current_slot = self.current_slot() + n;
  156. let next_slot_start =
  157. (current_slot * constants::SLOT_TIME) + (start_time.timestamp() as u64);
  158. let next_slot_start = NaiveDateTime::from_timestamp_opt(next_slot_start as i64, 0).unwrap();
  159. let current_time = NaiveDateTime::from_timestamp_opt(Utc::now().timestamp(), 0).unwrap();
  160. let diff = next_slot_start - current_time;
  161. Duration::new(diff.num_seconds().try_into().unwrap(), 0)
  162. }
  163. /// Calculate slots until next Nth epoch.
  164. /// Epoch duration is configured using the EPOCH_LENGTH value.
  165. pub fn slots_to_next_n_epoch(&self, n: u64) -> u64 {
  166. assert!(n > 0);
  167. let slots_till_next_epoch =
  168. constants::EPOCH_LENGTH as u64 - self.relative_slot(self.current_slot());
  169. ((n - 1) * constants::EPOCH_LENGTH as u64) + slots_till_next_epoch
  170. }
  171. /// Calculates seconds until next Nth epoch starting time.
  172. pub fn next_n_epoch_start(&self, n: u64) -> Duration {
  173. self.next_n_slot_start(self.slots_to_next_n_epoch(n))
  174. }
  175. /// Set participating slot to next.
  176. pub fn set_participating(&mut self) -> Result<()> {
  177. self.participating = Some(self.current_slot() + 1);
  178. Ok(())
  179. }
  180. /// Generate current slot checkpoint
  181. fn generate_slot_checkpoint(&mut self, sigma1: pallas::Base, sigma2: pallas::Base) {
  182. let slot = self.current_slot();
  183. let eta = self.get_eta();
  184. info!("generate_slot_checkpoint: slot: {:?}, eta: {:?}", slot, eta);
  185. let checkpoint = SlotCheckpoint { slot, eta, sigma1, sigma2 };
  186. self.slot_checkpoints.push(checkpoint);
  187. }
  188. // Initialize node lead coins and set current epoch and eta.
  189. pub async fn init_coins(&mut self) -> Result<()> {
  190. self.epoch = self.current_epoch();
  191. if self.slot_checkpoints.is_empty() {
  192. // Create slot checkpoint if not on genesis slot (already in db)
  193. if self.current_slot() != 0 {
  194. self.epoch_eta = self.get_eta();
  195. let (sigma1, sigma2) = self.sigmas();
  196. self.generate_slot_checkpoint(sigma1, sigma2);
  197. }
  198. } else {
  199. let last_slot_checkpoint = self.slot_checkpoints.last().unwrap();
  200. self.epoch_eta = last_slot_checkpoint.eta;
  201. };
  202. self.coins = self.create_coins().await?;
  203. self.update_forks_checkpoints();
  204. Ok(())
  205. }
  206. /// Check if new epoch has started and generate slot checkpoint.
  207. /// Returns flag to signify if epoch has changed.
  208. pub async fn epoch_changed(
  209. &mut self,
  210. sigma1: pallas::Base,
  211. sigma2: pallas::Base,
  212. ) -> Result<bool> {
  213. self.generate_slot_checkpoint(sigma1, sigma2);
  214. let epoch = self.current_epoch();
  215. if epoch <= self.epoch {
  216. return Ok(false)
  217. }
  218. self.epoch = epoch;
  219. self.epoch_eta = self.get_eta();
  220. Ok(true)
  221. }
  222. /// Return 2-term target approximation sigma coefficients.
  223. pub fn sigmas(&mut self) -> (pallas::Base, pallas::Base) {
  224. let f = self.win_inv_prob_with_full_stake();
  225. let total_stake = self.total_stake();
  226. let total_sigma = Float10::try_from(total_stake).unwrap();
  227. Self::calc_sigmas(f, total_sigma)
  228. }
  229. fn calc_sigmas(f: Float10, total_sigma: Float10) -> (pallas::Base, pallas::Base) {
  230. info!("sigmas(): f: {}", f);
  231. info!("sigmas(): stake: {:}", total_sigma);
  232. let one = constants::FLOAT10_ONE.clone();
  233. let neg_one = constants::FLOAT10_NEG_ONE.clone();
  234. let two = constants::FLOAT10_TWO.clone();
  235. let field_p = Float10::try_from(constants::P).unwrap();
  236. let x = one - f;
  237. let c = x.ln();
  238. let neg_c = neg_one * c;
  239. let sigma1_fbig = neg_c.clone() / total_sigma.clone() * field_p.clone();
  240. println!("sigma1_fbig: {:}", sigma1_fbig);
  241. let sigma1 = fbig2base(sigma1_fbig);
  242. let sigma2_fbig = (neg_c / total_sigma).powf(two.clone()) * (field_p / two);
  243. println!("sigma2_fbig: {:}", sigma2_fbig);
  244. let sigma2 = fbig2base(sigma2_fbig);
  245. (sigma1, sigma2)
  246. }
  247. /// Generate coins for provided sigmas.
  248. /// NOTE: The strategy here is having a single competing coin per slot.
  249. // TODO: DRK coin need to be burned, and consensus coin to be minted.
  250. async fn create_coins(&mut self,
  251. //eta: pallas::Base,
  252. ) -> Result<Vec<LeadCoin>> {
  253. let slot = self.current_slot();
  254. // TODO: cleanup LeadCoinSecrets, no need to keep a vector
  255. let mut rng = thread_rng();
  256. let mut seeds: Vec<u64> = Vec::with_capacity(constants::EPOCH_LENGTH);
  257. for _ in 0..constants::EPOCH_LENGTH {
  258. seeds.push(rng.gen());
  259. }
  260. let epoch_secrets = LeadCoinSecrets::generate();
  261. // LeadCoin matrix containing node competing coins.
  262. let mut coins: Vec<LeadCoin> = Vec::with_capacity(constants::EPOCH_LENGTH);
  263. // TODO: TESTNET: Here we would look into the wallet to find coins we're able to use.
  264. // The wallet has specific tables for consensus coins.
  265. // TODO: TESTNET: Token ID still has to be enforced properly in the consensus.
  266. // Temporarily, we compete with fixed stake.
  267. // This stake should be based on how many nodes we want to run, and they all
  268. // must sum to initial distribution total coins.
  269. //let stake = self.initial_distribution;
  270. let coin = LeadCoin::new(
  271. 200,
  272. slot,
  273. epoch_secrets.secret_keys[0].inner(),
  274. epoch_secrets.merkle_roots[0],
  275. 0,
  276. epoch_secrets.merkle_paths[0],
  277. pallas::Base::from(seeds[0]),
  278. &mut self.coins_tree,
  279. );
  280. coins.push(coin);
  281. Ok(coins)
  282. }
  283. /// Leadership reward, assuming constant reward
  284. /// TODO (res) implement reward mechanism with accord to DRK,DARK token-economics
  285. fn reward(&self) -> u64 {
  286. constants::REWARD
  287. }
  288. /// Auxillary function to receive current slot offset.
  289. /// If offset is None, its setted up as last block slot offset.
  290. pub fn get_current_offset(&mut self, current_slot: u64) -> u64 {
  291. // This is the case were we restarted our node, didn't receive offset from other nodes,
  292. // so we need to find offset from last block, exluding network dead period.
  293. if self.offset.is_none() {
  294. let (last_slot, last_offset) = self.blockchain.get_last_offset().unwrap();
  295. let offset = last_offset + (current_slot - last_slot);
  296. info!(target: "consensus::state", "get_current_offset(): Setting slot offset: {}", offset);
  297. self.offset = Some(offset);
  298. }
  299. self.offset.unwrap()
  300. }
  301. /// Auxillary function to calculate overall empty slots.
  302. /// We keep an offset from genesis indicating when the first slot actually started.
  303. /// This offset is shared between nodes.
  304. fn overall_empty_slots(&mut self, current_slot: u64) -> u64 {
  305. // Retrieve existing blocks excluding genesis
  306. let blocks = (self.blockchain.len() as u64) - 1;
  307. // Setup offset if only have genesis and havent received offset from other nodes
  308. if blocks == 0 && self.offset.is_none() {
  309. info!(
  310. target: "consensus::state",
  311. "overall_empty_slots(): Blockchain contains only genesis, setting slot offset: {}",
  312. current_slot
  313. );
  314. self.offset = Some(current_slot);
  315. }
  316. // Retrieve longest fork length, to also those proposals in the calculation
  317. let max_fork_length = self.longest_chain_length() as u64;
  318. current_slot - blocks - self.get_current_offset(current_slot) - max_fork_length
  319. }
  320. /// Network total stake, assuming constant reward.
  321. /// Only used for fine-tuning. At genesis epoch first slot, of absolute index 0,
  322. /// if no stake was distributed, the total stake would be 0.
  323. /// To avoid division by zero, we asume total stake at first division is GENESIS_TOTAL_STAKE(1).
  324. fn total_stake(&mut self) -> u64 {
  325. let current_slot = self.current_slot();
  326. let rewarded_slots = current_slot - self.overall_empty_slots(current_slot) - 1;
  327. let rewards = rewarded_slots * self.reward();
  328. let total_stake = rewards + self.initial_distribution;
  329. if total_stake == 0 {
  330. return constants::GENESIS_TOTAL_STAKE
  331. }
  332. total_stake
  333. }
  334. /// Calculate how many leaders existed in previous slot and appends
  335. /// it to history, to report it if win. On finalization sync period,
  336. /// node replaces its leaders history with the sequence extracted by
  337. /// the longest fork.
  338. fn extend_leaders_history(&mut self) -> Float10 {
  339. let slot = self.current_slot();
  340. let previous_slot = slot - 1;
  341. let mut count = 0;
  342. for chain in &self.forks {
  343. // Previous slot proposals exist at end of each fork
  344. if chain.sequence.last().unwrap().proposal.block.header.slot == previous_slot {
  345. count += 1;
  346. }
  347. }
  348. self.leaders_history.push(count);
  349. info!("extend_leaders_history(): Current leaders history: {:?}", self.leaders_history);
  350. let mut count_str : String = count.to_string();
  351. count_str.push_str(",");
  352. let f = File::options().append(true).open(constants::LEADER_HISTORY_LOG).unwrap();
  353. {
  354. let mut writer = BufWriter::new(f);
  355. writer.write(&count_str.into_bytes()).unwrap();
  356. }
  357. Float10::try_from(count as i64).unwrap()
  358. }
  359. fn f_err(&mut self) -> Float10 {
  360. let len = self.leaders_history.len();
  361. let feedback = Float10::try_from(self.leaders_history[len-1] as i64).unwrap();
  362. let target = constants::FLOAT10_ONE.clone();
  363. target - feedback
  364. }
  365. fn discrete_pid(&mut self) -> Float10 {
  366. let k1 = constants::KP.clone() +
  367. constants::KI.clone() +
  368. constants::KD.clone();
  369. let k2 = constants::FLOAT10_NEG_ONE.clone() * constants::KP.clone() + constants::FLOAT10_NEG_TWO.clone() * constants::KD.clone();
  370. let k3 = constants::KD.clone();
  371. let f_len = self.f_history.len();
  372. let err = self.f_err();
  373. let err_len = self.err_history.len();
  374. let ret = self.f_history[f_len-1].clone() +
  375. k1.clone() * err.clone() +
  376. k2.clone() * self.err_history[err_len-1].clone() +
  377. k3.clone() * self.err_history[err_len-2].clone();
  378. info!("pid::f-1: {:}", self.f_history[f_len-1].clone());
  379. info!("pid::err: {:}", err);
  380. info!("pid::err-1: {}", self.err_history[err_len-1].clone());
  381. info!("pid::err-2: {}", self.err_history[err_len-2].clone());
  382. info!("pid::k1: {}", k1.clone());
  383. info!("pid::k2: {}", k2.clone());
  384. info!("pid::k3: {}", k3.clone());
  385. self.err_history.push(err.clone());
  386. ret
  387. }
  388. /// the probability inverse of winnig lottery having all the stake
  389. /// returns f
  390. fn win_inv_prob_with_full_stake(&mut self) -> Float10 {
  391. self.extend_leaders_history();
  392. //
  393. let mut f = self.discrete_pid();
  394. if f <= constants::FLOAT10_ZERO.clone() {
  395. f = constants::MIN_F.clone()
  396. } else if f >= constants::FLOAT10_ONE.clone() {
  397. f = constants::MAX_F.clone()
  398. }
  399. // log f history
  400. let file = File::options().append(true).open(constants::F_HISTORY_LOG).unwrap();
  401. {
  402. let mut f_history = format!("{:}", f);
  403. f_history.push_str(",");
  404. let mut writer = BufWriter::new(file);
  405. writer.write(&f_history.into_bytes()).unwrap();
  406. }
  407. self.f_history.push(f.clone());
  408. f
  409. }
  410. /// Check that the participant/stakeholder coins win the slot lottery.
  411. /// If the stakeholder has multiple competing winning coins, only the highest value
  412. /// coin is selected, since the stakeholder can't give more than one proof per block/slot.
  413. /// * 'sigma1', 'sigma2': slot sigmas
  414. /// Returns: (check: bool, idx: usize) where idx is the winning coin's index
  415. pub fn is_slot_leader(
  416. &mut self,
  417. sigma1: pallas::Base,
  418. sigma2: pallas::Base,
  419. ) -> (bool, i64, usize) {
  420. // Check if node can produce proposals
  421. if !self.proposing {
  422. return (false, 0, 0)
  423. }
  424. let fork_index = self.longest_chain_index();
  425. let competing_coins = if fork_index == -1 {
  426. self.coins.clone()
  427. } else {
  428. self.forks[fork_index as usize].sequence.last().unwrap().coins.clone()
  429. };
  430. let mut won = false;
  431. let mut highest_stake = 0;
  432. let mut highest_stake_idx = 0;
  433. let total_stake = self.total_stake();
  434. for (winning_idx, coin) in competing_coins.iter().enumerate() {
  435. info!("is_slot_leader: coin stake: {:?}", coin.value);
  436. info!("is_slot_leader: total stake: {}", total_stake);
  437. info!("is_slot_leader: relative stake: {}", (coin.value as f64) / total_stake as f64);
  438. let first_winning = coin.is_leader(sigma1,
  439. sigma2,
  440. self.get_eta(),
  441. pallas::Base::from(self.current_slot()));
  442. if first_winning && !won {
  443. highest_stake_idx = winning_idx;
  444. }
  445. won |= first_winning;
  446. if won && coin.value > highest_stake {
  447. highest_stake = coin.value;
  448. highest_stake_idx = winning_idx;
  449. }
  450. }
  451. (won, fork_index, highest_stake_idx)
  452. }
  453. /// Finds the longest forkchain the node holds and
  454. /// returns its index.
  455. pub fn longest_chain_index(&self) -> i64 {
  456. let mut length = 0;
  457. let mut index = -1;
  458. if !self.forks.is_empty() {
  459. for (i, chain) in self.forks.iter().enumerate() {
  460. if chain.sequence.len() > length {
  461. length = chain.sequence.len();
  462. index = i as i64;
  463. }
  464. }
  465. }
  466. index
  467. }
  468. /// Finds the length of longest fork chain the node holds.
  469. pub fn longest_chain_length(&self) -> usize {
  470. let mut max = 0;
  471. for fork in &self.forks {
  472. if fork.sequence.len() > max {
  473. max = fork.sequence.len();
  474. }
  475. }
  476. max
  477. }
  478. /// Given a proposal, find the index of the fork chain it extends.
  479. pub fn find_extended_chain_index(&mut self, proposal: &BlockProposal) -> Result<i64> {
  480. // We iterate through all forks to find which fork to extend
  481. let mut chain_index = -1;
  482. let mut state_checkpoint_index = 0;
  483. for (c_index, chain) in self.forks.iter().enumerate() {
  484. // Traverse sequence in reverse
  485. for (sc_index, state_checkpoint) in chain.sequence.iter().enumerate().rev() {
  486. if proposal.block.header.previous == state_checkpoint.proposal.hash {
  487. chain_index = c_index as i64;
  488. state_checkpoint_index = sc_index;
  489. break
  490. }
  491. }
  492. if chain_index != -1 {
  493. break
  494. }
  495. }
  496. // If no fork was found, we check with canonical
  497. if chain_index == -1 {
  498. let (last_slot, last_block) = self.blockchain.last()?;
  499. if proposal.block.header.previous != last_block ||
  500. proposal.block.header.slot <= last_slot
  501. {
  502. info!(target: "consensus::state", "find_extended_chain_index(): Proposal doesn't extend any known chain");
  503. return Ok(-2)
  504. }
  505. // Proposal extends canonical chain
  506. return Ok(-1)
  507. }
  508. // Found fork chain
  509. let chain = &self.forks[chain_index as usize];
  510. // Proposal extends fork at last proposal
  511. if state_checkpoint_index == (chain.sequence.len() - 1) {
  512. return Ok(chain_index)
  513. }
  514. info!(target: "consensus::state", "find_extended_chain_index(): Proposal to fork a forkchain was received.");
  515. let mut chain = self.forks[chain_index as usize].clone();
  516. // We keep all proposals until the one it extends
  517. chain.sequence.drain((state_checkpoint_index + 1)..);
  518. self.forks.push(chain);
  519. Ok(self.forks.len() as i64 - 1)
  520. }
  521. /// Search the chains we're holding for the given proposal.
  522. pub fn proposal_exists(&self, input_proposal: &blake3::Hash) -> bool {
  523. for chain in self.forks.iter() {
  524. for state_checkpoint in chain.sequence.iter().rev() {
  525. if input_proposal == &state_checkpoint.proposal.hash {
  526. return true
  527. }
  528. }
  529. }
  530. false
  531. }
  532. /// Auxillary function to set nodes leaders count history to the largest fork sequence
  533. /// of leaders, by using provided index.
  534. pub fn set_leader_history(&mut self, index: i64, current_slot: u64) {
  535. // Check if we found longest fork to extract sequence from
  536. match index {
  537. -1 => {
  538. info!(target: "consensus::state", "set_leader_history(): No fork exists.");
  539. }
  540. _ => {
  541. info!(target: "consensus::state", "set_leader_history(): Checking last proposal of fork: {}", index);
  542. let last_proposal = &self.forks[index as usize].sequence.last().unwrap().proposal;
  543. if last_proposal.block.header.slot == current_slot {
  544. // Replacing our last history element with the leaders one
  545. self.leaders_history.pop();
  546. self.leaders_history.push(last_proposal.block.lead_info.leaders);
  547. info!(target: "consensus::state", "set_leader_history(): New leaders history: {:?}", self.leaders_history);
  548. return
  549. }
  550. }
  551. }
  552. //self.leaders_history.push(0);
  553. }
  554. /// Utility function to extract leader selection lottery randomness(eta),
  555. /// defined as the hash of the previous lead proof converted to pallas base.
  556. pub fn get_eta(&self) -> pallas::Base {
  557. let proof_tx_hash = self.blockchain.get_last_proof_hash().unwrap();
  558. let mut bytes: [u8; 32] = *proof_tx_hash.as_bytes();
  559. // read first 254 bits
  560. bytes[30] = 0;
  561. bytes[31] = 0;
  562. pallas::Base::from_repr(bytes).unwrap()
  563. }
  564. /// Auxillary function to retrieve slot checkpoint of provided slot UID.
  565. pub fn get_slot_checkpoint(&self, slot: u64) -> Result<SlotCheckpoint> {
  566. // Check hot/live slot checkpoints
  567. for slot_checkpoint in self.slot_checkpoints.iter().rev() {
  568. if slot_checkpoint.slot == slot {
  569. return Ok(slot_checkpoint.clone())
  570. }
  571. }
  572. // Check if slot is finalized
  573. if let Ok(slot_checkpoints) = self.blockchain.get_slot_checkpoints_by_slot(&[slot]) {
  574. if !slot_checkpoints.is_empty() {
  575. if let Some(slot_checkpoint) = &slot_checkpoints[0] {
  576. return Ok(slot_checkpoint.clone())
  577. }
  578. }
  579. }
  580. Err(Error::SlotCheckpointNotFound(slot))
  581. }
  582. /// Auxillary function to update all fork state checkpoints to nodes coins current canonical states.
  583. /// Note: This function should only be invoked once on nodes' coins creation.
  584. pub fn update_forks_checkpoints(&mut self) {
  585. for fork in &mut self.forks {
  586. for state_checkpoint in &mut fork.sequence {
  587. state_checkpoint.coins = self.coins.clone();
  588. state_checkpoint.coins_tree = self.coins_tree.clone();
  589. }
  590. }
  591. }
  592. /// Auxiliary structure to reset consensus state for a resync
  593. pub fn reset(&mut self) {
  594. self.participating = None;
  595. self.proposing = false;
  596. self.offset = None;
  597. self.forks = vec![];
  598. self.slot_checkpoints = vec![];
  599. self.leaders_history = vec![0];
  600. self.nullifiers = vec![];
  601. }
  602. }
  603. /// Auxiliary structure used for consensus syncing.
  604. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  605. pub struct ConsensusRequest {}
  606. impl net::Message for ConsensusRequest {
  607. fn name() -> &'static str {
  608. "consensusrequest"
  609. }
  610. }
  611. /// Auxiliary structure used for consensus syncing.
  612. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  613. pub struct ConsensusResponse {
  614. /// Slot the network was bootstrapped
  615. pub bootstrap_slot: u64,
  616. /// Slots offset since genesis,
  617. pub offset: Option<u64>,
  618. /// Hot/live data used by the consensus algorithm
  619. pub forks: Vec<ForkInfo>,
  620. /// Pending transactions
  621. pub unconfirmed_txs: Vec<Transaction>,
  622. /// Hot/live slot checkpoints
  623. pub slot_checkpoints: Vec<SlotCheckpoint>,
  624. /// Leaders count history
  625. pub leaders_history: Vec<u64>,
  626. /// Seen nullifiers from proposals
  627. pub nullifiers: Vec<pallas::Base>,
  628. }
  629. impl net::Message for ConsensusResponse {
  630. fn name() -> &'static str {
  631. "consensusresponse"
  632. }
  633. }
  634. /// Auxiliary structure used for consensus syncing.
  635. #[derive(Debug, SerialEncodable, SerialDecodable)]
  636. pub struct ConsensusSlotCheckpointsRequest {}
  637. impl net::Message for ConsensusSlotCheckpointsRequest {
  638. fn name() -> &'static str {
  639. "consensusslotcheckpointsrequest"
  640. }
  641. }
  642. /// Auxiliary structure used for consensus syncing.
  643. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  644. pub struct ConsensusSlotCheckpointsResponse {
  645. /// Node known bootstrap slot
  646. pub bootstrap_slot: u64,
  647. /// Node has hot/live slot checkpoints
  648. pub is_empty: bool,
  649. }
  650. impl net::Message for ConsensusSlotCheckpointsResponse {
  651. fn name() -> &'static str {
  652. "consensusslotcheckpointsresponse"
  653. }
  654. }
  655. /// Auxiliary structure used to keep track of slot validation parameters.
  656. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  657. pub struct SlotCheckpoint {
  658. /// Slot UID
  659. pub slot: u64,
  660. /// Slot eta
  661. pub eta: pallas::Base,
  662. /// Slot sigma1
  663. pub sigma1: pallas::Base,
  664. /// Slot sigma2
  665. pub sigma2: pallas::Base,
  666. }
  667. impl SlotCheckpoint {
  668. pub fn new(slot: u64, eta: pallas::Base, sigma1: pallas::Base, sigma2: pallas::Base) -> Self {
  669. Self { slot, eta, sigma1, sigma2 }
  670. }
  671. /// Generate the genesis slot checkpoint.
  672. pub fn genesis_slot_checkpoint() -> Self {
  673. let eta = pallas::Base::zero();
  674. let sigma1 = pallas::Base::zero();
  675. let sigma2 = pallas::Base::zero();
  676. Self::new(0, eta, sigma1, sigma2)
  677. }
  678. }
  679. impl net::Message for SlotCheckpoint {
  680. fn name() -> &'static str {
  681. "slotcheckpoint"
  682. }
  683. }
  684. /// Auxiliary structure used for slot checkpoints syncing
  685. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  686. pub struct SlotCheckpointRequest {
  687. /// Slot UID
  688. pub slot: u64,
  689. }
  690. impl net::Message for SlotCheckpointRequest {
  691. fn name() -> &'static str {
  692. "slotcheckpointrequest"
  693. }
  694. }
  695. /// Auxiliary structure used for slot checkpoints syncing
  696. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  697. pub struct SlotCheckpointResponse {
  698. /// Response blocks.
  699. pub slot_checkpoints: Vec<SlotCheckpoint>,
  700. }
  701. impl net::Message for SlotCheckpointResponse {
  702. fn name() -> &'static str {
  703. "slotcheckpointresponse"
  704. }
  705. }
  706. /// Auxiliary structure used to keep track of consensus state checkpoints.
  707. #[derive(Debug, Clone)]
  708. pub struct StateCheckpoint {
  709. /// Block proposal
  710. pub proposal: BlockProposal,
  711. /// Node competing coins current state
  712. pub coins: Vec<LeadCoin>,
  713. /// Coin commitments tree current state
  714. pub coins_tree: BridgeTree<MerkleNode, MERKLE_DEPTH>,
  715. /// Seen nullifiers from proposals current state
  716. pub nullifiers: Vec<pallas::Base>,
  717. }
  718. impl StateCheckpoint {
  719. pub fn new(
  720. proposal: BlockProposal,
  721. coins: Vec<LeadCoin>,
  722. coins_tree: BridgeTree<MerkleNode, MERKLE_DEPTH>,
  723. nullifiers: Vec<pallas::Base>,
  724. ) -> Self {
  725. Self { proposal, coins, coins_tree, nullifiers }
  726. }
  727. }
  728. /// Auxiliary structure used for forked consensus state checkpoints syncing
  729. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  730. pub struct StateCheckpointInfo {
  731. /// Block proposal
  732. pub proposal: BlockProposal,
  733. /// Seen nullifiers from proposals current state
  734. pub nullifiers: Vec<pallas::Base>,
  735. }
  736. impl From<StateCheckpoint> for StateCheckpointInfo {
  737. fn from(state_checkpoint: StateCheckpoint) -> Self {
  738. Self { proposal: state_checkpoint.proposal, nullifiers: state_checkpoint.nullifiers }
  739. }
  740. }
  741. impl From<StateCheckpointInfo> for StateCheckpoint {
  742. fn from(state_checkpoint_info: StateCheckpointInfo) -> Self {
  743. Self {
  744. proposal: state_checkpoint_info.proposal,
  745. coins: vec![],
  746. coins_tree: BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(constants::EPOCH_LENGTH * 100),
  747. nullifiers: state_checkpoint_info.nullifiers,
  748. }
  749. }
  750. }
  751. /// This struct represents a sequence of consensus state checkpoints.
  752. #[derive(Debug, Clone)]
  753. pub struct Fork {
  754. pub genesis_block: blake3::Hash,
  755. pub sequence: Vec<StateCheckpoint>,
  756. }
  757. impl Fork {
  758. pub fn new(genesis_block: blake3::Hash, initial_state_checkpoint: StateCheckpoint) -> Self {
  759. Self { genesis_block, sequence: vec![initial_state_checkpoint] }
  760. }
  761. /// Insertion of a valid state checkpoint.
  762. pub fn add(&mut self, state_checkpoint: &StateCheckpoint) {
  763. if self.check_state_checkpoint(state_checkpoint, self.sequence.last().unwrap()) {
  764. self.sequence.push(state_checkpoint.clone());
  765. }
  766. }
  767. /// A fork chain is considered valid when every state checkpoint is valid,
  768. /// based on the `check_state_checkpoint` function
  769. pub fn check_chain(&self) -> bool {
  770. for (index, state_checkpoint) in self.sequence[1..].iter().enumerate() {
  771. if !self.check_state_checkpoint(state_checkpoint, &self.sequence[index]) {
  772. return false
  773. }
  774. }
  775. true
  776. }
  777. /// A state checkpoint is considered valid when its proposal parent hash is equal to the
  778. /// hash of the previous checkpoint's proposal and their slots are incremental,
  779. /// excluding the genesis block proposal.
  780. pub fn check_state_checkpoint(
  781. &self,
  782. state_checkpoint: &StateCheckpoint,
  783. previous: &StateCheckpoint,
  784. ) -> bool {
  785. if state_checkpoint.proposal.block.header.previous == self.genesis_block {
  786. info!(target: "consensus::state", "check_checkpoint(): Genesis block proposal provided.");
  787. return false
  788. }
  789. if state_checkpoint.proposal.block.header.previous != previous.proposal.hash ||
  790. state_checkpoint.proposal.block.header.slot <= previous.proposal.block.header.slot
  791. {
  792. info!(target: "consensus::state", "check_checkpoint(): Provided state checkpoint proposal is invalid.");
  793. return false
  794. }
  795. // TODO: validate rest checkpoint info(like nullifiers)
  796. true
  797. }
  798. }
  799. /// Auxiliary structure used for forks syncing
  800. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  801. pub struct ForkInfo {
  802. pub genesis_block: blake3::Hash,
  803. pub sequence: Vec<StateCheckpointInfo>,
  804. }
  805. impl From<Fork> for ForkInfo {
  806. fn from(fork: Fork) -> Self {
  807. let mut sequence = vec![];
  808. for state_checkpoint in fork.sequence {
  809. sequence.push(state_checkpoint.into());
  810. }
  811. Self { genesis_block: fork.genesis_block, sequence }
  812. }
  813. }
  814. impl From<ForkInfo> for Fork {
  815. fn from(fork_info: ForkInfo) -> Self {
  816. let mut sequence = vec![];
  817. for checkpoint in fork_info.sequence {
  818. sequence.push(checkpoint.into());
  819. }
  820. Self { genesis_block: fork_info.genesis_block, sequence }
  821. }
  822. }
  823. #[cfg(test)]
  824. mod tests {
  825. use darkfi_sdk::{
  826. pasta::{group::ff::PrimeField, pallas},
  827. };
  828. use log::info;
  829. use crate::consensus::{
  830. constants,
  831. state::ConsensusState,
  832. utils::fbig2base,
  833. Float10,
  834. };
  835. use crate::{ Error, Result};
  836. use dashu::base::Abs;
  837. use std::io::{prelude::*, BufWriter};
  838. use std::fs::File;
  839. #[test]
  840. fn calc_sigmas_test() {
  841. let giga_epsilon = Float10::try_from("10000000000000000000000000000000000000000000000000000000000").unwrap();
  842. let giga_epsilon_base = fbig2base(giga_epsilon);
  843. let f = Float10::try_from("0.5").unwrap();
  844. let total_stake = Float10::try_from("1000").unwrap();
  845. let (sigma1, sigma2) = ConsensusState::calc_sigmas(f, total_stake);
  846. let sigma1_rhs = Float10::try_from("20065240046497827749443820209808913616958821867408735207193448041041362944").unwrap();
  847. let sigma1_rhs_base = fbig2base(sigma1_rhs);
  848. let sigma2_rhs = Float10::try_from("6954082282744237239883318512759812991231744634473746668074299461468160").unwrap();
  849. let sigma2_rhs_base = fbig2base(sigma2_rhs);
  850. let sigma1_delta = if sigma1_rhs_base>sigma1 {
  851. sigma1_rhs_base - sigma1
  852. } else {
  853. sigma1 - sigma1_rhs_base
  854. };
  855. let sigma2_delta = if sigma2_rhs_base > sigma2 {
  856. sigma2_rhs_base - sigma2
  857. } else {
  858. sigma2 - sigma2_rhs_base
  859. };
  860. //note! test cases were generated by low precision scripts.
  861. assert!(sigma1_delta < giga_epsilon_base);
  862. assert!(sigma2_delta < giga_epsilon_base);
  863. }
  864. }