main.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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::{HashMap, HashSet},
  20. sync::Arc,
  21. };
  22. use log::{error, info};
  23. use smol::{lock::Mutex, stream::StreamExt};
  24. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  25. use url::Url;
  26. use darkfi::{
  27. async_daemonize,
  28. blockchain::BlockInfo,
  29. cli_desc,
  30. net::{settings::SettingsOpt, P2pPtr},
  31. rpc::{jsonrpc::JsonSubscriber, server::listen_and_serve},
  32. system::{StoppableTask, StoppableTaskPtr},
  33. util::time::TimeKeeper,
  34. validator::{Validator, ValidatorConfig, ValidatorPtr},
  35. Error, Result,
  36. };
  37. use darkfi_contract_test_harness::vks;
  38. #[cfg(test)]
  39. mod tests;
  40. mod error;
  41. use error::{server_error, RpcError};
  42. /// JSON-RPC requests handler and methods
  43. mod rpc;
  44. mod rpc_blockchain;
  45. mod rpc_tx;
  46. /// Validator async tasks
  47. mod task;
  48. use task::sync::sync_task;
  49. /// P2P net protocols
  50. mod proto;
  51. /// Utility functions
  52. mod utils;
  53. use utils::{genesis_txs_total, spawn_consensus_p2p, spawn_sync_p2p};
  54. const CONFIG_FILE: &str = "darkfid_config.toml";
  55. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfid_config.toml");
  56. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  57. #[serde(default)]
  58. #[structopt(name = "darkfid", about = cli_desc!())]
  59. struct Args {
  60. #[structopt(short, long)]
  61. /// Configuration file to use
  62. config: Option<String>,
  63. #[structopt(long, default_value = "tcp://127.0.0.1:8340")]
  64. /// JSON-RPC listen URL
  65. rpc_listen: Url,
  66. #[structopt(long)]
  67. /// Participate in the consensus protocol
  68. consensus: bool,
  69. #[structopt(long)]
  70. /// Skip syncing process and start node right away
  71. skip_sync: bool,
  72. /// Syncing network settings
  73. #[structopt(flatten)]
  74. sync_net: SettingsOpt,
  75. /// Consensus network settings
  76. #[structopt(flatten)]
  77. consensus_net: SettingsOpt,
  78. #[structopt(long)]
  79. /// Enable testing mode for local testing
  80. testing_mode: bool,
  81. #[structopt(short, long)]
  82. /// Set log file to ouput into
  83. log: Option<String>,
  84. #[structopt(short, parse(from_occurrences))]
  85. /// Increase verbosity (-vvv supported)
  86. verbose: u8,
  87. }
  88. /// Daemon structure
  89. pub struct Darkfid {
  90. /// Syncing P2P network pointer
  91. sync_p2p: P2pPtr,
  92. /// Optional consensus P2P network pointer
  93. consensus_p2p: Option<P2pPtr>,
  94. /// Validator(node) pointer
  95. validator: ValidatorPtr,
  96. /// A map of various subscribers exporting live info from the blockchain
  97. subscribers: HashMap<&'static str, JsonSubscriber>,
  98. /// JSON-RPC connection tracker
  99. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  100. }
  101. impl Darkfid {
  102. pub async fn new(
  103. sync_p2p: P2pPtr,
  104. consensus_p2p: Option<P2pPtr>,
  105. validator: ValidatorPtr,
  106. subscribers: HashMap<&'static str, JsonSubscriber>,
  107. ) -> Self {
  108. Self {
  109. sync_p2p,
  110. consensus_p2p,
  111. validator,
  112. subscribers,
  113. rpc_connections: Mutex::new(HashSet::new()),
  114. }
  115. }
  116. }
  117. async_daemonize!(realmain);
  118. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  119. info!(target: "darkfid", "Initializing DarkFi node...");
  120. if args.testing_mode {
  121. info!(target: "darkfid", "Node is configured to run in testing mode!");
  122. }
  123. // NOTE: everything is dummy for now
  124. // FIXME: The VKS should only ever have to be generated on initial run.
  125. // Do not use the precompiles for actual production code.
  126. // Initialize or open sled database
  127. let sled_db = sled::Config::new().temporary(true).open()?;
  128. let (_, vks) = vks::read_or_gen_vks_and_pks()?;
  129. vks::inject(&sled_db, &vks)?;
  130. // Initialize validator configuration
  131. let genesis_block = BlockInfo::default();
  132. let genesis_txs_total = genesis_txs_total(&genesis_block.txs)?;
  133. let time_keeper = TimeKeeper::new(genesis_block.header.timestamp, 10, 90, 0);
  134. let config = ValidatorConfig::new(
  135. time_keeper,
  136. genesis_block,
  137. genesis_txs_total,
  138. vec![],
  139. args.testing_mode,
  140. );
  141. // Initialize validator
  142. let validator = Validator::new(&sled_db, config).await?;
  143. // Here we initialize various subscribers that can export live blockchain/consensus data.
  144. let mut subscribers = HashMap::new();
  145. subscribers.insert("blocks", JsonSubscriber::new("blockchain.subscribe_blocks"));
  146. subscribers.insert("txs", JsonSubscriber::new("blockchain.subscribe_txs"));
  147. if args.consensus {
  148. subscribers.insert("proposals", JsonSubscriber::new("blockchain.subscribe_proposals"));
  149. }
  150. // Initialize syncing P2P network
  151. let sync_p2p =
  152. spawn_sync_p2p(&args.sync_net.into(), &validator, &subscribers, ex.clone()).await;
  153. // Initialize consensus P2P network
  154. let consensus_p2p = if args.consensus {
  155. Some(
  156. spawn_consensus_p2p(&args.consensus_net.into(), &validator, &subscribers, ex.clone())
  157. .await,
  158. )
  159. } else {
  160. None
  161. };
  162. // Initialize node
  163. let darkfid =
  164. Darkfid::new(sync_p2p.clone(), consensus_p2p.clone(), validator.clone(), subscribers).await;
  165. let darkfid = Arc::new(darkfid);
  166. info!(target: "darkfid", "Node initialized successfully!");
  167. // JSON-RPC server
  168. info!(target: "darkfid", "Starting JSON-RPC server");
  169. // Here we create a task variable so we can manually close the
  170. // task later. P2P tasks don't need this since it has its own
  171. // stop() function to shut down, also terminating the task we
  172. // created for it.
  173. let rpc_task = StoppableTask::new();
  174. rpc_task.clone().start(
  175. listen_and_serve(args.rpc_listen, darkfid.clone(), None, ex.clone()),
  176. |res| async {
  177. match res {
  178. Ok(()) | Err(Error::RpcServerStopped) => { /* Do nothing */ }
  179. Err(e) => error!(target: "darkfid", "Failed starting sync JSON-RPC server: {}", e),
  180. }
  181. },
  182. Error::RpcServerStopped,
  183. ex.clone(),
  184. );
  185. info!(target: "darkfid", "Starting sync P2P network");
  186. sync_p2p.clone().start().await?;
  187. // Consensus protocol
  188. if args.consensus {
  189. info!("Starting consensus P2P network");
  190. let consensus_p2p = consensus_p2p.clone().unwrap();
  191. consensus_p2p.clone().start().await?;
  192. } else {
  193. info!("Not starting consensus P2P network");
  194. }
  195. // Sync blockchain
  196. if !args.skip_sync {
  197. sync_task(&darkfid).await?;
  198. } else {
  199. darkfid.validator.write().await.synced = true;
  200. }
  201. // Clean node pending transactions
  202. darkfid.validator.write().await.purge_pending_txs().await?;
  203. // Signal handling for graceful termination.
  204. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  205. signals_handler.wait_termination(signals_task).await?;
  206. info!(target: "darkfid", "Caught termination signal, cleaning up and exiting...");
  207. info!(target: "darkfid", "Stopping JSON-RPC server...");
  208. rpc_task.stop().await;
  209. info!(target: "darkfid", "Stopping syncing P2P network...");
  210. sync_p2p.stop().await;
  211. if args.consensus {
  212. info!(target: "darkfid", "Stopping consensus P2P network...");
  213. consensus_p2p.unwrap().stop().await;
  214. }
  215. info!(target: "darkfid", "Flushing sled database...");
  216. let flushed_bytes = sled_db.flush_async().await?;
  217. info!(target: "darkfid", "Flushed {} bytes", flushed_bytes);
  218. Ok(())
  219. }