state.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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::crypto::{constants::MERKLE_DEPTH, MerkleNode};
  21. use darkfi_serial::{SerialDecodable, SerialEncodable};
  22. use incrementalmerkletree::bridgetree::BridgeTree;
  23. use log::{debug, info};
  24. use pasta_curves::{group::ff::PrimeField, pallas};
  25. use rand::{thread_rng, Rng};
  26. use super::{
  27. constants,
  28. leadcoin::{LeadCoin, LeadCoinSecrets},
  29. utils::fbig2base,
  30. Block, BlockProposal, Float10, ProposalChain,
  31. };
  32. use crate::{blockchain::Blockchain, net, tx::Transaction, util::time::Timestamp, Error, Result};
  33. /// This struct represents the information required by the consensus algorithm
  34. pub struct ConsensusState {
  35. /// Canonical (finalized) blockchain
  36. pub blockchain: Blockchain,
  37. /// Genesis block creation timestamp
  38. pub genesis_ts: Timestamp,
  39. /// Genesis block hash
  40. pub genesis_block: blake3::Hash,
  41. /// Participating start slot
  42. pub participating: Option<u64>,
  43. /// Last slot node check for finalization
  44. pub checked_finalization: u64,
  45. /// Slots offset since genesis,
  46. pub offset: Option<u64>,
  47. /// Fork chains containing block proposals
  48. pub proposals: Vec<ProposalChain>,
  49. /// Current epoch
  50. pub epoch: u64,
  51. /// Current epoch eta
  52. pub epoch_eta: pallas::Base,
  53. /// Hot/live slot checkpoints
  54. pub slot_checkpoints: Vec<SlotCheckpoint>,
  55. // TODO: Aren't these already in db after finalization?
  56. /// Current competing coins
  57. pub coins: Vec<LeadCoin>,
  58. /// Coin commitments tree
  59. pub coins_tree: BridgeTree<MerkleNode, MERKLE_DEPTH>,
  60. /// Seen nullifiers from proposals
  61. pub leaders_nullifiers: Vec<pallas::Base>,
  62. /// Seen spent coins from proposals
  63. pub leaders_spent_coins: Vec<(pallas::Base, pallas::Base)>,
  64. /// Leaders count history
  65. pub leaders_history: Vec<u64>,
  66. }
  67. impl ConsensusState {
  68. pub fn new(
  69. blockchain: Blockchain,
  70. genesis_ts: Timestamp,
  71. genesis_data: blake3::Hash,
  72. ) -> Result<Self> {
  73. let genesis_block = Block::genesis_block(genesis_ts, genesis_data).blockhash();
  74. Ok(Self {
  75. blockchain,
  76. genesis_ts,
  77. genesis_block,
  78. participating: None,
  79. checked_finalization: 0,
  80. offset: None,
  81. proposals: vec![],
  82. epoch: 0,
  83. epoch_eta: pallas::Base::one(),
  84. slot_checkpoints: vec![],
  85. coins: vec![],
  86. coins_tree: BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(constants::EPOCH_LENGTH * 100),
  87. leaders_nullifiers: vec![],
  88. leaders_spent_coins: vec![],
  89. leaders_history: vec![0],
  90. })
  91. }
  92. /// Calculates current epoch.
  93. pub fn current_epoch(&self) -> u64 {
  94. self.slot_epoch(self.current_slot())
  95. }
  96. /// Calculates the epoch of the provided slot.
  97. /// Epoch duration is configured using the `EPOCH_LENGTH` value.
  98. pub fn slot_epoch(&self, slot: u64) -> u64 {
  99. slot / constants::EPOCH_LENGTH as u64
  100. }
  101. /// Calculates current slot, based on elapsed time from the genesis block.
  102. /// Slot duration is configured using the `SLOT_TIME` constant.
  103. pub fn current_slot(&self) -> u64 {
  104. self.genesis_ts.elapsed() / constants::SLOT_TIME
  105. }
  106. /// Calculates the relative number of the provided slot.
  107. pub fn relative_slot(&self, slot: u64) -> u64 {
  108. slot % constants::EPOCH_LENGTH as u64
  109. }
  110. /// Finds the last slot a proposal or block was generated.
  111. pub fn last_slot(&self) -> Result<u64> {
  112. let mut slot = 0;
  113. for chain in &self.proposals {
  114. for proposal in &chain.proposals {
  115. if proposal.block.header.slot > slot {
  116. slot = proposal.block.header.slot;
  117. }
  118. }
  119. }
  120. // We return here in case proposals exist,
  121. // so we don't query the sled database.
  122. if slot > 0 {
  123. return Ok(slot)
  124. }
  125. let (last_slot, _) = self.blockchain.last()?;
  126. Ok(last_slot)
  127. }
  128. /// Calculates seconds until next Nth slot starting time.
  129. /// Slots duration is configured using the SLOT_TIME constant.
  130. pub fn next_n_slot_start(&self, n: u64) -> Duration {
  131. assert!(n > 0);
  132. let start_time = NaiveDateTime::from_timestamp_opt(self.genesis_ts.0, 0).unwrap();
  133. let current_slot = self.current_slot() + n;
  134. let next_slot_start =
  135. (current_slot * constants::SLOT_TIME) + (start_time.timestamp() as u64);
  136. let next_slot_start = NaiveDateTime::from_timestamp_opt(next_slot_start as i64, 0).unwrap();
  137. let current_time = NaiveDateTime::from_timestamp_opt(Utc::now().timestamp(), 0).unwrap();
  138. let diff = next_slot_start - current_time;
  139. Duration::new(diff.num_seconds().try_into().unwrap(), 0)
  140. }
  141. /// Calculate slots until next Nth epoch.
  142. /// Epoch duration is configured using the EPOCH_LENGTH value.
  143. pub fn slots_to_next_n_epoch(&self, n: u64) -> u64 {
  144. assert!(n > 0);
  145. let slots_till_next_epoch =
  146. constants::EPOCH_LENGTH as u64 - self.relative_slot(self.current_slot());
  147. ((n - 1) * constants::EPOCH_LENGTH as u64) + slots_till_next_epoch
  148. }
  149. /// Calculates seconds until next Nth epoch starting time.
  150. pub fn next_n_epoch_start(&self, n: u64) -> Duration {
  151. self.next_n_slot_start(self.slots_to_next_n_epoch(n))
  152. }
  153. /// Set participating slot to next.
  154. pub fn set_participating(&mut self) -> Result<()> {
  155. self.participating = Some(self.current_slot() + 1);
  156. Ok(())
  157. }
  158. /// Generate current slot checkpoint
  159. fn generate_slot_checkpoint(&mut self, sigma1: pallas::Base, sigma2: pallas::Base) {
  160. let slot = self.current_slot();
  161. let checkpoint = SlotCheckpoint { slot, eta: self.epoch_eta, sigma1, sigma2 };
  162. self.slot_checkpoints.push(checkpoint);
  163. }
  164. /// Check if new epoch has started, to create new epoch coins.
  165. /// Returns flag to signify if epoch has changed and vector of
  166. /// new epoch competing coins.
  167. pub async fn epoch_changed(
  168. &mut self,
  169. sigma1: pallas::Base,
  170. sigma2: pallas::Base,
  171. ) -> Result<bool> {
  172. let epoch = self.current_epoch();
  173. if epoch <= self.epoch {
  174. self.generate_slot_checkpoint(sigma1.clone(), sigma2.clone());
  175. return Ok(false)
  176. }
  177. let eta = self.get_eta();
  178. // At start of epoch, relative slot is 0.
  179. if self.coins.len() == 0 {
  180. //TODO: DRK coin need to be burned, and consensus coin to be minted.
  181. self.coins = self.create_coins(eta).await?;
  182. }
  183. self.epoch = epoch;
  184. self.epoch_eta = eta;
  185. self.generate_slot_checkpoint(sigma1.clone(), sigma2.clone());
  186. Ok(true)
  187. }
  188. /// return 2-term target approximation sigma coefficients.
  189. pub fn sigmas(&mut self) -> (pallas::Base, pallas::Base) {
  190. let f = self.win_prob_with_full_stake();
  191. // Generate sigmas
  192. let mut total_stake = self.total_stake(); // Only used for fine-tuning
  193. // at genesis epoch first slot, of absolute index 0,
  194. // the total stake would be 0, to avoid division by zero,
  195. // we asume total stake at first division is GENESIS_TOTAL_STAKE.
  196. if total_stake == 0 {
  197. total_stake = constants::GENESIS_TOTAL_STAKE;
  198. }
  199. debug!("sigmas(): f: {}", f);
  200. debug!("sigmas(): stake: {}", total_stake);
  201. let one = constants::FLOAT10_ONE.clone();
  202. let two = constants::FLOAT10_TWO.clone();
  203. let field_p = Float10::from_str_native(constants::P)
  204. .unwrap()
  205. .with_precision(constants::RADIX_BITS)
  206. .value();
  207. let total_sigma =
  208. Float10::try_from(total_stake).unwrap().with_precision(constants::RADIX_BITS).value();
  209. let x = one - f;
  210. let c = x.ln();
  211. let sigma1_fbig = c.clone() / total_sigma.clone() * field_p.clone();
  212. let sigma1 = fbig2base(sigma1_fbig);
  213. let sigma2_fbig = (c / total_sigma).powf(two.clone()) * (field_p / two);
  214. let sigma2 = fbig2base(sigma2_fbig);
  215. (sigma1, sigma2)
  216. }
  217. /// Generate coins for provided sigmas.
  218. /// NOTE: The strategy here is having a single competing coin per slot.
  219. async fn create_coins(&mut self, eta: pallas::Base) -> Result<Vec<LeadCoin>> {
  220. let slot = self.current_slot();
  221. // TODO: cleanup LeadCoinSecrets, no need to keep a vector
  222. let mut rng = thread_rng();
  223. let mut seeds: Vec<u64> = Vec::with_capacity(constants::EPOCH_LENGTH);
  224. for _ in 0..constants::EPOCH_LENGTH {
  225. seeds.push(rng.gen());
  226. }
  227. let epoch_secrets = LeadCoinSecrets::generate();
  228. // LeadCoin matrix containing node competing coins.
  229. let mut coins: Vec<LeadCoin> = Vec::with_capacity(constants::EPOCH_LENGTH);
  230. // TODO: TESTNET: Here we would look into the wallet to find coins we're able to use.
  231. // The wallet has specific tables for consensus coins.
  232. // TODO: TESTNET: Token ID still has to be enforced properly in the consensus.
  233. // Temporarily, we compete with zero stake
  234. let coin = LeadCoin::new(
  235. eta,
  236. constants::LOTTERY_HEAD_START, // TODO: TESTNET: Why is this constant being used?
  237. slot,
  238. epoch_secrets.secret_keys[0].inner(),
  239. epoch_secrets.merkle_roots[0],
  240. 0,
  241. epoch_secrets.merkle_paths[0],
  242. seeds[0],
  243. epoch_secrets.secret_keys[0],
  244. &mut self.coins_tree,
  245. );
  246. coins.push(coin);
  247. Ok(coins)
  248. }
  249. /// leadership reward, assuming constant reward
  250. /// TODO (res) implement reward mechanism with accord to DRK,DARK token-economics
  251. fn reward() -> u64 {
  252. constants::REWARD
  253. }
  254. /// Auxillary function to receive current slot offset.
  255. /// If offset is None, its setted up as last block slot offset.
  256. pub fn get_current_offset(&mut self, current_slot: u64) -> u64 {
  257. // This is the case were we restarted our node, didn't receive offset from other nodes,
  258. // so we need to find offset from last block, exluding network dead period.
  259. if self.offset.is_none() {
  260. let (last_slot, last_offset) = self.blockchain.get_last_offset().unwrap();
  261. let offset = last_offset + (current_slot - last_slot);
  262. info!("get_current_offset(): Setting slot offset: {}", offset);
  263. self.offset = Some(offset);
  264. }
  265. self.offset.unwrap()
  266. }
  267. /// Auxillary function to calculate overall empty slots.
  268. /// We keep an offset from genesis indicating when the first slot actually started.
  269. /// This offset is shared between nodes.
  270. fn overall_empty_slots(&mut self, current_slot: u64) -> u64 {
  271. // Retrieve existing blocks excluding genesis
  272. let blocks = (self.blockchain.len() as u64) - 1;
  273. // Setup offset if only have genesis and havent received offset from other nodes
  274. if blocks == 0 && self.offset.is_none() {
  275. info!(
  276. "overall_empty_slots(): Blockchain contains only genesis, setting slot offset: {}",
  277. current_slot
  278. );
  279. self.offset = Some(current_slot);
  280. }
  281. // Retrieve longest fork length, to also those proposals in the calculation
  282. let max_fork_length = self.longest_chain_length() as u64;
  283. current_slot - blocks - self.get_current_offset(current_slot) - max_fork_length
  284. }
  285. /// total stake
  286. /// assuming constant Reward.
  287. fn total_stake(&mut self) -> i64 {
  288. let current_slot = self.current_slot();
  289. ((current_slot - self.overall_empty_slots(current_slot)) * Self::reward()) as i64
  290. }
  291. /// Calculate how many leaders existed in previous slot and appends
  292. /// it to history, to report it if win. On finalization sync period,
  293. /// node replaces its leaders history with the sequence extracted by
  294. /// the longest fork.
  295. fn extend_leaders_history(&mut self) -> Float10 {
  296. let slot = self.current_slot();
  297. let previous_slot = slot - 1;
  298. let mut count = 0;
  299. for chain in &self.proposals {
  300. // Previous slot proposals exist at end of each fork
  301. if chain.proposals.last().unwrap().block.header.slot == previous_slot {
  302. count += 1;
  303. }
  304. }
  305. self.leaders_history.push(count);
  306. debug!("extend_leaders_history(): Current leaders history: {:?}", self.leaders_history);
  307. Float10::try_from(count as i64).unwrap().with_precision(constants::RADIX_BITS).value()
  308. }
  309. fn pid_error(feedback: Float10) -> Float10 {
  310. let target = constants::FLOAT10_ONE.clone();
  311. target - feedback
  312. }
  313. fn f_dif(&mut self) -> Float10 {
  314. Self::pid_error(self.extend_leaders_history())
  315. }
  316. fn f_der(&self) -> Float10 {
  317. let len = self.leaders_history.len();
  318. let last = Float10::try_from(self.leaders_history[len - 1] as i64)
  319. .unwrap()
  320. .with_precision(constants::RADIX_BITS)
  321. .value();
  322. let second_to_last = Float10::try_from(self.leaders_history[len - 2] as i64)
  323. .unwrap()
  324. .with_precision(constants::RADIX_BITS)
  325. .value();
  326. let mut der =
  327. (Self::pid_error(second_to_last) - Self::pid_error(last)) / constants::DT.clone();
  328. der = if der > constants::MAX_DER.clone() { constants::MAX_DER.clone() } else { der };
  329. der = if der < constants::MIN_DER.clone() { constants::MIN_DER.clone() } else { der };
  330. der
  331. }
  332. fn f_int(&self) -> Float10 {
  333. let mut sum = constants::FLOAT10_ZERO.clone();
  334. let lead_history_len = self.leaders_history.len();
  335. let history_begin_index = if lead_history_len > 10 { lead_history_len - 10 } else { 0 };
  336. for lf in &self.leaders_history[history_begin_index..] {
  337. sum += Self::pid_error(Float10::try_from(lf.clone()).unwrap());
  338. }
  339. sum
  340. }
  341. fn pid(p: Float10, i: Float10, d: Float10) -> Float10 {
  342. constants::KP.clone() * p + constants::KI.clone() * i + constants::KD.clone() * d
  343. }
  344. /// the probability of winnig lottery having all the stake
  345. /// returns f
  346. fn win_prob_with_full_stake(&mut self) -> Float10 {
  347. let p = self.f_dif();
  348. let i = self.f_int();
  349. let d = self.f_der();
  350. debug!("win_prob_with_full_stake(): PID P: {:?}", p);
  351. debug!("win_prob_with_full_stake(): PID I: {:?}", i);
  352. debug!("win_prob_with_full_stake(): PID D: {:?}", d);
  353. let mut f = Self::pid(p, i, d);
  354. debug!("win_prob_with_full_stake(): PID f: {}", f);
  355. f = if f >= constants::FLOAT10_ONE.clone() {
  356. constants::MAX_F.clone()
  357. } else if f <= constants::FLOAT10_ZERO.clone() {
  358. constants::MIN_F.clone()
  359. } else {
  360. f
  361. };
  362. debug!("win_prob_with_full_stake(): PID clipped f: {}", f);
  363. f
  364. }
  365. /// Check that the participant/stakeholder coins win the slot lottery.
  366. /// If the stakeholder has multiple competing winning coins, only the highest value
  367. /// coin is selected, since the stakeholder can't give more than one proof per block/slot.
  368. /// * 'sigma1', 'sigma2': slot sigmas
  369. /// Returns: (check: bool, idx: usize) where idx is the winning coin's index
  370. pub fn is_slot_leader(&mut self, sigma1: pallas::Base, sigma2: pallas::Base) -> (bool, usize) {
  371. let competing_coins = &self.coins;
  372. let mut won = false;
  373. let mut highest_stake = 0;
  374. let mut highest_stake_idx = 0;
  375. for (winning_idx, coin) in competing_coins.iter().enumerate() {
  376. let first_winning = coin.is_leader(sigma1, sigma2);
  377. if first_winning && !won {
  378. highest_stake_idx = winning_idx;
  379. }
  380. won |= first_winning;
  381. if won && coin.value > highest_stake {
  382. highest_stake = coin.value;
  383. highest_stake_idx = winning_idx;
  384. }
  385. }
  386. (won, highest_stake_idx)
  387. }
  388. /// Finds the longest blockchain the node holds and
  389. /// returns the last block hash and the chain index.
  390. pub fn longest_chain_last_hash(&self) -> Result<(blake3::Hash, i64)> {
  391. let mut longest: Option<ProposalChain> = None;
  392. let mut length = 0;
  393. let mut index = -1;
  394. if !self.proposals.is_empty() {
  395. for (i, chain) in self.proposals.iter().enumerate() {
  396. if chain.proposals.len() > length {
  397. longest = Some(chain.clone());
  398. length = chain.proposals.len();
  399. index = i as i64;
  400. }
  401. }
  402. }
  403. let hash = match longest {
  404. Some(chain) => chain.proposals.last().unwrap().hash,
  405. None => self.blockchain.last()?.1,
  406. };
  407. Ok((hash, index))
  408. }
  409. /// Finds the length of longest fork chain the node holds.
  410. pub fn longest_chain_length(&self) -> usize {
  411. let mut max = 0;
  412. for proposal in &self.proposals {
  413. if proposal.proposals.len() > max {
  414. max = proposal.proposals.len();
  415. }
  416. }
  417. max
  418. }
  419. /// Given a proposal, find the index of the fork chain it extends.
  420. pub fn find_extended_chain_index(&mut self, proposal: &BlockProposal) -> Result<i64> {
  421. // We iterate through all forks to find which fork to extend
  422. let mut chain_index = -1;
  423. let mut prop_index = 0;
  424. for (c_index, chain) in self.proposals.iter().enumerate() {
  425. // Traverse proposals in reverse
  426. for (p_index, prop) in chain.proposals.iter().enumerate().rev() {
  427. if proposal.block.header.previous == prop.hash {
  428. chain_index = c_index as i64;
  429. prop_index = p_index;
  430. break
  431. }
  432. }
  433. if chain_index != -1 {
  434. break
  435. }
  436. }
  437. // If no fork was found, we check with canonical
  438. if chain_index == -1 {
  439. let (last_slot, last_block) = self.blockchain.last()?;
  440. if proposal.block.header.previous != last_block ||
  441. proposal.block.header.slot <= last_slot
  442. {
  443. debug!("find_extended_chain_index(): Proposal doesn't extend any known chain");
  444. return Ok(-2)
  445. }
  446. // Proposal extends canonical chain
  447. return Ok(-1)
  448. }
  449. // Found fork chain
  450. let chain = &self.proposals[chain_index as usize];
  451. // Proposal extends fork at last proposal
  452. if prop_index == (chain.proposals.len() - 1) {
  453. return Ok(chain_index)
  454. }
  455. debug!("find_extended_chain_index(): Proposal to fork a forkchain was received.");
  456. let mut chain = self.proposals[chain_index as usize].clone();
  457. // We keep all proposals until the one it extends
  458. chain.proposals.drain((prop_index + 1)..);
  459. self.proposals.push(chain);
  460. Ok(self.proposals.len() as i64 - 1)
  461. }
  462. /// Search the chains we're holding for the given proposal.
  463. pub fn proposal_exists(&self, input_proposal: &blake3::Hash) -> bool {
  464. for chain in self.proposals.iter() {
  465. for proposal in chain.proposals.iter() {
  466. if input_proposal == &proposal.hash {
  467. return true
  468. }
  469. }
  470. }
  471. false
  472. }
  473. /// Auxillary function to set nodes leaders count history to the largest fork sequence
  474. /// of leaders, by using provided index.
  475. pub fn set_leader_history(&mut self, index: i64) {
  476. // Check if we found longest fork to extract sequence from
  477. match index {
  478. -1 => {
  479. debug!("set_leader_history(): No fork exists.");
  480. }
  481. _ => {
  482. debug!("set_leader_history(): Checking last proposal of fork: {}", index);
  483. let last_proposal = self.proposals[index as usize].proposals.last().unwrap();
  484. if last_proposal.block.header.slot == self.current_slot() {
  485. // Replacing our last history element with the leaders one
  486. self.leaders_history.pop();
  487. self.leaders_history.push(last_proposal.block.lead_info.leaders);
  488. debug!("set_leader_history(): New leaders history: {:?}", self.leaders_history);
  489. return
  490. }
  491. }
  492. }
  493. self.leaders_history.push(0);
  494. }
  495. /// Utility function to extract leader selection lottery randomness(eta),
  496. /// defined as the hash of the previous lead proof converted to pallas base.
  497. fn get_eta(&self) -> pallas::Base {
  498. let proof_tx_hash = self.blockchain.get_last_proof_hash().unwrap();
  499. let mut bytes: [u8; 32] = *proof_tx_hash.as_bytes();
  500. // read first 254 bits
  501. bytes[30] = 0;
  502. bytes[31] = 0;
  503. pallas::Base::from_repr(bytes).unwrap()
  504. }
  505. /// Auxillary function to retrieve slot checkpoint of provided slot UID.
  506. pub fn get_slot_checkpoint(&self, slot: u64) -> Result<SlotCheckpoint> {
  507. // Check hot/live slot checkpoints
  508. for slot_checkpoint in self.slot_checkpoints.iter().rev() {
  509. if slot_checkpoint.slot == slot {
  510. return Ok(slot_checkpoint.clone())
  511. }
  512. }
  513. // Check if slot is finalized
  514. if let Ok(slot_checkpoints) = self.blockchain.get_slot_checkpoints_by_slot(&[slot]) {
  515. if slot_checkpoints.len() > 0 {
  516. if let Some(slot_checkpoint) = &slot_checkpoints[0] {
  517. return Ok(slot_checkpoint.clone())
  518. }
  519. }
  520. }
  521. Err(Error::SlotCheckpointNotFound(slot))
  522. }
  523. }
  524. /// Auxiliary structure used for consensus syncing.
  525. #[derive(Debug, SerialEncodable, SerialDecodable)]
  526. pub struct ConsensusRequest {}
  527. impl net::Message for ConsensusRequest {
  528. fn name() -> &'static str {
  529. "consensusrequest"
  530. }
  531. }
  532. /// Auxiliary structure used for consensus syncing.
  533. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  534. pub struct ConsensusResponse {
  535. /// Slots offset since genesis,
  536. pub offset: Option<u64>,
  537. /// Hot/live data used by the consensus algorithm
  538. pub proposals: Vec<ProposalChain>,
  539. /// Pending transactions
  540. pub unconfirmed_txs: Vec<Transaction>,
  541. /// Hot/live slot checkpoints
  542. pub slot_checkpoints: Vec<SlotCheckpoint>,
  543. /// Seen nullifiers from proposals
  544. pub leaders_nullifiers: Vec<pallas::Base>,
  545. /// Seen spent coins from proposals
  546. pub leaders_spent_coins: Vec<(pallas::Base, pallas::Base)>,
  547. }
  548. impl net::Message for ConsensusResponse {
  549. fn name() -> &'static str {
  550. "consensusresponse"
  551. }
  552. }
  553. /// Auxiliary structure used to keep track of slot validation parameters.
  554. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  555. pub struct SlotCheckpoint {
  556. /// Slot UID
  557. pub slot: u64,
  558. /// Slot eta
  559. pub eta: pallas::Base,
  560. /// Slot sigma1
  561. pub sigma1: pallas::Base,
  562. /// Slot sigma2
  563. pub sigma2: pallas::Base,
  564. }
  565. impl SlotCheckpoint {
  566. pub fn new(slot: u64, eta: pallas::Base, sigma1: pallas::Base, sigma2: pallas::Base) -> Self {
  567. Self { slot, eta, sigma1, sigma2 }
  568. }
  569. /// Generate the genesis slot checkpoint.
  570. pub fn genesis_slot_checkpoint() -> Self {
  571. let eta = pallas::Base::zero();
  572. let sigma1 = pallas::Base::zero();
  573. let sigma2 = pallas::Base::zero();
  574. Self::new(0, eta, sigma1, sigma2)
  575. }
  576. }
  577. /// Auxiliary structure used for slot checkpoints syncing
  578. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  579. pub struct SlotCheckpointRequest {
  580. /// Slot UID
  581. pub slot: u64,
  582. }
  583. impl net::Message for SlotCheckpointRequest {
  584. fn name() -> &'static str {
  585. "slotcheckpointrequest"
  586. }
  587. }
  588. /// Auxiliary structure used for slot checkpoints syncing
  589. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  590. pub struct SlotCheckpointResponse {
  591. /// Response blocks.
  592. pub slot_checkpoints: Vec<SlotCheckpoint>,
  593. }
  594. impl net::Message for SlotCheckpointResponse {
  595. fn name() -> &'static str {
  596. "slotcheckpointresponse"
  597. }
  598. }