main.rs 8.1 KB

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