validator.rs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  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::{TimeKeeper, 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
  218. .verify_transactions(&[tx.clone()], self.consensus.time_keeper.current_slot(), false)
  219. .await
  220. {
  221. Ok(erroneous_txs) => {
  222. if !erroneous_txs.is_empty() {
  223. error!(target: "consensus::validator", "append_tx(): Erroneous transaction detected");
  224. return false
  225. }
  226. }
  227. Err(e) => {
  228. error!(target: "consensus::validator", "append_tx(): Failed to verify transaction: {}", e);
  229. return false
  230. }
  231. }
  232. if let Err(e) = self.blockchain.add_pending_txs(&[tx]) {
  233. error!(target: "consensus::validator", "append_tx(): Failed to insert transaction to pending txs store: {}", e);
  234. return false
  235. }
  236. info!(target: "consensus::validator", "append_tx(): Appended tx to pending txs store");
  237. true
  238. }
  239. /// The node retrieves transactions vector, validates their state transition,
  240. /// and appends successfull ones to the pending txs store.
  241. pub async fn append_pending_txs(&mut self, txs: &[Transaction]) {
  242. let mut filtered_txs = vec![];
  243. // Filter already seen transactions
  244. for tx in txs {
  245. let tx_hash = blake3::hash(&serialize(tx));
  246. let tx_in_txstore = match self.blockchain.transactions.contains(&tx_hash) {
  247. Ok(v) => v,
  248. Err(e) => {
  249. error!(target: "consensus::validator", "append_pending_txs(): Failed querying txstore: {}", e);
  250. continue
  251. }
  252. };
  253. let tx_in_pending_txs_store = match self.blockchain.pending_txs.contains(&tx_hash) {
  254. Ok(v) => v,
  255. Err(e) => {
  256. error!(target: "consensus::validator", "append_pending_txs(): Failed querying pending txs store: {}", e);
  257. continue
  258. }
  259. };
  260. if tx_in_txstore || tx_in_pending_txs_store {
  261. info!(target: "consensus::validator", "append_pending_txs(): We have already seen this tx.");
  262. continue
  263. }
  264. filtered_txs.push(tx.clone());
  265. }
  266. // Verify transactions and filter erroneous ones
  267. info!(target: "consensus::validator", "append_pending_txs(): Starting state transition validation");
  268. let erroneous_txs = match self
  269. .verify_transactions(
  270. &filtered_txs[..],
  271. self.consensus.time_keeper.current_slot(),
  272. false,
  273. )
  274. .await
  275. {
  276. Ok(erroneous_txs) => erroneous_txs,
  277. Err(e) => {
  278. error!(target: "consensus::validator", "append_pending_txs(): Failed to verify transactions: {}", e);
  279. return
  280. }
  281. };
  282. if !erroneous_txs.is_empty() {
  283. filtered_txs.retain(|x| !erroneous_txs.contains(x));
  284. }
  285. if let Err(e) = self.blockchain.add_pending_txs(&filtered_txs) {
  286. error!(target: "consensus::validator", "append_pending_txs(): Failed to insert transactions to pending txs store: {}", e);
  287. return
  288. }
  289. info!(target: "consensus::validator", "append_pending_txs(): Appended tx to pending txs store");
  290. }
  291. /// The node removes erroneous transactions from the pending txs store.
  292. async fn purge_pending_txs(&self) -> Result<()> {
  293. info!(target: "consensus::validator", "purge_pending_txs(): Removing erroneous transactions from pending transactions store...");
  294. let pending_txs = self.blockchain.get_pending_txs()?;
  295. if pending_txs.is_empty() {
  296. info!(target: "consensus::validator", "purge_pending_txs(): No pending transactions found");
  297. return Ok(())
  298. }
  299. let erroneous_txs = self
  300. .verify_transactions(&pending_txs[..], self.consensus.time_keeper.current_slot(), false)
  301. .await?;
  302. if erroneous_txs.is_empty() {
  303. info!(target: "consensus::validator", "purge_pending_txs(): No erroneous transactions found");
  304. return Ok(())
  305. }
  306. info!(target: "consensus::validator", "purge_pending_txs(): Removing {} erroneous transactions...", erroneous_txs.len());
  307. self.blockchain.remove_pending_txs(&erroneous_txs)?;
  308. // TODO: Don't hardcode this:
  309. let err_txs_subscriber = self.subscribers.get("err_txs").unwrap();
  310. for err_tx in erroneous_txs {
  311. let tx_hash = blake3::hash(&serialize(&err_tx)).to_hex().as_str().to_string();
  312. let params = json!([bs58::encode(&serialize(&tx_hash)).into_string()]);
  313. let notif = JsonNotification::new("blockchain.subscribe_err_txs", params);
  314. info!(target: "consensus::validator", "purge_pending_txs(): Sending notification about erroneous transaction");
  315. err_txs_subscriber.notify(notif).await;
  316. }
  317. Ok(())
  318. }
  319. /// Generate a block proposal for the current slot, containing all
  320. /// pending transactions. Proposal extends the longest fork
  321. /// chain the node is holding.
  322. pub async fn propose(
  323. &mut self,
  324. slot: u64,
  325. fork_index: i64,
  326. coin_index: usize,
  327. sigma1: pallas::Base,
  328. sigma2: pallas::Base,
  329. ) -> Result<Option<(BlockProposal, LeadCoin, pallas::Scalar)>> {
  330. let eta = self.consensus.get_eta();
  331. // Check if node can produce proposals
  332. if !self.consensus.proposing {
  333. return Ok(None)
  334. }
  335. // Generate proposal
  336. let mut unproposed_txs = self.unproposed_txs(fork_index)?;
  337. // Verify transactions and filter erroneous ones
  338. let erroneous_txs = self
  339. .verify_transactions(
  340. &unproposed_txs[..],
  341. self.consensus.time_keeper.current_slot(),
  342. false,
  343. )
  344. .await?;
  345. if !erroneous_txs.is_empty() {
  346. unproposed_txs.retain(|x| !erroneous_txs.contains(x));
  347. }
  348. let mut tree = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(100);
  349. // The following is pretty weird, so something better should be done.
  350. for tx in &unproposed_txs {
  351. let mut hash = [0_u8; 32];
  352. hash[0..31].copy_from_slice(&blake3::hash(&serialize(tx)).as_bytes()[0..31]);
  353. tree.append(&MerkleNode::from(pallas::Base::from_repr(hash).unwrap()));
  354. }
  355. let root = tree.root(0).unwrap();
  356. // Checking if extending a fork or canonical
  357. let (prev_hash, coin) = if fork_index == -1 {
  358. (self.blockchain.last()?.1, self.consensus.coins[coin_index].clone())
  359. } else {
  360. let checkpoint = self.consensus.forks[fork_index as usize].sequence.last().unwrap();
  361. (checkpoint.proposal.hash, checkpoint.coins[coin_index].clone())
  362. };
  363. // Generate derived coin blind
  364. let derived_blind = pallas::Scalar::random(&mut OsRng);
  365. // Generating leader proof
  366. let (proof, public_inputs) = coin.create_lead_proof(
  367. sigma1,
  368. sigma2,
  369. eta,
  370. pallas::Base::from(self.consensus.time_keeper.current_slot()),
  371. self.lead_proving_key.as_ref().unwrap(),
  372. derived_blind,
  373. );
  374. // Signing using coin
  375. let secret_key = coin.coin1_sk;
  376. let header = Header::new(
  377. prev_hash,
  378. self.consensus.time_keeper.slot_epoch(slot),
  379. slot,
  380. Timestamp::current_time(),
  381. root,
  382. );
  383. let signed_proposal =
  384. SecretKey::from(secret_key).sign(&mut OsRng, &header.headerhash().as_bytes()[..]);
  385. let public_key = PublicKey::from_secret(secret_key.into());
  386. let lead_info = LeadInfo::new(
  387. signed_proposal,
  388. public_key,
  389. public_inputs,
  390. coin.slot,
  391. eta,
  392. LeadProof::from(proof?),
  393. self.consensus.previous_leaders,
  394. );
  395. Ok(Some((BlockProposal::new(header, unproposed_txs, lead_info), coin, derived_blind)))
  396. }
  397. /// Retrieve all pending transactions not proposed in previous blocks
  398. /// of provided index chain.
  399. pub fn unproposed_txs(&self, index: i64) -> Result<Vec<Transaction>> {
  400. let unproposed_txs = if index == -1 {
  401. // If index is -1 (canonical blockchain) a new fork will be generated,
  402. // therefore all unproposed transactions can be included in the proposal.
  403. self.blockchain.get_pending_txs()?
  404. } else {
  405. // We iterate over the fork chain proposals to find already proposed
  406. // transactions and remove them from the local unproposed_txs vector.
  407. let mut filtered_txs = self.blockchain.get_pending_txs()?;
  408. let chain = &self.consensus.forks[index as usize];
  409. for state_checkpoint in &chain.sequence {
  410. for tx in &state_checkpoint.proposal.block.txs {
  411. if let Some(pos) = filtered_txs.iter().position(|txs| *txs == *tx) {
  412. filtered_txs.remove(pos);
  413. }
  414. }
  415. }
  416. filtered_txs
  417. };
  418. // Check if transactions exceed configured cap
  419. let cap = constants::TXS_CAP;
  420. if unproposed_txs.len() > cap {
  421. return Ok(unproposed_txs[0..cap].to_vec())
  422. }
  423. Ok(unproposed_txs)
  424. }
  425. /// Given a proposal, the node verify its sender (slot leader) and finds which blockchain
  426. /// it extends. If the proposal extends the canonical blockchain, a new fork chain is created.
  427. /// Returns flag to signal if proposal should be broadcasted. Only active consensus participants
  428. /// should broadcast proposals.
  429. pub async fn receive_proposal(
  430. &mut self,
  431. proposal: &BlockProposal,
  432. coin: Option<(usize, LeadCoin, pallas::Scalar)>,
  433. ) -> Result<bool> {
  434. let current = self.consensus.time_keeper.current_slot();
  435. // Node hasn't started participating
  436. match self.consensus.participating {
  437. Some(start) => {
  438. if current < start {
  439. return Ok(false)
  440. }
  441. }
  442. None => return Ok(false),
  443. }
  444. // Node have already checked for finalization in this slot
  445. if current <= self.consensus.checked_finalization {
  446. warn!(target: "consensus::validator", "receive_proposal(): Proposal received after finalization sync period.");
  447. return Err(Error::ProposalAfterFinalizationError)
  448. }
  449. // Proposal validations
  450. let lf = &proposal.block.lead_info;
  451. let hdr = &proposal.block.header;
  452. // Ignore proposal if not for current slot
  453. if hdr.slot != current {
  454. return Err(Error::ProposalNotForCurrentSlotError)
  455. }
  456. // Verify that proposer can produce proposals.
  457. // Nodes that created coins in the bootstrap slot can propose immediately.
  458. // NOTE: Later, this will be enforced via contract, where it will be explicit
  459. // when a node can produce proposals, and after which slot they can be considered as valid.
  460. let elapsed_slots = current - lf.coin_slot;
  461. if lf.coin_slot != self.consensus.bootstrap_slot &&
  462. elapsed_slots <= (constants::EPOCH_LENGTH as u64)
  463. {
  464. warn!(
  465. target: "consensus::validator",
  466. "receive_proposal(): Proposer {} is not eligible to produce proposals",
  467. lf.public_key
  468. );
  469. return Err(Error::ProposalProposerNotEligible)
  470. }
  471. // Check if proposal extends any existing fork chains
  472. let index = self.consensus.find_extended_chain_index(proposal)?;
  473. if index == -2 {
  474. return Err(Error::ExtendedChainIndexNotFound)
  475. }
  476. // Check that proposal transactions don't exceed limit
  477. if proposal.block.txs.len() > constants::TXS_CAP {
  478. warn!(
  479. target: "consensus::validator",
  480. "receive_proposal(): Received proposal transactions exceed configured cap: {} - {}",
  481. proposal.block.txs.len(),
  482. constants::TXS_CAP
  483. );
  484. return Err(Error::ProposalTxsExceedCapError)
  485. }
  486. // Verify proposal signature is valid based on producer public key
  487. // TODO: derive public key from proof
  488. if !lf.public_key.verify(proposal.header.as_bytes(), &lf.signature) {
  489. warn!(target: "consensus::validator", "receive_proposal(): Proposer {} signature could not be verified", lf.public_key);
  490. return Err(Error::InvalidSignature)
  491. }
  492. // Check if proposal hash matches actual one
  493. let proposal_hash = proposal.block.blockhash();
  494. if proposal.hash != proposal_hash {
  495. warn!(
  496. target: "consensus::validator",
  497. "receive_proposal(): Received proposal contains mismatched hashes: {} - {}",
  498. proposal.hash, proposal_hash
  499. );
  500. return Err(Error::ProposalHashesMissmatchError)
  501. }
  502. // Check if proposal header matches actual one
  503. let proposal_header = hdr.headerhash();
  504. if proposal.header != proposal_header {
  505. warn!(
  506. target: "consensus::validator",
  507. "receive_proposal(): Received proposal contains mismatched headers: {} - {}",
  508. proposal.header, proposal_header
  509. );
  510. return Err(Error::ProposalHeadersMissmatchError)
  511. }
  512. // Ignore node coin validations if we oporate in single-node mode
  513. if !self.single_node {
  514. // Verify proposal leader proof
  515. if let Err(e) = lf.proof.verify(&self.lead_verifying_key, &lf.public_inputs) {
  516. error!(target: "consensus::validator", "receive_proposal(): Error during leader proof verification: {}", e);
  517. return Err(Error::LeaderProofVerification)
  518. };
  519. info!(target: "consensus::validator", "receive_proposal(): Leader proof verified successfully!");
  520. // Validate proposal public value against coin creation slot checkpoint
  521. let (mu_y, mu_rho) = LeadCoin::election_seeds_u64(
  522. self.consensus.get_eta(),
  523. self.consensus.time_keeper.current_slot(),
  524. );
  525. // y
  526. let prop_mu_y = lf.public_inputs[constants::PI_MU_Y_INDEX];
  527. if mu_y != prop_mu_y {
  528. error!(
  529. target: "consensus::validator",
  530. "receive_proposal(): Failed to verify mu_y: {:?}, proposed: {:?}",
  531. mu_y, prop_mu_y
  532. );
  533. return Err(Error::ProposalPublicValuesMismatched)
  534. }
  535. // rho
  536. let prop_mu_rho = lf.public_inputs[constants::PI_MU_RHO_INDEX];
  537. if mu_rho != prop_mu_rho {
  538. error!(
  539. target: "consensus::validator",
  540. "receive_proposal(): Failed to verify mu_rho: {:?}, proposed: {:?}",
  541. mu_rho, prop_mu_rho
  542. );
  543. return Err(Error::ProposalPublicValuesMismatched)
  544. }
  545. // Validate proposal coin sigmas against current slot checkpoint
  546. let checkpoint = self.consensus.get_slot_checkpoint(current)?;
  547. // sigma1
  548. let prop_sigma1 = lf.public_inputs[constants::PI_SIGMA1_INDEX];
  549. if checkpoint.sigma1 != prop_sigma1 {
  550. error!(
  551. target: "consensus::validator",
  552. "receive_proposal(): Failed to verify public value sigma1: {:?}, to proposed: {:?}",
  553. checkpoint.sigma1, prop_sigma1
  554. );
  555. }
  556. // sigma2
  557. let prop_sigma2 = lf.public_inputs[constants::PI_SIGMA2_INDEX];
  558. if checkpoint.sigma2 != prop_sigma2 {
  559. error!(
  560. target: "consensus::validator",
  561. "receive_proposal(): Failed to verify public value sigma2: {:?}, to proposed: {:?}",
  562. checkpoint.sigma2, prop_sigma2
  563. );
  564. }
  565. }
  566. // Create corresponding state checkpoint for validations
  567. let mut state_checkpoint = match index {
  568. -1 => {
  569. // Extends canonical
  570. StateCheckpoint::new(
  571. proposal.clone(),
  572. self.consensus.coins.clone(),
  573. self.consensus.coins_tree.clone(),
  574. self.consensus.nullifiers.clone(),
  575. )
  576. }
  577. _ => {
  578. // Extends a fork
  579. let previous = self.consensus.forks[index as usize].sequence.last().unwrap();
  580. StateCheckpoint::new(
  581. proposal.clone(),
  582. previous.coins.clone(),
  583. previous.coins_tree.clone(),
  584. previous.nullifiers.clone(),
  585. )
  586. }
  587. };
  588. // Check if proposal coin nullifiers already exist in the state checkpoint
  589. let prop_sn = lf.public_inputs[constants::PI_NULLIFIER_INDEX];
  590. for sn in &state_checkpoint.nullifiers {
  591. if *sn == prop_sn {
  592. error!(target: "consensus::validator", "receive_proposal(): Proposal nullifiers exist.");
  593. return Err(Error::ProposalIsSpent)
  594. }
  595. }
  596. // Validate state transition against canonical state
  597. // TODO: This should be validated against fork state
  598. info!(target: "consensus::validator", "receive_proposal(): Starting state transition validation");
  599. match self.verify_transactions(&proposal.block.txs, current, false).await {
  600. Ok(erroneous_txs) => {
  601. if !erroneous_txs.is_empty() {
  602. error!(target: "consensus::validator", "Proposal contains erroneous transactions");
  603. return Err(Error::ErroneousTxsDetected)
  604. }
  605. }
  606. Err(e) => {
  607. error!(target: "consensus::validator", "receive_proposal(): Transaction verifications failed: {}", e);
  608. return Err(e)
  609. }
  610. }
  611. // TODO: [PLACEHOLDER] Add rewards validation
  612. // If proposal came fromself, we derive new coin
  613. if let Some((idx, c, derived_blind)) = coin {
  614. info!(target: "consensus::validator", "receive_proposal(): Storing derived coin...");
  615. // Derive coin
  616. let derived = c.derive_coin(&mut state_checkpoint.coins_tree, derived_blind);
  617. // Update consensus coin in wallet
  618. // NOTE: In future this will be redundant as consensus coins will live in the money contract.
  619. // Get a wallet connection
  620. let mut conn = self.wallet.conn.acquire().await?;
  621. let query_str = format!(
  622. "UPDATE {} SET {} = ?1",
  623. constants::CONSENSUS_COIN_TABLE,
  624. constants::CONSENSUS_COIN_COL
  625. );
  626. let mut query = sqlx::query(&query_str);
  627. query = query.bind(serialize(&derived));
  628. query.execute(&mut conn).await?;
  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. /// slot checkpoints are apppended to canonical state.
  653. pub async fn chain_finalization(&mut self) -> Result<(Vec<BlockInfo>, Vec<SlotCheckpoint>)> {
  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 mut 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. match self.blockchain.add(&finalized) {
  704. Ok(v) => v,
  705. Err(e) => {
  706. error!(target: "consensus::validator", "consensus: Failed appending finalized blocks to canonical chain: {}", e);
  707. return Err(e)
  708. }
  709. };
  710. let blocks_subscriber = self.subscribers.get("blocks").unwrap().clone();
  711. // Validating state transitions
  712. for proposal in &finalized {
  713. // TODO: Is this the right place? We're already doing this in protocol_sync.
  714. // TODO: These state transitions have already been checked. (I wrote this, but where?)
  715. // TODO: FIXME: The state transitions have already been written, they have to be in memory
  716. // until this point.
  717. info!(target: "consensus::validator", "Applying state transition for finalized block");
  718. match self.verify_transactions(&proposal.txs, proposal.header.slot, true).await {
  719. Ok(erroneous_txs) => {
  720. if !erroneous_txs.is_empty() {
  721. error!(target: "consensus::validator", "Finalized block contains erroneous transactions");
  722. return Err(Error::ErroneousTxsDetected)
  723. }
  724. }
  725. Err(e) => {
  726. error!(target: "consensus::validator", "Finalized block transaction verifications failed: {}", e);
  727. return Err(e)
  728. }
  729. }
  730. // Remove proposal transactions from pending txs store
  731. if let Err(e) = self.blockchain.remove_pending_txs(&proposal.txs) {
  732. error!(target: "consensus::validator", "Removing finalized block transactions failed: {}", e);
  733. return Err(e)
  734. }
  735. // TODO: Don't hardcode this:
  736. let params = json!([bs58::encode(&serialize(proposal)).into_string()]);
  737. let notif = JsonNotification::new("blockchain.subscribe_blocks", params);
  738. info!(target: "consensus::validator", "consensus: Sending notification about finalized block");
  739. blocks_subscriber.notify(notif).await;
  740. }
  741. // Setting leaders history to last proposal leaders count
  742. let last_state_checkpoint = fork.sequence.last().unwrap().clone();
  743. // Setting canonical states from last finalized checkpoint
  744. self.consensus.coins = last_state_checkpoint.coins;
  745. self.consensus.coins_tree = last_state_checkpoint.coins_tree;
  746. self.consensus.nullifiers = last_state_checkpoint.nullifiers;
  747. // Adding finalized slot checkpoints to canonical
  748. let finalized_slot_checkpoints: Vec<SlotCheckpoint> =
  749. self.consensus.slot_checkpoints.clone();
  750. debug!(
  751. target: "consensus::validator",
  752. "consensus: Adding {} finalized slot checkpoints to canonical chain.",
  753. finalized_slot_checkpoints.len()
  754. );
  755. match self.blockchain.add_slot_checkpoints(&finalized_slot_checkpoints) {
  756. Ok(v) => v,
  757. Err(e) => {
  758. error!(
  759. target: "consensus::validator",
  760. "consensus: Failed appending finalized slot checkpoints to canonical chain: {}",
  761. e
  762. );
  763. return Err(e)
  764. }
  765. };
  766. // Resetting forks and slot checkpoints
  767. self.consensus.forks = vec![];
  768. self.consensus.slot_checkpoints = vec![];
  769. // Purge pending erroneous txs since canonical state has been changed
  770. if let Err(e) = self.purge_pending_txs().await {
  771. error!(target: "consensus::validator", "consensus: Purging pending transactions failed: {}", e);
  772. }
  773. Ok((finalized, finalized_slot_checkpoints))
  774. }
  775. // ==========================
  776. // State transition functions
  777. // ==========================
  778. // TODO TESTNET: Write down all cases below
  779. // State transition checks should be happening in the following cases for a sync node:
  780. // 1) When a finalized block is received
  781. // 2) When a transaction is being broadcasted to us
  782. // State transition checks should be happening in the following cases for a consensus participating node:
  783. // 1) When a finalized block is received
  784. // 2) When a transaction is being broadcasted to us
  785. // ==========================
  786. /// Validate and append to canonical state received blocks.
  787. async fn receive_blocks(&mut self, blocks: &[BlockInfo]) -> Result<()> {
  788. // Verify state transitions for all blocks and their respective transactions.
  789. info!(target: "consensus::validator", "receive_blocks(): Starting state transition validations");
  790. for block in blocks {
  791. match self.verify_transactions(&block.txs, block.header.slot, true).await {
  792. Ok(erroneous_txs) => {
  793. if !erroneous_txs.is_empty() {
  794. error!(target: "consensus::validator", "receive_blocks(): Block contains erroneous transactions");
  795. return Err(Error::ErroneousTxsDetected)
  796. }
  797. }
  798. Err(e) => {
  799. error!(target: "consensus::validator", "receive_blocks(): Transaction verifications failed: {}", e);
  800. return Err(e)
  801. }
  802. }
  803. }
  804. info!(target: "consensus::validator", "receive_blocks(): All state transitions passed. Appending blocks to ledger.");
  805. self.blockchain.add(blocks)?;
  806. Ok(())
  807. }
  808. /// Validate and append to canonical state received finalized block.
  809. /// Returns boolean flag indicating already existing block.
  810. pub async fn receive_finalized_block(&mut self, block: BlockInfo) -> Result<bool> {
  811. if block.header.slot > self.consensus.time_keeper.current_slot() {
  812. warn!(target: "consensus::validator", "receive_finalized_block(): Ignoring future block: {}", block.header.slot);
  813. return Ok(false)
  814. }
  815. match self.blockchain.has_block(&block) {
  816. Ok(v) => {
  817. if v {
  818. info!(target: "consensus::validator", "receive_finalized_block(): Existing block received");
  819. return Ok(false)
  820. }
  821. }
  822. Err(e) => {
  823. error!(target: "consensus::validator", "receive_finalized_block(): failed checking for has_block(): {}", e);
  824. return Ok(false)
  825. }
  826. };
  827. info!(target: "consensus::validator", "receive_finalized_block(): Executing state transitions");
  828. self.receive_blocks(&[block.clone()]).await?;
  829. // TODO: Don't hardcode this:
  830. let blocks_subscriber = self.subscribers.get("blocks").unwrap();
  831. let params = json!([bs58::encode(&serialize(&block)).into_string()]);
  832. let notif = JsonNotification::new("blockchain.subscribe_blocks", params);
  833. info!(target: "consensus::validator", "consensus: Sending notification about finalized block");
  834. blocks_subscriber.notify(notif).await;
  835. info!(target: "consensus::validator", "receive_finalized_block(): Removing block transactions from pending txs store");
  836. self.blockchain.remove_pending_txs(&block.txs)?;
  837. // Purge pending erroneous txs since canonical state has been changed
  838. if let Err(e) = self.purge_pending_txs().await {
  839. error!(target: "consensus::validator", "receive_finalized_block(): Purging pending transactions failed: {}", e);
  840. }
  841. Ok(true)
  842. }
  843. /// Validate and append to canonical state received finalized blocks from block sync task.
  844. /// Already existing blocks are ignored.
  845. pub async fn receive_sync_blocks(&mut self, blocks: &[BlockInfo]) -> Result<()> {
  846. let mut new_blocks = vec![];
  847. for block in blocks {
  848. if block.header.slot > self.consensus.time_keeper.current_slot() {
  849. warn!(target: "consensus::validator", "receive_sync_blocks(): Ignoring future block: {}", block.header.slot);
  850. continue
  851. }
  852. match self.blockchain.has_block(block) {
  853. Ok(v) => {
  854. if v {
  855. info!(target: "consensus::validator", "receive_sync_blocks(): Existing block received");
  856. continue
  857. }
  858. new_blocks.push(block.clone());
  859. }
  860. Err(e) => {
  861. error!(target: "consensus::validator", "receive_sync_blocks(): failed checking for has_block(): {}", e);
  862. continue
  863. }
  864. };
  865. }
  866. if new_blocks.is_empty() {
  867. info!(target: "consensus::validator", "receive_sync_blocks(): no new blocks to append");
  868. return Ok(())
  869. }
  870. info!(target: "consensus::validator", "receive_sync_blocks(): Executing state transitions");
  871. self.receive_blocks(&new_blocks[..]).await?;
  872. // TODO: Don't hardcode this:
  873. let blocks_subscriber = self.subscribers.get("blocks").unwrap();
  874. for block in new_blocks {
  875. let params = json!([bs58::encode(&serialize(&block)).into_string()]);
  876. let notif = JsonNotification::new("blockchain.subscribe_blocks", params);
  877. info!(target: "consensus::validator", "consensus: Sending notification about finalized block");
  878. blocks_subscriber.notify(notif).await;
  879. }
  880. Ok(())
  881. }
  882. /// Validate signatures, wasm execution, and zk proofs for given transaction in
  883. /// provided runtimes. If all of those succeed, try to execute a state update
  884. /// for the contract calls.
  885. async fn verify_transaction(
  886. &self,
  887. blockchain_overlay: BlockchainOverlayPtr,
  888. tx: &Transaction,
  889. verifying_slot: u64,
  890. ) -> Result<()> {
  891. let mut runtimes = HashMap::new();
  892. let tx_hash = blake3::hash(&serialize(tx));
  893. info!(target: "consensus::validator", "Verifying transaction {}", tx_hash);
  894. // Table of public inputs used for ZK proof verification
  895. let mut zkp_table = vec![];
  896. // Table of public keys used for signature verification
  897. let mut sig_table = vec![];
  898. // State updates produced by contract execution
  899. let mut updates = vec![];
  900. // Map of zk proof verifying keys for the current transaction
  901. let mut verifying_keys: HashMap<[u8; 32], HashMap<String, VerifyingKey>> = HashMap::new();
  902. // Initialize the map
  903. for call in tx.calls.iter() {
  904. verifying_keys.insert(call.contract_id.to_bytes(), HashMap::new());
  905. }
  906. // Generate a time keeper using transaction verifying slot
  907. let time_keeper = TimeKeeper::new(
  908. self.consensus.time_keeper.genesis_ts,
  909. self.consensus.time_keeper.epoch_length,
  910. self.consensus.time_keeper.slot_time,
  911. verifying_slot,
  912. );
  913. // Iterate over all calls to get the metadata
  914. for (idx, call) in tx.calls.iter().enumerate() {
  915. info!(target: "consensus::validator", "Executing contract call {}", idx);
  916. // Write the actual payload data
  917. let mut payload = vec![];
  918. payload.write_u32(idx as u32)?; // Call index
  919. tx.calls.encode(&mut payload)?; // Actual call data
  920. // Instantiate the wasm runtime
  921. let runtime_key = call.contract_id.to_string();
  922. if !runtimes.contains_key(&runtime_key) {
  923. let wasm = self.blockchain.wasm_bincode.get(call.contract_id)?;
  924. let r = Runtime::new(
  925. &wasm,
  926. blockchain_overlay.clone(),
  927. call.contract_id,
  928. time_keeper.clone(),
  929. )?;
  930. runtimes.insert(runtime_key.clone(), r);
  931. }
  932. let runtime = runtimes.get_mut(&runtime_key).unwrap();
  933. info!(target: "consensus::validator", "Executing \"metadata\" call");
  934. let metadata = runtime.metadata(&payload)?;
  935. // Decode the metadata retrieved from the execution
  936. let mut decoder = Cursor::new(&metadata);
  937. // The tuple is (zkas_ns, public_inputs)
  938. let zkp_pub: Vec<(String, Vec<pallas::Base>)> = Decodable::decode(&mut decoder)?;
  939. let sig_pub: Vec<PublicKey> = Decodable::decode(&mut decoder)?;
  940. // TODO: Make sure we've read all the bytes above.
  941. info!(target: "consensus::validator", "Successfully executed \"metadata\" call");
  942. // Here we'll look up verifying keys and insert them into the per-contract map.
  943. info!(target: "consensus::validator", "Performing VerifyingKey lookups from the sled db");
  944. for (zkas_ns, _) in &zkp_pub {
  945. let inner_vk_map = verifying_keys.get_mut(&call.contract_id.to_bytes()).unwrap();
  946. if inner_vk_map.contains_key(zkas_ns.as_str()) {
  947. continue
  948. }
  949. let (_, vk) = self.blockchain.contracts.get_zkas(
  950. &self.blockchain.sled_db,
  951. &call.contract_id,
  952. zkas_ns,
  953. )?;
  954. inner_vk_map.insert(zkas_ns.to_string(), vk);
  955. }
  956. zkp_table.push(zkp_pub);
  957. sig_table.push(sig_pub);
  958. // After getting the metadata, we run the "exec" function with the same
  959. // runtime and the same payload.
  960. info!(target: "consensus::validator", "Executing \"exec\" call");
  961. let state_update = runtime.exec(&payload)?;
  962. info!(target: "consensus::validator", "Successfully executed \"exec\" call");
  963. updates.push(state_update);
  964. // At this point we're done with the call and move on to the next one.
  965. }
  966. // When we're done looping and executing over the tx's contract calls, we
  967. // move on with verification. First we verify the signatures as that's
  968. // cheaper, and then finally we verify the ZK proofs.
  969. info!(target: "consensus::validator", "Verifying signatures for transaction {}", tx_hash);
  970. if sig_table.len() != tx.signatures.len() {
  971. error!(target: "consensus::validator", "Incorrect number of signatures in tx {}", tx_hash);
  972. return Err(Error::InvalidSignature)
  973. }
  974. match tx.verify_sigs(sig_table) {
  975. Ok(()) => {
  976. info!(target: "consensus::validator", "Signatures verification for tx {} successful", tx_hash)
  977. }
  978. Err(e) => {
  979. error!(target: "consensus::validator", "Signature verification for tx {} failed: {}", tx_hash, e);
  980. return Err(e)
  981. }
  982. };
  983. info!(target: "consensus::validator", "Verifying ZK proofs for transaction {}", tx_hash);
  984. match tx.verify_zkps(verifying_keys.clone(), zkp_table).await {
  985. Ok(()) => {
  986. info!(target: "consensus::validator", "ZK proof verification for tx {} successful", tx_hash)
  987. }
  988. Err(e) => {
  989. error!(target: "consensus::validator", "ZK proof verification for tx {} failed: {}", tx_hash, e);
  990. return Err(e)
  991. }
  992. };
  993. // After the verifications stage passes we can apply the state updates.
  994. assert!(tx.calls.len() == updates.len());
  995. info!(target: "consensus::validator", "Performing state updates");
  996. for (call, update) in tx.calls.iter().zip(updates.iter()) {
  997. // Retrieve already initiated runtime and apply update
  998. // TODO: Sum up the gas costs of previous calls during execution
  999. // and verification and these.
  1000. let runtime = runtimes.get_mut(&call.contract_id.to_string()).unwrap();
  1001. info!(target: "consensus::validator", "Executing \"apply\" call");
  1002. runtime.apply(update)?;
  1003. info!(target: "consensus::validator", "State update applied successfully")
  1004. }
  1005. info!(target: "consensus::validator", "Transaction {} verified successfully", tx_hash);
  1006. Ok(())
  1007. }
  1008. /// Validate a set of [`Transaction`] in sequence and apply them if all are valid.
  1009. /// Erroneous transactions are filtered out of the set and returned to caller.
  1010. /// The function takes a boolean called `write` which tells it to actually write
  1011. /// the state transitions to the database.
  1012. pub async fn verify_transactions(
  1013. &self,
  1014. txs: &[Transaction],
  1015. verifying_slot: u64,
  1016. write: bool,
  1017. ) -> Result<Vec<Transaction>> {
  1018. info!(target: "consensus::validator", "Verifying {} transaction(s)", txs.len());
  1019. let mut erroneous_txs = vec![];
  1020. let blockchain_overlay = BlockchainOverlay::new(&self.blockchain)?;
  1021. for tx in txs {
  1022. if let Err(e) =
  1023. self.verify_transaction(blockchain_overlay.clone(), tx, verifying_slot).await
  1024. {
  1025. warn!(target: "consensus::validator", "Transaction verification failed: {}", e);
  1026. erroneous_txs.push(tx.clone());
  1027. }
  1028. }
  1029. let lock = blockchain_overlay.lock().unwrap();
  1030. let mut overlay = lock.overlay.lock().unwrap();
  1031. if !erroneous_txs.is_empty() {
  1032. warn!(target: "consensus::validator", "Erroneous transactions found in set");
  1033. overlay.purge_new_trees()?;
  1034. return Ok(erroneous_txs)
  1035. }
  1036. if !write {
  1037. info!(target: "consensus::validator", "Skipping apply of state updates because write=false");
  1038. overlay.purge_new_trees()?;
  1039. return Ok(erroneous_txs)
  1040. }
  1041. overlay.apply()?;
  1042. Ok(erroneous_txs)
  1043. }
  1044. /// Append to canonical state received finalized slot checkpoints from block sync task.
  1045. pub async fn receive_slot_checkpoints(
  1046. &mut self,
  1047. slot_checkpoints: &[SlotCheckpoint],
  1048. ) -> Result<()> {
  1049. info!(target: "consensus::validator", "receive_slot_checkpoints(): Appending slot checkpoints to ledger");
  1050. let mut filtered = vec![];
  1051. for slot_checkpoint in slot_checkpoints {
  1052. if slot_checkpoint.slot > self.consensus.time_keeper.current_slot() {
  1053. warn!(target: "consensus::validator", "receive_slot_checkpoints(): Ignoring future slot checkpoint: {}", slot_checkpoint.slot);
  1054. continue
  1055. }
  1056. filtered.push(slot_checkpoint.clone());
  1057. }
  1058. self.blockchain.add_slot_checkpoints(&filtered[..])?;
  1059. Ok(())
  1060. }
  1061. /// Validate and append to canonical state received finalized slot checkpoint.
  1062. /// Returns boolean flag indicating already existing slot checkpoint.
  1063. pub async fn receive_finalized_slot_checkpoints(
  1064. &mut self,
  1065. slot_checkpoint: SlotCheckpoint,
  1066. ) -> Result<bool> {
  1067. match self.blockchain.has_slot_checkpoint(&slot_checkpoint) {
  1068. Ok(v) => {
  1069. if v {
  1070. info!(
  1071. target: "consensus::validator",
  1072. "receive_finalized_slot_checkpoints(): Existing slot checkpoint received"
  1073. );
  1074. return Ok(false)
  1075. }
  1076. }
  1077. Err(e) => {
  1078. error!(target: "consensus::validator", "receive_finalized_slot_checkpoints(): failed checking for has_slot_checkpoint(): {}", e);
  1079. return Ok(false)
  1080. }
  1081. };
  1082. self.receive_slot_checkpoints(&[slot_checkpoint]).await?;
  1083. Ok(true)
  1084. }
  1085. }