validator.rs 50 KB

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