blocks.rs 14 KB

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