blocks.rs 17 KB

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