main.rs 7.5 KB

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