main.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 log::{error, info};
  20. use smol::{lock::Mutex, stream::StreamExt};
  21. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  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. info!(target: "explorerd", "Syncing blocks from darkfid...");
  162. if let Err(e) = explorer.service.sync_blocks(args.reset).await {
  163. let error_message = format!("Error syncing blocks: {:?}", e);
  164. error!(target: "explorerd", "{error_message}");
  165. return Err(Error::DatabaseError(error_message));
  166. }
  167. // Subscribe blocks
  168. info!(target: "explorerd", "Subscribing to new blocks...");
  169. match subscribe_sync_blocks(explorer.clone(), config.endpoint.clone(), ex.clone()).await {
  170. Ok((sub_task, lst_task)) => {
  171. subscriber_task = Some(sub_task);
  172. listener_task = Some(lst_task);
  173. }
  174. Err(e) => {
  175. let error_message = format!("Error setting up blocks subscriber: {:?}", e);
  176. error!(target: "explorerd", "{error_message}");
  177. return Err(Error::DatabaseError(error_message));
  178. }
  179. };
  180. }
  181. log_started_banner(explorer.clone(), &config, &args, &config_path, args.no_sync);
  182. info!(target: "explorerd::", "All is good. Waiting for block notifications...");
  183. // Signal handling for graceful termination.
  184. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  185. signals_handler.wait_termination(signals_task).await?;
  186. info!(target: "explorerd", "Caught termination signal, cleaning up and exiting...");
  187. info!(target: "explorerd", "Stopping JSON-RPC server...");
  188. rpc_task.stop().await;
  189. // Stop darkfid listener task if it exists
  190. if let Some(task) = listener_task {
  191. info!(target: "explorerd", "Stopping darkfid listener...");
  192. task.stop().await;
  193. }
  194. // Stop darkfid subscribe task if it exists
  195. if let Some(task) = subscriber_task {
  196. info!(target: "explorerd", "Stopping darkfid subscriber...");
  197. task.stop().await;
  198. }
  199. info!(target: "explorerd", "Stopping JSON-RPC client...");
  200. let _ = explorer.darkfid_client.stop().await;
  201. Ok(())
  202. }
  203. /// Logs a banner displaying the startup details of the DarkFi Explorer Node.
  204. fn log_started_banner(
  205. explorer: Arc<Explorerd>,
  206. config: &ExplorerNetworkConfig,
  207. args: &Args,
  208. config_path: &Path,
  209. no_sync: bool,
  210. ) {
  211. // Generate the `connected_node` string based on sync mode
  212. let connected_node = if no_sync {
  213. "Not connected".to_string()
  214. } else {
  215. config.endpoint.to_string().trim_end_matches('/').to_string()
  216. };
  217. // Log the banner
  218. info!(target: "explorerd", "========================================================================================");
  219. info!(target: "explorerd", " Started DarkFi Explorer Node{} ",
  220. if no_sync { " (No-Sync Mode)" } else { "" });
  221. info!(target: "explorerd", "========================================================================================");
  222. info!(target: "explorerd", " - Network: {}", args.network);
  223. info!(target: "explorerd", " - JSON-RPC Endpoint: {}", config.rpc.rpc_listen.to_string().trim_end_matches('/'));
  224. info!(target: "explorerd", " - Database: {}", config.database);
  225. info!(target: "explorerd", " - Configuration: {}", config_path.to_str().unwrap_or("Error: configuration path not found!"));
  226. info!(target: "explorerd", " - Reset Blocks: {}", if args.reset { "Yes" } else { "No" });
  227. info!(target: "explorerd", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
  228. info!(target: "explorerd", " - Synced Blocks: {}", explorer.service.db.blockchain.len());
  229. info!(target: "explorerd", " - Synced Transactions: {}", explorer.service.db.blockchain.len());
  230. info!(target: "explorerd", " - Connected Darkfi Node: {}", connected_node);
  231. info!(target: "explorerd", "========================================================================================");
  232. }