main.rs 6.6 KB

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