consensus.rs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  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, HashSet};
  19. use darkfi_sdk::{crypto::MerkleTree, monotree::Monotree, tx::TransactionHash};
  20. use darkfi_serial::{async_trait, SerialDecodable, SerialEncodable};
  21. use log::{debug, info, warn};
  22. use num_bigint::BigUint;
  23. use sled_overlay::database::SledDbOverlayStateDiff;
  24. use smol::lock::RwLock;
  25. use crate::{
  26. blockchain::{
  27. block_store::{BlockDifficulty, BlockRanks},
  28. BlockInfo, Blockchain, BlockchainOverlay, BlockchainOverlayPtr, Header, HeaderHash,
  29. },
  30. runtime::vm_runtime::GAS_LIMIT,
  31. tx::{Transaction, MAX_TX_CALLS},
  32. validator::{
  33. pow::PoWModule,
  34. utils::{best_fork_index, block_rank, find_extended_fork_index},
  35. verification::{verify_proposal, verify_transaction},
  36. },
  37. zk::VerifyingKey,
  38. Error, Result,
  39. };
  40. /// Gas limit for total block transactions(50 full transactions).
  41. pub const BLOCK_GAS_LIMIT: u64 = GAS_LIMIT * MAX_TX_CALLS as u64 * 50;
  42. /// This struct represents the information required by the consensus algorithm
  43. pub struct Consensus {
  44. /// Canonical (confirmed) blockchain
  45. pub blockchain: Blockchain,
  46. /// Fork size(length) after which it can be confirmed
  47. pub confirmation_threshold: usize,
  48. /// Fork chains containing block proposals
  49. pub forks: RwLock<Vec<Fork>>,
  50. /// Canonical blockchain PoW module state
  51. pub module: RwLock<PoWModule>,
  52. /// Lock to restrict when proposals appends can happen
  53. pub append_lock: RwLock<()>,
  54. }
  55. impl Consensus {
  56. /// Generate a new Consensus state.
  57. pub fn new(
  58. blockchain: Blockchain,
  59. confirmation_threshold: usize,
  60. pow_target: u32,
  61. pow_fixed_difficulty: Option<BigUint>,
  62. ) -> Result<Self> {
  63. let forks = RwLock::new(vec![]);
  64. let module = RwLock::new(PoWModule::new(
  65. blockchain.clone(),
  66. pow_target,
  67. pow_fixed_difficulty,
  68. None,
  69. )?);
  70. let append_lock = RwLock::new(());
  71. Ok(Self { blockchain, confirmation_threshold, forks, module, append_lock })
  72. }
  73. /// Generate a new empty fork.
  74. pub async fn generate_empty_fork(&self) -> Result<()> {
  75. debug!(target: "validator::consensus::generate_empty_fork", "Generating new empty fork...");
  76. let mut forks = self.forks.write().await;
  77. // Check if we already have an empty fork
  78. for fork in forks.iter() {
  79. if fork.proposals.is_empty() {
  80. debug!(target: "validator::consensus::generate_empty_fork", "An empty fork already exists.");
  81. drop(forks);
  82. return Ok(())
  83. }
  84. }
  85. let fork = Fork::new(self.blockchain.clone(), self.module.read().await.clone()).await?;
  86. forks.push(fork);
  87. drop(forks);
  88. debug!(target: "validator::consensus::generate_empty_fork", "Fork generated!");
  89. Ok(())
  90. }
  91. /// Given a proposal, the node verifys it and finds which fork it extends.
  92. /// If the proposal extends the canonical blockchain, a new fork chain is created.
  93. pub async fn append_proposal(&self, proposal: &Proposal, verify_fees: bool) -> Result<()> {
  94. debug!(target: "validator::consensus::append_proposal", "Appending proposal {}", proposal.hash);
  95. // Check if proposal already exists
  96. let lock = self.forks.read().await;
  97. for fork in lock.iter() {
  98. for p in fork.proposals.iter().rev() {
  99. if p == &proposal.hash {
  100. drop(lock);
  101. debug!(target: "validator::consensus::append_proposal", "Proposal {} already exists", proposal.hash);
  102. return Err(Error::ProposalAlreadyExists)
  103. }
  104. }
  105. }
  106. // Check if proposal is canonical
  107. if let Ok(canonical_headers) =
  108. self.blockchain.blocks.get_order(&[proposal.block.header.height], true)
  109. {
  110. if canonical_headers[0].unwrap() == proposal.hash {
  111. drop(lock);
  112. debug!(target: "validator::consensus::append_proposal", "Proposal {} already exists", proposal.hash);
  113. return Err(Error::ProposalAlreadyExists)
  114. }
  115. }
  116. drop(lock);
  117. // Verify proposal and grab corresponding fork
  118. let (mut fork, index) = verify_proposal(self, proposal, verify_fees).await?;
  119. // Append proposal to the fork
  120. fork.append_proposal(proposal).await?;
  121. // TODO: to keep memory usage low, we should only append forks that
  122. // are higher ranking than our current best one
  123. // If a fork index was found, replace forks with the mutated one,
  124. // otherwise push the new fork.
  125. let mut lock = self.forks.write().await;
  126. match index {
  127. Some(i) => {
  128. if i < lock.len() && lock[i].proposals == fork.proposals[..fork.proposals.len() - 1]
  129. {
  130. lock[i] = fork;
  131. } else {
  132. lock.push(fork);
  133. }
  134. }
  135. None => {
  136. lock.push(fork);
  137. }
  138. }
  139. drop(lock);
  140. info!(target: "validator::consensus::append_proposal", "Appended proposal {}", proposal.hash);
  141. Ok(())
  142. }
  143. /// Given a proposal, find the fork chain it extends, and return its full clone.
  144. /// If the proposal extends the fork not on its tail, a new fork is created and
  145. /// we re-apply the proposals up to the extending one. If proposal extends canonical,
  146. /// a new fork is created. Additionally, we return the fork index if a new fork
  147. /// was not created, so caller can replace the fork.
  148. pub async fn find_extended_fork(&self, proposal: &Proposal) -> Result<(Fork, Option<usize>)> {
  149. // Grab a lock over current forks
  150. let forks = self.forks.read().await;
  151. // Check if proposal extends any fork
  152. let found = find_extended_fork_index(&forks, proposal);
  153. if found.is_err() {
  154. if let Err(Error::ProposalAlreadyExists) = found {
  155. return Err(Error::ProposalAlreadyExists)
  156. }
  157. // Check if proposal extends canonical
  158. let (last_height, last_block) = self.blockchain.last()?;
  159. if proposal.block.header.previous != last_block ||
  160. proposal.block.header.height <= last_height
  161. {
  162. return Err(Error::ExtendedChainIndexNotFound)
  163. }
  164. // Check if we have an empty fork to use
  165. for (f_index, fork) in forks.iter().enumerate() {
  166. if fork.proposals.is_empty() {
  167. return Ok((forks[f_index].full_clone()?, Some(f_index)))
  168. }
  169. }
  170. // Generate a new fork extending canonical
  171. let fork = Fork::new(self.blockchain.clone(), self.module.read().await.clone()).await?;
  172. return Ok((fork, None))
  173. }
  174. let (f_index, p_index) = found.unwrap();
  175. let original_fork = &forks[f_index];
  176. // Check if proposal extends fork at last proposal
  177. if p_index == (original_fork.proposals.len() - 1) {
  178. return Ok((original_fork.full_clone()?, Some(f_index)))
  179. }
  180. // Rebuild fork
  181. let mut fork = Fork::new(self.blockchain.clone(), self.module.read().await.clone()).await?;
  182. fork.proposals = original_fork.proposals[..p_index + 1].to_vec();
  183. fork.diffs = original_fork.diffs[..p_index + 1].to_vec();
  184. // Retrieve proposals blocks from original fork
  185. let blocks = &original_fork.overlay.lock().unwrap().get_blocks_by_hash(&fork.proposals)?;
  186. for (index, block) in blocks.iter().enumerate() {
  187. // Apply block diffs
  188. fork.overlay.lock().unwrap().overlay.lock().unwrap().add_diff(&fork.diffs[index])?;
  189. // Grab next mine target and difficulty
  190. let (next_target, next_difficulty) = fork.module.next_mine_target_and_difficulty()?;
  191. // Calculate block rank
  192. let (target_distance_sq, hash_distance_sq) = block_rank(block, &next_target);
  193. // Update PoW module
  194. fork.module.append(block.header.timestamp, &next_difficulty);
  195. // Update fork ranks
  196. fork.targets_rank += target_distance_sq;
  197. fork.hashes_rank += hash_distance_sq;
  198. }
  199. // Rebuild fork contracts states monotree
  200. fork.compute_monotree()?;
  201. // Drop forks lock
  202. drop(forks);
  203. Ok((fork, None))
  204. }
  205. /// Check if best fork proposals can be confirmed.
  206. /// Consensus confirmation logic:
  207. /// - If the current best fork has reached greater length than the security threshold,
  208. /// and no other fork exist with same rank, first proposal(s) in that fork can be
  209. /// appended to canonical blockchain (confirme).
  210. ///
  211. /// When best fork can be confirmed, first block(s) should be appended to canonical,
  212. /// and forks should be rebuilt.
  213. pub async fn confirmation(&self) -> Result<Option<usize>> {
  214. debug!(target: "validator::consensus::confirmation", "Started confirmation check");
  215. // Grab best fork
  216. let forks = self.forks.read().await;
  217. let index = best_fork_index(&forks)?;
  218. let fork = &forks[index];
  219. // Check its length
  220. let length = fork.proposals.len();
  221. if length < self.confirmation_threshold {
  222. debug!(target: "validator::consensus::confirmation", "Nothing to confirme yet, best fork size: {length}");
  223. drop(forks);
  224. return Ok(None)
  225. }
  226. // Drop forks lock
  227. drop(forks);
  228. Ok(Some(index))
  229. }
  230. /// Auxiliary function to retrieve the fork header hash of provided height.
  231. /// The fork is identified by the provided header hash.
  232. pub async fn get_fork_header_hash(
  233. &self,
  234. height: u32,
  235. fork_header: &HeaderHash,
  236. ) -> Result<Option<HeaderHash>> {
  237. // Grab a lock over current forks
  238. let forks = self.forks.read().await;
  239. // Find the fork containing the provided header
  240. let mut found = None;
  241. 'outer: for (index, fork) in forks.iter().enumerate() {
  242. for p in fork.proposals.iter().rev() {
  243. if p == fork_header {
  244. found = Some(index);
  245. break 'outer
  246. }
  247. }
  248. }
  249. if found.is_none() {
  250. drop(forks);
  251. return Ok(None)
  252. }
  253. let index = found.unwrap();
  254. // Grab header if it exists
  255. let header = forks[index].overlay.lock().unwrap().blocks.get_order(&[height], false)?[0];
  256. // Drop forks lock
  257. drop(forks);
  258. Ok(header)
  259. }
  260. /// Auxiliary function to retrieve the fork headers of provided hashes.
  261. /// The fork is identified by the provided header hash. If fork doesn't
  262. /// exists, an empty vector is returned.
  263. pub async fn get_fork_headers(
  264. &self,
  265. headers: &[HeaderHash],
  266. fork_header: &HeaderHash,
  267. ) -> Result<Vec<Header>> {
  268. // Grab a lock over current forks
  269. let forks = self.forks.read().await;
  270. // Find the fork containing the provided header
  271. let mut found = None;
  272. 'outer: for (index, fork) in forks.iter().enumerate() {
  273. for p in fork.proposals.iter().rev() {
  274. if p == fork_header {
  275. found = Some(index);
  276. break 'outer
  277. }
  278. }
  279. }
  280. let Some(index) = found else {
  281. drop(forks);
  282. return Ok(vec![])
  283. };
  284. // Grab headers
  285. let headers = forks[index].overlay.lock().unwrap().get_headers_by_hash(headers)?;
  286. // Drop forks lock
  287. drop(forks);
  288. Ok(headers)
  289. }
  290. /// Auxiliary function to retrieve the fork proposals of provided hashes.
  291. /// The fork is identified by the provided header hash. If fork doesn't
  292. /// exists, an empty vector is returned.
  293. pub async fn get_fork_proposals(
  294. &self,
  295. headers: &[HeaderHash],
  296. fork_header: &HeaderHash,
  297. ) -> Result<Vec<Proposal>> {
  298. // Grab a lock over current forks
  299. let forks = self.forks.read().await;
  300. // Find the fork containing the provided header
  301. let mut found = None;
  302. 'outer: for (index, fork) in forks.iter().enumerate() {
  303. for p in fork.proposals.iter().rev() {
  304. if p == fork_header {
  305. found = Some(index);
  306. break 'outer
  307. }
  308. }
  309. }
  310. let Some(index) = found else {
  311. drop(forks);
  312. return Ok(vec![])
  313. };
  314. // Grab proposals
  315. let blocks = forks[index].overlay.lock().unwrap().get_blocks_by_hash(headers)?;
  316. let mut proposals = Vec::with_capacity(blocks.len());
  317. for block in blocks {
  318. proposals.push(Proposal::new(block));
  319. }
  320. // Drop forks lock
  321. drop(forks);
  322. Ok(proposals)
  323. }
  324. /// Auxiliary function to retrieve a fork proposals, starting from provided tip.
  325. /// If provided tip is too far behind, unknown, or fork doesn't exists, an empty
  326. /// vector is returned. The fork is identified by the optional provided header hash.
  327. /// If its `None`, we use our best fork.
  328. pub async fn get_fork_proposals_after(
  329. &self,
  330. tip: HeaderHash,
  331. fork_tip: Option<HeaderHash>,
  332. limit: u32,
  333. ) -> Result<Vec<Proposal>> {
  334. // Grab a lock over current forks
  335. let forks = self.forks.read().await;
  336. // Create return vector
  337. let mut proposals = vec![];
  338. // Grab fork index to use
  339. let index = match fork_tip {
  340. Some(fork_tip) => {
  341. let mut found = None;
  342. 'outer: for (index, fork) in forks.iter().enumerate() {
  343. for p in fork.proposals.iter().rev() {
  344. if p == &fork_tip {
  345. found = Some(index);
  346. break 'outer
  347. }
  348. }
  349. }
  350. if found.is_none() {
  351. drop(forks);
  352. return Ok(proposals)
  353. }
  354. found.unwrap()
  355. }
  356. None => best_fork_index(&forks)?,
  357. };
  358. // Check tip exists
  359. let Ok(existing_tips) = forks[index].overlay.lock().unwrap().get_blocks_by_hash(&[tip])
  360. else {
  361. drop(forks);
  362. return Ok(proposals)
  363. };
  364. // Check tip is not far behind
  365. let last_block_height = forks[index].overlay.lock().unwrap().last()?.0;
  366. if last_block_height - existing_tips[0].header.height >= limit {
  367. drop(forks);
  368. return Ok(proposals)
  369. }
  370. // Retrieve all proposals after requested one
  371. let headers = self.blockchain.blocks.get_all_after(existing_tips[0].header.height)?;
  372. let blocks = self.blockchain.get_blocks_by_hash(&headers)?;
  373. for block in blocks {
  374. proposals.push(Proposal::new(block));
  375. }
  376. let blocks =
  377. forks[index].overlay.lock().unwrap().get_blocks_by_hash(&forks[index].proposals)?;
  378. for block in blocks {
  379. proposals.push(Proposal::new(block));
  380. }
  381. // Drop forks lock
  382. drop(forks);
  383. Ok(proposals)
  384. }
  385. /// Auxiliary function to retrieve current best fork last header.
  386. /// If no forks exist, grab the last header from canonical.
  387. pub async fn best_fork_last_header(&self) -> Result<(u32, HeaderHash)> {
  388. // Grab a lock over current forks
  389. let forks = self.forks.read().await;
  390. // Check if node has any forks
  391. if forks.is_empty() {
  392. drop(forks);
  393. return self.blockchain.last()
  394. }
  395. // Grab best fork
  396. let fork = &forks[best_fork_index(&forks)?];
  397. // Grab its last header
  398. let last = fork.last_proposal()?;
  399. drop(forks);
  400. Ok((last.block.header.height, last.hash))
  401. }
  402. /// Auxiliary function to purge current forks and reset the ones starting
  403. /// with the provided prefix, excluding provided confirmed fork.
  404. /// Additionally, remove confirmed transactions from the forks mempools,
  405. /// along with the unporposed transactions sled trees.
  406. /// This function assumes that the prefix blocks have already been appended
  407. /// to canonical chain from the confirmed fork.
  408. pub async fn reset_forks(
  409. &self,
  410. prefix: &[HeaderHash],
  411. confirmed_fork_index: &usize,
  412. confirmed_txs: &[Transaction],
  413. ) -> Result<()> {
  414. // Grab a lock over current forks
  415. let mut forks = self.forks.write().await;
  416. // Find all the forks that start with the provided prefix,
  417. // excluding confirmed fork index, and remove their prefixed
  418. // proposals, and their corresponding diffs.
  419. // If the fork is not starting with the provided prefix,
  420. // drop it. Additionally, keep track of all the referenced
  421. // trees in overlays that are valid.
  422. let excess = prefix.len();
  423. let prefix_last_index = excess - 1;
  424. let prefix_last = prefix.last().unwrap();
  425. let mut keep = vec![true; forks.len()];
  426. let mut referenced_trees = HashSet::new();
  427. let mut referenced_txs = HashSet::new();
  428. let confirmed_txs_hashes: Vec<TransactionHash> =
  429. confirmed_txs.iter().map(|tx| tx.hash()).collect();
  430. for (index, fork) in forks.iter_mut().enumerate() {
  431. if &index == confirmed_fork_index {
  432. // Store its tree references
  433. let fork_overlay = fork.overlay.lock().unwrap();
  434. let overlay = fork_overlay.overlay.lock().unwrap();
  435. for tree in &overlay.state.initial_tree_names {
  436. referenced_trees.insert(tree.clone());
  437. }
  438. for tree in &overlay.state.new_tree_names {
  439. referenced_trees.insert(tree.clone());
  440. }
  441. for tree in overlay.state.dropped_trees.keys() {
  442. referenced_trees.insert(tree.clone());
  443. }
  444. // Remove confirmed proposals txs from fork's mempool
  445. fork.mempool.retain(|tx| !confirmed_txs_hashes.contains(tx));
  446. // Store its txs references
  447. for tx in &fork.mempool {
  448. referenced_txs.insert(*tx);
  449. }
  450. drop(overlay);
  451. drop(fork_overlay);
  452. continue
  453. }
  454. if fork.proposals.is_empty() ||
  455. prefix_last_index >= fork.proposals.len() ||
  456. &fork.proposals[prefix_last_index] != prefix_last
  457. {
  458. keep[index] = false;
  459. continue
  460. }
  461. // Remove confirmed proposals txs from fork's mempool
  462. fork.mempool.retain(|tx| !confirmed_txs_hashes.contains(tx));
  463. // Store its txs references
  464. for tx in &fork.mempool {
  465. referenced_txs.insert(*tx);
  466. }
  467. // Remove the commited differences
  468. let rest_proposals = fork.proposals.split_off(excess);
  469. let rest_diffs = fork.diffs.split_off(excess);
  470. let mut diffs = fork.diffs.clone();
  471. fork.proposals = rest_proposals;
  472. fork.diffs = rest_diffs;
  473. for diff in diffs.iter_mut() {
  474. fork.overlay.lock().unwrap().overlay.lock().unwrap().remove_diff(diff);
  475. }
  476. // Store its tree references
  477. let fork_overlay = fork.overlay.lock().unwrap();
  478. let overlay = fork_overlay.overlay.lock().unwrap();
  479. for tree in &overlay.state.initial_tree_names {
  480. referenced_trees.insert(tree.clone());
  481. }
  482. for tree in &overlay.state.new_tree_names {
  483. referenced_trees.insert(tree.clone());
  484. }
  485. for tree in overlay.state.dropped_trees.keys() {
  486. referenced_trees.insert(tree.clone());
  487. }
  488. drop(overlay);
  489. drop(fork_overlay);
  490. }
  491. // Find the trees and pending txs that are no longer referenced by valid forks
  492. let mut dropped_trees = HashSet::new();
  493. let mut dropped_txs = HashSet::new();
  494. for (index, fork) in forks.iter_mut().enumerate() {
  495. if keep[index] {
  496. continue
  497. }
  498. for tx in &fork.mempool {
  499. if !referenced_txs.contains(tx) {
  500. dropped_txs.insert(*tx);
  501. }
  502. }
  503. let fork_overlay = fork.overlay.lock().unwrap();
  504. let overlay = fork_overlay.overlay.lock().unwrap();
  505. for tree in &overlay.state.initial_tree_names {
  506. if !referenced_trees.contains(tree) {
  507. dropped_trees.insert(tree.clone());
  508. }
  509. }
  510. for tree in &overlay.state.new_tree_names {
  511. if !referenced_trees.contains(tree) {
  512. dropped_trees.insert(tree.clone());
  513. }
  514. }
  515. for tree in overlay.state.dropped_trees.keys() {
  516. if !referenced_trees.contains(tree) {
  517. dropped_trees.insert(tree.clone());
  518. }
  519. }
  520. drop(overlay);
  521. drop(fork_overlay);
  522. }
  523. // Drop unreferenced trees from the database
  524. for tree in dropped_trees {
  525. self.blockchain.sled_db.drop_tree(tree)?;
  526. }
  527. // Drop invalid forks
  528. let mut iter = keep.iter();
  529. forks.retain(|_| *iter.next().unwrap());
  530. // Remove confirmed proposals txs from the unporposed txs sled tree
  531. self.blockchain.remove_pending_txs_hashes(&confirmed_txs_hashes)?;
  532. // Remove unreferenced txs from the unporposed txs sled tree
  533. self.blockchain.remove_pending_txs_hashes(&Vec::from_iter(dropped_txs))?;
  534. // Drop forks lock
  535. drop(forks);
  536. Ok(())
  537. }
  538. /// Auxiliary function to fully purge current forks and leave only a new empty fork.
  539. pub async fn purge_forks(&self) -> Result<()> {
  540. debug!(target: "validator::consensus::purge_forks", "Purging current forks...");
  541. let mut forks = self.forks.write().await;
  542. *forks = vec![Fork::new(self.blockchain.clone(), self.module.read().await.clone()).await?];
  543. drop(forks);
  544. debug!(target: "validator::consensus::purge_forks", "Forks purged!");
  545. Ok(())
  546. }
  547. /// Auxiliary function to reset PoW module.
  548. pub async fn reset_pow_module(&self) -> Result<()> {
  549. debug!(target: "validator::consensus::reset_pow_module", "Resetting PoW module...");
  550. let mut module = self.module.write().await;
  551. *module = PoWModule::new(
  552. self.blockchain.clone(),
  553. module.target,
  554. module.fixed_difficulty.clone(),
  555. None,
  556. )?;
  557. drop(module);
  558. debug!(target: "validator::consensus::reset_pow_module", "PoW module reset successfully!");
  559. Ok(())
  560. }
  561. /// Auxiliary function to check current contracts states checksums
  562. /// Monotree(SMT) validity in all active forks and canonical.
  563. pub async fn healthcheck(&self) -> Result<()> {
  564. // Grab a lock over current forks
  565. let lock = self.forks.read().await;
  566. // Rebuild current canonical contract states checksums monotree
  567. let state_monotree = self.blockchain.get_state_monotree()?;
  568. // Check that the root matches last block header state root
  569. let Some(state_root) = state_monotree.get_headroot()? else {
  570. return Err(Error::ContractsStatesRootNotFoundError);
  571. };
  572. let last_block_state_root = self.blockchain.last_header()?.state_root;
  573. if state_root != last_block_state_root {
  574. return Err(Error::ContractsStatesRootError(
  575. blake3::Hash::from_bytes(state_root).to_string(),
  576. blake3::Hash::from_bytes(last_block_state_root).to_string(),
  577. ));
  578. }
  579. // Check each fork health
  580. for fork in lock.iter() {
  581. fork.healthcheck()?;
  582. }
  583. Ok(())
  584. }
  585. }
  586. /// This struct represents a block proposal, used for consensus.
  587. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  588. pub struct Proposal {
  589. /// Block hash
  590. pub hash: HeaderHash,
  591. /// Block data
  592. pub block: BlockInfo,
  593. }
  594. impl Proposal {
  595. pub fn new(block: BlockInfo) -> Self {
  596. let hash = block.hash();
  597. Self { hash, block }
  598. }
  599. }
  600. impl From<Proposal> for BlockInfo {
  601. fn from(proposal: Proposal) -> BlockInfo {
  602. proposal.block
  603. }
  604. }
  605. /// Struct representing a forked blockchain state.
  606. ///
  607. /// An overlay over the original blockchain is used, containing all pending to-write
  608. /// records. Additionally, each fork keeps a vector of valid pending transactions hashes,
  609. /// in order of receival, and the proposals hashes sequence, for validations.
  610. #[derive(Clone)]
  611. pub struct Fork {
  612. /// Canonical (confirmed) blockchain
  613. pub blockchain: Blockchain,
  614. /// Overlay cache over canonical Blockchain
  615. pub overlay: BlockchainOverlayPtr,
  616. /// Current PoW module state
  617. pub module: PoWModule,
  618. /// Current contracts states checksums Monotree(SMT)
  619. pub state_monotree: Monotree,
  620. /// Fork proposal hashes sequence
  621. pub proposals: Vec<HeaderHash>,
  622. /// Fork proposal overlay diffs sequence
  623. pub diffs: Vec<SledDbOverlayStateDiff>,
  624. /// Valid pending transaction hashes
  625. pub mempool: Vec<TransactionHash>,
  626. /// Current fork mining targets rank, cached for better performance
  627. pub targets_rank: BigUint,
  628. /// Current fork hashes rank, cached for better performance
  629. pub hashes_rank: BigUint,
  630. }
  631. impl Fork {
  632. pub async fn new(blockchain: Blockchain, module: PoWModule) -> Result<Self> {
  633. let mempool = blockchain.get_pending_txs()?.iter().map(|tx| tx.hash()).collect();
  634. let overlay = BlockchainOverlay::new(&blockchain)?;
  635. // Build current contract states checksums monotree
  636. let state_monotree = overlay.lock().unwrap().get_state_monotree()?;
  637. // Retrieve last block difficulty to access current ranks
  638. let last_difficulty = blockchain.last_block_difficulty()?;
  639. let targets_rank = last_difficulty.ranks.targets_rank;
  640. let hashes_rank = last_difficulty.ranks.hashes_rank;
  641. Ok(Self {
  642. blockchain,
  643. overlay,
  644. module,
  645. state_monotree,
  646. proposals: vec![],
  647. diffs: vec![],
  648. mempool,
  649. targets_rank,
  650. hashes_rank,
  651. })
  652. }
  653. /// Auxiliary function to append a proposal and update current fork rank.
  654. pub async fn append_proposal(&mut self, proposal: &Proposal) -> Result<()> {
  655. // Grab next mine target and difficulty
  656. let (next_target, next_difficulty) = self.module.next_mine_target_and_difficulty()?;
  657. // Calculate block rank
  658. let (target_distance_sq, hash_distance_sq) = block_rank(&proposal.block, &next_target);
  659. // Update fork ranks
  660. self.targets_rank += target_distance_sq.clone();
  661. self.hashes_rank += hash_distance_sq.clone();
  662. // Generate block difficulty and update PoW module
  663. let cumulative_difficulty =
  664. self.module.cumulative_difficulty.clone() + next_difficulty.clone();
  665. let ranks = BlockRanks::new(
  666. target_distance_sq,
  667. self.targets_rank.clone(),
  668. hash_distance_sq,
  669. self.hashes_rank.clone(),
  670. );
  671. let block_difficulty = BlockDifficulty::new(
  672. proposal.block.header.height,
  673. proposal.block.header.timestamp,
  674. next_difficulty,
  675. cumulative_difficulty,
  676. ranks,
  677. );
  678. self.module.append_difficulty(&self.overlay, block_difficulty)?;
  679. // Push proposal's hash
  680. self.proposals.push(proposal.hash);
  681. // Push proposal overlay diff
  682. self.diffs.push(self.overlay.lock().unwrap().overlay.lock().unwrap().diff(&self.diffs)?);
  683. Ok(())
  684. }
  685. /// Auxiliary function to retrieve last proposal.
  686. pub fn last_proposal(&self) -> Result<Proposal> {
  687. let block = if let Some(last) = self.proposals.last() {
  688. self.overlay.lock().unwrap().get_blocks_by_hash(&[*last])?[0].clone()
  689. } else {
  690. self.overlay.lock().unwrap().last_block()?
  691. };
  692. Ok(Proposal::new(block))
  693. }
  694. /// Auxiliary function to compute forks' next block height.
  695. pub fn get_next_block_height(&self) -> Result<u32> {
  696. let proposal = self.last_proposal()?;
  697. Ok(proposal.block.header.height + 1)
  698. }
  699. /// Auxiliary function to retrieve unproposed valid transactions,
  700. /// along with their total gas used, total paid fees and the overlay
  701. /// used to verify the transactions for further processing.
  702. ///
  703. /// Note: Always remember to purge new trees from the overlay if not needed.
  704. pub async fn unproposed_txs(
  705. &self,
  706. blockchain: &Blockchain,
  707. verifying_block_height: u32,
  708. block_target: u32,
  709. verify_fees: bool,
  710. ) -> Result<(Vec<Transaction>, u64, u64, BlockchainOverlayPtr)> {
  711. // Clone forks' overlay
  712. let overlay = self.overlay.lock().unwrap().full_clone()?;
  713. // Check if our mempool is not empty
  714. if self.mempool.is_empty() {
  715. return Ok((vec![], 0, 0, overlay))
  716. }
  717. // Transactions Merkle tree
  718. let mut tree = MerkleTree::new(1);
  719. // Total gas accumulators
  720. let mut total_gas_used = 0;
  721. let mut total_gas_paid = 0;
  722. // Map of ZK proof verifying keys for the current transaction batch
  723. let mut vks: HashMap<[u8; 32], HashMap<String, VerifyingKey>> = HashMap::new();
  724. // Grab all current proposals transactions hashes
  725. let proposals_txs = overlay.lock().unwrap().get_blocks_txs_hashes(&self.proposals)?;
  726. // Iterate through all pending transactions in the forks' mempool
  727. let mut unproposed_txs = vec![];
  728. for tx in &self.mempool {
  729. // If the hash is contained in the proposals transactions vec, skip it
  730. if proposals_txs.contains(tx) {
  731. continue
  732. }
  733. // Retrieve the actual unproposed transaction
  734. let unproposed_tx =
  735. blockchain.transactions.get_pending(&[*tx], true)?[0].clone().unwrap();
  736. // Update the verifying keys map
  737. for call in &unproposed_tx.calls {
  738. vks.entry(call.data.contract_id.to_bytes()).or_default();
  739. }
  740. // Verify the transaction against current state
  741. overlay.lock().unwrap().checkpoint();
  742. let gas_data = match verify_transaction(
  743. &overlay,
  744. verifying_block_height,
  745. block_target,
  746. &unproposed_tx,
  747. &mut tree,
  748. &mut vks,
  749. verify_fees,
  750. )
  751. .await
  752. {
  753. Ok(gas_values) => gas_values,
  754. Err(e) => {
  755. debug!(target: "validator::consensus::unproposed_txs", "Transaction verification failed: {e}");
  756. overlay.lock().unwrap().revert_to_checkpoint()?;
  757. continue
  758. }
  759. };
  760. // Store the gas used by the verified transaction
  761. let tx_gas_used = gas_data.total_gas_used();
  762. // Calculate current accumulated gas usage
  763. let accumulated_gas_usage = total_gas_used + tx_gas_used;
  764. // Check gas limit - if accumulated gas used exceeds it, break out of loop
  765. if accumulated_gas_usage > BLOCK_GAS_LIMIT {
  766. warn!(
  767. target: "validator::consensus::unproposed_txs",
  768. "Retrieving transaction {tx} would exceed configured unproposed transaction gas limit: {accumulated_gas_usage} - {BLOCK_GAS_LIMIT}"
  769. );
  770. overlay.lock().unwrap().revert_to_checkpoint()?;
  771. break
  772. }
  773. // Update accumulated total gas
  774. total_gas_used += tx_gas_used;
  775. total_gas_paid += gas_data.paid;
  776. // Push the tx hash into the unproposed transactions vector
  777. unproposed_txs.push(unproposed_tx);
  778. }
  779. Ok((unproposed_txs, total_gas_used, total_gas_paid, overlay))
  780. }
  781. /// Auxiliary function to create a full clone using BlockchainOverlay::full_clone.
  782. /// Changes to this copy don't affect original fork overlay records, since underlying
  783. /// overlay pointer have been updated to the cloned one.
  784. pub fn full_clone(&self) -> Result<Self> {
  785. let blockchain = self.blockchain.clone();
  786. let overlay = self.overlay.lock().unwrap().full_clone()?;
  787. let module = self.module.clone();
  788. let state_monotree = self.state_monotree.clone();
  789. let proposals = self.proposals.clone();
  790. let diffs = self.diffs.clone();
  791. let mempool = self.mempool.clone();
  792. let targets_rank = self.targets_rank.clone();
  793. let hashes_rank = self.hashes_rank.clone();
  794. Ok(Self {
  795. blockchain,
  796. overlay,
  797. module,
  798. state_monotree,
  799. proposals,
  800. diffs,
  801. mempool,
  802. targets_rank,
  803. hashes_rank,
  804. })
  805. }
  806. /// Build current contract states checksums monotree.
  807. pub fn compute_monotree(&mut self) -> Result<()> {
  808. self.state_monotree = self.overlay.lock().unwrap().get_state_monotree()?;
  809. Ok(())
  810. }
  811. /// Auxiliary function to check current contracts states checksums
  812. /// Monotree(SMT) validity.
  813. ///
  814. /// Note: This should be executed on fresh forks and/or when
  815. /// a fork doesn't contain changes over the last appended
  816. // proposal.
  817. pub fn healthcheck(&self) -> Result<()> {
  818. // Rebuild current contract states checksums monotree
  819. let state_monotree = self.overlay.lock().unwrap().get_state_monotree()?;
  820. // Check that it matches forks' tree
  821. let Some(state_root) = state_monotree.get_headroot()? else {
  822. return Err(Error::ContractsStatesRootNotFoundError);
  823. };
  824. let Some(fork_state_root) = self.state_monotree.get_headroot()? else {
  825. return Err(Error::ContractsStatesRootNotFoundError);
  826. };
  827. if state_root != fork_state_root {
  828. return Err(Error::ContractsStatesRootError(
  829. blake3::Hash::from_bytes(state_root).to_string(),
  830. blake3::Hash::from_bytes(fork_state_root).to_string(),
  831. ));
  832. }
  833. // Check that the root matches last block header state root
  834. let last_block_state_root = self.last_proposal()?.block.header.state_root;
  835. if state_root != last_block_state_root {
  836. return Err(Error::ContractsStatesRootError(
  837. blake3::Hash::from_bytes(state_root).to_string(),
  838. blake3::Hash::from_bytes(last_block_state_root).to_string(),
  839. ));
  840. }
  841. Ok(())
  842. }
  843. }