main.rs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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},
  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
  38. mod rpc;
  39. mod rpc_blockchain;
  40. /// Utility functions
  41. mod utils;
  42. use utils::genesis_txs_total;
  43. const CONFIG_FILE: &str = "darkfid_config.toml";
  44. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfid_config.toml");
  45. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  46. #[serde(default)]
  47. #[structopt(name = "darkfid", about = cli_desc!())]
  48. struct Args {
  49. #[structopt(short, long)]
  50. /// Configuration file to use
  51. config: Option<String>,
  52. #[structopt(long, default_value = "tcp://127.0.0.1:8340")]
  53. /// JSON-RPC listen URL
  54. rpc_listen: Url,
  55. #[structopt(long)]
  56. /// Participate in the consensus protocol
  57. consensus: bool,
  58. /// Syncing network settings
  59. #[structopt(flatten)]
  60. sync_net: SettingsOpt,
  61. /// Consensus network settings
  62. #[structopt(flatten)]
  63. consensus_net: SettingsOpt,
  64. #[structopt(long)]
  65. /// Enable testing mode for local testing
  66. testing_mode: bool,
  67. #[structopt(short, long)]
  68. /// Set log file to ouput into
  69. log: Option<String>,
  70. #[structopt(short, parse(from_occurrences))]
  71. /// Increase verbosity (-vvv supported)
  72. verbose: u8,
  73. }
  74. pub struct Darkfid {
  75. sync_p2p: P2pPtr,
  76. consensus_p2p: Option<P2pPtr>,
  77. validator: ValidatorPtr,
  78. }
  79. impl Darkfid {
  80. pub async fn new(
  81. sync_p2p: P2pPtr,
  82. consensus_p2p: Option<P2pPtr>,
  83. validator: ValidatorPtr,
  84. ) -> Self {
  85. Self { sync_p2p, consensus_p2p, validator }
  86. }
  87. }
  88. async_daemonize!(realmain);
  89. async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
  90. info!("Initializing DarkFi node...");
  91. if args.testing_mode {
  92. info!("Node is configured to run in testing mode!");
  93. }
  94. // Initialize syncing P2P network
  95. let sync_p2p = P2p::new(args.sync_net.into()).await;
  96. // Initialize consensus P2P network
  97. let consensus_p2p = {
  98. if !args.consensus {
  99. None
  100. } else {
  101. Some(P2p::new(args.consensus_net.into()).await)
  102. }
  103. };
  104. // NOTE: everything is dummy for now
  105. // Initialize or open sled database
  106. let sled_db = sled::Config::new().temporary(true).open()?;
  107. vks::inject(&sled_db)?;
  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 node
  122. let darkfid = Darkfid::new(sync_p2p, consensus_p2p, validator).await;
  123. let darkfid = Arc::new(darkfid);
  124. info!("Node initialized successfully!");
  125. // JSON-RPC server
  126. info!("Starting JSON-RPC server");
  127. let _ex = ex.clone();
  128. ex.spawn(listen_and_serve(args.rpc_listen, darkfid.clone(), _ex)).detach();
  129. // Signal handling for graceful termination.
  130. let (signals_handler, signals_task) = SignalHandler::new()?;
  131. signals_handler.wait_termination(signals_task).await?;
  132. info!("Caught termination signal, cleaning up and exiting...");
  133. info!("Stopping syncing P2P network...");
  134. darkfid.sync_p2p.stop().await;
  135. if args.consensus {
  136. info!("Stopping consensus P2P network...");
  137. darkfid.consensus_p2p.clone().unwrap().stop().await;
  138. }
  139. info!("Flushing sled database...");
  140. let flushed_bytes = sled_db.flush_async().await?;
  141. info!("Flushed {} bytes", flushed_bytes);
  142. Ok(())
  143. }