main.rs 6.5 KB

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