validator.rs 51 KB

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