main.rs 5.8 KB

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