state.rs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. info!(target: "consensus::state", "sigmas(): f: {}", f);
  227. info!(target: "consensus::state", "sigmas(): stake: {}", total_stake);
  228. let one = constants::FLOAT10_ONE.clone();
  229. let two = constants::FLOAT10_TWO.clone();
  230. let field_p = Float10::try_from(constants::P).unwrap();
  231. let total_sigma = Float10::try_from(total_stake).unwrap();
  232. let x = one - f;
  233. let c = x.ln();
  234. let sigma1_fbig = c.clone() / total_sigma.clone() * field_p.clone();
  235. let sigma1 = fbig2base(sigma1_fbig);
  236. let sigma2_fbig = (c / total_sigma).powf(two.clone()) * (field_p / two);
  237. let sigma2 = fbig2base(sigma2_fbig);
  238. (sigma1, sigma2)
  239. }
  240. /// Generate coins for provided sigmas.
  241. /// NOTE: The strategy here is having a single competing coin per slot.
  242. // TODO: DRK coin need to be burned, and consensus coin to be minted.
  243. async fn create_coins(&mut self,
  244. //eta: pallas::Base,
  245. ) -> Result<Vec<LeadCoin>> {
  246. let slot = self.current_slot();
  247. // TODO: cleanup LeadCoinSecrets, no need to keep a vector
  248. let mut rng = thread_rng();
  249. let mut seeds: Vec<u64> = Vec::with_capacity(constants::EPOCH_LENGTH);
  250. for _ in 0..constants::EPOCH_LENGTH {
  251. seeds.push(rng.gen());
  252. }
  253. let epoch_secrets = LeadCoinSecrets::generate();
  254. // LeadCoin matrix containing node competing coins.
  255. let mut coins: Vec<LeadCoin> = Vec::with_capacity(constants::EPOCH_LENGTH);
  256. // TODO: TESTNET: Here we would look into the wallet to find coins we're able to use.
  257. // The wallet has specific tables for consensus coins.
  258. // TODO: TESTNET: Token ID still has to be enforced properly in the consensus.
  259. // Temporarily, we compete with fixed stake.
  260. // This stake should be based on how many nodes we want to run, and they all
  261. // must sum to initial distribution total coins.
  262. //let stake = self.initial_distribution;
  263. let coin = LeadCoin::new(
  264. 200,
  265. slot,
  266. epoch_secrets.secret_keys[0].inner(),
  267. epoch_secrets.merkle_roots[0],
  268. 0,
  269. epoch_secrets.merkle_paths[0],
  270. pallas::Base::from(seeds[0]),
  271. &mut self.coins_tree,
  272. );
  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 receive current slot offset.
  282. /// If offset is None, its setted up as last block slot offset.
  283. pub fn get_current_offset(&mut self, current_slot: u64) -> u64 {
  284. // This is the case were we restarted our node, didn't receive offset from other nodes,
  285. // so we need to find offset from last block, exluding network dead period.
  286. if self.offset.is_none() {
  287. let (last_slot, last_offset) = self.blockchain.get_last_offset().unwrap();
  288. let offset = last_offset + (current_slot - last_slot);
  289. info!(target: "consensus::state", "get_current_offset(): Setting slot offset: {}", offset);
  290. self.offset = Some(offset);
  291. }
  292. self.offset.unwrap()
  293. }
  294. /// Auxillary function to calculate overall empty slots.
  295. /// We keep an offset from genesis indicating when the first slot actually started.
  296. /// This offset is shared between nodes.
  297. fn overall_empty_slots(&mut self, current_slot: u64) -> u64 {
  298. // Retrieve existing blocks excluding genesis
  299. let blocks = (self.blockchain.len() as u64) - 1;
  300. // Setup offset if only have genesis and havent received offset from other nodes
  301. if blocks == 0 && self.offset.is_none() {
  302. info!(
  303. target: "consensus::state",
  304. "overall_empty_slots(): Blockchain contains only genesis, setting slot offset: {}",
  305. current_slot
  306. );
  307. self.offset = Some(current_slot);
  308. }
  309. // Retrieve longest fork length, to also those proposals in the calculation
  310. let max_fork_length = self.longest_chain_length() as u64;
  311. current_slot - blocks - self.get_current_offset(current_slot) - max_fork_length
  312. }
  313. /// Network total stake, assuming constant reward.
  314. /// Only used for fine-tuning. At genesis epoch first slot, of absolute index 0,
  315. /// if no stake was distributed, the total stake would be 0.
  316. /// To avoid division by zero, we asume total stake at first division is GENESIS_TOTAL_STAKE(1).
  317. fn total_stake(&mut self) -> u64 {
  318. let current_slot = self.current_slot();
  319. let rewarded_slots = current_slot - self.overall_empty_slots(current_slot) - 1;
  320. let rewards = rewarded_slots * self.reward();
  321. let total_stake = rewards + self.initial_distribution;
  322. if total_stake == 0 {
  323. return constants::GENESIS_TOTAL_STAKE
  324. }
  325. total_stake
  326. }
  327. /// Calculate how many leaders existed in previous slot and appends
  328. /// it to history, to report it if win. On finalization sync period,
  329. /// node replaces its leaders history with the sequence extracted by
  330. /// the longest fork.
  331. fn extend_leaders_history(&mut self) -> Float10 {
  332. let slot = self.current_slot();
  333. let previous_slot = slot - 1;
  334. let mut count = 0;
  335. for chain in &self.forks {
  336. // Previous slot proposals exist at end of each fork
  337. if chain.sequence.last().unwrap().proposal.block.header.slot == previous_slot {
  338. count += 1;
  339. }
  340. }
  341. self.leaders_history.push(count);
  342. info!("extend_leaders_history(): Current leaders history: {:?}", self.leaders_history);
  343. let mut count_str : String = count.to_string();
  344. count_str.push_str(",");
  345. let mut f = File::options().append(true).open(constants::LEADER_HISTORY_LOG).unwrap();
  346. {
  347. let mut writer = BufWriter::new(f);
  348. writer.write(&count_str.into_bytes()).unwrap();
  349. }
  350. Float10::try_from(count as i64).unwrap()
  351. }
  352. fn pid_error(feedback: Float10) -> Float10 {
  353. let target = constants::FLOAT10_ONE.clone();
  354. target - feedback
  355. }
  356. fn f_dif(&mut self) -> Float10 {
  357. let len = self.leaders_history.len();
  358. Self::pid_error(Float10::try_from(self.leaders_history[len-1] as i64).unwrap().with_precision(constants::RADIX_BITS).value())
  359. }
  360. fn max_windowed_forks(&self) -> Float10 {
  361. let mut max: u64 = 5;
  362. let window_size = 10;
  363. let len = self.leaders_history.len();
  364. let window_begining = if len <= (window_size + 1) { 0 } else { len - (window_size + 1) };
  365. for item in &self.leaders_history[window_begining..] {
  366. if *item > max {
  367. max = *item;
  368. }
  369. }
  370. Float10::try_from(max as i64).unwrap()
  371. }
  372. fn tuned_kp(&self) -> Float10 {
  373. //(constants::KP.clone() * constants::FLOAT10_FIVE.clone()) / self.max_windowed_forks()
  374. constants::KP.clone()
  375. }
  376. fn weighted_f_dif(&mut self) -> Float10 {
  377. self.tuned_kp() * self.f_dif()
  378. }
  379. fn f_der(&self) -> Float10 {
  380. let len = self.leaders_history.len();
  381. let last = Float10::try_from(self.leaders_history[len - 1] as i64).unwrap();
  382. let second_to_last = Float10::try_from(self.leaders_history[len - 2] as i64).unwrap();
  383. let mut der =
  384. (Self::pid_error(second_to_last) - Self::pid_error(last)) / constants::TD.clone();
  385. /*
  386. der = if der > constants::MAX_DER.clone() { constants::MAX_DER.clone() } else { der };
  387. der = if der < constants::MIN_DER.clone() { constants::MIN_DER.clone() } else { der };
  388. */
  389. der
  390. }
  391. fn weighted_f_der(&self) -> Float10 {
  392. constants::KD.clone() * self.f_der()
  393. }
  394. fn f_int(&self) -> Float10 {
  395. let mut sum = constants::FLOAT10_ZERO.clone();
  396. let lead_history_len = self.leaders_history.len();
  397. let history_begin_index = if lead_history_len > 10 { lead_history_len - 10 } else { 0 };
  398. for lf in &self.leaders_history[history_begin_index..] {
  399. sum += Float10::try_from(*lf).unwrap().abs();
  400. }
  401. sum
  402. }
  403. fn tuned_ki(&self) -> Float10 {
  404. //(constants::KI.clone() * constants::FLOAT10_FIVE.clone()) / self.max_windowed_forks()
  405. constants::KI.clone()
  406. }
  407. fn weighted_f_int(&self) -> Float10 {
  408. //constants::KI.clone() * self.f_int()
  409. self.tuned_ki() * self.f_int()
  410. }
  411. fn zero_leads_len(&self) -> Float10 {
  412. let mut count = constants::FLOAT10_ZERO.clone();
  413. let hist_len = self.leaders_history.len();
  414. for i in 1..hist_len {
  415. if self.leaders_history[hist_len - i] == 0 {
  416. count += constants::FLOAT10_ONE.clone();
  417. } else {
  418. break
  419. }
  420. }
  421. count
  422. }
  423. fn pid(&mut self) -> Float10 {
  424. let p = self.weighted_f_dif();
  425. let i = self.weighted_f_int();
  426. let d = self.weighted_f_der();
  427. info!(target: "consensus::state", "win_inv_prob_with_full_stake(): PID P: {:?}", p);
  428. info!(target: "consensus::state", "win_inv_prob_with_full_stake(): PID I: {:?}", i);
  429. info!(target: "consensus::state", "win_inv_prob_with_full_stake(): PID D: {:?}", d);
  430. let f = p + i.clone() + d;
  431. info!("win_inv_prob_with_full_stake(): PID f: {}", f);
  432. f
  433. }
  434. fn discrete_pid(&mut self) -> Float10 {
  435. let k1 = constants::KP.clone() +
  436. constants::KI.clone() +
  437. constants::KD.clone();
  438. let k2 = constants::FLOAT10_NEG_ONE.clone() * constants::KP.clone() + constants::FLOAT10_NEG_TWO.clone() * constants::KD.clone();
  439. let k3 = constants::KD.clone();
  440. let f_len = self.f_history.len();
  441. let err = self.f_dif();
  442. let err_len = self.err_history.len();
  443. let ret = self.f_history[f_len-1].clone() +
  444. k1.clone() * err.clone() +
  445. k2.clone() * self.err_history[err_len-1].clone() +
  446. k3.clone() * self.err_history[err_len-2].clone();
  447. info!("pid::f-1: {:}", self.f_history[f_len-1].clone());
  448. info!("pid::err: {:}", err);
  449. info!("pid::err-1: {}", self.err_history[err_len-1].clone());
  450. info!("pid::err-2: {}", self.err_history[err_len-2].clone());
  451. info!("pid::k1: {}", k1.clone());
  452. info!("pid::k2: {}", k2.clone());
  453. info!("pid::k3: {}", k3.clone());
  454. self.err_history.push(err.clone());
  455. ret
  456. }
  457. /// the probability inverse of winnig lottery having all the stake
  458. /// returns f
  459. fn win_inv_prob_with_full_stake(&mut self) -> Float10 {
  460. self.extend_leaders_history();
  461. //
  462. let mut f = self.discrete_pid();
  463. if f <= constants::FLOAT10_ZERO.clone() {
  464. f = constants::MIN_F.clone()
  465. } else if f >= constants::FLOAT10_ONE.clone() {
  466. f = constants::MAX_F.clone()
  467. }
  468. let hist_len = self.leaders_history.len();
  469. if hist_len > 3 &&
  470. self.leaders_history[hist_len - 1] == 0 &&
  471. self.leaders_history[hist_len - 2] == 0 &&
  472. self.leaders_history[hist_len - 3] == 0
  473. //&& i == constants::FLOAT10_ZERO.clone()
  474. {
  475. f = f.clone() * constants::DEG_RATE.clone().powf(self.zero_leads_len());
  476. }
  477. // log f history
  478. let file = File::options().append(true).open(constants::F_HISTORY_LOG).unwrap();
  479. {
  480. let mut f_history = format!("{:}", f);
  481. f_history.push_str(",");
  482. let mut writer = BufWriter::new(file);
  483. writer.write(&f_history.into_bytes()).unwrap();
  484. }
  485. self.f_history.push(f.clone());
  486. f
  487. }
  488. /// Check that the participant/stakeholder coins win the slot lottery.
  489. /// If the stakeholder has multiple competing winning coins, only the highest value
  490. /// coin is selected, since the stakeholder can't give more than one proof per block/slot.
  491. /// * 'sigma1', 'sigma2': slot sigmas
  492. /// Returns: (check: bool, idx: usize) where idx is the winning coin's index
  493. pub fn is_slot_leader(
  494. &mut self,
  495. sigma1: pallas::Base,
  496. sigma2: pallas::Base,
  497. ) -> (bool, i64, usize) {
  498. // Check if node can produce proposals
  499. if !self.proposing {
  500. return (false, 0, 0)
  501. }
  502. let fork_index = self.longest_chain_index();
  503. let competing_coins = if fork_index == -1 {
  504. self.coins.clone()
  505. } else {
  506. self.forks[fork_index as usize].sequence.last().unwrap().coins.clone()
  507. };
  508. let mut won = false;
  509. let mut highest_stake = 0;
  510. let mut highest_stake_idx = 0;
  511. let total_stake = self.total_stake();
  512. for (winning_idx, coin) in competing_coins.iter().enumerate() {
  513. info!("is_slot_leader: coin stake: {:?}", coin.value);
  514. info!("is_slot_leader: total stake: {}", total_stake);
  515. info!("is_slot_leader: relative stake: {}", (coin.value as f64) / total_stake as f64);
  516. let first_winning = coin.is_leader(sigma1,
  517. sigma2,
  518. self.get_eta(),
  519. pallas::Base::from(self.current_slot()));
  520. if first_winning && !won {
  521. highest_stake_idx = winning_idx;
  522. }
  523. won |= first_winning;
  524. if won && coin.value > highest_stake {
  525. highest_stake = coin.value;
  526. highest_stake_idx = winning_idx;
  527. }
  528. }
  529. (won, fork_index, highest_stake_idx)
  530. }
  531. /// Finds the longest forkchain the node holds and
  532. /// returns its index.
  533. pub fn longest_chain_index(&self) -> i64 {
  534. let mut length = 0;
  535. let mut index = -1;
  536. if !self.forks.is_empty() {
  537. for (i, chain) in self.forks.iter().enumerate() {
  538. if chain.sequence.len() > length {
  539. length = chain.sequence.len();
  540. index = i as i64;
  541. }
  542. }
  543. }
  544. index
  545. }
  546. /// Finds the length of longest fork chain the node holds.
  547. pub fn longest_chain_length(&self) -> usize {
  548. let mut max = 0;
  549. for fork in &self.forks {
  550. if fork.sequence.len() > max {
  551. max = fork.sequence.len();
  552. }
  553. }
  554. max
  555. }
  556. /// Given a proposal, find the index of the fork chain it extends.
  557. pub fn find_extended_chain_index(&mut self, proposal: &BlockProposal) -> Result<i64> {
  558. // We iterate through all forks to find which fork to extend
  559. let mut chain_index = -1;
  560. let mut state_checkpoint_index = 0;
  561. for (c_index, chain) in self.forks.iter().enumerate() {
  562. // Traverse sequence in reverse
  563. for (sc_index, state_checkpoint) in chain.sequence.iter().enumerate().rev() {
  564. if proposal.block.header.previous == state_checkpoint.proposal.hash {
  565. chain_index = c_index as i64;
  566. state_checkpoint_index = sc_index;
  567. break
  568. }
  569. }
  570. if chain_index != -1 {
  571. break
  572. }
  573. }
  574. // If no fork was found, we check with canonical
  575. if chain_index == -1 {
  576. let (last_slot, last_block) = self.blockchain.last()?;
  577. if proposal.block.header.previous != last_block ||
  578. proposal.block.header.slot <= last_slot
  579. {
  580. info!(target: "consensus::state", "find_extended_chain_index(): Proposal doesn't extend any known chain");
  581. return Ok(-2)
  582. }
  583. // Proposal extends canonical chain
  584. return Ok(-1)
  585. }
  586. // Found fork chain
  587. let chain = &self.forks[chain_index as usize];
  588. // Proposal extends fork at last proposal
  589. if state_checkpoint_index == (chain.sequence.len() - 1) {
  590. return Ok(chain_index)
  591. }
  592. info!(target: "consensus::state", "find_extended_chain_index(): Proposal to fork a forkchain was received.");
  593. let mut chain = self.forks[chain_index as usize].clone();
  594. // We keep all proposals until the one it extends
  595. chain.sequence.drain((state_checkpoint_index + 1)..);
  596. self.forks.push(chain);
  597. Ok(self.forks.len() as i64 - 1)
  598. }
  599. /// Search the chains we're holding for the given proposal.
  600. pub fn proposal_exists(&self, input_proposal: &blake3::Hash) -> bool {
  601. for chain in self.forks.iter() {
  602. for state_checkpoint in chain.sequence.iter().rev() {
  603. if input_proposal == &state_checkpoint.proposal.hash {
  604. return true
  605. }
  606. }
  607. }
  608. false
  609. }
  610. /// Auxillary function to set nodes leaders count history to the largest fork sequence
  611. /// of leaders, by using provided index.
  612. pub fn set_leader_history(&mut self, index: i64, current_slot: u64) {
  613. // Check if we found longest fork to extract sequence from
  614. match index {
  615. -1 => {
  616. info!(target: "consensus::state", "set_leader_history(): No fork exists.");
  617. }
  618. _ => {
  619. info!(target: "consensus::state", "set_leader_history(): Checking last proposal of fork: {}", index);
  620. let last_proposal = &self.forks[index as usize].sequence.last().unwrap().proposal;
  621. if last_proposal.block.header.slot == current_slot {
  622. // Replacing our last history element with the leaders one
  623. self.leaders_history.pop();
  624. self.leaders_history.push(last_proposal.block.lead_info.leaders);
  625. info!(target: "consensus::state", "set_leader_history(): New leaders history: {:?}", self.leaders_history);
  626. return
  627. }
  628. }
  629. }
  630. //self.leaders_history.push(0);
  631. }
  632. /// Utility function to extract leader selection lottery randomness(eta),
  633. /// defined as the hash of the previous lead proof converted to pallas base.
  634. pub fn get_eta(&self) -> pallas::Base {
  635. let proof_tx_hash = self.blockchain.get_last_proof_hash().unwrap();
  636. let mut bytes: [u8; 32] = *proof_tx_hash.as_bytes();
  637. // read first 254 bits
  638. bytes[30] = 0;
  639. bytes[31] = 0;
  640. pallas::Base::from_repr(bytes).unwrap()
  641. }
  642. /// Auxillary function to retrieve slot checkpoint of provided slot UID.
  643. pub fn get_slot_checkpoint(&self, slot: u64) -> Result<SlotCheckpoint> {
  644. // Check hot/live slot checkpoints
  645. for slot_checkpoint in self.slot_checkpoints.iter().rev() {
  646. if slot_checkpoint.slot == slot {
  647. return Ok(slot_checkpoint.clone())
  648. }
  649. }
  650. // Check if slot is finalized
  651. if let Ok(slot_checkpoints) = self.blockchain.get_slot_checkpoints_by_slot(&[slot]) {
  652. if !slot_checkpoints.is_empty() {
  653. if let Some(slot_checkpoint) = &slot_checkpoints[0] {
  654. return Ok(slot_checkpoint.clone())
  655. }
  656. }
  657. }
  658. Err(Error::SlotCheckpointNotFound(slot))
  659. }
  660. /// Auxillary function to update all fork state checkpoints to nodes coins current canonical states.
  661. /// Note: This function should only be invoked once on nodes' coins creation.
  662. pub fn update_forks_checkpoints(&mut self) {
  663. for fork in &mut self.forks {
  664. for state_checkpoint in &mut fork.sequence {
  665. state_checkpoint.coins = self.coins.clone();
  666. state_checkpoint.coins_tree = self.coins_tree.clone();
  667. }
  668. }
  669. }
  670. /// Auxiliary structure to reset consensus state for a resync
  671. pub fn reset(&mut self) {
  672. self.participating = None;
  673. self.proposing = false;
  674. self.offset = None;
  675. self.forks = vec![];
  676. self.slot_checkpoints = vec![];
  677. self.leaders_history = vec![0];
  678. self.nullifiers = vec![];
  679. }
  680. }
  681. /// Auxiliary structure used for consensus syncing.
  682. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  683. pub struct ConsensusRequest {}
  684. impl net::Message for ConsensusRequest {
  685. fn name() -> &'static str {
  686. "consensusrequest"
  687. }
  688. }
  689. /// Auxiliary structure used for consensus syncing.
  690. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  691. pub struct ConsensusResponse {
  692. /// Slot the network was bootstrapped
  693. pub bootstrap_slot: u64,
  694. /// Slots offset since genesis,
  695. pub offset: Option<u64>,
  696. /// Hot/live data used by the consensus algorithm
  697. pub forks: Vec<ForkInfo>,
  698. /// Pending transactions
  699. pub unconfirmed_txs: Vec<Transaction>,
  700. /// Hot/live slot checkpoints
  701. pub slot_checkpoints: Vec<SlotCheckpoint>,
  702. /// Leaders count history
  703. pub leaders_history: Vec<u64>,
  704. /// Seen nullifiers from proposals
  705. pub nullifiers: Vec<pallas::Base>,
  706. }
  707. impl net::Message for ConsensusResponse {
  708. fn name() -> &'static str {
  709. "consensusresponse"
  710. }
  711. }
  712. /// Auxiliary structure used for consensus syncing.
  713. #[derive(Debug, SerialEncodable, SerialDecodable)]
  714. pub struct ConsensusSlotCheckpointsRequest {}
  715. impl net::Message for ConsensusSlotCheckpointsRequest {
  716. fn name() -> &'static str {
  717. "consensusslotcheckpointsrequest"
  718. }
  719. }
  720. /// Auxiliary structure used for consensus syncing.
  721. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  722. pub struct ConsensusSlotCheckpointsResponse {
  723. /// Node known bootstrap slot
  724. pub bootstrap_slot: u64,
  725. /// Node has hot/live slot checkpoints
  726. pub is_empty: bool,
  727. }
  728. impl net::Message for ConsensusSlotCheckpointsResponse {
  729. fn name() -> &'static str {
  730. "consensusslotcheckpointsresponse"
  731. }
  732. }
  733. /// Auxiliary structure used to keep track of slot validation parameters.
  734. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  735. pub struct SlotCheckpoint {
  736. /// Slot UID
  737. pub slot: u64,
  738. /// Slot eta
  739. pub eta: pallas::Base,
  740. /// Slot sigma1
  741. pub sigma1: pallas::Base,
  742. /// Slot sigma2
  743. pub sigma2: pallas::Base,
  744. }
  745. impl SlotCheckpoint {
  746. pub fn new(slot: u64, eta: pallas::Base, sigma1: pallas::Base, sigma2: pallas::Base) -> Self {
  747. Self { slot, eta, sigma1, sigma2 }
  748. }
  749. /// Generate the genesis slot checkpoint.
  750. pub fn genesis_slot_checkpoint() -> Self {
  751. let eta = pallas::Base::zero();
  752. let sigma1 = pallas::Base::zero();
  753. let sigma2 = pallas::Base::zero();
  754. Self::new(0, eta, sigma1, sigma2)
  755. }
  756. }
  757. impl net::Message for SlotCheckpoint {
  758. fn name() -> &'static str {
  759. "slotcheckpoint"
  760. }
  761. }
  762. /// Auxiliary structure used for slot checkpoints syncing
  763. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  764. pub struct SlotCheckpointRequest {
  765. /// Slot UID
  766. pub slot: u64,
  767. }
  768. impl net::Message for SlotCheckpointRequest {
  769. fn name() -> &'static str {
  770. "slotcheckpointrequest"
  771. }
  772. }
  773. /// Auxiliary structure used for slot checkpoints syncing
  774. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  775. pub struct SlotCheckpointResponse {
  776. /// Response blocks.
  777. pub slot_checkpoints: Vec<SlotCheckpoint>,
  778. }
  779. impl net::Message for SlotCheckpointResponse {
  780. fn name() -> &'static str {
  781. "slotcheckpointresponse"
  782. }
  783. }
  784. /// Auxiliary structure used to keep track of consensus state checkpoints.
  785. #[derive(Debug, Clone)]
  786. pub struct StateCheckpoint {
  787. /// Block proposal
  788. pub proposal: BlockProposal,
  789. /// Node competing coins current state
  790. pub coins: Vec<LeadCoin>,
  791. /// Coin commitments tree current state
  792. pub coins_tree: BridgeTree<MerkleNode, MERKLE_DEPTH>,
  793. /// Seen nullifiers from proposals current state
  794. pub nullifiers: Vec<pallas::Base>,
  795. }
  796. impl StateCheckpoint {
  797. pub fn new(
  798. proposal: BlockProposal,
  799. coins: Vec<LeadCoin>,
  800. coins_tree: BridgeTree<MerkleNode, MERKLE_DEPTH>,
  801. nullifiers: Vec<pallas::Base>,
  802. ) -> Self {
  803. Self { proposal, coins, coins_tree, nullifiers }
  804. }
  805. }
  806. /// Auxiliary structure used for forked consensus state checkpoints syncing
  807. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  808. pub struct StateCheckpointInfo {
  809. /// Block proposal
  810. pub proposal: BlockProposal,
  811. /// Seen nullifiers from proposals current state
  812. pub nullifiers: Vec<pallas::Base>,
  813. }
  814. impl From<StateCheckpoint> for StateCheckpointInfo {
  815. fn from(state_checkpoint: StateCheckpoint) -> Self {
  816. Self { proposal: state_checkpoint.proposal, nullifiers: state_checkpoint.nullifiers }
  817. }
  818. }
  819. impl From<StateCheckpointInfo> for StateCheckpoint {
  820. fn from(state_checkpoint_info: StateCheckpointInfo) -> Self {
  821. Self {
  822. proposal: state_checkpoint_info.proposal,
  823. coins: vec![],
  824. coins_tree: BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(constants::EPOCH_LENGTH * 100),
  825. nullifiers: state_checkpoint_info.nullifiers,
  826. }
  827. }
  828. }
  829. /// This struct represents a sequence of consensus state checkpoints.
  830. #[derive(Debug, Clone)]
  831. pub struct Fork {
  832. pub genesis_block: blake3::Hash,
  833. pub sequence: Vec<StateCheckpoint>,
  834. }
  835. impl Fork {
  836. pub fn new(genesis_block: blake3::Hash, initial_state_checkpoint: StateCheckpoint) -> Self {
  837. Self { genesis_block, sequence: vec![initial_state_checkpoint] }
  838. }
  839. /// Insertion of a valid state checkpoint.
  840. pub fn add(&mut self, state_checkpoint: &StateCheckpoint) {
  841. if self.check_state_checkpoint(state_checkpoint, self.sequence.last().unwrap()) {
  842. self.sequence.push(state_checkpoint.clone());
  843. }
  844. }
  845. /// A fork chain is considered valid when every state checkpoint is valid,
  846. /// based on the `check_state_checkpoint` function
  847. pub fn check_chain(&self) -> bool {
  848. for (index, state_checkpoint) in self.sequence[1..].iter().enumerate() {
  849. if !self.check_state_checkpoint(state_checkpoint, &self.sequence[index]) {
  850. return false
  851. }
  852. }
  853. true
  854. }
  855. /// A state checkpoint is considered valid when its proposal parent hash is equal to the
  856. /// hash of the previous checkpoint's proposal and their slots are incremental,
  857. /// excluding the genesis block proposal.
  858. pub fn check_state_checkpoint(
  859. &self,
  860. state_checkpoint: &StateCheckpoint,
  861. previous: &StateCheckpoint,
  862. ) -> bool {
  863. if state_checkpoint.proposal.block.header.previous == self.genesis_block {
  864. info!(target: "consensus::state", "check_checkpoint(): Genesis block proposal provided.");
  865. return false
  866. }
  867. if state_checkpoint.proposal.block.header.previous != previous.proposal.hash ||
  868. state_checkpoint.proposal.block.header.slot <= previous.proposal.block.header.slot
  869. {
  870. info!(target: "consensus::state", "check_checkpoint(): Provided state checkpoint proposal is invalid.");
  871. return false
  872. }
  873. // TODO: validate rest checkpoint info(like nullifiers)
  874. true
  875. }
  876. }
  877. /// Auxiliary structure used for forks syncing
  878. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  879. pub struct ForkInfo {
  880. pub genesis_block: blake3::Hash,
  881. pub sequence: Vec<StateCheckpointInfo>,
  882. }
  883. impl From<Fork> for ForkInfo {
  884. fn from(fork: Fork) -> Self {
  885. let mut sequence = vec![];
  886. for state_checkpoint in fork.sequence {
  887. sequence.push(state_checkpoint.into());
  888. }
  889. Self { genesis_block: fork.genesis_block, sequence }
  890. }
  891. }
  892. impl From<ForkInfo> for Fork {
  893. fn from(fork_info: ForkInfo) -> Self {
  894. let mut sequence = vec![];
  895. for checkpoint in fork_info.sequence {
  896. sequence.push(checkpoint.into());
  897. }
  898. Self { genesis_block: fork_info.genesis_block, sequence }
  899. }
  900. }