main.rs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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 log::{debug, error, info};
  20. use smol::{fs::read_to_string, stream::StreamExt};
  21. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  22. use url::Url;
  23. use darkfi::{
  24. async_daemonize,
  25. blockchain::BlockInfo,
  26. cli_desc,
  27. net::settings::SettingsOpt,
  28. rpc::settings::RpcSettingsOpt,
  29. util::{
  30. encoding::base64,
  31. path::{expand_path, get_config_path},
  32. },
  33. validator::{Validator, ValidatorConfig},
  34. Error, Result,
  35. };
  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. /// Set log file to ouput into
  61. log: Option<String>,
  62. #[structopt(short, parse(from_occurrences))]
  63. /// Increase verbosity (-vvv supported)
  64. verbose: u8,
  65. }
  66. #[derive(Clone, Debug, serde::Deserialize, structopt::StructOpt, structopt_toml::StructOptToml)]
  67. #[structopt()]
  68. /// Defines a blockchain network configuration.
  69. /// Default values correspond to a local network.
  70. pub struct BlockchainNetwork {
  71. #[structopt(long, default_value = "~/.local/share/darkfi/darkfid/localnet")]
  72. /// Path to blockchain database
  73. database: String,
  74. #[structopt(long, default_value = "3")]
  75. /// Confirmation threshold, denominated by number of blocks
  76. threshold: usize,
  77. #[structopt(long)]
  78. /// minerd JSON-RPC endpoint
  79. minerd_endpoint: Option<Url>,
  80. #[structopt(skip)]
  81. /// Optional JSON-RPC settings for p2pool merge mining requests
  82. mm_rpc: Option<RpcSettingsOpt>,
  83. #[structopt(long, default_value = "10")]
  84. /// PoW block production target, in seconds
  85. pow_target: u32,
  86. #[structopt(long)]
  87. /// Optional fixed PoW difficulty, used for testing
  88. pow_fixed_difficulty: Option<usize>,
  89. #[structopt(long)]
  90. /// Wallet address to receive mining rewards
  91. recipient: Option<String>,
  92. #[structopt(long)]
  93. /// Optional contract spend hook to use in the mining reward
  94. spend_hook: Option<String>,
  95. #[structopt(long)]
  96. /// Optional user data to use in the mining reward
  97. user_data: Option<String>,
  98. #[structopt(long)]
  99. /// Skip syncing process and start node right away
  100. skip_sync: bool,
  101. #[structopt(long)]
  102. /// Disable transaction's fee verification, used for testing
  103. skip_fees: bool,
  104. #[structopt(long)]
  105. /// Optional sync checkpoint height
  106. checkpoint_height: Option<u32>,
  107. #[structopt(long)]
  108. /// Optional sync checkpoint hash
  109. checkpoint: Option<String>,
  110. #[structopt(long)]
  111. /// Optional bootstrap timestamp
  112. bootstrap: Option<u64>,
  113. #[structopt(long)]
  114. /// Garbage collection task transactions batch size
  115. txs_batch_size: Option<usize>,
  116. #[structopt(flatten)]
  117. /// P2P network settings
  118. net: SettingsOpt,
  119. #[structopt(flatten)]
  120. /// JSON-RPC settings
  121. rpc: 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 (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. // Compute the bootstrap timestamp
  146. let bootstrap = match blockchain_config.bootstrap {
  147. Some(b) => b,
  148. None => genesis_block.header.timestamp.inner(),
  149. };
  150. // Initialize or open sled database
  151. let db_path = expand_path(&blockchain_config.database)?;
  152. let sled_db = sled_overlay::sled::open(&db_path)?;
  153. // Initialize validator configuration
  154. let pow_fixed_difficulty = if let Some(diff) = blockchain_config.pow_fixed_difficulty {
  155. info!(target: "darkfid", "Node is configured to run with fixed PoW difficulty: {}", diff);
  156. Some(diff.into())
  157. } else {
  158. None
  159. };
  160. let config = ValidatorConfig {
  161. confirmation_threshold: blockchain_config.threshold,
  162. pow_target: blockchain_config.pow_target,
  163. pow_fixed_difficulty,
  164. genesis_block,
  165. verify_fees: !blockchain_config.skip_fees,
  166. };
  167. // Check if reset was requested
  168. if let Some(height) = args.reset {
  169. info!(target: "darkfid", "Node will reset validator state to height: {}", height);
  170. let validator = Validator::new(&sled_db, &config).await?;
  171. validator.reset_to_height(height).await?;
  172. info!(target: "darkfid", "Validator state reset successfully!");
  173. return Ok(())
  174. }
  175. // Generate the daemon
  176. let daemon = Darkfid::init(
  177. &sled_db,
  178. &config,
  179. &blockchain_config.net.into(),
  180. &blockchain_config.minerd_endpoint,
  181. &blockchain_config.txs_batch_size,
  182. &ex,
  183. )
  184. .await?;
  185. // Start the daemon
  186. let config = ConsensusInitTaskConfig {
  187. skip_sync: blockchain_config.skip_sync,
  188. checkpoint_height: blockchain_config.checkpoint_height,
  189. checkpoint: blockchain_config.checkpoint,
  190. miner: blockchain_config.minerd_endpoint.is_some(),
  191. recipient: blockchain_config.recipient,
  192. spend_hook: blockchain_config.spend_hook,
  193. user_data: blockchain_config.user_data,
  194. bootstrap,
  195. };
  196. daemon
  197. .start(
  198. &ex,
  199. &blockchain_config.rpc.into(),
  200. &blockchain_config.mm_rpc.map(|mm_rpc_opts| mm_rpc_opts.into()),
  201. &config,
  202. )
  203. .await?;
  204. // Signal handling for graceful termination.
  205. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  206. signals_handler.wait_termination(signals_task).await?;
  207. info!(target: "darkfid", "Caught termination signal, cleaning up and exiting...");
  208. daemon.stop().await?;
  209. info!(target: "darkfid", "Shut down successfully");
  210. Ok(())
  211. }
  212. /// Auxiliary function to parse darkfid configuration file and extract requested
  213. /// blockchain network config.
  214. pub async fn parse_blockchain_config(
  215. config: Option<String>,
  216. network: &str,
  217. ) -> Result<BlockchainNetwork> {
  218. // Grab config path
  219. let config_path = get_config_path(config, CONFIG_FILE)?;
  220. debug!(target: "darkfid", "Parsing configuration file: {:?}", config_path);
  221. // Parse TOML file contents
  222. let contents = read_to_string(&config_path).await?;
  223. let contents: toml::Value = match toml::from_str(&contents) {
  224. Ok(v) => v,
  225. Err(e) => {
  226. error!(target: "darkfid", "Failed parsing TOML config: {}", e);
  227. return Err(Error::ParseFailed("Failed parsing TOML config"))
  228. }
  229. };
  230. // Grab requested network config
  231. let Some(table) = contents.as_table() else { return Err(Error::ParseFailed("TOML not a map")) };
  232. let Some(network_configs) = table.get("network_config") else {
  233. return Err(Error::ParseFailed("TOML does not contain network configurations"))
  234. };
  235. let Some(network_configs) = network_configs.as_table() else {
  236. return Err(Error::ParseFailed("`network_config` not a map"))
  237. };
  238. let Some(network_config) = network_configs.get(network) else {
  239. return Err(Error::ParseFailed("TOML does not contain requested network configuration"))
  240. };
  241. let network_config = toml::to_string(&network_config).unwrap();
  242. let network_config =
  243. match BlockchainNetwork::from_iter_with_toml::<Vec<String>>(&network_config, vec![]) {
  244. Ok(v) => v,
  245. Err(e) => {
  246. error!(target: "darkfid", "Failed parsing requested network configuration: {}", e);
  247. return Err(Error::ParseFailed("Failed parsing requested network configuration"))
  248. }
  249. };
  250. debug!(target: "darkfid", "Parsed network configuration: {:?}", network_config);
  251. Ok(network_config)
  252. }