main.rs 9.1 KB

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