mod.rs 35 KB

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