sync.rs 21 KB

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