main.rs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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::{
  26. client::RpcClient,
  27. server::{listen_and_serve, RequestHandler},
  28. },
  29. system::{StoppableTask, StoppableTaskPtr},
  30. util::path::get_config_path,
  31. Error, Result,
  32. };
  33. use crate::{
  34. config::ExplorerNetworkConfig, rpc::blocks::subscribe_blocks, service::ExplorerService,
  35. };
  36. /// Configuration management across multiple networks (localnet, testnet, mainnet)
  37. mod config;
  38. /// Manages JSON-RPC interactions for the explorer
  39. mod rpc;
  40. /// Core logic for block synchronization, chain data access, metadata storage/retrieval,
  41. /// and statistics computation
  42. mod service;
  43. /// Manages persistent storage for blockchain, contracts, metrics, and metadata
  44. mod store;
  45. /// Crate errors
  46. mod error;
  47. /// Test utilities used for unit and integration testing
  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. }
  71. /// Defines a daemon structure responsible for handling incoming JSON-RPC requests and delegating them
  72. /// to the backend layer for processing. It provides a JSON-RPC interface for managing operations related to
  73. /// blocks, transactions, contracts, and metrics.
  74. ///
  75. /// Upon startup, the daemon initializes a background task to handle incoming JSON-RPC requests.
  76. /// This includes processing operations related to blocks, transactions, contracts, and metrics by
  77. /// delegating them to the backend and returning appropriate RPC responses. Additionally, the daemon
  78. /// synchronizes blocks from the `darkfid` daemon into the explorer database and subscribes
  79. /// to new blocks, ensuring that the local database remains updated in real-time.
  80. pub struct Explorerd {
  81. /// Explorer service instance
  82. pub service: ExplorerService,
  83. /// JSON-RPC connection tracker
  84. pub rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  85. /// JSON-RPC client to execute requests to darkfid daemon
  86. pub rpc_client: RpcClient,
  87. }
  88. impl Explorerd {
  89. /// Creates a new `BlockchainExplorer` instance.
  90. async fn new(db_path: String, endpoint: Url, ex: Arc<smol::Executor<'static>>) -> Result<Self> {
  91. // Initialize rpc client
  92. let rpc_client = RpcClient::new(endpoint.clone(), ex).await?;
  93. info!(target: "explorerd", "Connected to Darkfi node: {}", endpoint.to_string().trim_end_matches('/'));
  94. // Create explorer service
  95. let service = ExplorerService::new(db_path)?;
  96. // Initialize the explorer service
  97. service.init().await?;
  98. Ok(Self { rpc_connections: Mutex::new(HashSet::new()), rpc_client, service })
  99. }
  100. }
  101. async_daemonize!(realmain);
  102. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  103. info!(target: "explorerd", "Initializing DarkFi blockchain explorer node...");
  104. // Resolve the configuration path
  105. let config_path = get_config_path(args.config.clone(), CONFIG_FILE)?;
  106. // Get explorer network configuration
  107. let config: ExplorerNetworkConfig = (&config_path, &args.network).try_into()?;
  108. // Initialize the explorer daemon instance
  109. let explorer =
  110. Explorerd::new(config.database.clone(), config.endpoint.clone(), ex.clone()).await?;
  111. let explorer = Arc::new(explorer);
  112. info!(target: "explorerd", "Node initialized successfully!");
  113. // JSON-RPC server
  114. // Here we create a task variable so we can manually close the task later.
  115. let rpc_task = StoppableTask::new();
  116. let explorer_ = explorer.clone();
  117. rpc_task.clone().start(
  118. listen_and_serve(config.rpc.clone().into(), explorer.clone(), None, ex.clone()),
  119. |res| async move {
  120. match res {
  121. Ok(()) | Err(Error::RpcServerStopped) => explorer_.stop_connections().await,
  122. Err(e) => {
  123. error!(target: "explorerd", "Failed starting sync JSON-RPC server: {}", e)
  124. }
  125. }
  126. },
  127. Error::RpcServerStopped,
  128. ex.clone(),
  129. );
  130. info!(target: "explorerd", "Started JSON-RPC server: {}", config.rpc.rpc_listen.to_string().trim_end_matches("/"));
  131. // Sync blocks
  132. info!(target: "explorerd", "Syncing blocks from darkfid...");
  133. if let Err(e) = explorer.sync_blocks(args.reset).await {
  134. let error_message = format!("Error syncing blocks: {:?}", e);
  135. error!(target: "explorerd", "{error_message}");
  136. return Err(Error::DatabaseError(error_message));
  137. }
  138. // Subscribe blocks
  139. info!(target: "explorerd", "Subscribing to new blocks...");
  140. let (subscriber_task, listener_task) =
  141. match subscribe_blocks(explorer.clone(), config.endpoint.clone(), ex.clone()).await {
  142. Ok(pair) => pair,
  143. Err(e) => {
  144. let error_message = format!("Error setting up blocks subscriber: {:?}", e);
  145. error!(target: "explorerd", "{error_message}");
  146. return Err(Error::DatabaseError(error_message));
  147. }
  148. };
  149. log_started_banner(explorer.clone(), &config, &args, &config_path);
  150. info!(target: "explorerd::", "All is good. Waiting for block notifications...");
  151. // Signal handling for graceful termination.
  152. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  153. signals_handler.wait_termination(signals_task).await?;
  154. info!(target: "explorerd", "Caught termination signal, cleaning up and exiting...");
  155. info!(target: "explorerd", "Stopping JSON-RPC server...");
  156. rpc_task.stop().await;
  157. info!(target: "explorerd", "Stopping darkfid listener...");
  158. listener_task.stop().await;
  159. info!(target: "explorerd", "Stopping darkfid subscriber...");
  160. subscriber_task.stop().await;
  161. info!(target: "explorerd", "Stopping JSON-RPC client...");
  162. explorer.rpc_client.stop().await;
  163. Ok(())
  164. }
  165. /// Logs a banner displaying the startup details of the DarkFi Explorer Node.
  166. fn log_started_banner(
  167. explorer: Arc<Explorerd>,
  168. config: &ExplorerNetworkConfig,
  169. args: &Args,
  170. config_path: &Path,
  171. ) {
  172. info!(target: "explorerd", "========================================================================================");
  173. info!(target: "explorerd", " Started DarkFi Explorer Node ");
  174. info!(target: "explorerd", "========================================================================================");
  175. info!(target: "explorerd", " - Network: {}", args.network);
  176. info!(target: "explorerd", " - JSON-RPC Endpoint: {}", config.rpc.rpc_listen.to_string().trim_end_matches("/"));
  177. info!(target: "explorerd", " - Database: {}", config.database);
  178. info!(target: "explorerd", " - Configuration: {}", config_path.to_str().unwrap_or("Error: configuration path not found!"));
  179. info!(target: "explorerd", " - Reset Blocks: {}", if args.reset { "Yes" } else { "No" });
  180. info!(target: "explorerd", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
  181. info!(target: "explorerd", " - Synced Blocks: {}", explorer.service.db.blockchain.len());
  182. info!(target: "explorerd", " - Synced Transactions: {}", explorer.service.db.blockchain.len());
  183. info!(target: "explorerd", " - Connected Darkfi Node: {}", config.endpoint.to_string().trim_end_matches("/"));
  184. info!(target: "explorerd", "========================================================================================");
  185. }