blocks.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 log::{debug, warn};
  19. use sled_overlay::sled::{transaction::ConflictableTransactionError, Transactional};
  20. use tinyjson::JsonValue;
  21. use darkfi::{
  22. blockchain::{
  23. BlockInfo, BlockchainOverlay, HeaderHash, SLED_BLOCK_DIFFICULTY_TREE,
  24. SLED_BLOCK_ORDER_TREE, SLED_BLOCK_TREE,
  25. },
  26. util::time::Timestamp,
  27. Error, Result,
  28. };
  29. use darkfi_sdk::{crypto::schnorr::Signature, tx::TransactionHash};
  30. use crate::{error::ExplorerdError, ExplorerService};
  31. #[derive(Debug, Clone)]
  32. /// Structure representing a block record.
  33. pub struct BlockRecord {
  34. /// Header hash identifier of the block
  35. pub header_hash: String,
  36. /// Block version
  37. pub version: u8,
  38. /// Previous block hash
  39. pub previous: String,
  40. /// Block height
  41. pub height: u32,
  42. /// Block creation timestamp
  43. pub timestamp: Timestamp,
  44. /// The block's nonce. This value changes arbitrarily with mining.
  45. pub nonce: u64,
  46. /// Merkle tree root of the transactions hashes contained in this block
  47. pub transactions_root: String,
  48. /// Contracts states Monotree(SMT) root this block commits to
  49. pub state_root: String,
  50. /// Block producer signature
  51. pub signature: Signature,
  52. }
  53. impl BlockRecord {
  54. /// Auxiliary function to convert a `BlockRecord` into a `JsonValue` array.
  55. pub fn to_json_array(&self) -> JsonValue {
  56. JsonValue::Array(vec![
  57. JsonValue::String(self.header_hash.clone()),
  58. JsonValue::Number(self.version as f64),
  59. JsonValue::String(self.previous.clone()),
  60. JsonValue::Number(self.height as f64),
  61. JsonValue::String(self.timestamp.to_string()),
  62. JsonValue::Number(self.nonce as f64),
  63. JsonValue::String(self.transactions_root.clone()),
  64. JsonValue::String(self.state_root.clone()),
  65. JsonValue::String(format!("{:?}", self.signature)),
  66. ])
  67. }
  68. }
  69. impl From<&BlockInfo> for BlockRecord {
  70. fn from(block: &BlockInfo) -> Self {
  71. Self {
  72. header_hash: block.hash().to_string(),
  73. version: block.header.version,
  74. previous: block.header.previous.to_string(),
  75. height: block.header.height,
  76. timestamp: block.header.timestamp,
  77. nonce: block.header.nonce,
  78. transactions_root: block.header.transactions_root.to_string(),
  79. state_root: blake3::hash(&block.header.state_root).to_string(),
  80. signature: block.signature,
  81. }
  82. }
  83. }
  84. impl ExplorerService {
  85. /// Resets blocks in the database by clearing all block related trees, returning an Ok result on success.
  86. pub fn reset_blocks(&self) -> Result<()> {
  87. let db = &self.db.blockchain.sled_db;
  88. // Initialize block related trees to reset
  89. let trees_to_reset = [SLED_BLOCK_TREE, SLED_BLOCK_ORDER_TREE, SLED_BLOCK_DIFFICULTY_TREE];
  90. // Iterate over each tree and remove its entries
  91. for tree_name in &trees_to_reset {
  92. let tree = db.open_tree(tree_name)?;
  93. tree.clear()?;
  94. let tree_name_str = std::str::from_utf8(tree_name)?;
  95. debug!(target: "explorerd::blocks", "Successfully reset block tree: {tree_name_str}");
  96. }
  97. Ok(())
  98. }
  99. /// Adds the provided [`BlockInfo`] to the block explorer database.
  100. ///
  101. /// This function processes each transaction in the block, calculating and updating the
  102. /// latest [`GasMetrics`] for non-genesis blocks and for transactions that are not
  103. /// PoW rewards. After processing all transactions, the block is permanently persisted to
  104. /// the explorer database.
  105. pub async fn put_block(&self, block: &BlockInfo) -> Result<()> {
  106. let blockchain_overlay = BlockchainOverlay::new(&self.db.blockchain)?;
  107. // Initialize collections to hold gas data and transactions that have gas data
  108. let mut tx_gas_data = Vec::with_capacity(block.txs.len());
  109. let mut txs_hashes_with_gas_data = Vec::with_capacity(block.txs.len());
  110. // Calculate gas data for non-PoW reward transactions and non-genesis blocks
  111. for (i, tx) in block.txs.iter().enumerate() {
  112. if !tx.is_pow_reward() && block.header.height != 0 {
  113. tx_gas_data.insert(i, self.calculate_tx_gas_data(tx, false).await?);
  114. txs_hashes_with_gas_data.insert(i, tx.hash());
  115. }
  116. }
  117. // If the block contains transaction gas data, insert the gas metrics into the metrics store
  118. if !tx_gas_data.is_empty() {
  119. self.db.metrics_store.insert_gas_metrics(
  120. block.header.height,
  121. &block.header.timestamp,
  122. &txs_hashes_with_gas_data,
  123. &tx_gas_data,
  124. )?;
  125. }
  126. // Add the block and commit the changes to persist it
  127. let _ = blockchain_overlay.lock().unwrap().add_block(block)?;
  128. blockchain_overlay.lock().unwrap().overlay.lock().unwrap().apply()?;
  129. debug!(target: "explorerd::blocks::put_block", "Added block {:?}", block);
  130. Ok(())
  131. }
  132. /// Provides the total block count.
  133. pub fn get_block_count(&self) -> usize {
  134. self.db.blockchain.len()
  135. }
  136. /// Fetch all known blocks from the database.
  137. pub fn get_blocks(&self) -> Result<Vec<BlockRecord>> {
  138. // Fetch blocks and handle any errors encountered
  139. let blocks = &self.db.blockchain.get_all().map_err(|e| {
  140. Error::DatabaseError(format!("[get_blocks] Block retrieval failed: {e:?}"))
  141. })?;
  142. // Transform the found blocks into a vector of block records
  143. let block_records: Vec<BlockRecord> = blocks.iter().map(BlockRecord::from).collect();
  144. Ok(block_records)
  145. }
  146. /// Fetch a block given its header hash from the database.
  147. pub fn get_block_by_hash(&self, header_hash: &str) -> Result<Option<BlockRecord>> {
  148. // Parse header hash, returning an error if parsing fails
  149. let header_hash = header_hash
  150. .parse::<HeaderHash>()
  151. .map_err(|_| ExplorerdError::InvalidHeaderHash(header_hash.to_string()))?;
  152. // Fetch block by hash and handle encountered errors
  153. match self.db.blockchain.get_blocks_by_hash(&[header_hash]) {
  154. Ok(blocks) => Ok(blocks.first().map(BlockRecord::from)),
  155. Err(Error::BlockNotFound(_)) => Ok(None),
  156. Err(e) => Err(Error::DatabaseError(format!(
  157. "[get_block_by_hash] Block retrieval failed: {e:?}"
  158. ))),
  159. }
  160. }
  161. /// Fetch a block given its height from the database.
  162. pub fn get_block_by_height(&self, height: u32) -> Result<Option<BlockRecord>> {
  163. // Fetch block by height and handle encountered errors
  164. match self.db.blockchain.get_blocks_by_heights(&[height]) {
  165. Ok(blocks) => Ok(blocks.first().map(BlockRecord::from)),
  166. Err(Error::BlockNotFound(_)) => Ok(None),
  167. Err(e) => Err(Error::DatabaseError(format!(
  168. "[get_block_by_height] Block retrieval failed: {e:?}"
  169. ))),
  170. }
  171. }
  172. /// Fetch the last block from the database.
  173. pub fn last_block(&self) -> Result<Option<(u32, String)>> {
  174. let block_store = &self.db.blockchain.blocks;
  175. // Return None result when no blocks exist
  176. if block_store.is_empty() {
  177. return Ok(None);
  178. }
  179. // Blocks exist, retrieve last block
  180. let (height, header_hash) = block_store.get_last().map_err(|e| {
  181. Error::DatabaseError(format!("[last_block] Block retrieval failed: {e:?}"))
  182. })?;
  183. // Convert header hash to a string and return result
  184. Ok(Some((height, header_hash.to_string())))
  185. }
  186. /// Fetch the last N blocks from the database.
  187. pub fn get_last_n(&self, n: usize) -> Result<Vec<BlockRecord>> {
  188. // Fetch the last n blocks and handle any errors encountered
  189. let blocks_result = &self.db.blockchain.get_last_n(n).map_err(|e| {
  190. Error::DatabaseError(format!("[get_last_n] Block retrieval failed: {e:?}"))
  191. })?;
  192. // Transform the found blocks into a vector of block records
  193. let block_records: Vec<BlockRecord> = blocks_result.iter().map(BlockRecord::from).collect();
  194. Ok(block_records)
  195. }
  196. /// Fetch blocks within a specified range from the database.
  197. pub fn get_by_range(&self, start: u32, end: u32) -> Result<Vec<BlockRecord>> {
  198. // Fetch blocks in the specified range and handle any errors encountered
  199. let blocks_result = &self.db.blockchain.get_by_range(start, end).map_err(|e| {
  200. Error::DatabaseError(format!("[get_by_range]: Block retrieval failed: {e:?}"))
  201. })?;
  202. // Transform the found blocks into a vector of block records
  203. let block_records: Vec<BlockRecord> = blocks_result.iter().map(BlockRecord::from).collect();
  204. Ok(block_records)
  205. }
  206. /// Resets the [`ExplorerDb::blockchain::blocks`] and [`ExplorerDb::blockchain::transactions`]
  207. /// trees to a specified height by removing entries above the `reset_height`, returning a result
  208. /// that indicates success or failure.
  209. ///
  210. /// The function retrieves the last explorer block and iteratively rolls back entries
  211. /// in the [`BlockStore::main`], [`BlockStore::order`], and [`BlockStore::difficulty`] trees
  212. /// to the specified `reset_height`. It also resets the [`TxStore::main`] and
  213. /// [`TxStore::location`] trees to reflect the transaction state at the given height.
  214. ///
  215. /// This operation is performed atomically using a sled transaction applied across the affected sled
  216. /// trees, ensuring consistency and avoiding partial updates.
  217. pub fn reset_to_height(&self, reset_height: u32) -> Result<()> {
  218. let block_store = &self.db.blockchain.blocks;
  219. let tx_store = &self.db.blockchain.transactions;
  220. debug!(target: "explorerd::blocks::reset_to_height", "Resetting to height {reset_height}: block_count={}, txs_count={}", block_store.len(), tx_store.len());
  221. // Get the last block height
  222. let (last_block_height, _) = block_store.get_last().map_err(|e| {
  223. Error::DatabaseError(format!(
  224. "[reset_to_height]: Failed to get the last block height: {e:?}"
  225. ))
  226. })?;
  227. // Skip resetting blocks if `reset_height` is greater than or equal to `last_block_height`
  228. if reset_height >= last_block_height {
  229. warn!(target: "explorerd::blocks::reset_to_height",
  230. "Nothing to reset because reset_height is greater than or equal to last_block_height: {reset_height} >= {last_block_height}");
  231. return Ok(());
  232. }
  233. // Get the associated block infos in order to obtain transactions to reset
  234. let block_infos_to_reset =
  235. &self.db.blockchain.get_by_range(reset_height, last_block_height).map_err(|e| {
  236. Error::DatabaseError(format!(
  237. "[reset_to_height]: Failed to get the transaction hashes to reset: {e:?}"
  238. ))
  239. })?;
  240. // Collect the transaction hashes from the blocks that need resetting
  241. let txs_hashes_to_reset: Vec<TransactionHash> = block_infos_to_reset
  242. .iter()
  243. .flat_map(|block_info| block_info.txs.iter().map(|tx| tx.hash()))
  244. .collect();
  245. // Perform the reset operation atomically using a sled transaction
  246. let tx_result = (&block_store.main, &block_store.order, &block_store.difficulty, &tx_store.main, &tx_store.location)
  247. .transaction(|(block_main, block_order, block_difficulty, tx_main, tx_location)| {
  248. // Traverse the block heights in reverse, removing each block up to (but not including) reset_height
  249. for height in (reset_height + 1..=last_block_height).rev() {
  250. let height_key = height.to_be_bytes();
  251. // Fetch block from `order` tree to obtain the block hash needed to remove blocks from `main` tree
  252. let order_header_hash = block_order.get(height_key).map_err(ConflictableTransactionError::Abort)?;
  253. if let Some(header_hash) = order_header_hash {
  254. // Remove block from the `main` tree
  255. block_main.remove(&header_hash).map_err(ConflictableTransactionError::Abort)?;
  256. // Remove block from the `difficulty` tree
  257. block_difficulty.remove(&height_key).map_err(ConflictableTransactionError::Abort)?;
  258. // Remove block from the `order` tree
  259. block_order.remove(&height_key).map_err(ConflictableTransactionError::Abort)?;
  260. }
  261. debug!(target: "explorerd::blocks::reset_to_height", "Removed block at height: {height}");
  262. }
  263. // Iterate through the transaction hashes, removing the related transactions
  264. for (tx_count, tx_hash) in txs_hashes_to_reset.iter().enumerate() {
  265. // Remove transaction from the `main` tree
  266. tx_main.remove(tx_hash.inner()).map_err(ConflictableTransactionError::Abort)?;
  267. // Remove transaction from the `location` tree
  268. tx_location.remove(tx_hash.inner()).map_err(ConflictableTransactionError::Abort)?;
  269. debug!(target: "explorerd::blocks::reset_to_height", "Removed transaction ({tx_count}): {tx_hash}");
  270. }
  271. Ok(())
  272. })
  273. .map_err(|e| {
  274. Error::DatabaseError(format!("[reset_to_height]: Resetting height failed: {e:?}"))
  275. });
  276. debug!(target: "explorerd::blocks::reset_to_height", "Successfully reset to height {reset_height}: block_count={}, txs_count={}", block_store.len(), tx_store.len());
  277. tx_result
  278. }
  279. }