validator.rs 50 KB

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