main.rs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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, sync::Arc};
  19. use log::{error, info};
  20. use sled_overlay::sled;
  21. use smol::{lock::Mutex, stream::StreamExt};
  22. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  23. use url::Url;
  24. use darkfi::{
  25. async_daemonize,
  26. blockchain::Blockchain,
  27. cli_desc,
  28. rpc::{
  29. client::RpcClient,
  30. server::{listen_and_serve, RequestHandler},
  31. },
  32. system::{StoppableTask, StoppableTaskPtr},
  33. util::path::expand_path,
  34. Error, Result,
  35. };
  36. /// Crate errors
  37. mod error;
  38. /// JSON-RPC requests handler and methods
  39. mod rpc;
  40. mod rpc_blocks;
  41. use rpc_blocks::subscribe_blocks;
  42. mod rpc_statistics;
  43. mod rpc_transactions;
  44. /// Database functionality related to blocks
  45. mod blocks;
  46. /// Database functionality related to transactions
  47. mod transactions;
  48. /// Database functionality related to statistics
  49. mod statistics;
  50. /// Test utilities used for unit and integration testing
  51. mod test_utils;
  52. const CONFIG_FILE: &str = "blockchain_explorer_config.toml";
  53. const CONFIG_FILE_CONTENTS: &str = include_str!("../blockchain_explorer_config.toml");
  54. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  55. #[serde(default)]
  56. #[structopt(name = "blockchain-explorer", about = cli_desc!())]
  57. struct Args {
  58. #[structopt(short, long)]
  59. /// Configuration file to use
  60. config: Option<String>,
  61. #[structopt(short, long, default_value = "tcp://127.0.0.1:14567")]
  62. /// JSON-RPC listen URL
  63. rpc_listen: Url,
  64. #[structopt(long, default_value = "~/.local/darkfi/blockchain-explorer/daemon.db")]
  65. /// Path to daemon database
  66. db_path: String,
  67. #[structopt(long)]
  68. /// Reset the database and start syncing from first block
  69. reset: bool,
  70. #[structopt(short, long, default_value = "tcp://127.0.0.1:8340")]
  71. /// darkfid JSON-RPC endpoint
  72. endpoint: Url,
  73. #[structopt(short, long)]
  74. /// Set log file to output into
  75. log: Option<String>,
  76. #[structopt(short, parse(from_occurrences))]
  77. /// Increase verbosity (-vvv supported)
  78. verbose: u8,
  79. }
  80. /// Structure represents the explorer database backed by a sled DB connection.
  81. pub struct ExplorerDb {
  82. /// Main pointer to the sled db connection
  83. pub sled_db: sled::Db,
  84. /// Explorer darkfid blockchain copy
  85. pub blockchain: Blockchain,
  86. }
  87. impl ExplorerDb {
  88. /// Creates a new `BlockExplorerDb` instance
  89. pub fn new(db_path: String) -> Result<ExplorerDb> {
  90. let db_path = expand_path(db_path.as_str())?;
  91. let sled_db = sled::open(&db_path)?;
  92. let blockchain = Blockchain::new(&sled_db)?;
  93. info!(target: "blockchain-explorer", "Initialized explorer database {}, block count: {}", db_path.display(), blockchain.len());
  94. Ok(ExplorerDb { sled_db, blockchain })
  95. }
  96. }
  97. /// Daemon structure
  98. pub struct Explorerd {
  99. /// Explorer database instance
  100. pub db: ExplorerDb,
  101. /// JSON-RPC connection tracker
  102. pub rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  103. /// JSON-RPC client to execute requests to darkfid daemon
  104. pub rpc_client: RpcClient,
  105. }
  106. impl Explorerd {
  107. /// Creates a new `BlockchainExplorer` instance.
  108. async fn new(db_path: String, endpoint: Url, ex: Arc<smol::Executor<'static>>) -> Result<Self> {
  109. // Initialize rpc client
  110. let rpc_client = RpcClient::new(endpoint.clone(), ex).await?;
  111. info!(target: "explorerd", "Created rpc client: {:?}", endpoint);
  112. // Initialize explorer database
  113. let explorer_db = ExplorerDb::new(db_path)?;
  114. Ok(Self { rpc_connections: Mutex::new(HashSet::new()), rpc_client, db: explorer_db })
  115. }
  116. }
  117. async_daemonize!(realmain);
  118. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  119. info!(target: "blockchain-explorer", "Initializing DarkFi blockchain explorer node...");
  120. let explorer = Explorerd::new(args.db_path, args.endpoint.clone(), ex.clone()).await?;
  121. let explorer = Arc::new(explorer);
  122. info!(target: "blockchain-explorer", "Node initialized successfully!");
  123. // JSON-RPC server
  124. info!(target: "blockchain-explorer", "Starting JSON-RPC server");
  125. // Here we create a task variable so we can manually close the task later.
  126. let rpc_task = StoppableTask::new();
  127. let explorer_ = explorer.clone();
  128. rpc_task.clone().start(
  129. listen_and_serve(args.rpc_listen, explorer.clone(), None, ex.clone()),
  130. |res| async move {
  131. match res {
  132. Ok(()) | Err(Error::RpcServerStopped) => explorer_.stop_connections().await,
  133. Err(e) => error!(target: "blockchain-explorer", "Failed starting sync JSON-RPC server: {}", e),
  134. }
  135. },
  136. Error::RpcServerStopped,
  137. ex.clone(),
  138. );
  139. // Sync blocks
  140. info!(target: "blockchain-explorer", "Syncing blocks from darkfid...");
  141. if let Err(e) = explorer.sync_blocks(args.reset).await {
  142. let error_message = format!("Error syncing blocks: {:?}", e);
  143. error!(target: "blockchain-explorer", "{error_message}");
  144. return Err(Error::DatabaseError(error_message));
  145. }
  146. // Subscribe blocks
  147. info!(target: "blockchain-explorer", "Subscribing to new blocks...");
  148. let (subscriber_task, listener_task) =
  149. match subscribe_blocks(explorer.clone(), args.endpoint, ex.clone()).await {
  150. Ok(pair) => pair,
  151. Err(e) => {
  152. let error_message = format!("Error setting up blocks subscriber: {:?}", e);
  153. error!(target: "blockchain-explorer", "{error_message}");
  154. return Err(Error::DatabaseError(error_message));
  155. }
  156. };
  157. // Signal handling for graceful termination.
  158. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  159. signals_handler.wait_termination(signals_task).await?;
  160. info!(target: "blockchain-explorer", "Caught termination signal, cleaning up and exiting...");
  161. info!(target: "blockchain-explorer", "Stopping JSON-RPC server...");
  162. rpc_task.stop().await;
  163. info!(target: "blockchain-explorer", "Stopping darkfid listener...");
  164. listener_task.stop().await;
  165. info!(target: "blockchain-explorer", "Stopping darkfid subscriber...");
  166. subscriber_task.stop().await;
  167. info!(target: "blockchain-explorer", "Stopping JSON-RPC client...");
  168. explorer.rpc_client.stop().await;
  169. Ok(())
  170. }