mod.rs 36 KB

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