main.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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::sync::Arc;
  19. use smol::{fs::read_to_string, stream::StreamExt};
  20. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  21. use tracing::{debug, error, info};
  22. use darkfi::{
  23. async_daemonize,
  24. blockchain::BlockInfo,
  25. cli_desc,
  26. net::settings::SettingsOpt,
  27. rpc::settings::RpcSettingsOpt,
  28. util::{
  29. encoding::base64,
  30. path::{expand_path, get_config_path},
  31. },
  32. validator::{Validator, ValidatorConfig},
  33. Error, Result,
  34. };
  35. use darkfi_sdk::crypto::keypair::Network;
  36. use darkfi_serial::deserialize_async;
  37. use darkfid::{task::consensus::ConsensusInitTaskConfig, Darkfid};
  38. const CONFIG_FILE: &str = "darkfid_config.toml";
  39. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfid_config.toml");
  40. /// Note:
  41. /// If you change these don't forget to remove their corresponding database folder,
  42. /// since if it already has a genesis block, provided one is ignored.
  43. const GENESIS_BLOCK_LOCALNET: &str = include_str!("../genesis_block_localnet");
  44. const GENESIS_BLOCK_TESTNET: &str = include_str!("../genesis_block_testnet");
  45. const GENESIS_BLOCK_MAINNET: &str = include_str!("../genesis_block_mainnet");
  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(short, long, default_value = "testnet")]
  54. /// Blockchain network to use
  55. network: String,
  56. #[structopt(short, long)]
  57. /// Reset validator state to given block height
  58. reset: Option<u32>,
  59. #[structopt(short, long)]
  60. /// Purge pending sync headers
  61. purge_sync: bool,
  62. #[structopt(long)]
  63. /// Fully validates existing blockchain state
  64. validate: bool,
  65. #[structopt(long)]
  66. /// Fully rebuild the difficulties database based on existing blockchain state
  67. rebuild_difficulties: 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. #[derive(Clone, Debug, serde::Deserialize, structopt::StructOpt, structopt_toml::StructOptToml)]
  76. #[structopt()]
  77. /// Defines a blockchain network configuration.
  78. /// Default values correspond to a local network.
  79. pub struct BlockchainNetwork {
  80. #[structopt(long, default_value = "~/.local/share/darkfi/darkfid/localnet")]
  81. /// Path to blockchain database
  82. database: String,
  83. #[structopt(long, default_value = "3")]
  84. /// Confirmation threshold, denominated by number of blocks
  85. threshold: usize,
  86. #[structopt(long, default_value = "120")]
  87. /// PoW block production target, in seconds
  88. pow_target: u32,
  89. #[structopt(long)]
  90. /// Optional fixed PoW difficulty, used for testing
  91. pow_fixed_difficulty: Option<usize>,
  92. #[structopt(long)]
  93. /// Skip syncing process and start node right away
  94. skip_sync: bool,
  95. #[structopt(long)]
  96. /// Disable transaction's fee verification, used for testing
  97. skip_fees: bool,
  98. #[structopt(long)]
  99. /// Optional sync checkpoint height
  100. checkpoint_height: Option<u32>,
  101. #[structopt(long)]
  102. /// Optional sync checkpoint hash
  103. checkpoint: Option<String>,
  104. #[structopt(long)]
  105. /// Garbage collection task transactions batch size
  106. txs_batch_size: Option<usize>,
  107. #[structopt(flatten)]
  108. /// P2P network settings
  109. net: SettingsOpt,
  110. #[structopt(flatten)]
  111. /// Main server JSON-RPC settings
  112. rpc: RpcSettingsOpt,
  113. #[structopt(flatten)]
  114. /// Management server JSON-RPC settings
  115. management_rpc: RpcSettingsOpt,
  116. #[structopt(skip)]
  117. /// Stratum server JSON-RPC settings (optional)
  118. stratum_rpc: Option<RpcSettingsOpt>,
  119. #[structopt(skip)]
  120. /// Merge mining server JSON-RPC settings (optional)
  121. mm_rpc: Option<RpcSettingsOpt>,
  122. }
  123. async_daemonize!(realmain);
  124. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  125. info!(target: "darkfid", "Initializing DarkFi node...");
  126. // Grab blockchain network configuration
  127. let ((network, blockchain_config), genesis_block) = match args.network.as_str() {
  128. "localnet" => {
  129. (parse_blockchain_config(args.config, "localnet").await?, GENESIS_BLOCK_LOCALNET)
  130. }
  131. "testnet" => {
  132. (parse_blockchain_config(args.config, "testnet").await?, GENESIS_BLOCK_TESTNET)
  133. }
  134. "mainnet" => {
  135. (parse_blockchain_config(args.config, "mainnet").await?, GENESIS_BLOCK_MAINNET)
  136. }
  137. _ => {
  138. error!("Unsupported chain `{}`", args.network);
  139. return Err(Error::UnsupportedChain)
  140. }
  141. };
  142. // Parse the genesis block
  143. let bytes = base64::decode(genesis_block.trim()).unwrap();
  144. let genesis_block: BlockInfo = deserialize_async(&bytes).await?;
  145. // Initialize or open sled database
  146. let db_path = expand_path(&blockchain_config.database)?;
  147. let sled_db = sled_overlay::sled::open(&db_path)?;
  148. // Initialize validator configuration
  149. let pow_fixed_difficulty = if let Some(diff) = blockchain_config.pow_fixed_difficulty {
  150. info!(target: "darkfid", "Node is configured to run with fixed PoW difficulty: {diff}");
  151. Some(diff.into())
  152. } else {
  153. None
  154. };
  155. let config = ValidatorConfig {
  156. confirmation_threshold: blockchain_config.threshold,
  157. pow_target: blockchain_config.pow_target,
  158. pow_fixed_difficulty,
  159. genesis_block,
  160. verify_fees: !blockchain_config.skip_fees,
  161. };
  162. // Check if reset was requested
  163. if let Some(height) = args.reset {
  164. info!(target: "darkfid", "Node will reset validator state to height: {height}");
  165. let validator = Validator::new(&sled_db, &config).await?;
  166. validator.write().await.reset_to_height(height).await?;
  167. info!(target: "darkfid", "Validator state reset successfully!");
  168. return Ok(())
  169. }
  170. // Check if sync headers purge was requested
  171. if args.purge_sync {
  172. info!(target: "darkfid", "Node will purge all pending sync headers.");
  173. let validator = Validator::new(&sled_db, &config).await?;
  174. validator.read().await.blockchain.headers.remove_all_sync()?;
  175. info!(target: "darkfid", "Validator pending sync headers purged successfully!");
  176. return Ok(())
  177. }
  178. // Check if validate was requested
  179. if args.validate {
  180. info!(target: "darkfid", "Node will validate existing blockchain state.");
  181. let validator = Validator::new(&sled_db, &config).await?;
  182. validator
  183. .read()
  184. .await
  185. .validate_blockchain(config.pow_target, config.pow_fixed_difficulty)
  186. .await?;
  187. info!(target: "darkfid", "Validator blockchain state validated successfully!");
  188. return Ok(())
  189. }
  190. // Check if rebuild difficulties was requested
  191. if args.rebuild_difficulties {
  192. info!(target: "darkfid", "Node will rebuild difficulties of existing blockchain state.");
  193. let validator = Validator::new(&sled_db, &config).await?;
  194. validator
  195. .read()
  196. .await
  197. .rebuild_block_difficulties(config.pow_target, config.pow_fixed_difficulty)
  198. .await?;
  199. info!(target: "darkfid", "Validator difficulties rebuilt successfully!");
  200. return Ok(())
  201. }
  202. let p2p_settings: darkfi::net::Settings =
  203. (env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), blockchain_config.net).try_into()?;
  204. // Generate the daemon
  205. let daemon = Darkfid::init(
  206. network,
  207. &sled_db,
  208. &config,
  209. &p2p_settings,
  210. &blockchain_config.txs_batch_size,
  211. &ex,
  212. )
  213. .await?;
  214. // Start the daemon
  215. let config = ConsensusInitTaskConfig {
  216. skip_sync: blockchain_config.skip_sync,
  217. checkpoint_height: blockchain_config.checkpoint_height,
  218. checkpoint: blockchain_config.checkpoint,
  219. };
  220. daemon
  221. .start(
  222. &ex,
  223. &blockchain_config.rpc.into(),
  224. &blockchain_config.management_rpc.into(),
  225. &blockchain_config.stratum_rpc.map(|stratum_rpc_opts| stratum_rpc_opts.into()),
  226. &blockchain_config.mm_rpc.map(|mm_rpc_opts| mm_rpc_opts.into()),
  227. &config,
  228. )
  229. .await?;
  230. // Signal handling for graceful termination.
  231. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  232. signals_handler.wait_termination(signals_task).await?;
  233. info!(target: "darkfid", "Caught termination signal, cleaning up and exiting...");
  234. daemon.stop().await?;
  235. info!(target: "darkfid", "Shut down successfully");
  236. Ok(())
  237. }
  238. /// Auxiliary function to parse darkfid configuration file and extract requested
  239. /// blockchain network config.
  240. pub async fn parse_blockchain_config(
  241. config: Option<String>,
  242. network: &str,
  243. ) -> Result<(Network, BlockchainNetwork)> {
  244. // Grab network prefix
  245. let used_net = match network {
  246. "mainnet" | "localnet" => Network::Mainnet,
  247. "testnet" => Network::Testnet,
  248. _ => return Err(Error::ParseFailed("Invalid blockchain network")),
  249. };
  250. // Grab config path
  251. let config_path = get_config_path(config, CONFIG_FILE)?;
  252. debug!(target: "darkfid", "Parsing configuration file: {config_path:?}");
  253. // Parse TOML file contents
  254. let contents = read_to_string(&config_path).await?;
  255. let contents: toml::Value = match toml::from_str(&contents) {
  256. Ok(v) => v,
  257. Err(e) => {
  258. error!(target: "darkfid", "Failed parsing TOML config: {e}");
  259. return Err(Error::ParseFailed("Failed parsing TOML config"))
  260. }
  261. };
  262. // Grab requested network config
  263. let Some(table) = contents.as_table() else { return Err(Error::ParseFailed("TOML not a map")) };
  264. let Some(network_configs) = table.get("network_config") else {
  265. return Err(Error::ParseFailed("TOML does not contain network configurations"))
  266. };
  267. let Some(network_configs) = network_configs.as_table() else {
  268. return Err(Error::ParseFailed("`network_config` not a map"))
  269. };
  270. let Some(network_config) = network_configs.get(network) else {
  271. return Err(Error::ParseFailed("TOML does not contain requested network configuration"))
  272. };
  273. let network_config = toml::to_string(&network_config).unwrap();
  274. let network_config =
  275. match BlockchainNetwork::from_iter_with_toml::<Vec<String>>(&network_config, vec![]) {
  276. Ok(v) => v,
  277. Err(e) => {
  278. error!(target: "darkfid", "Failed parsing requested network configuration: {e}");
  279. return Err(Error::ParseFailed("Failed parsing requested network configuration"))
  280. }
  281. };
  282. debug!(target: "darkfid", "Parsed network configuration: {network_config:?}");
  283. Ok((used_net, network_config))
  284. }