sync.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. //! # Sync Module
  19. //!
  20. //! The `sync` module is responsible for synchronizing the explorer's database with the Darkfi
  21. //! blockchain network. It ensures consistency between the explorer and the blockchain by
  22. //! fetching missing blocks, handling reorganizations (reorgs), and subscribing to live updates
  23. //! through Darkfi's JSON-RPC service.
  24. //!
  25. //! ## Responsibilities
  26. //!
  27. //! - **Block Synchronization**: Handles fetching and storing blocks from a Darkfi
  28. //! blockchain node during startup or when syncing, ensuring the explorer stays synchronized
  29. //! with the latest confirmed blocks.
  30. //! - **Real-Time Updates**: Subscribes to Darkfi's JSON-RPC notification service,
  31. //! allowing the explorer to process and sync new blocks as they are confirmed.
  32. //! - **Reorg Handling**: Detects and resolves blockchain reorganizations by identifying
  33. //! the last common block (in case of divergence) and re-aligning the explorer's state with the
  34. //! latest blockchain state. Reorgs are an importnt part of synchronization because they prevent
  35. //! syncing invalid or outdated states, ensuring the explorer maintains an accurate view of a
  36. //! Darkfi blockchain network.
  37. use std::{sync::Arc, time::Instant};
  38. use log::{debug, error, info, warn};
  39. use tinyjson::JsonValue;
  40. use url::Url;
  41. use darkfi::{
  42. blockchain::BlockInfo,
  43. rpc::{
  44. client::RpcClient,
  45. jsonrpc::{JsonRequest, JsonResult},
  46. },
  47. system::{Publisher, StoppableTask, StoppableTaskPtr},
  48. util::{encoding::base64, time::fmt_duration},
  49. Error,
  50. };
  51. use darkfi_serial::deserialize_async;
  52. use crate::{error::handle_database_error, service::ExplorerService, Explorerd};
  53. impl ExplorerService {
  54. /// Synchronizes blocks between the explorer and a Darkfi blockchain node, ensuring
  55. /// the database remains consistent by syncing any missing or outdated blocks.
  56. ///
  57. /// If provided `reset` is true, the explorer's blockchain-related and metric sled trees are purged
  58. /// and syncing starts from the genesis block. The function also handles reorgs by re-aligning the
  59. /// explorer state to the correct height when blocks are outdated. Returns a result indicating
  60. /// success or failure.
  61. ///
  62. /// Reorg handling is delegated to the [`Self::reorg_blocks`] function, whose
  63. /// documentation provides more details on the reorg process during block syncing.
  64. pub async fn sync_blocks(&self, reset: bool) -> darkfi::Result<()> {
  65. // Grab last synced block height from the explorer's database.
  66. let last_synced_block = self.last_block().map_err(|e| {
  67. handle_database_error(
  68. "rpc_blocks::sync_blocks",
  69. "[sync_blocks] Retrieving last synced block failed",
  70. e,
  71. )
  72. })?;
  73. // Grab the last confirmed block height and hash from the darkfi node
  74. let (last_darkfid_height, last_darkfid_hash) =
  75. self.darkfid_client.get_last_confirmed_block().await?;
  76. // Initialize the current height to sync from, starting from genesis block if last sync block does not exist
  77. let (last_synced_height, last_synced_hash) = last_synced_block
  78. .map_or((0, "".to_string()), |(height, header_hash)| (height, header_hash));
  79. // Declare a mutable variable to track the current sync height while processing blocks
  80. let mut current_height = last_synced_height;
  81. info!(target: "explorerd::rpc_blocks::sync_blocks", "Syncing from block number: {current_height}");
  82. info!(target: "explorerd::rpc_blocks::sync_blocks", "Last confirmed darkfid block: {last_darkfid_height} - {last_darkfid_hash}");
  83. // A reorg is detected if the hash of the last synced block differs from the hash of the last confirmed block,
  84. // unless the reset flag is set or the current height is 0
  85. let reorg_detected = last_synced_hash != last_darkfid_hash && !reset && current_height != 0;
  86. // If the reset flag is set, reset the explorer state and start syncing from the genesis block height.
  87. // Otherwise, handle reorgs if detected, or proceed to the next block if not at the genesis height.
  88. if reset {
  89. self.reset_explorer_state(0)?;
  90. current_height = 0;
  91. info!(target: "explorerd::rpc_blocks::sync_blocks", "Reset explorer database based on set reset parameter");
  92. } else if reorg_detected {
  93. // Record the start time to measure the duration of potential reorg
  94. let start_reorg_time = Instant::now();
  95. // Process reorg
  96. current_height = self.reorg_blocks(last_synced_height, last_darkfid_height).await?;
  97. // Log only if a reorg occurred (i.e., the explorer wasn't merely catching up to Darkfi node blocks)
  98. if current_height != last_synced_height {
  99. info!(target: "explorerd::rpc_blocks::sync_blocks", "Completed reorg to height: {current_height} [{}]", fmt_duration(start_reorg_time.elapsed()));
  100. }
  101. // Prepare to sync the next block after reorg if not from genesis height
  102. if current_height != 0 {
  103. current_height += 1;
  104. }
  105. } else if current_height != 0 {
  106. // Resume syncing from the block after the last synced height
  107. current_height += 1;
  108. }
  109. // Record the sync start time to measure the total block sync duration
  110. let sync_start_time = Instant::now();
  111. // Track the number of blocks synced for reporting
  112. let mut blocks_synced = 0;
  113. // Sync blocks until the explorer is up to date with the last confirmed block
  114. while current_height <= last_darkfid_height {
  115. // Record the start time to measure the duration it took to sync the block
  116. let block_sync_start = Instant::now();
  117. // Retrieve the block from darkfi node by height
  118. let block = match self.darkfid_client.get_block_by_height(current_height).await {
  119. Ok(r) => r,
  120. Err(e) => {
  121. return Err(handle_database_error(
  122. "rpc_blocks::sync_blocks",
  123. "[sync_blocks] RPC client request failed",
  124. e,
  125. ))
  126. }
  127. };
  128. // Store the retrieved block in the explorer's database
  129. if let Err(e) = self.put_block(&block).await {
  130. return Err(handle_database_error(
  131. "rpc_blocks::sync_blocks",
  132. "[sync_blocks] Put block failed",
  133. e,
  134. ));
  135. };
  136. debug!(
  137. target: "explorerd::rpc_blocks::sync_blocks",
  138. "Synced block {current_height} [{}]",
  139. fmt_duration(block_sync_start.elapsed())
  140. );
  141. // Increment the current height to sync the next block
  142. current_height += 1;
  143. // Increment the count of successfully synced blocks
  144. blocks_synced += 1;
  145. }
  146. info!(
  147. target: "explorerd::rpc_blocks::sync_blocks",
  148. "Synced {} blocks: explorer blocks total {} [{}]",
  149. blocks_synced,
  150. self.db.blockchain.blocks.len(),
  151. fmt_duration(sync_start_time.elapsed()),
  152. );
  153. Ok(())
  154. }
  155. /// Handles blockchain reorganizations (reorgs) during the explorer node's startup synchronization
  156. /// with Darkfi nodes, ensuring the explorer provides a consistent and accurate view of the blockchain.
  157. ///
  158. /// A reorg occurs when the blocks stored by the blockchain nodes diverge from those stored by the explorer.
  159. /// This function resolves inconsistencies by identifying the point of divergence, searching backward through
  160. /// block heights, and comparing block hashes between the explorer database and the blockchain node. Once a
  161. /// common block height is found, the explorer is re-aligned to that height.
  162. ///
  163. /// If no common block can be found, the explorer resets to the "genesis height," removing all blocks,
  164. /// transactions, and metrics from its database to resynchronize with the canonical chain from the nodes.
  165. ///
  166. /// Returns the last height at which the explorer's state was successfully re-aligned with the blockchain.
  167. async fn reorg_blocks(
  168. &self,
  169. last_synced_height: u32,
  170. last_darkfid_height: u32,
  171. ) -> darkfi::Result<u32> {
  172. // Log reorg detection in the case that explorer height is greater or equal to height of darkfi node
  173. if last_synced_height >= last_darkfid_height {
  174. info!(target: "explorerd::rpc_blocks::process_sync_blocks_reorg",
  175. "Reorg detected with heights: explorer.{last_synced_height} >= darkfid.{last_darkfid_height}");
  176. }
  177. // Declare a mutable variable to track the current height while searching for a common block
  178. let mut cur_height = last_synced_height;
  179. // Search for an explorer block that matches a darkfi node block
  180. while cur_height > 0 {
  181. let synced_block = self.get_block_by_height(cur_height)?;
  182. debug!(target: "explorerd::rpc_blocks::process_sync_blocks_reorg", "Searching for common block: {}", cur_height);
  183. // Check if we found a synced block for current height being searched
  184. if let Some(synced_block) = synced_block {
  185. // Fetch the block from darkfi node to check for a match
  186. match self.darkfid_client.get_block_by_height(cur_height).await {
  187. Ok(darkfid_block) => {
  188. // If hashes match, we've found the point of divergence
  189. if synced_block.header_hash == darkfid_block.hash().to_string() {
  190. // If hashes match but the cur_height differs from the last synced height, reset the explorer state
  191. if cur_height != last_synced_height {
  192. self.reset_explorer_state(cur_height)?;
  193. debug!(target: "explorerd::rpc_blocks::process_sync_blocks_reorg", "Completed reorg to height: {cur_height}");
  194. }
  195. break;
  196. } else {
  197. // Log reorg detection with height and header hash mismatch details
  198. if cur_height == last_synced_height {
  199. info!(
  200. target: "explorerd::rpc_blocks::process_sync_blocks_reorg",
  201. "Reorg detected at height {}: explorer.{} != darkfid.{}",
  202. cur_height,
  203. synced_block.header_hash,
  204. darkfid_block.hash()
  205. );
  206. }
  207. }
  208. }
  209. // Continue searching for blocks that do not exist on darkfi nodes
  210. Err(Error::JsonRpcError((-32121, _))) => (),
  211. Err(e) => {
  212. return Err(handle_database_error(
  213. "rpc_blocks::process_sync_blocks_reorg",
  214. "[process_sync_blocks_reorg] RPC client request failed",
  215. e,
  216. ))
  217. }
  218. }
  219. }
  220. // Move to previous block to search for a match
  221. cur_height = cur_height.saturating_sub(1);
  222. }
  223. // Check if genesis block reorg is needed
  224. if cur_height == 0 {
  225. self.reset_explorer_state(0)?;
  226. }
  227. // Return the last height we reorged to
  228. Ok(cur_height)
  229. }
  230. }
  231. /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
  232. /// new confirmed blocks. Upon receiving them, store them to the database.
  233. pub async fn subscribe_sync_blocks(
  234. explorer: Arc<Explorerd>,
  235. endpoint: Url,
  236. ex: Arc<smol::Executor<'static>>,
  237. ) -> darkfi::Result<(StoppableTaskPtr, StoppableTaskPtr)> {
  238. // Grab last confirmed block
  239. let (last_darkfid_height, last_darkfid_hash) =
  240. explorer.darkfid_client.get_last_confirmed_block().await?;
  241. // Grab last synced block
  242. let (mut height, hash) = match explorer.service.last_block() {
  243. Ok(Some((height, hash))) => (height, hash),
  244. Ok(None) => (0, "".to_string()),
  245. Err(e) => {
  246. return Err(Error::DatabaseError(format!(
  247. "[subscribe_blocks] Retrieving last synced block failed: {e:?}"
  248. )))
  249. }
  250. };
  251. // Evaluates whether there is a mismatch between the last confirmed block and the last synced block
  252. let blocks_mismatch = (last_darkfid_height != height || last_darkfid_hash != hash)
  253. && last_darkfid_height != 0
  254. && height != 0;
  255. // Check if there is a mismatch, throwing an error to prevent operating in a potentially inconsistent state
  256. if blocks_mismatch {
  257. warn!(target: "explorerd::rpc_blocks::subscribe_blocks",
  258. "Warning: Last synced block is not the last confirmed block: \
  259. last_darkfid_height={last_darkfid_height}, last_synced_height={height}, last_darkfid_hash={last_darkfid_hash}, last_synced_hash={hash}");
  260. warn!(target: "explorerd::rpc_blocks::subscribe_blocks", "You should first fully sync the blockchain, and then subscribe");
  261. return Err(Error::DatabaseError(
  262. "[subscribe_blocks] Blockchain not fully synced".to_string(),
  263. ));
  264. }
  265. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "Subscribing to receive notifications of incoming blocks");
  266. let publisher = Publisher::new();
  267. let subscription = publisher.clone().subscribe().await;
  268. let _ex = ex.clone();
  269. let subscriber_task = StoppableTask::new();
  270. subscriber_task.clone().start(
  271. // Weird hack to prevent lifetimes hell
  272. async move {
  273. let ex = _ex.clone();
  274. let rpc_client = RpcClient::new(endpoint, ex).await?;
  275. let req = JsonRequest::new("blockchain.subscribe_blocks", JsonValue::Array(vec![]));
  276. rpc_client.subscribe(req, publisher).await
  277. },
  278. |res| async move {
  279. match res {
  280. Ok(()) => { /* Do nothing */ }
  281. Err(e) => error!(target: "explorerd::rpc_blocks::subscribe_blocks", "[subscribe_blocks] JSON-RPC server error: {e:?}"),
  282. }
  283. },
  284. Error::RpcServerStopped,
  285. ex.clone(),
  286. );
  287. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "Detached subscription to background");
  288. let listener_task = StoppableTask::new();
  289. listener_task.clone().start(
  290. // Weird hack to prevent lifetimes hell
  291. async move {
  292. loop {
  293. match subscription.receive().await {
  294. JsonResult::Notification(n) => {
  295. debug!(target: "explorerd::rpc_blocks::subscribe_blocks", "Got Block notification from darkfid subscription");
  296. if n.method != "blockchain.subscribe_blocks" {
  297. return Err(Error::UnexpectedJsonRpc(format!(
  298. "Got foreign notification from darkfid: {}",
  299. n.method
  300. )))
  301. }
  302. // Verify parameters
  303. if !n.params.is_array() {
  304. return Err(Error::UnexpectedJsonRpc(
  305. "Received notification params are not an array".to_string(),
  306. ))
  307. }
  308. let params = n.params.get::<Vec<JsonValue>>().unwrap();
  309. if params.is_empty() {
  310. return Err(Error::UnexpectedJsonRpc(
  311. "Notification parameters are empty".to_string(),
  312. ))
  313. }
  314. for param in params {
  315. let param = param.get::<String>().unwrap();
  316. let bytes = base64::decode(param).unwrap();
  317. let darkfid_block: BlockInfo = match deserialize_async(&bytes).await {
  318. Ok(b) => b,
  319. Err(e) => {
  320. return Err(Error::UnexpectedJsonRpc(format!(
  321. "[subscribe_blocks] Deserializing block failed: {e:?}"
  322. )))
  323. },
  324. };
  325. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "========================================================================================");
  326. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "| Block Notification: {} |", darkfid_block.hash());
  327. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "========================================================================================");
  328. // Store darkfi node block height for later use
  329. let darkfid_block_height = darkfid_block.header.height;
  330. // Check if we need to perform a reorg due to mismatch in block heights
  331. if darkfid_block_height <= height {
  332. info!(target: "explorerd::rpc_blocks::subscribe_blocks",
  333. "Reorg detected with heights: darkfid.{darkfid_block_height} <= explorer.{height}");
  334. // Calculate the reset height
  335. let reset_height = darkfid_block_height.saturating_sub(1);
  336. // Record the start time to measure the duration of the reorg
  337. let start_reorg_time = Instant::now();
  338. // Execute the reorg by resetting the explorer state to reset height
  339. explorer.service.reset_explorer_state(reset_height)?;
  340. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "Completed reorg to height: {reset_height} [{}]", fmt_duration(start_reorg_time.elapsed()));
  341. }
  342. // Record the start time to measure the duration to store the block
  343. let start_reorg_time = Instant::now();
  344. if let Err(e) = explorer.service.put_block(&darkfid_block).await {
  345. return Err(Error::DatabaseError(format!(
  346. "[subscribe_blocks] Put block failed: {e:?}"
  347. )))
  348. }
  349. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "Stored new block at height: {} [{}]", darkfid_block.header.height, fmt_duration(start_reorg_time.elapsed()));
  350. // Process the next block
  351. height = darkfid_block.header.height;
  352. }
  353. }
  354. JsonResult::Error(e) => {
  355. // Some error happened in the transmission
  356. return Err(Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}")))
  357. }
  358. x => {
  359. // And this is weird
  360. return Err(Error::UnexpectedJsonRpc(format!(
  361. "Got unexpected data from JSON-RPC: {x:?}"
  362. )))
  363. }
  364. }
  365. };
  366. },
  367. |res| async move {
  368. match res {
  369. Ok(()) => { /* Do nothing */ }
  370. Err(e) => error!(target: "explorerd::rpc_blocks::subscribe_blocks", "[subscribe_blocks] JSON-RPC server error: {e:?}"),
  371. }
  372. },
  373. Error::RpcServerStopped,
  374. ex,
  375. );
  376. Ok((subscriber_task, listener_task))
  377. }