validator.rs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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::{collections::HashMap, io::Cursor, sync::Arc};
  19. use darkfi_sdk::{
  20. blockchain::Slot,
  21. crypto::{
  22. contract_id::{CONSENSUS_CONTRACT_ID, DAO_CONTRACT_ID, MONEY_CONTRACT_ID},
  23. schnorr::{SchnorrPublic, SchnorrSecret},
  24. MerkleNode, MerkleTree, PublicKey, SecretKey,
  25. },
  26. pasta::{group::ff::PrimeField, pallas},
  27. };
  28. use darkfi_serial::{serialize, Decodable, Encodable, WriteExt};
  29. use halo2_proofs::arithmetic::Field;
  30. use log::{debug, error, info, warn};
  31. use rand::rngs::OsRng;
  32. use smol::lock::RwLock;
  33. use crate::{
  34. blockchain::{BlockInfo, Blockchain, BlockchainOverlay, BlockchainOverlayPtr},
  35. rpc::jsonrpc::JsonSubscriber,
  36. runtime::vm_runtime::Runtime,
  37. tx::Transaction,
  38. util::time::{TimeKeeper, Timestamp},
  39. wallet::WalletPtr,
  40. zk::{
  41. proof::{ProvingKey, VerifyingKey},
  42. vm::ZkCircuit,
  43. vm_heap::empty_witnesses,
  44. },
  45. zkas::ZkBinary,
  46. Error, Result,
  47. };
  48. use super::{
  49. constants,
  50. lead_coin::LeadCoin,
  51. state::{ConsensusState, Fork, StateCheckpoint},
  52. BlockProposal, Header, LeadInfo, LeadProof,
  53. };
  54. /// Atomic pointer to validator state.
  55. pub type ValidatorStatePtr = Arc<RwLock<ValidatorState>>;
  56. /// This struct represents the state of a validator node.
  57. pub struct ValidatorState {
  58. /// Leader proof proving key
  59. pub lead_proving_key: Option<ProvingKey>,
  60. /// Leader proof verifying key
  61. pub lead_verifying_key: VerifyingKey,
  62. /// Hot/Live data used by the consensus algorithm
  63. pub consensus: ConsensusState,
  64. /// Canonical (finalized) blockchain
  65. pub blockchain: Blockchain,
  66. /// A map of various subscribers exporting live info from the blockchain
  67. pub subscribers: HashMap<&'static str, JsonSubscriber>,
  68. /// Wallet interface
  69. pub wallet: WalletPtr,
  70. /// Flag signalling node has finished initial sync
  71. pub synced: bool,
  72. /// Flag to enable single-node mode
  73. pub single_node: bool,
  74. }
  75. impl ValidatorState {
  76. #[allow(clippy::too_many_arguments)]
  77. pub async fn new(
  78. db: &sled::Db,
  79. bootstrap_ts: Timestamp,
  80. genesis_ts: Timestamp,
  81. genesis_data: blake3::Hash,
  82. initial_distribution: u64,
  83. wallet: WalletPtr,
  84. faucet_pubkeys: Vec<PublicKey>,
  85. enable_participation: bool,
  86. single_node: bool,
  87. ) -> Result<ValidatorStatePtr> {
  88. debug!(target: "consensus::validator", "Initializing ValidatorState");
  89. debug!(target: "consensus::validator", "Initializing wallet tables for consensus");
  90. // Initialize consensus coin table.
  91. // NOTE: In future this will be redundant as consensus coins will live in the money contract.
  92. if enable_participation {
  93. wallet.exec_sql(include_str!("consensus_coin.sql")).await?;
  94. }
  95. debug!(target: "consensus::validator", "Generating leader proof keys with k: {}", constants::LEADER_PROOF_K);
  96. let bincode = include_bytes!("../../proof/lead.zk.bin");
  97. let zkbin = ZkBinary::decode(bincode)?;
  98. let circuit = ZkCircuit::new(empty_witnesses(&zkbin)?, &zkbin);
  99. let lead_verifying_key = VerifyingKey::build(constants::LEADER_PROOF_K, &circuit);
  100. // We only need this proving key if we're going to participate in the consensus.
  101. let lead_proving_key = if enable_participation {
  102. Some(ProvingKey::build(constants::LEADER_PROOF_K, &circuit))
  103. } else {
  104. None
  105. };
  106. let blockchain = Blockchain::new(db)?;
  107. let mut genesis_block = BlockInfo::default();
  108. genesis_block.header.timestamp = genesis_ts;
  109. blockchain.add_block(&genesis_block)?;
  110. let consensus = ConsensusState::new(
  111. wallet.clone(),
  112. blockchain.clone(),
  113. bootstrap_ts,
  114. genesis_ts,
  115. genesis_data,
  116. initial_distribution,
  117. single_node,
  118. );
  119. // -----NATIVE WASM CONTRACTS-----
  120. // This is the current place where native contracts are being deployed.
  121. // When the `Blockchain` object is created, it doesn't care whether it
  122. // already has the contract data or not. If there's existing data, it
  123. // will just open the necessary db and trees, and give back what it has.
  124. // This means that on subsequent runs our native contracts will already
  125. // be in a deployed state, so what we actually do here is a redeployment.
  126. // This kind of operation should only modify the contract's state in case
  127. // it wasn't deployed before (meaning the initial run). Otherwise, it
  128. // shouldn't touch anything, or just potentially update the db schemas or
  129. // whatever is necessary. This logic should be handled in the init function
  130. // of the actual contract, so make sure the native contracts handle this well.
  131. // The faucet pubkeys are pubkeys which are allowed to create clear inputs
  132. // in the money contract.
  133. let money_contract_deploy_payload = serialize(&faucet_pubkeys);
  134. let dao_contract_deploy_payload = vec![];
  135. let consensus_contract_deploy_payload = vec![];
  136. let native_contracts = vec![
  137. (
  138. "Money Contract",
  139. *MONEY_CONTRACT_ID,
  140. include_bytes!("../contract/money/darkfi_money_contract.wasm").to_vec(),
  141. money_contract_deploy_payload,
  142. ),
  143. (
  144. "DAO Contract",
  145. *DAO_CONTRACT_ID,
  146. include_bytes!("../contract/dao/darkfi_dao_contract.wasm").to_vec(),
  147. dao_contract_deploy_payload,
  148. ),
  149. (
  150. "Consensus Contract",
  151. *CONSENSUS_CONTRACT_ID,
  152. include_bytes!("../contract/consensus/darkfi_consensus_contract.wasm").to_vec(),
  153. consensus_contract_deploy_payload,
  154. ),
  155. ];
  156. info!(target: "consensus::validator", "Deploying native wasm contracts");
  157. let blockchain_overlay = BlockchainOverlay::new(&blockchain)?;
  158. for nc in native_contracts {
  159. info!(target: "consensus::validator", "Deploying {} with ContractID {}", nc.0, nc.1);
  160. let mut runtime = Runtime::new(
  161. &nc.2[..],
  162. blockchain_overlay.clone(),
  163. nc.1,
  164. consensus.time_keeper.clone(),
  165. )?;
  166. runtime.deploy(&nc.3)?;
  167. info!(target: "consensus::validator", "Successfully deployed {}", nc.0);
  168. }
  169. blockchain_overlay.lock().unwrap().overlay.lock().unwrap().apply()?;
  170. info!(target: "consensus::validator", "Finished deployment of native wasm contracts");
  171. // -----END NATIVE WASM CONTRACTS-----
  172. // Here we initialize various subscribers that can export live consensus/blockchain data.
  173. let mut subscribers = HashMap::new();
  174. let block_subscriber = JsonSubscriber::new("blockchain.subscribe_blocks");
  175. let err_txs_subscriber = JsonSubscriber::new("blockchain.subscribe_err_txs");
  176. subscribers.insert("blocks", block_subscriber);
  177. subscribers.insert("err_txs", err_txs_subscriber);
  178. let state = Arc::new(RwLock::new(ValidatorState {
  179. lead_proving_key,
  180. lead_verifying_key,
  181. consensus,
  182. blockchain,
  183. subscribers,
  184. wallet,
  185. synced: false,
  186. single_node,
  187. }));
  188. Ok(state)
  189. }
  190. /// The node retrieves a transaction, validates its state transition,
  191. /// and appends it to the pending txs store.
  192. pub async fn append_tx(&mut self, tx: Transaction) -> bool {
  193. let tx_hash = blake3::hash(&serialize(&tx));
  194. let tx_in_txstore = match self.blockchain.transactions.contains(&tx_hash) {
  195. Ok(v) => v,
  196. Err(e) => {
  197. error!(target: "consensus::validator", "append_tx(): Failed querying txstore: {}", e);
  198. return false
  199. }
  200. };
  201. let tx_in_pending_txs_store = match self.blockchain.pending_txs.contains(&tx_hash) {
  202. Ok(v) => v,
  203. Err(e) => {
  204. error!(target: "consensus::validator", "append_tx(): Failed querying pending txs store: {}", e);
  205. return false
  206. }
  207. };
  208. if tx_in_txstore || tx_in_pending_txs_store {
  209. info!(target: "consensus::validator", "append_tx(): We have already seen this tx.");
  210. return false
  211. }
  212. info!(target: "consensus::validator", "append_tx(): Starting state transition validation");
  213. match self
  214. .verify_transactions(&[tx.clone()], self.consensus.time_keeper.current_slot(), false)
  215. .await
  216. {
  217. Ok(erroneous_txs) => {
  218. if !erroneous_txs.is_empty() {
  219. error!(target: "consensus::validator", "append_tx(): Erroneous transaction detected");
  220. return false
  221. }
  222. }
  223. Err(e) => {
  224. error!(target: "consensus::validator", "append_tx(): Failed to verify transaction: {}", e);
  225. return false
  226. }
  227. }
  228. if let Err(e) = self.blockchain.add_pending_txs(&[tx]) {
  229. error!(target: "consensus::validator", "append_tx(): Failed to insert transaction to pending txs store: {}", e);
  230. return false
  231. }
  232. info!(target: "consensus::validator", "append_tx(): Appended tx to pending txs store");
  233. true
  234. }
  235. /// The node retrieves transactions vector, validates their state transition,
  236. /// and appends successfull ones to the pending txs store.
  237. pub async fn append_pending_txs(&mut self, txs: &[Transaction]) {
  238. let mut filtered_txs = vec![];
  239. // Filter already seen transactions
  240. for tx in txs {
  241. let tx_hash = blake3::hash(&serialize(tx));
  242. let tx_in_txstore = match self.blockchain.transactions.contains(&tx_hash) {
  243. Ok(v) => v,
  244. Err(e) => {
  245. error!(target: "consensus::validator", "append_pending_txs(): Failed querying txstore: {}", e);
  246. continue
  247. }
  248. };
  249. let tx_in_pending_txs_store = match self.blockchain.pending_txs.contains(&tx_hash) {
  250. Ok(v) => v,
  251. Err(e) => {
  252. error!(target: "consensus::validator", "append_pending_txs(): Failed querying pending txs store: {}", e);
  253. continue
  254. }
  255. };
  256. if tx_in_txstore || tx_in_pending_txs_store {
  257. info!(target: "consensus::validator", "append_pending_txs(): We have already seen this tx.");
  258. continue
  259. }
  260. filtered_txs.push(tx.clone());
  261. }
  262. // Verify transactions and filter erroneous ones
  263. info!(target: "consensus::validator", "append_pending_txs(): Starting state transition validation");
  264. let erroneous_txs = match self
  265. .verify_transactions(
  266. &filtered_txs[..],
  267. self.consensus.time_keeper.current_slot(),
  268. false,
  269. )
  270. .await
  271. {
  272. Ok(erroneous_txs) => erroneous_txs,
  273. Err(e) => {
  274. error!(target: "consensus::validator", "append_pending_txs(): Failed to verify transactions: {}", e);
  275. return
  276. }
  277. };
  278. if !erroneous_txs.is_empty() {
  279. filtered_txs.retain(|x| !erroneous_txs.contains(x));
  280. }
  281. if let Err(e) = self.blockchain.add_pending_txs(&filtered_txs) {
  282. error!(target: "consensus::validator", "append_pending_txs(): Failed to insert transactions to pending txs store: {}", e);
  283. return
  284. }
  285. info!(target: "consensus::validator", "append_pending_txs(): Appended tx to pending txs store");
  286. }
  287. /// The node removes erroneous transactions from the pending txs store.
  288. async fn purge_pending_txs(&self) -> Result<()> {
  289. info!(target: "consensus::validator", "purge_pending_txs(): Removing erroneous transactions from pending transactions store...");
  290. let pending_txs = self.blockchain.get_pending_txs()?;
  291. if pending_txs.is_empty() {
  292. info!(target: "consensus::validator", "purge_pending_txs(): No pending transactions found");
  293. return Ok(())
  294. }
  295. let erroneous_txs = self
  296. .verify_transactions(&pending_txs[..], self.consensus.time_keeper.current_slot(), false)
  297. .await?;
  298. if erroneous_txs.is_empty() {
  299. info!(target: "consensus::validator", "purge_pending_txs(): No erroneous transactions found");
  300. return Ok(())
  301. }
  302. info!(target: "consensus::validator", "purge_pending_txs(): Removing {} erroneous transactions...", erroneous_txs.len());
  303. self.blockchain.remove_pending_txs(&erroneous_txs)?;
  304. let _err_txs_subscriber = self.subscribers.get("err_txs").unwrap();
  305. for err_tx in erroneous_txs {
  306. let _tx_hash = blake3::hash(&serialize(&err_tx)).to_hex().as_str().to_string();
  307. info!(target: "consensus::validator", "purge_pending_txs(): Sending notification about erroneous transaction");
  308. // TODO: err_txs_subscriber.notify(&[tx_hash]).await;
  309. }
  310. Ok(())
  311. }
  312. /// Generate a block proposal for the current slot, containing all
  313. /// pending transactions. Proposal extends the longest fork
  314. /// chain the node is holding.
  315. pub async fn propose(
  316. &mut self,
  317. slot: u64,
  318. fork_index: i64,
  319. coin_index: usize,
  320. sigma1: pallas::Base,
  321. sigma2: pallas::Base,
  322. ) -> Result<Option<(BlockProposal, LeadCoin, pallas::Scalar)>> {
  323. let eta = self.consensus.get_last_eta();
  324. // Check if node can produce proposals
  325. if !self.consensus.proposing {
  326. return Ok(None)
  327. }
  328. // Generate proposal
  329. let mut unproposed_txs = self.unproposed_txs(fork_index)?;
  330. // Verify transactions and filter erroneous ones
  331. let erroneous_txs = self
  332. .verify_transactions(
  333. &unproposed_txs[..],
  334. self.consensus.time_keeper.current_slot(),
  335. false,
  336. )
  337. .await?;
  338. if !erroneous_txs.is_empty() {
  339. unproposed_txs.retain(|x| !erroneous_txs.contains(x));
  340. }
  341. let mut tree = MerkleTree::new(100);
  342. // The following is pretty weird, so something better should be done.
  343. for tx in &unproposed_txs {
  344. let mut hash = [0_u8; 32];
  345. hash[0..31].copy_from_slice(&blake3::hash(&serialize(tx)).as_bytes()[0..31]);
  346. tree.append(MerkleNode::from(pallas::Base::from_repr(hash).unwrap()));
  347. }
  348. let root = tree.root(0).unwrap();
  349. // Checking if extending a fork or canonical
  350. let (prev_hash, coin) = if fork_index == -1 {
  351. (self.blockchain.last()?.1, self.consensus.coins[coin_index].clone())
  352. } else {
  353. let checkpoint = self.consensus.forks[fork_index as usize].sequence.last().unwrap();
  354. (checkpoint.proposal.hash, checkpoint.coins[coin_index].clone())
  355. };
  356. // Generate derived coin blind
  357. let derived_blind = pallas::Scalar::random(&mut OsRng);
  358. // Generating leader proof
  359. let (proof, public_inputs) = coin.create_lead_proof(
  360. sigma1,
  361. sigma2,
  362. eta,
  363. pallas::Base::from(self.consensus.time_keeper.current_slot()),
  364. self.lead_proving_key.as_ref().unwrap(),
  365. derived_blind,
  366. );
  367. // Signing using coin
  368. let secret_key = coin.coin1_sk;
  369. let header = Header::new(
  370. prev_hash,
  371. self.consensus.time_keeper.slot_epoch(slot),
  372. slot,
  373. Timestamp::current_time(),
  374. root,
  375. );
  376. let signed_proposal =
  377. SecretKey::from(secret_key).sign(&mut OsRng, &header.headerhash().as_bytes()[..]);
  378. let public_key = PublicKey::from_secret(secret_key.into());
  379. let lead_info = LeadInfo::new(
  380. signed_proposal,
  381. public_key,
  382. public_inputs,
  383. coin.slot,
  384. eta,
  385. LeadProof::from(proof?),
  386. self.consensus.previous_leaders,
  387. );
  388. Ok(Some((BlockProposal::new(header, unproposed_txs, lead_info), coin, derived_blind)))
  389. }
  390. /// Retrieve all pending transactions not proposed in previous blocks
  391. /// of provided index chain.
  392. pub fn unproposed_txs(&self, index: i64) -> Result<Vec<Transaction>> {
  393. let unproposed_txs = if index == -1 {
  394. // If index is -1 (canonical blockchain) a new fork will be generated,
  395. // therefore all unproposed transactions can be included in the proposal.
  396. self.blockchain.get_pending_txs()?
  397. } else {
  398. // We iterate over the fork chain proposals to find already proposed
  399. // transactions and remove them from the local unproposed_txs vector.
  400. let mut filtered_txs = self.blockchain.get_pending_txs()?;
  401. let chain = &self.consensus.forks[index as usize];
  402. for state_checkpoint in &chain.sequence {
  403. for tx in &state_checkpoint.proposal.block.txs {
  404. if let Some(pos) = filtered_txs.iter().position(|txs| *txs == *tx) {
  405. filtered_txs.remove(pos);
  406. }
  407. }
  408. }
  409. filtered_txs
  410. };
  411. // Check if transactions exceed configured cap
  412. let cap = constants::TXS_CAP;
  413. if unproposed_txs.len() > cap {
  414. return Ok(unproposed_txs[0..cap].to_vec())
  415. }
  416. Ok(unproposed_txs)
  417. }
  418. /// Given a proposal, the node verify its sender (slot leader) and finds which blockchain
  419. /// it extends. If the proposal extends the canonical blockchain, a new fork chain is created.
  420. /// Returns flag to signal if proposal should be broadcasted. Only active consensus participants
  421. /// should broadcast proposals.
  422. pub async fn receive_proposal(
  423. &mut self,
  424. proposal: &BlockProposal,
  425. coin: Option<(usize, LeadCoin, pallas::Scalar)>,
  426. ) -> Result<bool> {
  427. let current = self.consensus.time_keeper.current_slot();
  428. // Node hasn't started participating
  429. match self.consensus.participating {
  430. Some(start) => {
  431. if current < start {
  432. return Ok(false)
  433. }
  434. }
  435. None => return Ok(false),
  436. }
  437. // Node have already checked for finalization in this slot
  438. if current <= self.consensus.checked_finalization {
  439. warn!(target: "consensus::validator", "receive_proposal(): Proposal received after finalization sync period.");
  440. return Err(Error::ProposalAfterFinalizationError)
  441. }
  442. // Proposal validations
  443. let lf = &proposal.block.lead_info;
  444. let hdr = &proposal.block.header;
  445. // Ignore proposal if not for current slot
  446. if hdr.slot != current {
  447. return Err(Error::ProposalNotForCurrentSlotError)
  448. }
  449. // Verify that proposer can produce proposals.
  450. // Nodes that created coins in the bootstrap slot can propose immediately.
  451. // NOTE: Later, this will be enforced via contract, where it will be explicit
  452. // when a node can produce proposals, and after which slot they can be considered as valid.
  453. let elapsed_slots = current - lf.coin_slot;
  454. if lf.coin_slot != self.consensus.bootstrap_slot &&
  455. elapsed_slots <= (constants::EPOCH_LENGTH as u64)
  456. {
  457. warn!(
  458. target: "consensus::validator",
  459. "receive_proposal(): Proposer {} is not eligible to produce proposals",
  460. lf.public_key
  461. );
  462. return Err(Error::ProposalProposerNotEligible)
  463. }
  464. // Check if proposal extends any existing fork chains
  465. let index = self.consensus.find_extended_chain_index(proposal)?;
  466. if index == -2 {
  467. return Err(Error::ExtendedChainIndexNotFound)
  468. }
  469. // Check that proposal transactions don't exceed limit
  470. if proposal.block.txs.len() > constants::TXS_CAP {
  471. warn!(
  472. target: "consensus::validator",
  473. "receive_proposal(): Received proposal transactions exceed configured cap: {} - {}",
  474. proposal.block.txs.len(),
  475. constants::TXS_CAP
  476. );
  477. return Err(Error::ProposalTxsExceedCapError)
  478. }
  479. // Verify proposal signature is valid based on producer public key
  480. // TODO: derive public key from proof
  481. if !lf.public_key.verify(proposal.header.as_bytes(), &lf.signature) {
  482. warn!(target: "consensus::validator", "receive_proposal(): Proposer {} signature could not be verified", lf.public_key);
  483. return Err(Error::InvalidSignature)
  484. }
  485. // Check if proposal hash matches actual one
  486. let proposal_hash = proposal.block.blockhash();
  487. if proposal.hash != proposal_hash {
  488. warn!(
  489. target: "consensus::validator",
  490. "receive_proposal(): Received proposal contains mismatched hashes: {} - {}",
  491. proposal.hash, proposal_hash
  492. );
  493. return Err(Error::ProposalHashesMissmatchError)
  494. }
  495. // Check if proposal header matches actual one
  496. let proposal_header = hdr.headerhash();
  497. if proposal.header != proposal_header {
  498. warn!(
  499. target: "consensus::validator",
  500. "receive_proposal(): Received proposal contains mismatched headers: {} - {}",
  501. proposal.header, proposal_header
  502. );
  503. return Err(Error::ProposalHeadersMissmatchError)
  504. }
  505. // Ignore node coin validations if we oporate in single-node mode
  506. if !self.single_node {
  507. // Verify proposal leader proof
  508. if let Err(e) = lf.proof.verify(&self.lead_verifying_key, &lf.public_inputs) {
  509. error!(target: "consensus::validator", "receive_proposal(): Error during leader proof verification: {}", e);
  510. return Err(Error::LeaderProofVerification)
  511. };
  512. info!(target: "consensus::validator", "receive_proposal(): Leader proof verified successfully!");
  513. // Validate proposal public value against coin creation slot
  514. let (mu_y, mu_rho) = LeadCoin::election_seeds_u64(
  515. self.consensus.get_last_eta(),
  516. self.consensus.time_keeper.current_slot(),
  517. );
  518. // y
  519. let prop_mu_y = lf.public_inputs[constants::PI_MU_Y_INDEX];
  520. if mu_y != prop_mu_y {
  521. error!(
  522. target: "consensus::validator",
  523. "receive_proposal(): Failed to verify mu_y: {:?}, proposed: {:?}",
  524. mu_y, prop_mu_y
  525. );
  526. return Err(Error::ProposalPublicValuesMismatched)
  527. }
  528. // rho
  529. let prop_mu_rho = lf.public_inputs[constants::PI_MU_RHO_INDEX];
  530. if mu_rho != prop_mu_rho {
  531. error!(
  532. target: "consensus::validator",
  533. "receive_proposal(): Failed to verify mu_rho: {:?}, proposed: {:?}",
  534. mu_rho, prop_mu_rho
  535. );
  536. return Err(Error::ProposalPublicValuesMismatched)
  537. }
  538. // Validate proposal coin sigmas against current slot
  539. let slot = self.consensus.get_slot(current)?;
  540. // sigma1
  541. let prop_sigma1 = lf.public_inputs[constants::PI_SIGMA1_INDEX];
  542. if slot.pid.sigma1 != prop_sigma1 {
  543. error!(
  544. target: "consensus::validator",
  545. "receive_proposal(): Failed to verify public value sigma1: {:?}, to proposed: {:?}",
  546. slot.pid.sigma1, prop_sigma1
  547. );
  548. }
  549. // sigma2
  550. let prop_sigma2 = lf.public_inputs[constants::PI_SIGMA2_INDEX];
  551. if slot.pid.sigma2 != prop_sigma2 {
  552. error!(
  553. target: "consensus::validator",
  554. "receive_proposal(): Failed to verify public value sigma2: {:?}, to proposed: {:?}",
  555. slot.pid.sigma2, prop_sigma2
  556. );
  557. }
  558. }
  559. // Create corresponding state checkpoint for validations
  560. let mut state_checkpoint = match index {
  561. -1 => {
  562. // Extends canonical
  563. StateCheckpoint::new(
  564. proposal.clone(),
  565. self.consensus.coins.clone(),
  566. self.consensus.coins_tree.clone(),
  567. self.consensus.nullifiers.clone(),
  568. )
  569. }
  570. _ => {
  571. // Extends a fork
  572. let previous = self.consensus.forks[index as usize].sequence.last().unwrap();
  573. StateCheckpoint::new(
  574. proposal.clone(),
  575. previous.coins.clone(),
  576. previous.coins_tree.clone(),
  577. previous.nullifiers.clone(),
  578. )
  579. }
  580. };
  581. // Check if proposal coin nullifiers already exist in the state checkpoint
  582. let prop_sn = lf.public_inputs[constants::PI_NULLIFIER_INDEX];
  583. for sn in &state_checkpoint.nullifiers {
  584. if *sn == prop_sn {
  585. error!(target: "consensus::validator", "receive_proposal(): Proposal nullifiers exist.");
  586. return Err(Error::ProposalIsSpent)
  587. }
  588. }
  589. // Validate state transition against canonical state
  590. // TODO: This should be validated against fork state
  591. info!(target: "consensus::validator", "receive_proposal(): Starting state transition validation");
  592. match self.verify_transactions(&proposal.block.txs, current, false).await {
  593. Ok(erroneous_txs) => {
  594. if !erroneous_txs.is_empty() {
  595. error!(target: "consensus::validator", "Proposal contains erroneous transactions");
  596. return Err(Error::ErroneousTxsDetected)
  597. }
  598. }
  599. Err(e) => {
  600. error!(target: "consensus::validator", "receive_proposal(): Transaction verifications failed: {}", e);
  601. return Err(e)
  602. }
  603. }
  604. // TODO: [PLACEHOLDER] Add rewards validation
  605. // If proposal came fromself, we derive new coin
  606. if let Some((idx, c, derived_blind)) = coin {
  607. info!(target: "consensus::validator", "receive_proposal(): Storing derived coin...");
  608. // Derive coin
  609. let derived = c.derive_coin(&mut state_checkpoint.coins_tree, derived_blind);
  610. // Update consensus coin in wallet
  611. // NOTE: In future this will be redundant as consensus coins will live in the money contract.
  612. let query_str = format!(
  613. "UPDATE {} SET {} = ?1",
  614. constants::CONSENSUS_COIN_TABLE,
  615. constants::CONSENSUS_COIN_COL
  616. );
  617. let wallet_conn = self.wallet.conn.lock().await;
  618. let mut stmt = wallet_conn.prepare(&query_str)?;
  619. stmt.execute([serialize(&derived)])?;
  620. stmt.finalize()?;
  621. state_checkpoint.coins[idx] = derived;
  622. }
  623. // Store proposal coins nullifiers
  624. state_checkpoint.nullifiers.push(prop_sn);
  625. // Extend corresponding chain
  626. match index {
  627. -1 => {
  628. let fork = Fork::new(self.consensus.genesis_block, state_checkpoint);
  629. self.consensus.forks.push(fork);
  630. }
  631. _ => {
  632. self.consensus.forks[index as usize].add(&state_checkpoint);
  633. }
  634. };
  635. // Increase slot leaders count
  636. self.consensus.previous_leaders += 1;
  637. Ok(true)
  638. }
  639. /// Node checks if any of the fork chains can be finalized.
  640. /// Consensus finalization logic:
  641. /// - If the node has observed the creation of a fork chain and no other forks exists at same or greater height,
  642. /// it finalizes (appends to canonical blockchain) all proposals in that fork chain.
  643. /// When fork chain proposals are finalized, the rest of fork chains are removed and all
  644. /// slots are apppended to canonical state.
  645. pub async fn chain_finalization(&mut self) -> Result<(Vec<BlockInfo>, Vec<Slot>)> {
  646. let slot = self.consensus.time_keeper.current_slot();
  647. info!(target: "consensus::validator", "chain_finalization(): Started finalization check for slot: {}", slot);
  648. // Set last slot finalization check occured to current slot
  649. self.consensus.checked_finalization = slot;
  650. // First we find longest fork without any other forks at same height
  651. let mut fork_index = -1;
  652. let mut max_length = 0;
  653. for (index, fork) in self.consensus.forks.iter().enumerate() {
  654. let length = fork.sequence.len();
  655. // Check if less than max
  656. if length < max_length {
  657. continue
  658. }
  659. // Check if same length as max
  660. if length == max_length {
  661. // Setting fork_index so we know we have multiple
  662. // forks at same length.
  663. fork_index = -2;
  664. continue
  665. }
  666. // Set fork as max
  667. fork_index = index as i64;
  668. max_length = length;
  669. }
  670. // Check if we found any fork to finalize
  671. match fork_index {
  672. -2 => {
  673. info!(target: "consensus::validator", "chain_finalization(): Eligible forks with same height exist, nothing to finalize.");
  674. return Ok((vec![], vec![]))
  675. }
  676. -1 => {
  677. info!(target: "consensus::validator", "chain_finalization(): Nothing to finalize.");
  678. }
  679. _ => {
  680. info!(target: "consensus::validator", "chain_finalization(): Chain {} can be finalized!", fork_index)
  681. }
  682. }
  683. if max_length == 0 {
  684. return Ok((vec![], vec![]))
  685. }
  686. // Starting finalization
  687. let fork = self.consensus.forks[fork_index as usize].clone();
  688. // Retrieving proposals to finalize
  689. let finalized: Vec<BlockInfo> = vec![];
  690. for _state_checkpoint in &fork.sequence {
  691. //finalized.push(state_checkpoint.proposal.clone().into());
  692. }
  693. // Adding finalized proposals to canonical
  694. info!(target: "consensus::validator", "consensus: Adding {} finalized block to canonical chain.", finalized.len());
  695. /*
  696. match self.blockchain.add(&finalized) {
  697. Ok(v) => v,
  698. Err(e) => {
  699. error!(target: "consensus::validator", "consensus: Failed appending finalized blocks to canonical chain: {}", e);
  700. return Err(e)
  701. }
  702. };
  703. */
  704. let _blocks_subscriber = self.subscribers.get("blocks").unwrap().clone();
  705. // Validating state transitions
  706. for proposal in &finalized {
  707. // TODO: Is this the right place? We're already doing this in protocol_sync.
  708. // TODO: These state transitions have already been checked. (I wrote this, but where?)
  709. // TODO: FIXME: The state transitions have already been written, they have to be in memory
  710. // until this point.
  711. info!(target: "consensus::validator", "Applying state transition for finalized block");
  712. match self.verify_transactions(&proposal.txs, proposal.header.height, true).await {
  713. Ok(erroneous_txs) => {
  714. if !erroneous_txs.is_empty() {
  715. error!(target: "consensus::validator", "Finalized block contains erroneous transactions");
  716. return Err(Error::ErroneousTxsDetected)
  717. }
  718. }
  719. Err(e) => {
  720. error!(target: "consensus::validator", "Finalized block transaction verifications failed: {}", e);
  721. return Err(e)
  722. }
  723. }
  724. // Remove proposal transactions from pending txs store
  725. if let Err(e) = self.blockchain.remove_pending_txs(&proposal.txs) {
  726. error!(target: "consensus::validator", "Removing finalized block transactions failed: {}", e);
  727. return Err(e)
  728. }
  729. info!(target: "consensus::validator", "consensus: Sending notification about finalized block");
  730. // TODO: blocks_subscriber.notify(&[proposal.clone()]).await;
  731. }
  732. // Setting leaders history to last proposal leaders count
  733. let last_state_checkpoint = fork.sequence.last().unwrap().clone();
  734. // Setting canonical states from last finalized checkpoint
  735. self.consensus.coins = last_state_checkpoint.coins;
  736. self.consensus.coins_tree = last_state_checkpoint.coins_tree;
  737. self.consensus.nullifiers = last_state_checkpoint.nullifiers;
  738. // Adding finalized slots to canonical
  739. let finalized_slots: Vec<Slot> = self.consensus.slots.clone();
  740. debug!(
  741. target: "consensus::validator",
  742. "consensus: Adding {} finalized slots to canonical chain.",
  743. finalized_slots.len()
  744. );
  745. /*
  746. match self.blockchain.add_slots(&finalized_slots) {
  747. Ok(v) => v,
  748. Err(e) => {
  749. error!(
  750. target: "consensus::validator",
  751. "consensus: Failed appending finalized slots to canonical chain: {}",
  752. e
  753. );
  754. return Err(e)
  755. }
  756. };
  757. */
  758. // Resetting forks and slots
  759. self.consensus.forks = vec![];
  760. self.consensus.slots = vec![];
  761. // Purge pending erroneous txs since canonical state has been changed
  762. if let Err(e) = self.purge_pending_txs().await {
  763. error!(target: "consensus::validator", "consensus: Purging pending transactions failed: {}", e);
  764. }
  765. Ok((finalized, finalized_slots))
  766. }
  767. // ==========================
  768. // State transition functions
  769. // ==========================
  770. // TODO TESTNET: Write down all cases below
  771. // State transition checks should be happening in the following cases for a sync node:
  772. // 1) When a finalized block is received
  773. // 2) When a transaction is being broadcasted to us
  774. // State transition checks should be happening in the following cases for a consensus participating node:
  775. // 1) When a finalized block is received
  776. // 2) When a transaction is being broadcasted to us
  777. // ==========================
  778. /// Validate and append to canonical state received blocks.
  779. async fn receive_blocks(&mut self, blocks: &[BlockInfo]) -> Result<()> {
  780. // Verify state transitions for all blocks and their respective transactions.
  781. info!(target: "consensus::validator", "receive_blocks(): Starting state transition validations");
  782. for block in blocks {
  783. match self.verify_transactions(&block.txs, block.header.height, true).await {
  784. Ok(erroneous_txs) => {
  785. if !erroneous_txs.is_empty() {
  786. error!(target: "consensus::validator", "receive_blocks(): Block contains erroneous transactions");
  787. return Err(Error::ErroneousTxsDetected)
  788. }
  789. }
  790. Err(e) => {
  791. error!(target: "consensus::validator", "receive_blocks(): Transaction verifications failed: {}", e);
  792. return Err(e)
  793. }
  794. }
  795. }
  796. info!(target: "consensus::validator", "receive_blocks(): All state transitions passed. Appending blocks to ledger.");
  797. //self.blockchain.add(blocks)?;
  798. Ok(())
  799. }
  800. /// Validate and append to canonical state received finalized block.
  801. /// Returns boolean flag indicating already existing block.
  802. pub async fn receive_finalized_block(&mut self, block: BlockInfo) -> Result<bool> {
  803. if block.header.height > self.consensus.time_keeper.current_slot() {
  804. warn!(target: "consensus::validator", "receive_finalized_block(): Ignoring future block: {}", block.header.height);
  805. return Ok(false)
  806. }
  807. match self.blockchain.has_block(&block) {
  808. Ok(v) => {
  809. if v {
  810. info!(target: "consensus::validator", "receive_finalized_block(): Existing block received");
  811. return Ok(false)
  812. }
  813. }
  814. Err(e) => {
  815. error!(target: "consensus::validator", "receive_finalized_block(): failed checking for has_block(): {}", e);
  816. return Ok(false)
  817. }
  818. };
  819. info!(target: "consensus::validator", "receive_finalized_block(): Executing state transitions");
  820. self.receive_blocks(&[block.clone()]).await?;
  821. let _blocks_subscriber = self.subscribers.get("blocks").unwrap();
  822. info!(target: "consensus::validator", "consensus: Sending notification about finalized block");
  823. // TODO: blocks_subscriber.notify(&[block.clone()]).await;
  824. info!(target: "consensus::validator", "receive_finalized_block(): Removing block transactions from pending txs store");
  825. self.blockchain.remove_pending_txs(&block.txs)?;
  826. // Purge pending erroneous txs since canonical state has been changed
  827. if let Err(e) = self.purge_pending_txs().await {
  828. error!(target: "consensus::validator", "receive_finalized_block(): Purging pending transactions failed: {}", e);
  829. }
  830. Ok(true)
  831. }
  832. /// Validate and append to canonical state received finalized blocks from block sync task.
  833. /// Already existing blocks are ignored.
  834. pub async fn receive_sync_blocks(&mut self, blocks: &[BlockInfo]) -> Result<()> {
  835. let mut new_blocks = vec![];
  836. for block in blocks {
  837. if block.header.height > self.consensus.time_keeper.current_slot() {
  838. warn!(target: "consensus::validator", "receive_sync_blocks(): Ignoring future block: {}", block.header.height);
  839. continue
  840. }
  841. match self.blockchain.has_block(block) {
  842. Ok(v) => {
  843. if v {
  844. info!(target: "consensus::validator", "receive_sync_blocks(): Existing block received");
  845. continue
  846. }
  847. new_blocks.push(block.clone());
  848. }
  849. Err(e) => {
  850. error!(target: "consensus::validator", "receive_sync_blocks(): failed checking for has_block(): {}", e);
  851. continue
  852. }
  853. };
  854. }
  855. if new_blocks.is_empty() {
  856. info!(target: "consensus::validator", "receive_sync_blocks(): no new blocks to append");
  857. return Ok(())
  858. }
  859. info!(target: "consensus::validator", "receive_sync_blocks(): Executing state transitions");
  860. self.receive_blocks(&new_blocks[..]).await?;
  861. let _blocks_subscriber = self.subscribers.get("blocks").unwrap();
  862. for _block in new_blocks {
  863. info!(target: "consensus::validator", "consensus: Sending notification about finalized block");
  864. // TODO: blocks_subscriber.notify(&[block]).await;
  865. }
  866. Ok(())
  867. }
  868. /// Validate signatures, wasm execution, and zk proofs for given transaction in
  869. /// provided runtimes. If all of those succeed, try to execute a state update
  870. /// for the contract calls.
  871. async fn verify_transaction(
  872. &self,
  873. overlay: &BlockchainOverlayPtr,
  874. tx: &Transaction,
  875. verifying_slot: u64,
  876. ) -> Result<()> {
  877. let mut runtimes = HashMap::new();
  878. let tx_hash = blake3::hash(&serialize(tx));
  879. info!(target: "consensus::validator", "Verifying transaction {}", tx_hash);
  880. // Table of public inputs used for ZK proof verification
  881. let mut zkp_table = vec![];
  882. // Table of public keys used for signature verification
  883. let mut sig_table = vec![];
  884. // State updates produced by contract execution
  885. let mut updates = vec![];
  886. // Map of zk proof verifying keys for the current transaction
  887. let mut verifying_keys: HashMap<[u8; 32], HashMap<String, VerifyingKey>> = HashMap::new();
  888. // Initialize the map
  889. for call in tx.calls.iter() {
  890. verifying_keys.insert(call.contract_id.to_bytes(), HashMap::new());
  891. }
  892. // Generate a time keeper using transaction verifying slot
  893. let time_keeper = TimeKeeper::new(
  894. self.consensus.time_keeper.genesis_ts,
  895. self.consensus.time_keeper.epoch_length,
  896. self.consensus.time_keeper.slot_time,
  897. verifying_slot,
  898. );
  899. // Iterate over all calls to get the metadata
  900. for (idx, call) in tx.calls.iter().enumerate() {
  901. info!(target: "consensus::validator", "Executing contract call {}", idx);
  902. // Write the actual payload data
  903. let mut payload = vec![];
  904. payload.write_u32(idx as u32)?; // Call index
  905. tx.calls.encode(&mut payload)?; // Actual call data
  906. // Instantiate the wasm runtime
  907. let runtime_key = call.contract_id.to_string();
  908. if !runtimes.contains_key(&runtime_key) {
  909. let wasm = self.blockchain.wasm_bincode.get(call.contract_id)?;
  910. let r =
  911. Runtime::new(&wasm, overlay.clone(), call.contract_id, time_keeper.clone())?;
  912. runtimes.insert(runtime_key.clone(), r);
  913. }
  914. let runtime = runtimes.get_mut(&runtime_key).unwrap();
  915. info!(target: "consensus::validator", "Executing \"metadata\" call");
  916. let metadata = runtime.metadata(&payload)?;
  917. // Decode the metadata retrieved from the execution
  918. let mut decoder = Cursor::new(&metadata);
  919. // The tuple is (zkas_ns, public_inputs)
  920. let zkp_pub: Vec<(String, Vec<pallas::Base>)> = Decodable::decode(&mut decoder)?;
  921. let sig_pub: Vec<PublicKey> = Decodable::decode(&mut decoder)?;
  922. // TODO: Make sure we've read all the bytes above.
  923. info!(target: "consensus::validator", "Successfully executed \"metadata\" call");
  924. // Here we'll look up verifying keys and insert them into the per-contract map.
  925. info!(target: "consensus::validator", "Performing VerifyingKey lookups from the sled db");
  926. for (zkas_ns, _) in &zkp_pub {
  927. let inner_vk_map = verifying_keys.get_mut(&call.contract_id.to_bytes()).unwrap();
  928. if inner_vk_map.contains_key(zkas_ns.as_str()) {
  929. continue
  930. }
  931. let (_, vk) = self.blockchain.contracts.get_zkas(
  932. &self.blockchain.sled_db,
  933. &call.contract_id,
  934. zkas_ns,
  935. )?;
  936. inner_vk_map.insert(zkas_ns.to_string(), vk);
  937. }
  938. zkp_table.push(zkp_pub);
  939. sig_table.push(sig_pub);
  940. // After getting the metadata, we run the "exec" function with the same
  941. // runtime and the same payload.
  942. info!(target: "consensus::validator", "Executing \"exec\" call");
  943. let state_update = runtime.exec(&payload)?;
  944. info!(target: "consensus::validator", "Successfully executed \"exec\" call");
  945. updates.push(state_update);
  946. // At this point we're done with the call and move on to the next one.
  947. }
  948. // When we're done looping and executing over the tx's contract calls, we
  949. // move on with verification. First we verify the signatures as that's
  950. // cheaper, and then finally we verify the ZK proofs.
  951. info!(target: "consensus::validator", "Verifying signatures for transaction {}", tx_hash);
  952. if sig_table.len() != tx.signatures.len() {
  953. error!(target: "consensus::validator", "Incorrect number of signatures in tx {}", tx_hash);
  954. return Err(Error::InvalidSignature)
  955. }
  956. match tx.verify_sigs(sig_table) {
  957. Ok(()) => {
  958. info!(target: "consensus::validator", "Signatures verification for tx {} successful", tx_hash)
  959. }
  960. Err(e) => {
  961. error!(target: "consensus::validator", "Signature verification for tx {} failed: {}", tx_hash, e);
  962. return Err(e)
  963. }
  964. };
  965. info!(target: "consensus::validator", "Verifying ZK proofs for transaction {}", tx_hash);
  966. match tx.verify_zkps(&verifying_keys, zkp_table).await {
  967. Ok(()) => {
  968. info!(target: "consensus::validator", "ZK proof verification for tx {} successful", tx_hash)
  969. }
  970. Err(e) => {
  971. error!(target: "consensus::validator", "ZK proof verification for tx {} failed: {}", tx_hash, e);
  972. return Err(e)
  973. }
  974. };
  975. // After the verifications stage passes we can apply the state updates.
  976. assert!(tx.calls.len() == updates.len());
  977. info!(target: "consensus::validator", "Performing state updates");
  978. for (call, update) in tx.calls.iter().zip(updates.iter()) {
  979. // Retrieve already initiated runtime and apply update
  980. // TODO: Sum up the gas costs of previous calls during execution
  981. // and verification and these.
  982. let runtime = runtimes.get_mut(&call.contract_id.to_string()).unwrap();
  983. info!(target: "consensus::validator", "Executing \"apply\" call");
  984. runtime.apply(update)?;
  985. info!(target: "consensus::validator", "State update applied successfully")
  986. }
  987. info!(target: "consensus::validator", "Transaction {} verified successfully", tx_hash);
  988. Ok(())
  989. }
  990. /// Validate a set of [`Transaction`] in sequence and apply them if all are valid.
  991. /// Erroneous transactions are filtered out of the set and returned to caller.
  992. /// The function takes a boolean called `write` which tells it to actually write
  993. /// the state transitions to the database.
  994. pub async fn verify_transactions(
  995. &self,
  996. txs: &[Transaction],
  997. verifying_slot: u64,
  998. write: bool,
  999. ) -> Result<Vec<Transaction>> {
  1000. info!(target: "consensus::validator", "Verifying {} transaction(s)", txs.len());
  1001. let mut erroneous_txs = vec![];
  1002. let overlay = BlockchainOverlay::new(&self.blockchain)?;
  1003. for tx in txs {
  1004. if let Err(e) = self.verify_transaction(&overlay, tx, verifying_slot).await {
  1005. warn!(target: "consensus::validator", "Transaction verification failed: {}", e);
  1006. erroneous_txs.push(tx.clone());
  1007. }
  1008. }
  1009. let lock = overlay.lock().unwrap();
  1010. let mut overlay = lock.overlay.lock().unwrap();
  1011. if !erroneous_txs.is_empty() {
  1012. warn!(target: "consensus::validator", "Erroneous transactions found in set");
  1013. overlay.purge_new_trees()?;
  1014. return Ok(erroneous_txs)
  1015. }
  1016. if !write {
  1017. info!(target: "consensus::validator", "Skipping apply of state updates because write=false");
  1018. overlay.purge_new_trees()?;
  1019. return Ok(erroneous_txs)
  1020. }
  1021. overlay.apply()?;
  1022. Ok(erroneous_txs)
  1023. }
  1024. /// Append to canonical state received finalized slots from block sync task.
  1025. pub async fn receive_slots(&mut self, slots: &[Slot]) -> Result<()> {
  1026. info!(target: "consensus::validator", "receive_slots(): Appending slots to ledger");
  1027. let mut filtered = vec![];
  1028. for slot in slots {
  1029. if slot.id > self.consensus.time_keeper.current_slot() {
  1030. warn!(target: "consensus::validator", "receive_slots(): Ignoring future slot: {}", slot.id);
  1031. continue
  1032. }
  1033. filtered.push(slot.clone());
  1034. }
  1035. //self.blockchain.add_slots(&filtered[..])?;
  1036. Ok(())
  1037. }
  1038. /// Validate and append to canonical state received finalized slot.
  1039. /// Returns boolean flag indicating already existing slot.
  1040. pub async fn receive_finalized_slots(&mut self, slot: Slot) -> Result<bool> {
  1041. match self.blockchain.has_slot(&slot) {
  1042. Ok(v) => {
  1043. if v {
  1044. info!(
  1045. target: "consensus::validator",
  1046. "receive_finalized_slots(): Existing slot received"
  1047. );
  1048. return Ok(false)
  1049. }
  1050. }
  1051. Err(e) => {
  1052. error!(target: "consensus::validator", "receive_finalized_slots(): failed checking for has_slot(): {}", e);
  1053. return Ok(false)
  1054. }
  1055. };
  1056. self.receive_slots(&[slot]).await?;
  1057. Ok(true)
  1058. }
  1059. }