mod.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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, sync::Arc};
  19. use darkfi_sdk::crypto::MerkleTree;
  20. use log::{debug, error, info, warn};
  21. use num_bigint::BigUint;
  22. use smol::lock::RwLock;
  23. use crate::{
  24. blockchain::{
  25. block_store::{BlockDifficulty, BlockInfo, BlockRanks},
  26. Blockchain, BlockchainOverlay, HeaderHash,
  27. },
  28. error::TxVerifyFailed,
  29. tx::Transaction,
  30. zk::VerifyingKey,
  31. Error, Result,
  32. };
  33. /// DarkFi consensus module
  34. pub mod consensus;
  35. use consensus::{Consensus, Fork, Proposal};
  36. /// DarkFi PoW module
  37. pub mod pow;
  38. use pow::PoWModule;
  39. /// Verification functions
  40. pub mod verification;
  41. use verification::{
  42. verify_block, verify_checkpoint_block, verify_genesis_block, verify_producer_transaction,
  43. verify_transaction, verify_transactions,
  44. };
  45. /// Fee calculation helpers
  46. pub mod fees;
  47. /// Helper utilities
  48. pub mod utils;
  49. use utils::{best_fork_index, block_rank, deploy_native_contracts};
  50. /// Configuration for initializing [`Validator`]
  51. #[derive(Clone)]
  52. pub struct ValidatorConfig {
  53. /// Currently configured finalization security threshold
  54. pub finalization_threshold: usize,
  55. /// Currently configured PoW target
  56. pub pow_target: u32,
  57. /// Optional fixed difficulty, for testing purposes
  58. pub pow_fixed_difficulty: Option<BigUint>,
  59. /// Genesis block
  60. pub genesis_block: BlockInfo,
  61. /// Flag to enable tx fee verification
  62. pub verify_fees: bool,
  63. }
  64. /// Atomic pointer to validator.
  65. pub type ValidatorPtr = Arc<Validator>;
  66. /// This struct represents a DarkFi validator node.
  67. pub struct Validator {
  68. /// Canonical (finalized) blockchain
  69. pub blockchain: Blockchain,
  70. /// Hot/Live data used by the consensus algorithm
  71. pub consensus: Consensus,
  72. /// Flag signalling node has finished initial sync
  73. pub synced: RwLock<bool>,
  74. /// Flag to enable tx fee verification
  75. pub verify_fees: bool,
  76. }
  77. impl Validator {
  78. pub async fn new(db: &sled::Db, config: ValidatorConfig) -> Result<ValidatorPtr> {
  79. info!(target: "validator::new", "Initializing Validator");
  80. info!(target: "validator::new", "Initializing Blockchain");
  81. let blockchain = Blockchain::new(db)?;
  82. // Create an overlay over whole blockchain so we can write stuff
  83. let overlay = BlockchainOverlay::new(&blockchain)?;
  84. // Deploy native wasm contracts
  85. deploy_native_contracts(&overlay, config.pow_target).await?;
  86. // Add genesis block if blockchain is empty
  87. if blockchain.genesis().is_err() {
  88. info!(target: "validator::new", "Appending genesis block");
  89. verify_genesis_block(&overlay, &config.genesis_block, config.pow_target).await?;
  90. };
  91. // Write the changes to the actual chain db
  92. overlay.lock().unwrap().overlay.lock().unwrap().apply()?;
  93. info!(target: "validator::new", "Initializing Consensus");
  94. let consensus = Consensus::new(
  95. blockchain.clone(),
  96. config.finalization_threshold,
  97. config.pow_target,
  98. config.pow_fixed_difficulty,
  99. )?;
  100. // Create the actual state
  101. let state = Arc::new(Self {
  102. blockchain,
  103. consensus,
  104. synced: RwLock::new(false),
  105. verify_fees: config.verify_fees,
  106. });
  107. info!(target: "validator::new", "Finished initializing validator");
  108. Ok(state)
  109. }
  110. /// Auxiliary function to compute provided transaction's total gas,
  111. /// against current best fork.
  112. /// The function takes a boolean called `verify_fee` to overwrite
  113. /// the nodes configured `verify_fees` flag.
  114. pub async fn calculate_gas(&self, tx: &Transaction, verify_fee: bool) -> Result<u64> {
  115. // Grab the best fork to verify against
  116. let forks = self.consensus.forks.read().await;
  117. let fork = forks[best_fork_index(&forks)?].full_clone()?;
  118. drop(forks);
  119. // Map of ZK proof verifying keys for the transaction
  120. let mut vks: HashMap<[u8; 32], HashMap<String, VerifyingKey>> = HashMap::new();
  121. for call in &tx.calls {
  122. vks.insert(call.data.contract_id.to_bytes(), HashMap::new());
  123. }
  124. // Grab forks' next block height
  125. let next_block_height = fork.get_next_block_height()?;
  126. // Verify transaction to grab the gas used
  127. let verify_result = verify_transaction(
  128. &fork.overlay,
  129. next_block_height,
  130. self.consensus.module.read().await.target,
  131. tx,
  132. &mut MerkleTree::new(1),
  133. &mut vks,
  134. verify_fee,
  135. )
  136. .await;
  137. // Purge new trees
  138. fork.overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  139. Ok(verify_result?.0)
  140. }
  141. /// The node retrieves a transaction, validates its state transition,
  142. /// and appends it to the pending txs store.
  143. pub async fn append_tx(&self, tx: &Transaction, write: bool) -> Result<()> {
  144. let tx_hash = tx.hash();
  145. // Check if we have already seen this tx
  146. let tx_in_txstore = self.blockchain.transactions.contains(&tx_hash)?;
  147. let tx_in_pending_txs_store = self.blockchain.transactions.contains_pending(&tx_hash)?;
  148. if tx_in_txstore || tx_in_pending_txs_store {
  149. info!(target: "validator::append_tx", "We have already seen this tx");
  150. return Err(TxVerifyFailed::AlreadySeenTx(tx_hash.as_string()).into())
  151. }
  152. // Verify state transition
  153. info!(target: "validator::append_tx", "Starting state transition validation");
  154. let tx_vec = [tx.clone()];
  155. let mut valid = false;
  156. // Grab a lock over current consensus forks state
  157. let mut forks = self.consensus.forks.write().await;
  158. // Iterate over node forks to verify transaction validity in their overlays
  159. for fork in forks.iter_mut() {
  160. // Clone fork state
  161. let fork_clone = fork.full_clone()?;
  162. // Grab forks' next block height
  163. let next_block_height = fork_clone.get_next_block_height()?;
  164. // Verify transaction
  165. let verify_result = verify_transactions(
  166. &fork_clone.overlay,
  167. next_block_height,
  168. self.consensus.module.read().await.target,
  169. &tx_vec,
  170. &mut MerkleTree::new(1),
  171. self.verify_fees,
  172. )
  173. .await;
  174. // Purge new trees
  175. fork_clone.overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  176. // Handle response
  177. match verify_result {
  178. Ok(_) => {}
  179. Err(Error::TxVerifyFailed(TxVerifyFailed::ErroneousTxs(_))) => continue,
  180. Err(e) => return Err(e),
  181. }
  182. valid = true;
  183. // Store transaction hash in forks' mempool
  184. if write {
  185. fork.mempool.push(tx_hash);
  186. }
  187. }
  188. // Drop forks lock
  189. drop(forks);
  190. // Return error if transaction is not valid for any fork
  191. if !valid {
  192. return Err(TxVerifyFailed::ErroneousTxs(tx_vec.to_vec()).into())
  193. }
  194. // Add transaction to pending txs store
  195. if write {
  196. self.blockchain.add_pending_txs(&tx_vec)?;
  197. info!(target: "validator::append_tx", "Appended tx to pending txs store");
  198. }
  199. Ok(())
  200. }
  201. /// The node removes invalid transactions from the pending txs store.
  202. pub async fn purge_pending_txs(&self) -> Result<()> {
  203. info!(target: "validator::purge_pending_txs", "Removing invalid transactions from pending transactions store...");
  204. // Check if any pending transactions exist
  205. let pending_txs = self.blockchain.get_pending_txs()?;
  206. if pending_txs.is_empty() {
  207. info!(target: "validator::purge_pending_txs", "No pending transactions found");
  208. return Ok(())
  209. }
  210. // Grab a lock over current consensus forks state
  211. let mut forks = self.consensus.forks.write().await;
  212. let mut removed_txs = vec![];
  213. for tx in pending_txs {
  214. let tx_hash = tx.hash();
  215. let tx_vec = [tx.clone()];
  216. let mut valid = false;
  217. // Iterate over node forks to verify transaction validity in their overlays
  218. for fork in forks.iter_mut() {
  219. // Clone fork state
  220. let fork_clone = fork.full_clone()?;
  221. // Grab forks' next block height
  222. let next_block_height = fork_clone.get_next_block_height()?;
  223. // Verify transaction
  224. let verify_result = verify_transactions(
  225. &fork_clone.overlay,
  226. next_block_height,
  227. self.consensus.module.read().await.target,
  228. &tx_vec,
  229. &mut MerkleTree::new(1),
  230. self.verify_fees,
  231. )
  232. .await;
  233. // Purge new trees
  234. fork_clone.overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  235. // Handle response
  236. match verify_result {
  237. Ok(_) => {
  238. valid = true;
  239. continue
  240. }
  241. Err(Error::TxVerifyFailed(TxVerifyFailed::ErroneousTxs(_))) => {}
  242. Err(e) => return Err(e),
  243. }
  244. // Remove erroneous transaction from forks' mempool
  245. fork.mempool.retain(|x| *x != tx_hash);
  246. }
  247. // Remove pending transaction if it's not valid for canonical or any fork
  248. if !valid {
  249. removed_txs.push(tx)
  250. }
  251. }
  252. // Drop forks lock
  253. drop(forks);
  254. if removed_txs.is_empty() {
  255. info!(target: "validator::purge_pending_txs", "No erroneous transactions found");
  256. return Ok(())
  257. }
  258. info!(target: "validator::purge_pending_txs", "Removing {} erroneous transactions...", removed_txs.len());
  259. self.blockchain.remove_pending_txs(&removed_txs)?;
  260. Ok(())
  261. }
  262. /// The node locks its consensus state and tries to append provided proposal.
  263. pub async fn append_proposal(&self, proposal: &Proposal) -> Result<()> {
  264. // Grab append lock so we restrict concurrent calls of this function
  265. let append_lock = self.consensus.append_lock.write().await;
  266. // Execute append
  267. let result = self.consensus.append_proposal(proposal, self.verify_fees).await;
  268. // Release append lock
  269. drop(append_lock);
  270. result
  271. }
  272. /// The node checks if best fork can be finalized.
  273. /// If proposals can be finalized, node appends them to canonical,
  274. /// and resets the current forks.
  275. pub async fn finalization(&self) -> Result<Vec<BlockInfo>> {
  276. // Grab append lock so no new proposals can be appended while
  277. // we execute finalization
  278. let append_lock = self.consensus.append_lock.write().await;
  279. info!(target: "validator::finalization", "Performing finalization check");
  280. // Grab best fork index that can be finalized
  281. let finalized_fork = match self.consensus.finalization().await {
  282. Ok(f) => f,
  283. Err(e) => {
  284. drop(append_lock);
  285. return Err(e)
  286. }
  287. };
  288. if finalized_fork.is_none() {
  289. info!(target: "validator::finalization", "No proposals can be finalized");
  290. drop(append_lock);
  291. return Ok(vec![])
  292. }
  293. // Grab the actual best fork
  294. let finalized_fork = finalized_fork.unwrap();
  295. let mut forks = self.consensus.forks.write().await;
  296. let fork = &mut forks[finalized_fork];
  297. // Find the excess over finalization threshold
  298. let excess = (fork.proposals.len() - self.consensus.finalization_threshold) + 1;
  299. // Grab finalized proposals and update fork's sequences
  300. let rest_proposals = fork.proposals.split_off(excess);
  301. let rest_diffs = fork.diffs.split_off(excess);
  302. let finalized_proposals = fork.proposals.clone();
  303. let mut diffs = fork.diffs.clone();
  304. fork.proposals = rest_proposals;
  305. fork.diffs = rest_diffs;
  306. // Grab finalized proposals blocks
  307. let finalized_blocks =
  308. fork.overlay.lock().unwrap().get_blocks_by_hash(&finalized_proposals)?;
  309. // Apply finalized proposals diffs and update PoW module
  310. let mut module = self.consensus.module.write().await;
  311. let mut finalized_txs = vec![];
  312. info!(target: "validator::finalization", "Finalizing proposals:");
  313. for (index, proposal) in finalized_proposals.iter().enumerate() {
  314. info!(target: "validator::finalization", "\t{} - {}", proposal, finalized_blocks[index].header.height);
  315. fork.overlay.lock().unwrap().overlay.lock().unwrap().apply_diff(&mut diffs[index])?;
  316. let next_difficulty = module.next_difficulty()?;
  317. module.append(finalized_blocks[index].header.timestamp, &next_difficulty);
  318. finalized_txs.extend_from_slice(&finalized_blocks[index].txs);
  319. }
  320. drop(module);
  321. drop(forks);
  322. // Reset forks starting with the finalized blocks
  323. self.consensus.reset_forks(&finalized_proposals, &finalized_fork, &finalized_txs).await?;
  324. info!(target: "validator::finalization", "Finalization completed!");
  325. // Release append lock
  326. drop(append_lock);
  327. Ok(finalized_blocks)
  328. }
  329. /// Apply provided set of [`BlockInfo`] without doing formal verification.
  330. /// A set of ['HeaderHash`] is also provided, to verify that the provided
  331. /// block hash matches the expected header one.
  332. /// Note: this function should only be used for blocks received using a
  333. /// checkpoint, since in that case we enforce the node to follow the sequence,
  334. /// assuming they all its blocks are valid. Additionally, it will update
  335. /// any forks to a single empty one, holding the updated module.
  336. pub async fn add_checkpoint_blocks(
  337. &self,
  338. blocks: &[BlockInfo],
  339. headers: &[HeaderHash],
  340. ) -> Result<()> {
  341. // Check provided sequences are the same length
  342. if blocks.len() != headers.len() {
  343. return Err(Error::InvalidInputLengths)
  344. }
  345. debug!(target: "validator::add_checkpoint_blocks", "Instantiating BlockchainOverlay");
  346. let overlay = BlockchainOverlay::new(&self.blockchain)?;
  347. // Retrieve last block difficulty to access current ranks
  348. let last_difficulty = self.blockchain.last_block_difficulty()?;
  349. let mut current_targets_rank = last_difficulty.ranks.targets_rank;
  350. let mut current_hashes_rank = last_difficulty.ranks.hashes_rank;
  351. // Grab current PoW module to validate each block
  352. let mut module = self.consensus.module.read().await.clone();
  353. // Keep track of all blocks transactions to remove them from pending txs store
  354. let mut removed_txs = vec![];
  355. // Validate and insert each block
  356. for (index, block) in blocks.iter().enumerate() {
  357. // Verify block
  358. match verify_checkpoint_block(&overlay, block, &headers[index], module.target).await {
  359. Ok(()) => { /* Do nothing */ }
  360. // Skip already existing block
  361. Err(Error::BlockAlreadyExists(_)) => continue,
  362. Err(e) => {
  363. error!(target: "validator::add_checkpoint_blocks", "Erroneous block found in set: {}", e);
  364. overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  365. return Err(Error::BlockIsInvalid(block.hash().as_string()))
  366. }
  367. };
  368. // Grab next mine target and difficulty
  369. let (next_target, next_difficulty) = module.next_mine_target_and_difficulty()?;
  370. // Calculate block rank
  371. let (target_distance_sq, hash_distance_sq) = block_rank(block, &next_target);
  372. // Update current ranks
  373. current_targets_rank += target_distance_sq.clone();
  374. current_hashes_rank += hash_distance_sq.clone();
  375. // Generate block difficulty and update PoW module
  376. let cummulative_difficulty =
  377. module.cummulative_difficulty.clone() + next_difficulty.clone();
  378. let ranks = BlockRanks::new(
  379. target_distance_sq,
  380. current_targets_rank.clone(),
  381. hash_distance_sq,
  382. current_hashes_rank.clone(),
  383. );
  384. let block_difficulty = BlockDifficulty::new(
  385. block.header.height,
  386. block.header.timestamp,
  387. next_difficulty,
  388. cummulative_difficulty,
  389. ranks,
  390. );
  391. module.append_difficulty(&overlay, block_difficulty)?;
  392. // Store block transactions
  393. for tx in &block.txs {
  394. removed_txs.push(tx.clone());
  395. }
  396. }
  397. debug!(target: "validator::add_checkpoint_blocks", "Applying overlay changes");
  398. overlay.lock().unwrap().overlay.lock().unwrap().apply()?;
  399. // Remove blocks transactions from pending txs store
  400. self.blockchain.remove_pending_txs(&removed_txs)?;
  401. // Update PoW module
  402. *self.consensus.module.write().await = module.clone();
  403. // Update forks
  404. *self.consensus.forks.write().await =
  405. vec![Fork::new(self.blockchain.clone(), module).await?];
  406. Ok(())
  407. }
  408. /// Validate a set of [`BlockInfo`] in sequence and apply them if all are valid.
  409. /// Note: this function should only be used in tests when we don't want to
  410. /// perform consensus logic.
  411. pub async fn add_test_blocks(&self, blocks: &[BlockInfo]) -> Result<()> {
  412. debug!(target: "validator::add_test_blocks", "Instantiating BlockchainOverlay");
  413. let overlay = BlockchainOverlay::new(&self.blockchain)?;
  414. // Retrieve last block
  415. let mut previous = &overlay.lock().unwrap().last_block()?;
  416. // Retrieve last block difficulty to access current ranks
  417. let last_difficulty = self.blockchain.last_block_difficulty()?;
  418. let mut current_targets_rank = last_difficulty.ranks.targets_rank;
  419. let mut current_hashes_rank = last_difficulty.ranks.hashes_rank;
  420. // Grab current PoW module to validate each block
  421. let mut module = self.consensus.module.read().await.clone();
  422. // Keep track of all blocks transactions to remove them from pending txs store
  423. let mut removed_txs = vec![];
  424. // Validate and insert each block
  425. for block in blocks {
  426. // Verify block
  427. match verify_block(&overlay, &module, block, previous, self.verify_fees).await {
  428. Ok(()) => { /* Do nothing */ }
  429. // Skip already existing block
  430. Err(Error::BlockAlreadyExists(_)) => {
  431. previous = block;
  432. continue
  433. }
  434. Err(e) => {
  435. error!(target: "validator::add_test_blocks", "Erroneous block found in set: {}", e);
  436. overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  437. return Err(Error::BlockIsInvalid(block.hash().as_string()))
  438. }
  439. };
  440. // Grab next mine target and difficulty
  441. let (next_target, next_difficulty) = module.next_mine_target_and_difficulty()?;
  442. // Calculate block rank
  443. let (target_distance_sq, hash_distance_sq) = block_rank(block, &next_target);
  444. // Update current ranks
  445. current_targets_rank += target_distance_sq.clone();
  446. current_hashes_rank += hash_distance_sq.clone();
  447. // Generate block difficulty and update PoW module
  448. let cummulative_difficulty =
  449. module.cummulative_difficulty.clone() + next_difficulty.clone();
  450. let ranks = BlockRanks::new(
  451. target_distance_sq,
  452. current_targets_rank.clone(),
  453. hash_distance_sq,
  454. current_hashes_rank.clone(),
  455. );
  456. let block_difficulty = BlockDifficulty::new(
  457. block.header.height,
  458. block.header.timestamp,
  459. next_difficulty,
  460. cummulative_difficulty,
  461. ranks,
  462. );
  463. module.append_difficulty(&overlay, block_difficulty)?;
  464. // Store block transactions
  465. for tx in &block.txs {
  466. removed_txs.push(tx.clone());
  467. }
  468. // Use last inserted block as next iteration previous
  469. previous = block;
  470. }
  471. debug!(target: "validator::add_test_blocks", "Applying overlay changes");
  472. overlay.lock().unwrap().overlay.lock().unwrap().apply()?;
  473. // Purge pending erroneous txs since canonical state has been changed
  474. self.blockchain.remove_pending_txs(&removed_txs)?;
  475. self.purge_pending_txs().await?;
  476. // Update PoW module
  477. *self.consensus.module.write().await = module;
  478. Ok(())
  479. }
  480. /// Validate a set of [`Transaction`] in sequence and apply them if all are valid.
  481. /// In case any of the transactions fail, they will be returned to the caller.
  482. /// The function takes a boolean called `write` which tells it to actually write
  483. /// the state transitions to the database, and a boolean called `verify_fees` to
  484. /// overwrite the nodes configured `verify_fees` flag.
  485. ///
  486. /// Returns the total gas used and total paid fees for the given transactions.
  487. /// Note: this function should only be used in tests.
  488. pub async fn add_test_transactions(
  489. &self,
  490. txs: &[Transaction],
  491. verifying_block_height: u32,
  492. block_target: u32,
  493. write: bool,
  494. verify_fees: bool,
  495. ) -> Result<(u64, u64)> {
  496. debug!(target: "validator::add_transactions", "Instantiating BlockchainOverlay");
  497. let overlay = BlockchainOverlay::new(&self.blockchain)?;
  498. // Verify all transactions and get erroneous ones
  499. let verify_result = verify_transactions(
  500. &overlay,
  501. verifying_block_height,
  502. block_target,
  503. txs,
  504. &mut MerkleTree::new(1),
  505. verify_fees,
  506. )
  507. .await;
  508. let lock = overlay.lock().unwrap();
  509. let mut overlay = lock.overlay.lock().unwrap();
  510. if let Err(e) = verify_result {
  511. overlay.purge_new_trees()?;
  512. return Err(e)
  513. }
  514. let gas_values = verify_result.unwrap();
  515. if !write {
  516. debug!(target: "validator::add_transactions", "Skipping apply of state updates because write=false");
  517. overlay.purge_new_trees()?;
  518. return Ok(gas_values)
  519. }
  520. debug!(target: "validator::add_transactions", "Applying overlay changes");
  521. overlay.apply()?;
  522. Ok(gas_values)
  523. }
  524. /// Validate a producer `Transaction` and apply it if valid.
  525. /// In case the transactions fail, ir will be returned to the caller.
  526. /// The function takes a boolean called `write` which tells it to actually write
  527. /// the state transitions to the database.
  528. /// This should be only used for test purposes.
  529. pub async fn add_test_producer_transaction(
  530. &self,
  531. tx: &Transaction,
  532. verifying_block_height: u32,
  533. block_target: u32,
  534. write: bool,
  535. ) -> Result<()> {
  536. debug!(target: "validator::add_test_producer_transaction", "Instantiating BlockchainOverlay");
  537. let overlay = BlockchainOverlay::new(&self.blockchain)?;
  538. // Verify transaction
  539. let mut erroneous_txs = vec![];
  540. if let Err(e) = verify_producer_transaction(
  541. &overlay,
  542. verifying_block_height,
  543. block_target,
  544. tx,
  545. &mut MerkleTree::new(1),
  546. )
  547. .await
  548. {
  549. warn!(target: "validator::add_test_producer_transaction", "Transaction verification failed: {}", e);
  550. erroneous_txs.push(tx.clone());
  551. }
  552. let lock = overlay.lock().unwrap();
  553. let mut overlay = lock.overlay.lock().unwrap();
  554. if !erroneous_txs.is_empty() {
  555. warn!(target: "validator::add_test_producer_transaction", "Erroneous transactions found in set");
  556. overlay.purge_new_trees()?;
  557. return Err(TxVerifyFailed::ErroneousTxs(erroneous_txs).into())
  558. }
  559. if !write {
  560. debug!(target: "validator::add_test_producer_transaction", "Skipping apply of state updates because write=false");
  561. overlay.purge_new_trees()?;
  562. return Ok(())
  563. }
  564. debug!(target: "validator::add_test_producer_transaction", "Applying overlay changes");
  565. overlay.apply()?;
  566. Ok(())
  567. }
  568. /// Retrieve all existing blocks and try to apply them
  569. /// to an in memory overlay to verify their correctness.
  570. /// Be careful as this will try to load everything in memory.
  571. pub async fn validate_blockchain(
  572. &self,
  573. pow_target: u32,
  574. pow_fixed_difficulty: Option<BigUint>,
  575. ) -> Result<()> {
  576. let blocks = self.blockchain.get_all()?;
  577. // An empty blockchain is considered valid
  578. if blocks.is_empty() {
  579. return Ok(())
  580. }
  581. // Create an in memory blockchain overlay
  582. let sled_db = sled::Config::new().temporary(true).open()?;
  583. let blockchain = Blockchain::new(&sled_db)?;
  584. let overlay = BlockchainOverlay::new(&blockchain)?;
  585. // Set previous
  586. let mut previous = &blocks[0];
  587. // Deploy native wasm contracts
  588. deploy_native_contracts(&overlay, pow_target).await?;
  589. // Validate genesis block
  590. verify_genesis_block(&overlay, previous, pow_target).await?;
  591. // Write the changes to the in memory db
  592. overlay.lock().unwrap().overlay.lock().unwrap().apply()?;
  593. // Create a PoW module to validate each block
  594. let mut module = PoWModule::new(blockchain, pow_target, pow_fixed_difficulty)?;
  595. // Validate and insert each block
  596. for block in &blocks[1..] {
  597. // Verify block
  598. if verify_block(&overlay, &module, block, previous, self.verify_fees).await.is_err() {
  599. error!(target: "validator::validate_blockchain", "Erroneous block found in set");
  600. overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  601. return Err(Error::BlockIsInvalid(block.hash().as_string()))
  602. };
  603. // Update PoW module
  604. module.append(block.header.timestamp, &module.next_difficulty()?);
  605. // Use last inserted block as next iteration previous
  606. previous = block;
  607. }
  608. Ok(())
  609. }
  610. /// Auxiliary function to retrieve current best fork next block height.
  611. pub async fn best_fork_next_block_height(&self) -> Result<u32> {
  612. let forks = self.consensus.forks.read().await;
  613. let fork = &forks[best_fork_index(&forks)?];
  614. let next_block_height = fork.get_next_block_height()?;
  615. drop(forks);
  616. Ok(next_block_height)
  617. }
  618. }