sync.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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_synced} blocks: explorer blocks total {} [{}]",
  149. self.db.blockchain.blocks.len(),
  150. fmt_duration(sync_start_time.elapsed()),
  151. );
  152. Ok(())
  153. }
  154. /// Handles blockchain reorganizations (reorgs) during the explorer node's startup synchronization
  155. /// with Darkfi nodes, ensuring the explorer provides a consistent and accurate view of the blockchain.
  156. ///
  157. /// A reorg occurs when the blocks stored by the blockchain nodes diverge from those stored by the explorer.
  158. /// This function resolves inconsistencies by identifying the point of divergence, searching backward through
  159. /// block heights, and comparing block hashes between the explorer database and the blockchain node. Once a
  160. /// common block height is found, the explorer is re-aligned to that height.
  161. ///
  162. /// If no common block can be found, the explorer resets to the "genesis height," removing all blocks,
  163. /// transactions, and metrics from its database to resynchronize with the canonical chain from the nodes.
  164. ///
  165. /// Returns the last height at which the explorer's state was successfully re-aligned with the blockchain.
  166. async fn reorg_blocks(
  167. &self,
  168. last_synced_height: u32,
  169. last_darkfid_height: u32,
  170. ) -> darkfi::Result<u32> {
  171. // Log reorg detection in the case that explorer height is greater or equal to height of darkfi node
  172. if last_synced_height >= last_darkfid_height {
  173. info!(target: "explorerd::rpc_blocks::process_sync_blocks_reorg",
  174. "Reorg detected with heights: explorer.{last_synced_height} >= darkfid.{last_darkfid_height}");
  175. }
  176. // Declare a mutable variable to track the current height while searching for a common block
  177. let mut cur_height = last_synced_height;
  178. // Search for an explorer block that matches a darkfi node block
  179. while cur_height > 0 {
  180. let synced_block = self.get_block_by_height(cur_height)?;
  181. debug!(target: "explorerd::rpc_blocks::process_sync_blocks_reorg", "Searching for common block: {cur_height}");
  182. // Check if we found a synced block for current height being searched
  183. if let Some(synced_block) = synced_block {
  184. // Fetch the block from darkfi node to check for a match
  185. match self.darkfid_client.get_block_by_height(cur_height).await {
  186. Ok(darkfid_block) => {
  187. // If hashes match, we've found the point of divergence
  188. if synced_block.header_hash == darkfid_block.hash().to_string() {
  189. // If hashes match but the cur_height differs from the last synced height, reset the explorer state
  190. if cur_height != last_synced_height {
  191. self.reset_explorer_state(cur_height)?;
  192. debug!(target: "explorerd::rpc_blocks::process_sync_blocks_reorg", "Completed reorg to height: {cur_height}");
  193. }
  194. break;
  195. } else {
  196. // Log reorg detection with height and header hash mismatch details
  197. if cur_height == last_synced_height {
  198. info!(
  199. target: "explorerd::rpc_blocks::process_sync_blocks_reorg",
  200. "Reorg detected at height {cur_height}: explorer.{} != darkfid.{}",
  201. synced_block.header_hash,
  202. darkfid_block.hash()
  203. );
  204. }
  205. }
  206. }
  207. // Continue searching for blocks that do not exist on darkfi nodes
  208. Err(Error::JsonRpcError((-32121, _))) => (),
  209. Err(e) => {
  210. return Err(handle_database_error(
  211. "rpc_blocks::process_sync_blocks_reorg",
  212. "[process_sync_blocks_reorg] RPC client request failed",
  213. e,
  214. ))
  215. }
  216. }
  217. }
  218. // Move to previous block to search for a match
  219. cur_height = cur_height.saturating_sub(1);
  220. }
  221. // Check if genesis block reorg is needed
  222. if cur_height == 0 {
  223. self.reset_explorer_state(0)?;
  224. }
  225. // Return the last height we reorged to
  226. Ok(cur_height)
  227. }
  228. }
  229. /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
  230. /// new confirmed blocks. Upon receiving them, store them to the database.
  231. pub async fn subscribe_sync_blocks(
  232. explorer: Arc<Explorerd>,
  233. endpoint: Url,
  234. ex: Arc<smol::Executor<'static>>,
  235. ) -> darkfi::Result<(StoppableTaskPtr, StoppableTaskPtr)> {
  236. // Grab last confirmed block
  237. let (last_darkfid_height, last_darkfid_hash) =
  238. explorer.darkfid_client.get_last_confirmed_block().await?;
  239. // Grab last synced block
  240. let (mut height, hash) = match explorer.service.last_block() {
  241. Ok(Some((height, hash))) => (height, hash),
  242. Ok(None) => (0, "".to_string()),
  243. Err(e) => {
  244. return Err(Error::DatabaseError(format!(
  245. "[subscribe_blocks] Retrieving last synced block failed: {e:?}"
  246. )))
  247. }
  248. };
  249. // Evaluates whether there is a mismatch between the last confirmed block and the last synced block
  250. let blocks_mismatch = (last_darkfid_height != height || last_darkfid_hash != hash) &&
  251. last_darkfid_height != 0 &&
  252. height != 0;
  253. // Check if there is a mismatch, throwing an error to prevent operating in a potentially inconsistent state
  254. if blocks_mismatch {
  255. warn!(target: "explorerd::rpc_blocks::subscribe_blocks",
  256. "Warning: Last synced block is not the last confirmed block: \
  257. last_darkfid_height={last_darkfid_height}, last_synced_height={height}, last_darkfid_hash={last_darkfid_hash}, last_synced_hash={hash}");
  258. warn!(target: "explorerd::rpc_blocks::subscribe_blocks", "You should first fully sync the blockchain, and then subscribe");
  259. return Err(Error::DatabaseError(
  260. "[subscribe_blocks] Blockchain not fully synced".to_string(),
  261. ));
  262. }
  263. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "Subscribing to receive notifications of incoming blocks");
  264. let publisher = Publisher::new();
  265. let subscription = publisher.clone().subscribe().await;
  266. let _ex = ex.clone();
  267. let subscriber_task = StoppableTask::new();
  268. subscriber_task.clone().start(
  269. // Weird hack to prevent lifetimes hell
  270. async move {
  271. let ex = _ex.clone();
  272. let rpc_client = RpcClient::new(endpoint, ex).await?;
  273. let req = JsonRequest::new("blockchain.subscribe_blocks", JsonValue::Array(vec![]));
  274. rpc_client.subscribe(req, publisher).await
  275. },
  276. |res| async move {
  277. match res {
  278. Ok(()) => { /* Do nothing */ }
  279. Err(e) => error!(target: "explorerd::rpc_blocks::subscribe_blocks", "[subscribe_blocks] JSON-RPC server error: {e:?}"),
  280. }
  281. },
  282. Error::RpcServerStopped,
  283. ex.clone(),
  284. );
  285. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "Detached subscription to background");
  286. let listener_task = StoppableTask::new();
  287. listener_task.clone().start(
  288. // Weird hack to prevent lifetimes hell
  289. async move {
  290. loop {
  291. match subscription.receive().await {
  292. JsonResult::Notification(n) => {
  293. debug!(target: "explorerd::rpc_blocks::subscribe_blocks", "Got Block notification from darkfid subscription");
  294. if n.method != "blockchain.subscribe_blocks" {
  295. return Err(Error::UnexpectedJsonRpc(format!(
  296. "Got foreign notification from darkfid: {}",
  297. n.method
  298. )))
  299. }
  300. // Verify parameters
  301. if !n.params.is_array() {
  302. return Err(Error::UnexpectedJsonRpc(
  303. "Received notification params are not an array".to_string(),
  304. ))
  305. }
  306. let params = n.params.get::<Vec<JsonValue>>().unwrap();
  307. if params.is_empty() {
  308. return Err(Error::UnexpectedJsonRpc(
  309. "Notification parameters are empty".to_string(),
  310. ))
  311. }
  312. for param in params {
  313. let param = param.get::<String>().unwrap();
  314. let bytes = base64::decode(param).unwrap();
  315. let darkfid_block: BlockInfo = match deserialize_async(&bytes).await {
  316. Ok(b) => b,
  317. Err(e) => {
  318. return Err(Error::UnexpectedJsonRpc(format!(
  319. "[subscribe_blocks] Deserializing block failed: {e:?}"
  320. )))
  321. },
  322. };
  323. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "========================================================================================");
  324. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "| Block Notification: {} |", darkfid_block.hash());
  325. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "========================================================================================");
  326. // Store darkfi node block height for later use
  327. let darkfid_block_height = darkfid_block.header.height;
  328. // Check if we need to perform a reorg due to mismatch in block heights
  329. if darkfid_block_height <= height {
  330. info!(target: "explorerd::rpc_blocks::subscribe_blocks",
  331. "Reorg detected with heights: darkfid.{darkfid_block_height} <= explorer.{height}");
  332. // Calculate the reset height
  333. let reset_height = darkfid_block_height.saturating_sub(1);
  334. // Record the start time to measure the duration of the reorg
  335. let start_reorg_time = Instant::now();
  336. // Execute the reorg by resetting the explorer state to reset height
  337. explorer.service.reset_explorer_state(reset_height)?;
  338. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "Completed reorg to height: {reset_height} [{}]", fmt_duration(start_reorg_time.elapsed()));
  339. }
  340. // Record the start time to measure the duration to store the block
  341. let start_reorg_time = Instant::now();
  342. if let Err(e) = explorer.service.put_block(&darkfid_block).await {
  343. return Err(Error::DatabaseError(format!(
  344. "[subscribe_blocks] Put block failed: {e:?}"
  345. )))
  346. }
  347. info!(target: "explorerd::rpc_blocks::subscribe_blocks", "Stored new block at height: {} [{}]", darkfid_block.header.height, fmt_duration(start_reorg_time.elapsed()));
  348. // Process the next block
  349. height = darkfid_block.header.height;
  350. }
  351. }
  352. JsonResult::Error(e) => {
  353. // Some error happened in the transmission
  354. return Err(Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}")))
  355. }
  356. x => {
  357. // And this is weird
  358. return Err(Error::UnexpectedJsonRpc(format!(
  359. "Got unexpected data from JSON-RPC: {x:?}"
  360. )))
  361. }
  362. }
  363. };
  364. },
  365. |res| async move {
  366. match res {
  367. Ok(()) => { /* Do nothing */ }
  368. Err(e) => error!(target: "explorerd::rpc_blocks::subscribe_blocks", "[subscribe_blocks] JSON-RPC server error: {e:?}"),
  369. }
  370. },
  371. Error::RpcServerStopped,
  372. ex,
  373. );
  374. Ok((subscriber_task, listener_task))
  375. }