rpc_blocks.rs 26 KB

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