main.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. /// 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)]
  87. /// minerd JSON-RPC endpoint
  88. minerd_endpoint: Option<Url>,
  89. #[structopt(skip)]
  90. /// Optional JSON-RPC settings for p2pool merge mining requests
  91. mm_rpc: Option<RpcSettingsOpt>,
  92. #[structopt(long, default_value = "120")]
  93. /// PoW block production target, in seconds
  94. pow_target: u32,
  95. #[structopt(long)]
  96. /// Optional fixed PoW difficulty, used for testing
  97. pow_fixed_difficulty: Option<usize>,
  98. #[structopt(long)]
  99. /// Wallet address to receive mining rewards
  100. recipient: Option<String>,
  101. #[structopt(long)]
  102. /// Optional contract spend hook to use in the mining reward
  103. spend_hook: Option<String>,
  104. #[structopt(long)]
  105. /// Optional contract user data to use in the mining reward.
  106. /// This is not arbitrary data.
  107. user_data: Option<String>,
  108. #[structopt(long)]
  109. /// Skip syncing process and start node right away
  110. skip_sync: bool,
  111. #[structopt(long)]
  112. /// Disable transaction's fee verification, used for testing
  113. skip_fees: bool,
  114. #[structopt(long)]
  115. /// Optional sync checkpoint height
  116. checkpoint_height: Option<u32>,
  117. #[structopt(long)]
  118. /// Optional sync checkpoint hash
  119. checkpoint: Option<String>,
  120. #[structopt(long)]
  121. /// Optional bootstrap timestamp
  122. bootstrap: Option<u64>,
  123. #[structopt(long)]
  124. /// Garbage collection task transactions batch size
  125. txs_batch_size: Option<usize>,
  126. #[structopt(flatten)]
  127. /// P2P network settings
  128. net: SettingsOpt,
  129. #[structopt(flatten)]
  130. /// JSON-RPC settings
  131. rpc: RpcSettingsOpt,
  132. }
  133. async_daemonize!(realmain);
  134. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  135. info!(target: "darkfid", "Initializing DarkFi node...");
  136. // Grab blockchain network configuration
  137. let (blockchain_config, genesis_block) = match args.network.as_str() {
  138. "localnet" => {
  139. (parse_blockchain_config(args.config, "localnet").await?, GENESIS_BLOCK_LOCALNET)
  140. }
  141. "testnet" => {
  142. (parse_blockchain_config(args.config, "testnet").await?, GENESIS_BLOCK_TESTNET)
  143. }
  144. "mainnet" => {
  145. (parse_blockchain_config(args.config, "mainnet").await?, GENESIS_BLOCK_MAINNET)
  146. }
  147. _ => {
  148. error!("Unsupported chain `{}`", args.network);
  149. return Err(Error::UnsupportedChain)
  150. }
  151. };
  152. // Parse the genesis block
  153. let bytes = base64::decode(genesis_block.trim()).unwrap();
  154. let genesis_block: BlockInfo = deserialize_async(&bytes).await?;
  155. // Compute the bootstrap timestamp
  156. let bootstrap = match blockchain_config.bootstrap {
  157. Some(b) => b,
  158. None => genesis_block.header.timestamp.inner(),
  159. };
  160. // Initialize or open sled database
  161. let db_path = expand_path(&blockchain_config.database)?;
  162. let sled_db = sled_overlay::sled::open(&db_path)?;
  163. // Initialize validator configuration
  164. let pow_fixed_difficulty = if let Some(diff) = blockchain_config.pow_fixed_difficulty {
  165. info!(target: "darkfid", "Node is configured to run with fixed PoW difficulty: {diff}");
  166. Some(diff.into())
  167. } else {
  168. None
  169. };
  170. let config = ValidatorConfig {
  171. confirmation_threshold: blockchain_config.threshold,
  172. pow_target: blockchain_config.pow_target,
  173. pow_fixed_difficulty,
  174. genesis_block,
  175. verify_fees: !blockchain_config.skip_fees,
  176. };
  177. // Check if reset was requested
  178. if let Some(height) = args.reset {
  179. info!(target: "darkfid", "Node will reset validator state to height: {height}");
  180. let validator = Validator::new(&sled_db, &config).await?;
  181. validator.reset_to_height(height).await?;
  182. info!(target: "darkfid", "Validator state reset successfully!");
  183. return Ok(())
  184. }
  185. // Check if sync headers purge was requested
  186. if args.purge_sync {
  187. info!(target: "darkfid", "Node will purge all pending sync headers.");
  188. let validator = Validator::new(&sled_db, &config).await?;
  189. validator.blockchain.headers.remove_all_sync()?;
  190. info!(target: "darkfid", "Validator pending sync headers purged successfully!");
  191. return Ok(())
  192. }
  193. // Check if validate was requested
  194. if args.validate {
  195. info!(target: "darkfid", "Node will validate existing blockchain state.");
  196. let validator = Validator::new(&sled_db, &config).await?;
  197. validator.validate_blockchain(config.pow_target, config.pow_fixed_difficulty).await?;
  198. info!(target: "darkfid", "Validator blockchain state validated successfully!");
  199. return Ok(())
  200. }
  201. // Check if rebuild difficulties was requested
  202. if args.rebuild_difficulties {
  203. info!(target: "darkfid", "Node will rebuild difficulties of existing blockchain state.");
  204. let validator = Validator::new(&sled_db, &config).await?;
  205. validator
  206. .rebuild_block_difficulties(config.pow_target, config.pow_fixed_difficulty)
  207. .await?;
  208. info!(target: "darkfid", "Validator difficulties rebuilt successfully!");
  209. return Ok(())
  210. }
  211. // Generate the daemon
  212. let daemon = Darkfid::init(
  213. &sled_db,
  214. &config,
  215. &blockchain_config.net.into(),
  216. &blockchain_config.minerd_endpoint,
  217. &blockchain_config.txs_batch_size,
  218. &ex,
  219. )
  220. .await?;
  221. // Start the daemon
  222. let config = ConsensusInitTaskConfig {
  223. skip_sync: blockchain_config.skip_sync,
  224. checkpoint_height: blockchain_config.checkpoint_height,
  225. checkpoint: blockchain_config.checkpoint,
  226. miner: blockchain_config.minerd_endpoint.is_some(),
  227. recipient: blockchain_config.recipient,
  228. spend_hook: blockchain_config.spend_hook,
  229. user_data: blockchain_config.user_data,
  230. bootstrap,
  231. };
  232. daemon
  233. .start(
  234. &ex,
  235. &blockchain_config.rpc.into(),
  236. &blockchain_config.mm_rpc.map(|mm_rpc_opts| mm_rpc_opts.into()),
  237. &config,
  238. )
  239. .await?;
  240. // Signal handling for graceful termination.
  241. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  242. signals_handler.wait_termination(signals_task).await?;
  243. info!(target: "darkfid", "Caught termination signal, cleaning up and exiting...");
  244. daemon.stop().await?;
  245. info!(target: "darkfid", "Shut down successfully");
  246. Ok(())
  247. }
  248. /// Auxiliary function to parse darkfid configuration file and extract requested
  249. /// blockchain network config.
  250. pub async fn parse_blockchain_config(
  251. config: Option<String>,
  252. network: &str,
  253. ) -> Result<BlockchainNetwork> {
  254. // Grab config path
  255. let config_path = get_config_path(config, CONFIG_FILE)?;
  256. debug!(target: "darkfid", "Parsing configuration file: {config_path:?}");
  257. // Parse TOML file contents
  258. let contents = read_to_string(&config_path).await?;
  259. let contents: toml::Value = match toml::from_str(&contents) {
  260. Ok(v) => v,
  261. Err(e) => {
  262. error!(target: "darkfid", "Failed parsing TOML config: {e}");
  263. return Err(Error::ParseFailed("Failed parsing TOML config"))
  264. }
  265. };
  266. // Grab requested network config
  267. let Some(table) = contents.as_table() else { return Err(Error::ParseFailed("TOML not a map")) };
  268. let Some(network_configs) = table.get("network_config") else {
  269. return Err(Error::ParseFailed("TOML does not contain network configurations"))
  270. };
  271. let Some(network_configs) = network_configs.as_table() else {
  272. return Err(Error::ParseFailed("`network_config` not a map"))
  273. };
  274. let Some(network_config) = network_configs.get(network) else {
  275. return Err(Error::ParseFailed("TOML does not contain requested network configuration"))
  276. };
  277. let network_config = toml::to_string(&network_config).unwrap();
  278. let network_config =
  279. match BlockchainNetwork::from_iter_with_toml::<Vec<String>>(&network_config, vec![]) {
  280. Ok(v) => v,
  281. Err(e) => {
  282. error!(target: "darkfid", "Failed parsing requested network configuration: {e}");
  283. return Err(Error::ParseFailed("Failed parsing requested network configuration"))
  284. }
  285. };
  286. debug!(target: "darkfid", "Parsed network configuration: {network_config:?}");
  287. Ok(network_config)
  288. }