main.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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::{collections::HashSet, path::Path, sync::Arc};
  19. use smol::{lock::Mutex, stream::StreamExt};
  20. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  21. use tracing::{error, info};
  22. use url::Url;
  23. use darkfi::{
  24. async_daemonize, cli_desc,
  25. rpc::server::{listen_and_serve, RequestHandler},
  26. system::{StoppableTask, StoppableTaskPtr},
  27. util::path::get_config_path,
  28. Error, Result,
  29. };
  30. use crate::{
  31. config::ExplorerNetworkConfig,
  32. rpc::DarkfidRpcClient,
  33. service::{sync::subscribe_sync_blocks, ExplorerService},
  34. };
  35. /// Configuration management across multiple networks (localnet, testnet, mainnet)
  36. mod config;
  37. /// Manages JSON-RPC interactions for the explorer
  38. mod rpc;
  39. /// Core logic for block synchronization, chain data access, metadata storage/retrieval,
  40. /// and statistics computation
  41. mod service;
  42. /// Manages persistent storage for blockchain, contracts, metrics, and metadata
  43. mod store;
  44. /// Crate errors
  45. mod error;
  46. /// Test utilities used for unit and integration testing
  47. #[cfg(test)]
  48. mod test_utils;
  49. const CONFIG_FILE: &str = "explorerd_config.toml";
  50. const CONFIG_FILE_CONTENTS: &str = include_str!("../explorerd_config.toml");
  51. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  52. #[serde(default)]
  53. #[structopt(name = "explorerd", about = cli_desc!())]
  54. struct Args {
  55. #[structopt(short, long)]
  56. /// Configuration file to use
  57. config: Option<String>,
  58. #[structopt(short, long, default_value = "testnet")]
  59. /// Explorer network (localnet, testnet, mainnet)
  60. network: String,
  61. #[structopt(long)]
  62. /// Reset the database and start syncing from first block
  63. reset: bool,
  64. #[structopt(short, long)]
  65. /// Set log file to output to
  66. log: Option<String>,
  67. #[structopt(short, parse(from_occurrences))]
  68. /// Increase verbosity (-vvv supported)
  69. verbose: u8,
  70. #[structopt(short, long)]
  71. /// Disable synchronization and connections to `darkfid`, operating solely
  72. /// on the local explorer database without attempting to connect or sync.
  73. /// If not specified, the application will attempt to connect and sync by default.
  74. no_sync: bool,
  75. }
  76. /// Defines a daemon structure responsible for handling incoming JSON-RPC requests and delegating them
  77. /// to the backend layer for processing. It provides a JSON-RPC interface for managing operations related to
  78. /// blocks, transactions, contracts, and metrics.
  79. ///
  80. /// Upon startup, the daemon initializes a background task to handle incoming JSON-RPC requests.
  81. /// This includes processing operations related to blocks, transactions, contracts, and metrics by
  82. /// delegating them to the backend and returning appropriate RPC responses. Additionally, the daemon
  83. /// synchronizes blocks from the `darkfid` daemon into the explorer database and subscribes
  84. /// to new blocks, ensuring that the local database remains updated in real-time.
  85. pub struct Explorerd {
  86. /// Explorer service instance
  87. pub service: ExplorerService,
  88. /// JSON-RPC connection tracker
  89. pub rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  90. /// JSON-RPC client to execute requests to darkfid daemon
  91. pub darkfid_client: Arc<DarkfidRpcClient>,
  92. /// Darkfi blockchain node endpoint to sync with when not in no-sync mode
  93. darkfid_endpoint: Url,
  94. /// A asynchronous executor used to create an RPC client when not in no-sync mode
  95. executor: Arc<smol::Executor<'static>>,
  96. }
  97. impl Explorerd {
  98. /// Creates a new `BlockchainExplorer` instance.
  99. async fn new(
  100. db_path: String,
  101. darkfid_endpoint: Url,
  102. ex: Arc<smol::Executor<'static>>,
  103. ) -> Result<Self> {
  104. // Initialize darkfid rpc client
  105. let darkfid_client = Arc::new(DarkfidRpcClient::new());
  106. // Create explorer service
  107. let service = ExplorerService::new(db_path, darkfid_client.clone())?;
  108. // Initialize the explorer service
  109. service.init().await?;
  110. Ok(Self {
  111. service,
  112. rpc_connections: Mutex::new(HashSet::new()),
  113. darkfid_client,
  114. darkfid_endpoint,
  115. executor: ex,
  116. })
  117. }
  118. /// Establishes a connection to the configured darkfid endpoint, returning a successful
  119. /// result if the connection is successful, or an error otherwise.
  120. async fn connect(&self) -> Result<()> {
  121. self.darkfid_client.connect(self.darkfid_endpoint.clone(), self.executor.clone()).await
  122. }
  123. }
  124. async_daemonize!(realmain);
  125. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  126. info!(target: "explorerd", "Initializing DarkFi blockchain explorer node...");
  127. // Resolve the configuration path
  128. let config_path = get_config_path(args.config.clone(), CONFIG_FILE)?;
  129. // Get explorer network configuration
  130. let config: ExplorerNetworkConfig = (&config_path, &args.network).try_into()?;
  131. // Initialize the explorer daemon instance
  132. let explorer =
  133. Explorerd::new(config.database.clone(), config.endpoint.clone(), ex.clone()).await?;
  134. let explorer = Arc::new(explorer);
  135. info!(target: "explorerd", "Node initialized successfully!");
  136. // JSON-RPC server
  137. // Here we create a task variable so we can manually close the task later.
  138. let rpc_task = StoppableTask::new();
  139. let explorer_ = explorer.clone();
  140. rpc_task.clone().start(
  141. listen_and_serve(config.rpc.clone().into(), explorer.clone(), None, ex.clone()),
  142. |res| async move {
  143. match res {
  144. Ok(()) | Err(Error::RpcServerStopped) => explorer_.stop_connections().await,
  145. Err(e) => {
  146. error!(target: "explorerd", "Failed starting sync JSON-RPC server: {e}")
  147. }
  148. }
  149. },
  150. Error::RpcServerStopped,
  151. ex.clone(),
  152. );
  153. info!(target: "explorerd", "Started JSON-RPC server: {}", config.rpc.rpc_listen.to_string().trim_end_matches("/"));
  154. // Declare task variables optional in case we are in no-sync mode
  155. let mut subscriber_task = None;
  156. let mut listener_task = None;
  157. // Do not sync when in no-sync mode
  158. if !args.no_sync {
  159. explorer.connect().await?;
  160. // Sync blocks
  161. sync_blocks(explorer.clone(), args.reset).await?;
  162. // Subscribe blocks
  163. (subscriber_task, listener_task) =
  164. subscribe_blocks(explorer.clone(), config.endpoint.clone(), ex.clone(), args.reset)
  165. .await?;
  166. }
  167. log_started_banner(explorer.clone(), &config, &args, &config_path, args.no_sync);
  168. info!(target: "explorerd::", "All is good. Waiting for block notifications...");
  169. // Signal handling for graceful termination.
  170. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  171. signals_handler.wait_termination(signals_task).await?;
  172. info!(target: "explorerd", "Caught termination signal, cleaning up and exiting...");
  173. info!(target: "explorerd", "Stopping JSON-RPC server...");
  174. rpc_task.stop().await;
  175. // Stop darkfid listener task if it exists
  176. if let Some(task) = listener_task {
  177. info!(target: "explorerd", "Stopping darkfid listener...");
  178. task.stop().await;
  179. }
  180. // Stop darkfid subscribe task if it exists
  181. if let Some(task) = subscriber_task {
  182. info!(target: "explorerd", "Stopping darkfid subscriber...");
  183. task.stop().await;
  184. }
  185. info!(target: "explorerd", "Stopping JSON-RPC client...");
  186. let _ = explorer.darkfid_client.stop().await;
  187. Ok(())
  188. }
  189. /// Synchronizes blocks from the `darkfid` daemon.
  190. async fn sync_blocks(explorer: Arc<Explorerd>, reset: bool) -> Result<()> {
  191. info!(target: "explorerd", "Syncing blocks from darkfid...");
  192. if let Err(e) = explorer.service.sync_blocks(reset).await {
  193. let error_message = format!("Error syncing blocks: {e:?}");
  194. error!(target: "explorerd", "{error_message}");
  195. return Err(Error::DatabaseError(error_message));
  196. }
  197. Ok(())
  198. }
  199. /// Subscribes to new blocks from the `darkfid` daemon, returning optional
  200. /// stoppable tasks for the subscriber and listener.
  201. async fn subscribe_blocks(
  202. explorer: Arc<Explorerd>,
  203. endpoint: Url,
  204. executor: Arc<smol::Executor<'static>>,
  205. reset: bool,
  206. ) -> Result<(Option<StoppableTaskPtr>, Option<StoppableTaskPtr>)> {
  207. info!(target: "explorerd", "Subscribing to new blocks...");
  208. let result = match subscribe_sync_blocks(explorer.clone(), endpoint.clone(), executor.clone())
  209. .await
  210. {
  211. Ok((subscriber_task, listener_task)) => Ok((subscriber_task, listener_task)),
  212. Err(e) => {
  213. // If out of sync, sync blocks and retry subscription
  214. if e.to_string().contains("Blockchain not fully synced") {
  215. sync_blocks(explorer.clone(), reset).await?;
  216. subscribe_sync_blocks(explorer.clone(), endpoint.clone(), executor.clone()).await
  217. } else {
  218. let error_message = format!("Error setting up blocks subscriber: {e:?}");
  219. error!(target: "explorerd", "{error_message}");
  220. return Err(Error::DatabaseError(error_message));
  221. }
  222. }
  223. };
  224. let (subscriber_task, listener_task) = result?;
  225. info!(target: "explorerd", "Successfully subscribed to new blocks!");
  226. Ok((Some(subscriber_task), Some(listener_task)))
  227. }
  228. /// Logs a banner displaying the startup details of the DarkFi Explorer Node.
  229. fn log_started_banner(
  230. explorer: Arc<Explorerd>,
  231. config: &ExplorerNetworkConfig,
  232. args: &Args,
  233. config_path: &Path,
  234. no_sync: bool,
  235. ) {
  236. // Generate the `connected_node` string based on sync mode
  237. let connected_node = if no_sync {
  238. "Not connected".to_string()
  239. } else {
  240. config.endpoint.to_string().trim_end_matches('/').to_string()
  241. };
  242. // Log the banner
  243. info!(target: "explorerd", "========================================================================================");
  244. info!(target: "explorerd", " Started DarkFi Explorer Node{} ",
  245. if no_sync { " (No-Sync Mode)" } else { "" });
  246. info!(target: "explorerd", "========================================================================================");
  247. info!(target: "explorerd", " - Network: {}", args.network);
  248. info!(target: "explorerd", " - JSON-RPC Endpoint: {}", config.rpc.rpc_listen.to_string().trim_end_matches('/'));
  249. info!(target: "explorerd", " - Database: {}", config.database);
  250. info!(target: "explorerd", " - Configuration: {}", config_path.to_str().unwrap_or("Error: configuration path not found!"));
  251. info!(target: "explorerd", " - Reset Blocks: {}", if args.reset { "Yes" } else { "No" });
  252. info!(target: "explorerd", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
  253. info!(target: "explorerd", " - Synced Blocks: {}", explorer.service.db.blockchain.len());
  254. info!(target: "explorerd", " - Synced Transactions: {}", explorer.service.db.blockchain.len());
  255. info!(target: "explorerd", " - Connected Darkfi Node: {connected_node}");
  256. info!(target: "explorerd", "========================================================================================");
  257. }