main.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. util::{
  29. encoding::base64,
  30. path::{expand_path, get_config_path},
  31. },
  32. validator::{Validator, ValidatorConfig},
  33. Error, Result,
  34. };
  35. use darkfi_serial::deserialize_async;
  36. use darkfid::{task::consensus::ConsensusInitTaskConfig, Darkfid};
  37. const CONFIG_FILE: &str = "darkfid_config.toml";
  38. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfid_config.toml");
  39. /// Note:
  40. /// If you change these don't forget to remove their corresponding database folder,
  41. /// since if it already has a genesis block, provided one is ignored.
  42. const GENESIS_BLOCK_LOCALNET: &str = include_str!("../genesis_block_localnet");
  43. const GENESIS_BLOCK_TESTNET: &str = include_str!("../genesis_block_testnet");
  44. const GENESIS_BLOCK_MAINNET: &str = include_str!("../genesis_block_mainnet");
  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(short, long, default_value = "testnet")]
  53. /// Blockchain network to use
  54. network: String,
  55. #[structopt(short, long)]
  56. /// Reset validator state to given block height
  57. reset: Option<u32>,
  58. #[structopt(short, long)]
  59. /// Set log file to ouput into
  60. log: Option<String>,
  61. #[structopt(short, parse(from_occurrences))]
  62. /// Increase verbosity (-vvv supported)
  63. verbose: u8,
  64. }
  65. /// Defines a blockchain network configuration.
  66. /// Default values correspond to a local network.
  67. #[derive(Clone, Debug, serde::Deserialize, structopt::StructOpt, structopt_toml::StructOptToml)]
  68. #[structopt()]
  69. pub struct BlockchainNetwork {
  70. #[structopt(short, long, default_value = "tcp://127.0.0.1:8240")]
  71. /// JSON-RPC listen URL
  72. rpc_listen: Url,
  73. #[structopt(long, default_value = "~/.local/share/darkfi/darkfid/localnet")]
  74. /// Path to blockchain database
  75. database: String,
  76. #[structopt(long, default_value = "3")]
  77. /// Confirmation threshold, denominated by number of blocks
  78. threshold: usize,
  79. #[structopt(long)]
  80. /// minerd JSON-RPC endpoint
  81. minerd_endpoint: Option<Url>,
  82. #[structopt(long)]
  83. /// Optional HTTP JSON-RPC listen URL to serve handlers for p2pool merge mining requests
  84. mm_rpc_listen: Option<Url>,
  85. #[structopt(long, default_value = "10")]
  86. /// PoW block production target, in seconds
  87. pow_target: u32,
  88. #[structopt(long)]
  89. /// Optional fixed PoW difficulty, used for testing
  90. pow_fixed_difficulty: Option<usize>,
  91. #[structopt(long)]
  92. /// Wallet address to receive mining rewards
  93. recipient: Option<String>,
  94. #[structopt(long)]
  95. /// Optional contract spend hook to use in the mining reward
  96. spend_hook: Option<String>,
  97. #[structopt(long)]
  98. /// Optional user data to use in the mining reward
  99. user_data: Option<String>,
  100. #[structopt(long)]
  101. /// Skip syncing process and start node right away
  102. skip_sync: bool,
  103. #[structopt(long)]
  104. /// Disable transaction's fee verification, used for testing
  105. skip_fees: bool,
  106. #[structopt(long)]
  107. /// Optional sync checkpoint height
  108. checkpoint_height: Option<u32>,
  109. #[structopt(long)]
  110. /// Optional sync checkpoint hash
  111. checkpoint: Option<String>,
  112. #[structopt(long)]
  113. /// Optional bootstrap timestamp
  114. bootstrap: Option<u64>,
  115. #[structopt(long)]
  116. /// Garbage collection task transactions batch size
  117. txs_batch_size: Option<usize>,
  118. /// P2P network settings
  119. #[structopt(flatten)]
  120. net: SettingsOpt,
  121. }
  122. async_daemonize!(realmain);
  123. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  124. info!(target: "darkfid", "Initializing DarkFi node...");
  125. // Grab blockchain network configuration
  126. let (blockchain_config, genesis_block) = match args.network.as_str() {
  127. "localnet" => {
  128. (parse_blockchain_config(args.config, "localnet").await?, GENESIS_BLOCK_LOCALNET)
  129. }
  130. "testnet" => {
  131. (parse_blockchain_config(args.config, "testnet").await?, GENESIS_BLOCK_TESTNET)
  132. }
  133. "mainnet" => {
  134. (parse_blockchain_config(args.config, "mainnet").await?, GENESIS_BLOCK_MAINNET)
  135. }
  136. _ => {
  137. error!("Unsupported chain `{}`", args.network);
  138. return Err(Error::UnsupportedChain)
  139. }
  140. };
  141. // Parse the genesis block
  142. let bytes = base64::decode(genesis_block.trim()).unwrap();
  143. let genesis_block: BlockInfo = deserialize_async(&bytes).await?;
  144. // Compute the bootstrap timestamp
  145. let bootstrap = match blockchain_config.bootstrap {
  146. Some(b) => b,
  147. None => genesis_block.header.timestamp.inner(),
  148. };
  149. // Initialize or open sled database
  150. let db_path = expand_path(&blockchain_config.database)?;
  151. let sled_db = sled_overlay::sled::open(&db_path)?;
  152. // Initialize validator configuration
  153. let pow_fixed_difficulty = if let Some(diff) = blockchain_config.pow_fixed_difficulty {
  154. info!(target: "darkfid", "Node is configured to run with fixed PoW difficulty: {}", diff);
  155. Some(diff.into())
  156. } else {
  157. None
  158. };
  159. let config = ValidatorConfig {
  160. confirmation_threshold: blockchain_config.threshold,
  161. pow_target: blockchain_config.pow_target,
  162. pow_fixed_difficulty,
  163. genesis_block,
  164. verify_fees: !blockchain_config.skip_fees,
  165. };
  166. // Check if reset was requested
  167. if let Some(height) = args.reset {
  168. info!(target: "darkfid", "Node will reset validator state to height: {}", height);
  169. let validator = Validator::new(&sled_db, &config).await?;
  170. validator.reset_to_height(height).await?;
  171. info!(target: "darkfid", "Validator state reset successfully!");
  172. return Ok(())
  173. }
  174. // Generate the daemon
  175. let daemon = Darkfid::init(
  176. &sled_db,
  177. &config,
  178. &blockchain_config.net.into(),
  179. &blockchain_config.minerd_endpoint,
  180. &blockchain_config.txs_batch_size,
  181. &ex,
  182. )
  183. .await?;
  184. // Start the daemon
  185. let config = ConsensusInitTaskConfig {
  186. skip_sync: blockchain_config.skip_sync,
  187. checkpoint_height: blockchain_config.checkpoint_height,
  188. checkpoint: blockchain_config.checkpoint,
  189. miner: blockchain_config.minerd_endpoint.is_some(),
  190. recipient: blockchain_config.recipient,
  191. spend_hook: blockchain_config.spend_hook,
  192. user_data: blockchain_config.user_data,
  193. bootstrap,
  194. };
  195. daemon
  196. .start(&ex, &blockchain_config.rpc_listen, &blockchain_config.mm_rpc_listen, &config)
  197. .await?;
  198. // Signal handling for graceful termination.
  199. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  200. signals_handler.wait_termination(signals_task).await?;
  201. info!(target: "darkfid", "Caught termination signal, cleaning up and exiting...");
  202. daemon.stop().await?;
  203. info!(target: "darkfid", "Shut down successfully");
  204. Ok(())
  205. }
  206. /// Auxiliary function to parse darkfid configuration file and extract requested
  207. /// blockchain network config.
  208. pub async fn parse_blockchain_config(
  209. config: Option<String>,
  210. network: &str,
  211. ) -> Result<BlockchainNetwork> {
  212. // Grab config path
  213. let config_path = get_config_path(config, CONFIG_FILE)?;
  214. debug!(target: "darkfid", "Parsing configuration file: {:?}", config_path);
  215. // Parse TOML file contents
  216. let contents = read_to_string(&config_path).await?;
  217. let contents: toml::Value = match toml::from_str(&contents) {
  218. Ok(v) => v,
  219. Err(e) => {
  220. error!(target: "darkfid", "Failed parsing TOML config: {}", e);
  221. return Err(Error::ParseFailed("Failed parsing TOML config"))
  222. }
  223. };
  224. // Grab requested network config
  225. let Some(table) = contents.as_table() else { return Err(Error::ParseFailed("TOML not a map")) };
  226. let Some(network_configs) = table.get("network_config") else {
  227. return Err(Error::ParseFailed("TOML does not contain network configurations"))
  228. };
  229. let Some(network_configs) = network_configs.as_table() else {
  230. return Err(Error::ParseFailed("`network_config` not a map"))
  231. };
  232. let Some(network_config) = network_configs.get(network) else {
  233. return Err(Error::ParseFailed("TOML does not contain requested network configuration"))
  234. };
  235. let network_config = toml::to_string(&network_config).unwrap();
  236. let network_config =
  237. match BlockchainNetwork::from_iter_with_toml::<Vec<String>>(&network_config, vec![]) {
  238. Ok(v) => v,
  239. Err(e) => {
  240. error!(target: "darkfid", "Failed parsing requested network configuration: {}", e);
  241. return Err(Error::ParseFailed("Failed parsing requested network configuration"))
  242. }
  243. };
  244. debug!(target: "darkfid", "Parsed network configuration: {:?}", network_config);
  245. Ok(network_config)
  246. }