main.rs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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/darkfi/darkfid/localnet")]
  74. /// Path to blockchain database
  75. database: String,
  76. #[structopt(long, default_value = "3")]
  77. /// Finalization 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, default_value = "10")]
  83. /// PoW block production target, in seconds
  84. pow_target: u32,
  85. #[structopt(long)]
  86. /// Optional fixed PoW difficulty, used for testing
  87. pow_fixed_difficulty: Option<usize>,
  88. #[structopt(long)]
  89. /// Wallet address to receive mining rewards
  90. recipient: Option<String>,
  91. #[structopt(long)]
  92. /// Optional contract spend hook to use in the mining reward
  93. spend_hook: Option<String>,
  94. #[structopt(long)]
  95. /// Optional user data to use in the mining reward
  96. user_data: Option<String>,
  97. #[structopt(long)]
  98. /// Skip syncing process and start node right away
  99. skip_sync: bool,
  100. #[structopt(long)]
  101. /// Disable transaction's fee verification, used for testing
  102. skip_fees: bool,
  103. #[structopt(long)]
  104. /// Optional sync checkpoint height
  105. checkpoint_height: Option<u32>,
  106. #[structopt(long)]
  107. /// Optional sync checkpoint hash
  108. checkpoint: Option<String>,
  109. #[structopt(long)]
  110. /// Optional bootstrap timestamp
  111. bootstrap: Option<u64>,
  112. #[structopt(long)]
  113. /// Garbage collection task transactions batch size
  114. txs_batch_size: Option<usize>,
  115. /// P2P network settings
  116. #[structopt(flatten)]
  117. net: SettingsOpt,
  118. }
  119. async_daemonize!(realmain);
  120. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  121. info!(target: "darkfid", "Initializing DarkFi node...");
  122. // Grab blockchain network configuration
  123. let (blockchain_config, genesis_block) = match args.network.as_str() {
  124. "localnet" => {
  125. (parse_blockchain_config(args.config, "localnet").await?, GENESIS_BLOCK_LOCALNET)
  126. }
  127. "testnet" => {
  128. (parse_blockchain_config(args.config, "testnet").await?, GENESIS_BLOCK_TESTNET)
  129. }
  130. "mainnet" => {
  131. (parse_blockchain_config(args.config, "mainnet").await?, GENESIS_BLOCK_MAINNET)
  132. }
  133. _ => {
  134. error!("Unsupported chain `{}`", args.network);
  135. return Err(Error::UnsupportedChain)
  136. }
  137. };
  138. // Parse the genesis block
  139. let bytes = base64::decode(genesis_block.trim()).unwrap();
  140. let genesis_block: BlockInfo = deserialize_async(&bytes).await?;
  141. // Compute the bootstrap timestamp
  142. let bootstrap = match blockchain_config.bootstrap {
  143. Some(b) => b,
  144. None => genesis_block.header.timestamp.inner(),
  145. };
  146. // Initialize or open sled database
  147. let db_path = expand_path(&blockchain_config.database)?;
  148. let sled_db = sled_overlay::sled::open(&db_path)?;
  149. // Initialize validator configuration
  150. let pow_fixed_difficulty = if let Some(diff) = blockchain_config.pow_fixed_difficulty {
  151. info!(target: "darkfid", "Node is configured to run with fixed PoW difficulty: {}", diff);
  152. Some(diff.into())
  153. } else {
  154. None
  155. };
  156. let config = ValidatorConfig {
  157. finalization_threshold: blockchain_config.threshold,
  158. pow_target: blockchain_config.pow_target,
  159. pow_fixed_difficulty,
  160. genesis_block,
  161. verify_fees: !blockchain_config.skip_fees,
  162. };
  163. // Check if reset was requested
  164. if let Some(height) = args.reset {
  165. info!(target: "darkfid", "Node will reset validator state to height: {}", height);
  166. let validator = Validator::new(&sled_db, &config).await?;
  167. validator.reset_to_height(height).await?;
  168. info!(target: "darkfid", "Validator state reset successfully!");
  169. return Ok(())
  170. }
  171. // Generate the daemon
  172. let daemon = Darkfid::init(
  173. &sled_db,
  174. &config,
  175. &blockchain_config.net.into(),
  176. &blockchain_config.minerd_endpoint,
  177. &blockchain_config.txs_batch_size,
  178. &ex,
  179. )
  180. .await?;
  181. // Start the daemon
  182. let config = ConsensusInitTaskConfig {
  183. skip_sync: blockchain_config.skip_sync,
  184. checkpoint_height: blockchain_config.checkpoint_height,
  185. checkpoint: blockchain_config.checkpoint,
  186. miner: blockchain_config.minerd_endpoint.is_some(),
  187. recipient: blockchain_config.recipient,
  188. spend_hook: blockchain_config.spend_hook,
  189. user_data: blockchain_config.user_data,
  190. bootstrap,
  191. };
  192. daemon.start(&ex, &blockchain_config.rpc_listen, &config).await?;
  193. // Signal handling for graceful termination.
  194. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  195. signals_handler.wait_termination(signals_task).await?;
  196. info!(target: "darkfid", "Caught termination signal, cleaning up and exiting...");
  197. daemon.stop().await?;
  198. info!(target: "darkfid", "Shut down successfully");
  199. Ok(())
  200. }
  201. /// Auxiliary function to parse darkfid configuration file and extract requested
  202. /// blockchain network config.
  203. pub async fn parse_blockchain_config(
  204. config: Option<String>,
  205. network: &str,
  206. ) -> Result<BlockchainNetwork> {
  207. // Grab config path
  208. let config_path = get_config_path(config, CONFIG_FILE)?;
  209. debug!(target: "darkfid", "Parsing configuration file: {:?}", config_path);
  210. // Parse TOML file contents
  211. let contents = read_to_string(&config_path).await?;
  212. let contents: toml::Value = match toml::from_str(&contents) {
  213. Ok(v) => v,
  214. Err(e) => {
  215. error!(target: "darkfid", "Failed parsing TOML config: {}", e);
  216. return Err(Error::ParseFailed("Failed parsing TOML config"))
  217. }
  218. };
  219. // Grab requested network config
  220. let Some(table) = contents.as_table() else { return Err(Error::ParseFailed("TOML not a map")) };
  221. let Some(network_configs) = table.get("network_config") else {
  222. return Err(Error::ParseFailed("TOML does not contain network configurations"))
  223. };
  224. let Some(network_configs) = network_configs.as_table() else {
  225. return Err(Error::ParseFailed("`network_config` not a map"))
  226. };
  227. let Some(network_config) = network_configs.get(network) else {
  228. return Err(Error::ParseFailed("TOML does not contain requested network configuration"))
  229. };
  230. let network_config = toml::to_string(&network_config).unwrap();
  231. let network_config =
  232. match BlockchainNetwork::from_iter_with_toml::<Vec<String>>(&network_config, vec![]) {
  233. Ok(v) => v,
  234. Err(e) => {
  235. error!(target: "darkfid", "Failed parsing requested network configuration: {}", e);
  236. return Err(Error::ParseFailed("Failed parsing requested network configuration"))
  237. }
  238. };
  239. debug!(target: "darkfid", "Parsed network configuration: {:?}", network_config);
  240. Ok(network_config)
  241. }