main.rs 7.7 KB

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