rpc_blocks.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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::sync::Arc;
  19. use log::{debug, error, info, warn};
  20. use tinyjson::JsonValue;
  21. use url::Url;
  22. use darkfi::{
  23. blockchain::BlockInfo,
  24. rpc::{
  25. client::RpcClient,
  26. jsonrpc::{
  27. ErrorCode::{InternalError, InvalidParams, ParseError},
  28. JsonError, JsonRequest, JsonResponse, JsonResult,
  29. },
  30. },
  31. system::{Publisher, StoppableTask, StoppableTaskPtr},
  32. util::encoding::base64,
  33. Error, Result,
  34. };
  35. use darkfi_serial::deserialize_async;
  36. use crate::{error::handle_database_error, Explorerd};
  37. impl Explorerd {
  38. // Queries darkfid for a block with given height.
  39. async fn get_darkfid_block_by_height(&self, height: u32) -> Result<BlockInfo> {
  40. let params = self
  41. .darkfid_daemon_request(
  42. "blockchain.get_block",
  43. &JsonValue::Array(vec![JsonValue::String(height.to_string())]),
  44. )
  45. .await?;
  46. let param = params.get::<String>().unwrap();
  47. let bytes = base64::decode(param).unwrap();
  48. let block = deserialize_async(&bytes).await?;
  49. Ok(block)
  50. }
  51. /// Synchronizes blocks between the explorer and a Darkfi blockchain node, ensuring
  52. /// the database remains consistent by syncing any missing or outdated blocks.
  53. ///
  54. /// If provided `reset` is true, the explorer's blockchain-related and metric sled trees are purged
  55. /// and syncing starts from the genesis block. The function also handles reorgs by re-aligning the
  56. /// explorer state to the correct height when blocks are outdated. Returns a result indicating
  57. /// success or failure.
  58. ///
  59. /// Reorg handling is delegated to the [`Self::process_sync_blocks_reorg`] function, whose
  60. /// documentation provides more details on the reorg process during block syncing.
  61. pub async fn sync_blocks(&self, reset: bool) -> Result<()> {
  62. // Grab last synced block height from the explorer's database.
  63. let last_synced_block = self.service.last_block().map_err(|e| {
  64. handle_database_error(
  65. "rpc_blocks::sync_blocks",
  66. "[sync_blocks] Retrieving last synced block failed",
  67. e,
  68. )
  69. })?;
  70. // Grab the last confirmed block height and hash from the darkfi node
  71. let (last_darkfid_height, last_darkfid_hash) = self.get_last_confirmed_block().await?;
  72. // Initialize the current height to sync from, starting from genesis block if last sync block does not exist
  73. let (last_synced_height, last_synced_hash) = last_synced_block
  74. .map_or((0, "".to_string()), |(height, header_hash)| (height, header_hash));
  75. // Declare a mutable variable to track the current sync height while processing blocks
  76. let mut current_height = last_synced_height;
  77. info!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "Requested to sync from block number: {current_height}");
  78. info!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "Last confirmed block number reported by darkfid: {last_darkfid_height} - {last_darkfid_hash}");
  79. // A reorg is detected if the hash of the last synced block differs from the hash of the last confirmed block,
  80. // unless the reset flag is set or the current height is 0
  81. let reorg_detected = last_synced_hash != last_darkfid_hash && !reset && current_height != 0;
  82. // If the reset flag is set, reset the explorer state and start syncing from the genesis block height.
  83. // Otherwise, handle reorgs if detected, or proceed to the next block if not at the genesis height.
  84. if reset {
  85. self.service.reset_explorer_state(0)?;
  86. current_height = 0;
  87. info!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "Successfully reset explorer database based on set reset parameter");
  88. } else if reorg_detected {
  89. current_height =
  90. self.process_sync_blocks_reorg(last_synced_height, last_darkfid_height).await?;
  91. // Log only if a reorg occurred
  92. if current_height != last_synced_height {
  93. info!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "Successfully completed reorg to height: {current_height}");
  94. }
  95. // Prepare to sync the next block after reorg
  96. current_height += 1;
  97. } else if current_height != 0 {
  98. // Resume syncing from the block after the last synced height
  99. current_height += 1;
  100. }
  101. // Sync blocks until the explorer is up to date with the last confirmed block
  102. while current_height <= last_darkfid_height {
  103. // Retrieve the block from darkfi node by height
  104. let block = match self.get_darkfid_block_by_height(current_height).await {
  105. Ok(r) => r,
  106. Err(e) => {
  107. return Err(handle_database_error(
  108. "rpc_blocks::sync_blocks",
  109. "[sync_blocks] RPC client request failed",
  110. e,
  111. ))
  112. }
  113. };
  114. // Store the retrieved block in the explorer's database
  115. if let Err(e) = self.service.put_block(&block).await {
  116. return Err(handle_database_error(
  117. "rpc_blocks::sync_blocks",
  118. "[sync_blocks] Put block failed",
  119. e,
  120. ))
  121. };
  122. info!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "Synced block {current_height}");
  123. // Increment the current height to sync the next block
  124. current_height += 1;
  125. }
  126. info!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "Completed sync, total number of explorer blocks: {}", self.service.db.blockchain.blocks.len());
  127. Ok(())
  128. }
  129. /// Handles blockchain reorganizations (reorgs) during the explorer node's startup synchronization
  130. /// with Darkfi nodes, ensuring the explorer provides a consistent and accurate view of the blockchain.
  131. ///
  132. /// A reorg occurs when the blocks stored by the blockchain nodes diverge from those stored by the explorer.
  133. /// This function resolves inconsistencies by identifying the point of divergence, searching backward through
  134. /// block heights, and comparing block hashes between the explorer database and the blockchain node. Once a
  135. /// common block height is found, the explorer is re-aligned to that height.
  136. ///
  137. /// If no common block can be found, the explorer resets to the "genesis height," removing all blocks,
  138. /// transactions, and metrics from its database to resynchronize with the canonical chain from the nodes.
  139. ///
  140. /// Returns the last height at which the explorer's state was successfully re-aligned with the blockchain.
  141. async fn process_sync_blocks_reorg(
  142. &self,
  143. last_synced_height: u32,
  144. last_darkfid_height: u32,
  145. ) -> Result<u32> {
  146. // Log reorg detection in the case that explorer height is greater or equal to height of darkfi node
  147. if last_synced_height >= last_darkfid_height {
  148. info!(target: "blockchain-explorer::rpc_blocks::process_sync_blocks_reorg",
  149. "Reorg detected with heights: explorer.{last_synced_height} >= darkfid.{last_darkfid_height}");
  150. }
  151. // Declare a mutable variable to track the current height while searching for a common block
  152. let mut cur_height = last_synced_height;
  153. // Search for an explorer block that matches a darkfi node block
  154. while cur_height > 0 {
  155. let synced_block = self.service.get_block_by_height(cur_height)?;
  156. debug!(target: "blockchain-explorer::rpc_blocks::process_sync_blocks_reorg", "Searching for common block: {}", cur_height);
  157. // Check if we found a synced block for current height being searched
  158. if let Some(synced_block) = synced_block {
  159. // Fetch the block from darkfi node to check for a match
  160. match self.get_darkfid_block_by_height(cur_height).await {
  161. Ok(darkfid_block) => {
  162. // If hashes match, we've found the point of divergence
  163. if synced_block.header_hash == darkfid_block.hash().to_string() {
  164. // If hashes match but the cur_height differs from the last synced height, reset the explorer state
  165. if cur_height != last_synced_height {
  166. self.service.reset_explorer_state(cur_height)?;
  167. debug!(target: "blockchain-explorer::rpc_blocks::process_sync_blocks_reorg", "Successfully completed reorg to height: {cur_height}");
  168. }
  169. break;
  170. } else {
  171. // Log reorg detection with height and header hash mismatch details
  172. if cur_height == last_synced_height {
  173. info!(
  174. target: "blockchain-explorer::rpc_blocks::process_sync_blocks_reorg",
  175. "Reorg detected at height {}: explorer.{} != darkfid.{}",
  176. cur_height,
  177. synced_block.header_hash,
  178. darkfid_block.hash().to_string()
  179. );
  180. }
  181. }
  182. }
  183. // Continue searching for blocks that do not exist on darkfi nodes
  184. Err(Error::JsonRpcError((-32121, _))) => (),
  185. Err(e) => {
  186. return Err(handle_database_error(
  187. "rpc_blocks::process_sync_blocks_reorg",
  188. "[process_sync_blocks_reorg] RPC client request failed",
  189. e,
  190. ))
  191. }
  192. }
  193. }
  194. // Move to previous block to search for a match
  195. cur_height = cur_height.saturating_sub(1);
  196. }
  197. // Check if genesis block reorg is needed
  198. if cur_height == 0 {
  199. self.service.reset_explorer_state(0)?;
  200. }
  201. // Return the last height we reorged to
  202. Ok(cur_height)
  203. }
  204. // RPCAPI:
  205. // Queries the database to retrieve last N blocks.
  206. // Returns an array of readable blocks upon success.
  207. //
  208. // **Params:**
  209. // * `array[0]`: `u16` Number of blocks to retrieve (as string)
  210. //
  211. // **Returns:**
  212. // * Array of `BlockRecord` encoded into a JSON.
  213. //
  214. // --> {"jsonrpc": "2.0", "method": "blocks.get_last_n_blocks", "params": ["10"], "id": 1}
  215. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  216. pub async fn blocks_get_last_n_blocks(&self, id: u16, params: JsonValue) -> JsonResult {
  217. let params = params.get::<Vec<JsonValue>>().unwrap();
  218. if params.len() != 1 || !params[0].is_string() {
  219. return JsonError::new(InvalidParams, None, id).into()
  220. }
  221. // Extract the number of last blocks to retrieve from parameters
  222. let n = match params[0].get::<String>().unwrap().parse::<usize>() {
  223. Ok(v) => v,
  224. Err(_) => return JsonError::new(ParseError, None, id).into(),
  225. };
  226. // Fetch the blocks and handle potential errors
  227. let blocks_result = match self.service.get_last_n(n) {
  228. Ok(blocks) => blocks,
  229. Err(e) => {
  230. error!(target: "blockchain-explorer::rpc_blocks::blocks_get_last_n_blocks", "Failed fetching blocks: {}", e);
  231. return JsonError::new(InternalError, None, id).into();
  232. }
  233. };
  234. // Transform blocks to json and return result
  235. if blocks_result.is_empty() {
  236. JsonResponse::new(JsonValue::Array(vec![]), id).into()
  237. } else {
  238. let json_blocks: Vec<JsonValue> =
  239. blocks_result.into_iter().map(|block| block.to_json_array()).collect();
  240. JsonResponse::new(JsonValue::Array(json_blocks), id).into()
  241. }
  242. }
  243. // RPCAPI:
  244. // Queries the database to retrieve blocks in provided heights range.
  245. // Returns an array of readable blocks upon success.
  246. //
  247. // **Params:**
  248. // * `array[0]`: `u32` Starting height (as string)
  249. // * `array[1]`: `u32` Ending height range (as string)
  250. //
  251. // **Returns:**
  252. // * Array of `BlockRecord` encoded into a JSON.
  253. //
  254. // --> {"jsonrpc": "2.0", "method": "blocks.get_blocks_in_heights_range", "params": ["10", "15"], "id": 1}
  255. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  256. pub async fn blocks_get_blocks_in_heights_range(
  257. &self,
  258. id: u16,
  259. params: JsonValue,
  260. ) -> JsonResult {
  261. let params = params.get::<Vec<JsonValue>>().unwrap();
  262. if params.len() != 2 || !params[0].is_string() || !params[1].is_string() {
  263. return JsonError::new(InvalidParams, None, id).into()
  264. }
  265. let start = match params[0].get::<String>().unwrap().parse::<u32>() {
  266. Ok(v) => v,
  267. Err(_) => return JsonError::new(ParseError, None, id).into(),
  268. };
  269. let end = match params[1].get::<String>().unwrap().parse::<u32>() {
  270. Ok(v) => v,
  271. Err(_) => return JsonError::new(ParseError, None, id).into(),
  272. };
  273. if start > end {
  274. return JsonError::new(ParseError, None, id).into()
  275. }
  276. // Fetch the blocks and handle potential errors
  277. let blocks_result = match self.service.get_by_range(start, end) {
  278. Ok(blocks) => blocks,
  279. Err(e) => {
  280. error!(target: "blockchain-explorer::rpc_blocks::blocks_get_blocks_in_height_range", "Failed fetching blocks: {}", e);
  281. return JsonError::new(InternalError, None, id).into();
  282. }
  283. };
  284. // Transform blocks to json and return result
  285. if blocks_result.is_empty() {
  286. JsonResponse::new(JsonValue::Array(vec![]), id).into()
  287. } else {
  288. let json_blocks: Vec<JsonValue> =
  289. blocks_result.into_iter().map(|block| block.to_json_array()).collect();
  290. JsonResponse::new(JsonValue::Array(json_blocks), id).into()
  291. }
  292. }
  293. // RPCAPI:
  294. // Queries the database to retrieve the block corresponding to the provided hash.
  295. // Returns the readable block upon success.
  296. //
  297. // **Params:**
  298. // * `array[0]`: `String` Block header hash
  299. //
  300. // **Returns:**
  301. // * `BlockRecord` encoded into a JSON.
  302. //
  303. // --> {"jsonrpc": "2.0", "method": "blocks.get_block_by_hash", "params": ["5cc...2f9"], "id": 1}
  304. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  305. pub async fn blocks_get_block_by_hash(&self, id: u16, params: JsonValue) -> JsonResult {
  306. let params = params.get::<Vec<JsonValue>>().unwrap();
  307. if params.len() != 1 || !params[0].is_string() {
  308. return JsonError::new(InvalidParams, None, id).into()
  309. }
  310. // Extract header hash from params, returning error if not provided
  311. let header_hash = match params[0].get::<String>() {
  312. Some(hash) => hash,
  313. None => return JsonError::new(InvalidParams, None, id).into(),
  314. };
  315. // Fetch and transform block to json, handling any errors and returning the result
  316. match self.service.get_block_by_hash(header_hash) {
  317. Ok(Some(block)) => JsonResponse::new(block.to_json_array(), id).into(),
  318. Ok(None) => JsonResponse::new(JsonValue::Array(vec![]), id).into(),
  319. Err(e) => {
  320. error!(target: "blockchain-explorer::rpc_blocks", "Failed fetching block: {:?}", e);
  321. JsonError::new(InternalError, None, id).into()
  322. }
  323. }
  324. }
  325. // Queries darkfid for last confirmed block.
  326. async fn get_last_confirmed_block(&self) -> Result<(u32, String)> {
  327. let rep = self
  328. .darkfid_daemon_request("blockchain.last_confirmed_block", &JsonValue::Array(vec![]))
  329. .await?;
  330. let params = rep.get::<Vec<JsonValue>>().unwrap();
  331. let height = *params[0].get::<f64>().unwrap() as u32;
  332. let hash = params[1].get::<String>().unwrap().clone();
  333. Ok((height, hash))
  334. }
  335. }
  336. /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
  337. /// new confirmed blocks. Upon receiving them, store them to the database.
  338. pub async fn subscribe_blocks(
  339. explorer: Arc<Explorerd>,
  340. endpoint: Url,
  341. ex: Arc<smol::Executor<'static>>,
  342. ) -> Result<(StoppableTaskPtr, StoppableTaskPtr)> {
  343. // Grab last confirmed block
  344. let (last_darkfid_height, last_darkfid_hash) = explorer.get_last_confirmed_block().await?;
  345. // Grab last synced block
  346. let (mut height, hash) = match explorer.service.last_block() {
  347. Ok(Some((height, hash))) => (height, hash),
  348. Ok(None) => (0, "".to_string()),
  349. Err(e) => {
  350. return Err(Error::DatabaseError(format!(
  351. "[subscribe_blocks] Retrieving last synced block failed: {e:?}"
  352. )))
  353. }
  354. };
  355. // Evaluates whether there is a mismatch between the last confirmed block and the last synced block
  356. let blocks_mismatch = (last_darkfid_height != height || last_darkfid_hash != hash) &&
  357. last_darkfid_height != 0 &&
  358. height != 0;
  359. // Check if there is a mismatch, throwing an error to prevent operating in a potentially inconsistent state
  360. if blocks_mismatch {
  361. warn!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks",
  362. "Warning: Last synced block is not the last confirmed block: \
  363. last_darkfid_height={last_darkfid_height}, last_synced_height={height}, last_darkfid_hash={last_darkfid_hash}, last_synced_hash={hash}");
  364. warn!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "You should first fully sync the blockchain, and then subscribe");
  365. return Err(Error::DatabaseError(
  366. "[subscribe_blocks] Blockchain not fully synced".to_string(),
  367. ));
  368. }
  369. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Subscribing to receive notifications of incoming blocks");
  370. let publisher = Publisher::new();
  371. let subscription = publisher.clone().subscribe().await;
  372. let _ex = ex.clone();
  373. let subscriber_task = StoppableTask::new();
  374. subscriber_task.clone().start(
  375. // Weird hack to prevent lifetimes hell
  376. async move {
  377. let ex = _ex.clone();
  378. let rpc_client = RpcClient::new(endpoint, ex).await?;
  379. let req = JsonRequest::new("blockchain.subscribe_blocks", JsonValue::Array(vec![]));
  380. rpc_client.subscribe(req, publisher).await
  381. },
  382. |res| async move {
  383. match res {
  384. Ok(()) => { /* Do nothing */ }
  385. Err(e) => error!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "[subscribe_blocks] JSON-RPC server error: {e:?}"),
  386. }
  387. },
  388. Error::RpcServerStopped,
  389. ex.clone(),
  390. );
  391. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Detached subscription to background");
  392. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "All is good. Waiting for block notifications...");
  393. let listener_task = StoppableTask::new();
  394. listener_task.clone().start(
  395. // Weird hack to prevent lifetimes hell
  396. async move {
  397. loop {
  398. match subscription.receive().await {
  399. JsonResult::Notification(n) => {
  400. debug!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Got Block notification from darkfid subscription");
  401. if n.method != "blockchain.subscribe_blocks" {
  402. return Err(Error::UnexpectedJsonRpc(format!(
  403. "Got foreign notification from darkfid: {}",
  404. n.method
  405. )))
  406. }
  407. // Verify parameters
  408. if !n.params.is_array() {
  409. return Err(Error::UnexpectedJsonRpc(
  410. "Received notification params are not an array".to_string(),
  411. ))
  412. }
  413. let params = n.params.get::<Vec<JsonValue>>().unwrap();
  414. if params.is_empty() {
  415. return Err(Error::UnexpectedJsonRpc(
  416. "Notification parameters are empty".to_string(),
  417. ))
  418. }
  419. for param in params {
  420. let param = param.get::<String>().unwrap();
  421. let bytes = base64::decode(param).unwrap();
  422. let darkfid_block: BlockInfo = match deserialize_async(&bytes).await {
  423. Ok(b) => b,
  424. Err(e) => {
  425. return Err(Error::UnexpectedJsonRpc(format!(
  426. "[subscribe_blocks] Deserializing block failed: {e:?}"
  427. )))
  428. },
  429. };
  430. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "=======================================");
  431. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Block Notification: {}", darkfid_block.hash().to_string());
  432. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "=======================================");
  433. // Store darkfi node block height for later use
  434. let darkfid_block_height = darkfid_block.header.height;
  435. // Check if we need to perform a reorg due to mismatch in block heights
  436. if darkfid_block_height <= height {
  437. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks",
  438. "Reorg detected with heights: darkfid.{darkfid_block_height} <= explorer.{height}");
  439. // Calculate the reset height
  440. let reset_height = darkfid_block_height.saturating_sub(1);
  441. // Execute the reorg by resetting the explorer state to reset height
  442. explorer.service.reset_explorer_state(reset_height)?;
  443. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Successfully completed reorg to height: {reset_height}");
  444. }
  445. if let Err(e) = explorer.service.put_block(&darkfid_block).await {
  446. return Err(Error::DatabaseError(format!(
  447. "[subscribe_blocks] Put block failed: {e:?}"
  448. )))
  449. }
  450. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Successfully stored new block at height: {}", darkfid_block.header.height );
  451. // Process the next block
  452. height = darkfid_block.header.height;
  453. }
  454. }
  455. JsonResult::Error(e) => {
  456. // Some error happened in the transmission
  457. return Err(Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}")))
  458. }
  459. x => {
  460. // And this is weird
  461. return Err(Error::UnexpectedJsonRpc(format!(
  462. "Got unexpected data from JSON-RPC: {x:?}"
  463. )))
  464. }
  465. }
  466. };
  467. },
  468. |res| async move {
  469. match res {
  470. Ok(()) => { /* Do nothing */ }
  471. Err(e) => error!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "[subscribe_blocks] JSON-RPC server error: {e:?}"),
  472. }
  473. },
  474. Error::RpcServerStopped,
  475. ex,
  476. );
  477. Ok((subscriber_task, listener_task))
  478. }