mod.rs 35 KB

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