main.rs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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::{
  19. collections::HashSet,
  20. fs,
  21. io::{stdin, stdout, Write},
  22. sync::Arc,
  23. };
  24. use log::{error, info};
  25. use smol::{lock::Mutex, stream::StreamExt};
  26. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  27. use url::Url;
  28. use darkfi::{
  29. async_daemonize, cli_desc,
  30. rpc::{
  31. client::RpcClient,
  32. server::{listen_and_serve, RequestHandler},
  33. },
  34. system::{StoppableTask, StoppableTaskPtr},
  35. util::path::expand_path,
  36. Error, Result,
  37. };
  38. use drk::walletdb::{WalletDb, WalletPtr};
  39. /// Crate errors
  40. mod error;
  41. /// JSON-RPC requests handler and methods
  42. mod rpc;
  43. mod rpc_blocks;
  44. use rpc_blocks::subscribe_blocks;
  45. mod rpc_statistics;
  46. mod rpc_transactions;
  47. /// Database functionality related to blocks
  48. mod blocks;
  49. /// Database functionality related to transactions
  50. mod transactions;
  51. /// Database functionality related to statistics
  52. mod statistics;
  53. const CONFIG_FILE: &str = "blockchain_explorer_config.toml";
  54. const CONFIG_FILE_CONTENTS: &str = include_str!("../blockchain_explorer_config.toml");
  55. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  56. #[serde(default)]
  57. #[structopt(name = "blockcahin-explorer", about = cli_desc!())]
  58. struct Args {
  59. #[structopt(short, long)]
  60. /// Configuration file to use
  61. config: Option<String>,
  62. #[structopt(short, long, default_value = "tcp://127.0.0.1:14567")]
  63. /// JSON-RPC listen URL
  64. rpc_listen: Url,
  65. #[structopt(long, default_value = "~/.local/darkfi/blockchain-explorer/daemon.db")]
  66. /// Path to daemon database
  67. db_path: String,
  68. #[structopt(long)]
  69. /// Password for the daemon database.
  70. /// If it's not present, daemon will prompt the user for it.
  71. db_pass: Option<String>,
  72. #[structopt(long)]
  73. /// Reset the databae and start syncing from first block
  74. reset: bool,
  75. #[structopt(short, long, default_value = "tcp://127.0.0.1:8340")]
  76. /// darkfid JSON-RPC endpoint
  77. endpoint: Url,
  78. #[structopt(short, long)]
  79. /// Set log file to ouput into
  80. log: Option<String>,
  81. #[structopt(short, parse(from_occurrences))]
  82. /// Increase verbosity (-vvv supported)
  83. verbose: u8,
  84. }
  85. /// Daemon structure
  86. pub struct BlockchainExplorer {
  87. /// Daemon database operations handler
  88. pub database: WalletPtr,
  89. /// JSON-RPC connection tracker
  90. pub rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  91. /// JSON-RPC client to execute requests to darkfid daemon
  92. pub rpc_client: RpcClient,
  93. }
  94. impl BlockchainExplorer {
  95. async fn new(
  96. db_path: String,
  97. db_pass: Option<String>,
  98. endpoint: Url,
  99. ex: Arc<smol::Executor<'static>>,
  100. ) -> Result<Self> {
  101. // Grab password
  102. let db_pass = match db_pass {
  103. Some(pass) => pass,
  104. None => {
  105. let mut pass = String::new();
  106. while pass.trim().is_empty() {
  107. info!(target: "blockchain-explorer", "Provide database passsword:");
  108. stdout().flush()?;
  109. stdin().read_line(&mut pass).unwrap_or(0);
  110. }
  111. pass.trim().to_string()
  112. }
  113. };
  114. // Script kiddies protection
  115. if db_pass == "changeme" {
  116. error!(target: "blockchain-explorer", "Please don't use default database password...");
  117. return Err(Error::ParseFailed("Default database password usage"))
  118. }
  119. // Initialize database
  120. let db_path = expand_path(&db_path)?;
  121. if !db_path.exists() {
  122. if let Some(parent) = db_path.parent() {
  123. fs::create_dir_all(parent)?;
  124. }
  125. }
  126. let database = match WalletDb::new(Some(db_path), Some(&db_pass)) {
  127. Ok(w) => w,
  128. Err(e) => {
  129. let err = format!("{e:?}");
  130. error!(target: "blockchain-explorer", "Error initializing database: {err}");
  131. return Err(Error::RusqliteError(err))
  132. }
  133. };
  134. // Initialize rpc client
  135. let rpc_client = RpcClient::new(endpoint, ex).await?;
  136. let explorer = Self { database, rpc_connections: Mutex::new(HashSet::new()), rpc_client };
  137. // Initialize all the database tables
  138. if let Err(e) = explorer.initialize_blocks().await {
  139. let err = format!("{e:?}");
  140. error!(target: "blockchain-explorer", "Error initializing blocks database table: {err}");
  141. return Err(Error::RusqliteError(err))
  142. }
  143. if let Err(e) = explorer.initialize_transactions().await {
  144. let err = format!("{e:?}");
  145. error!(target: "blockchain-explorer", "Error initializing transactions database table: {err}");
  146. return Err(Error::RusqliteError(err))
  147. }
  148. // TODO: Map deployed contracts to their corresponding files with sql table and retrieval methods
  149. Ok(explorer)
  150. }
  151. }
  152. async_daemonize!(realmain);
  153. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  154. info!(target: "blockchain-explorer", "Initializing DarkFi blockchain explorer node...");
  155. let explorer =
  156. BlockchainExplorer::new(args.db_path, args.db_pass, args.endpoint.clone(), ex.clone())
  157. .await?;
  158. let explorer = Arc::new(explorer);
  159. info!(target: "blockchain-explorer", "Node initialized successfully!");
  160. // JSON-RPC server
  161. info!(target: "blockchain-explorer", "Starting JSON-RPC server");
  162. // Here we create a task variable so we can manually close the
  163. // task later.
  164. let rpc_task = StoppableTask::new();
  165. let explorer_ = explorer.clone();
  166. rpc_task.clone().start(
  167. listen_and_serve(args.rpc_listen, explorer.clone(), None, ex.clone()),
  168. |res| async move {
  169. match res {
  170. Ok(()) | Err(Error::RpcServerStopped) => explorer_.stop_connections().await,
  171. Err(e) => error!(target: "blockchain-explorer", "Failed starting sync JSON-RPC server: {}", e),
  172. }
  173. },
  174. Error::RpcServerStopped,
  175. ex.clone(),
  176. );
  177. // Sync blocks
  178. info!(target: "blockchain-explorer", "Syncing blocks from darkfid...");
  179. if let Err(e) = explorer.sync_blocks(args.reset).await {
  180. let err = format!("{e:?}");
  181. error!(target: "blockchain-explorer", "Error syncing blocks: {err}");
  182. return Err(Error::RusqliteError(err))
  183. }
  184. info!(target: "blockchain-explorer", "Subscribing to new blocks...");
  185. let (subscriber_task, listener_task) = match subscribe_blocks(
  186. explorer.clone(),
  187. args.endpoint,
  188. ex.clone(),
  189. )
  190. .await
  191. {
  192. Ok(pair) => pair,
  193. Err(e) => {
  194. let err = format!("{e:?}");
  195. error!(target: "blockchain-explorer", "Error while setting up blocks subscriber: {err}");
  196. return Err(Error::RusqliteError(err))
  197. }
  198. };
  199. // Signal handling for graceful termination.
  200. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  201. signals_handler.wait_termination(signals_task).await?;
  202. info!(target: "blockchain-explorer", "Caught termination signal, cleaning up and exiting...");
  203. info!(target: "blockchain-explorer", "Stopping JSON-RPC server...");
  204. rpc_task.stop().await;
  205. info!(target: "blockchain-explorer", "Stopping darkfid listener...");
  206. listener_task.stop().await;
  207. info!(target: "blockchain-explorer", "Stopping darkfid subscriber...");
  208. subscriber_task.stop().await;
  209. info!(target: "blockchain-explorer", "Stopping JSON-RPC client...");
  210. explorer.rpc_client.stop().await;
  211. Ok(())
  212. }