main.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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::{
  19. collections::{HashMap, HashSet},
  20. str::FromStr,
  21. sync::Arc,
  22. };
  23. use log::{error, info};
  24. use smol::{lock::Mutex, stream::StreamExt};
  25. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  26. use url::Url;
  27. use darkfi::{
  28. async_daemonize,
  29. blockchain::BlockInfo,
  30. cli_desc,
  31. net::{settings::SettingsOpt, P2pPtr},
  32. rpc::{
  33. client::RpcChadClient,
  34. jsonrpc::JsonSubscriber,
  35. server::{listen_and_serve, RequestHandler},
  36. },
  37. system::{StoppableTask, StoppableTaskPtr},
  38. util::{encoding::base64, path::expand_path},
  39. validator::{Validator, ValidatorConfig, ValidatorPtr},
  40. Error, Result,
  41. };
  42. use darkfi_sdk::crypto::PublicKey;
  43. use darkfi_serial::deserialize_async;
  44. #[cfg(test)]
  45. mod tests;
  46. mod error;
  47. use error::{server_error, RpcError};
  48. /// JSON-RPC requests handler and methods
  49. mod rpc;
  50. mod rpc_blockchain;
  51. mod rpc_tx;
  52. /// Validator async tasks
  53. mod task;
  54. use task::{consensus_task, miner_task, sync_task};
  55. /// P2P net protocols
  56. mod proto;
  57. /// Utility functions
  58. mod utils;
  59. use utils::{parse_blockchain_config, spawn_p2p};
  60. const CONFIG_FILE: &str = "darkfid_config.toml";
  61. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfid_config.toml");
  62. /// Note:
  63. /// If you change these don't forget to remove their corresponding database folder,
  64. /// since if it already has a genesis block, provided one is ignored.
  65. const GENESIS_BLOCK_LOCALNET: &str = include_str!("../genesis_block_localnet");
  66. const GENESIS_BLOCK_TESTNET: &str = include_str!("../genesis_block_testnet");
  67. const GENESIS_BLOCK_MAINNET: &str = include_str!("../genesis_block_mainnet");
  68. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  69. #[serde(default)]
  70. #[structopt(name = "darkfid", about = cli_desc!())]
  71. struct Args {
  72. #[structopt(short, long)]
  73. /// Configuration file to use
  74. config: Option<String>,
  75. #[structopt(short, long, default_value = "tcp://127.0.0.1:8340")]
  76. /// JSON-RPC listen URL
  77. rpc_listen: Url,
  78. #[structopt(short, long, default_value = "testnet")]
  79. /// Blockchain network to use
  80. network: String,
  81. #[structopt(short, long)]
  82. /// Set log file to ouput into
  83. log: Option<String>,
  84. #[structopt(short, parse(from_occurrences))]
  85. /// Increase verbosity (-vvv supported)
  86. verbose: u8,
  87. }
  88. /// Defines a blockchain network configuration.
  89. /// Default values correspond to a local network.
  90. #[derive(Clone, Debug, serde::Deserialize, structopt::StructOpt, structopt_toml::StructOptToml)]
  91. #[structopt()]
  92. pub struct BlockchainNetwork {
  93. #[structopt(long, default_value = "~/.local/darkfi/darkfid_blockchain_localnet")]
  94. /// Path to blockchain database
  95. pub database: String,
  96. #[structopt(long, default_value = "3")]
  97. /// Finalization threshold, denominated by number of blocks
  98. pub threshold: usize,
  99. #[structopt(long, default_value = "tcp://127.0.0.1:28467")]
  100. /// minerd JSON-RPC endpoint
  101. pub minerd_endpoint: Url,
  102. #[structopt(long, default_value = "10")]
  103. /// PoW block production target, in seconds
  104. pub pow_target: usize,
  105. #[structopt(long)]
  106. /// Optional fixed PoW difficulty, used for testing
  107. pub pow_fixed_difficulty: Option<usize>,
  108. #[structopt(long)]
  109. /// Participate in block production
  110. pub miner: bool,
  111. #[structopt(long)]
  112. /// Wallet address to receive mining rewards
  113. pub recipient: Option<String>,
  114. #[structopt(long)]
  115. /// Skip syncing process and start node right away
  116. pub skip_sync: bool,
  117. /// P2P network settings
  118. #[structopt(flatten)]
  119. pub net: SettingsOpt,
  120. }
  121. /// Daemon structure
  122. pub struct Darkfid {
  123. /// P2P network pointer
  124. p2p: P2pPtr,
  125. /// Validator(node) pointer
  126. validator: ValidatorPtr,
  127. /// Flag to specify node is a miner
  128. miner: bool,
  129. /// A map of various subscribers exporting live info from the blockchain
  130. subscribers: HashMap<&'static str, JsonSubscriber>,
  131. /// JSON-RPC connection tracker
  132. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  133. /// JSON-RPC client to execute requests to the miner daemon
  134. rpc_client: Option<RpcChadClient>,
  135. }
  136. impl Darkfid {
  137. pub async fn new(
  138. p2p: P2pPtr,
  139. validator: ValidatorPtr,
  140. miner: bool,
  141. subscribers: HashMap<&'static str, JsonSubscriber>,
  142. rpc_client: Option<RpcChadClient>,
  143. ) -> Self {
  144. Self {
  145. p2p,
  146. validator,
  147. miner,
  148. subscribers,
  149. rpc_connections: Mutex::new(HashSet::new()),
  150. rpc_client,
  151. }
  152. }
  153. }
  154. async_daemonize!(realmain);
  155. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  156. info!(target: "darkfid", "Initializing DarkFi node...");
  157. // Grab blockchain network configuration
  158. let (blockchain_config, genesis_block) = match args.network.as_str() {
  159. "localnet" => {
  160. (parse_blockchain_config(args.config, "localnet").await?, GENESIS_BLOCK_LOCALNET)
  161. }
  162. "testnet" => {
  163. (parse_blockchain_config(args.config, "testnet").await?, GENESIS_BLOCK_TESTNET)
  164. }
  165. "mainnet" => {
  166. (parse_blockchain_config(args.config, "mainnet").await?, GENESIS_BLOCK_MAINNET)
  167. }
  168. _ => {
  169. error!("Unsupported chain `{}`", args.network);
  170. return Err(Error::UnsupportedChain)
  171. }
  172. };
  173. // Parse the genesis block
  174. let bytes = base64::decode(genesis_block.trim()).unwrap();
  175. let genesis_block: BlockInfo = deserialize_async(&bytes).await?;
  176. // Initialize or open sled database
  177. let db_path = expand_path(&blockchain_config.database)?;
  178. let sled_db = sled::open(&db_path)?;
  179. // Initialize validator configuration
  180. let pow_fixed_difficulty = if let Some(diff) = blockchain_config.pow_fixed_difficulty {
  181. info!(target: "darkfid", "Node is configured to run with fixed PoW difficulty: {}", diff);
  182. Some(diff.into())
  183. } else {
  184. None
  185. };
  186. let config = ValidatorConfig {
  187. finalization_threshold: blockchain_config.threshold,
  188. pow_target: blockchain_config.pow_target,
  189. pow_fixed_difficulty,
  190. genesis_block,
  191. verify_fees: false, // TODO: Make configurable
  192. };
  193. // Initialize validator
  194. let validator = Validator::new(&sled_db, config).await?;
  195. // Here we initialize various subscribers that can export live blockchain/consensus data.
  196. let mut subscribers = HashMap::new();
  197. subscribers.insert("blocks", JsonSubscriber::new("blockchain.subscribe_blocks"));
  198. subscribers.insert("txs", JsonSubscriber::new("blockchain.subscribe_txs"));
  199. subscribers.insert("proposals", JsonSubscriber::new("blockchain.subscribe_proposals"));
  200. // Initialize P2P network
  201. let p2p = spawn_p2p(&blockchain_config.net.into(), &validator, &subscribers, ex.clone()).await;
  202. // Initialize JSON-RPC client to perform requests to minerd
  203. let rpc_client = if blockchain_config.miner {
  204. let Ok(rpc_client) =
  205. RpcChadClient::new(blockchain_config.minerd_endpoint, ex.clone()).await
  206. else {
  207. error!(target: "darkfid", "Failed to initialize miner daemon rpc client, check if minerd is running");
  208. return Err(Error::RpcClientStopped)
  209. };
  210. Some(rpc_client)
  211. } else {
  212. None
  213. };
  214. // Initialize node
  215. let darkfid = Darkfid::new(
  216. p2p.clone(),
  217. validator.clone(),
  218. blockchain_config.miner,
  219. subscribers,
  220. rpc_client,
  221. )
  222. .await;
  223. let darkfid = Arc::new(darkfid);
  224. info!(target: "darkfid", "Node initialized successfully!");
  225. // Pinging minerd daemon to verify it listens
  226. if blockchain_config.miner {
  227. if let Err(e) = darkfid.ping_miner_daemon().await {
  228. error!(target: "darkfid", "Failed to ping miner daemon: {}", e);
  229. return Err(Error::RpcClientStopped)
  230. }
  231. }
  232. // JSON-RPC server
  233. info!(target: "darkfid", "Starting JSON-RPC server");
  234. // Here we create a task variable so we can manually close the
  235. // task later. P2P tasks don't need this since it has its own
  236. // stop() function to shut down, also terminating the task we
  237. // created for it.
  238. let rpc_task = StoppableTask::new();
  239. let darkfid_ = darkfid.clone();
  240. rpc_task.clone().start(
  241. listen_and_serve(args.rpc_listen, darkfid.clone(), None, ex.clone()),
  242. |res| async move {
  243. match res {
  244. Ok(()) | Err(Error::RpcServerStopped) => darkfid_.stop_connections().await,
  245. Err(e) => error!(target: "darkfid", "Failed starting sync JSON-RPC server: {}", e),
  246. }
  247. },
  248. Error::RpcServerStopped,
  249. ex.clone(),
  250. );
  251. info!(target: "darkfid", "Starting P2P network");
  252. p2p.clone().start().await?;
  253. // Sync blockchain
  254. if !blockchain_config.skip_sync {
  255. sync_task(&darkfid).await?;
  256. } else {
  257. *darkfid.validator.synced.write().await = true;
  258. }
  259. // Clean node pending transactions
  260. darkfid.validator.purge_pending_txs().await?;
  261. // Consensus protocol
  262. info!(target: "darkfid", "Starting consensus protocol task");
  263. let consensus_task = if blockchain_config.miner {
  264. // Grab rewards recipient public key(address)
  265. if blockchain_config.recipient.is_none() {
  266. return Err(Error::ParseFailed("Recipient address missing"))
  267. }
  268. let recipient = match PublicKey::from_str(&blockchain_config.recipient.unwrap()) {
  269. Ok(address) => address,
  270. Err(_) => return Err(Error::InvalidAddress),
  271. };
  272. let task = StoppableTask::new();
  273. task.clone().start(
  274. // Weird hack to prevent lifetimes hell
  275. async move { miner_task(&darkfid, &recipient, blockchain_config.skip_sync).await },
  276. |res| async {
  277. match res {
  278. Ok(()) | Err(Error::MinerTaskStopped) => { /* Do nothing */ }
  279. Err(e) => error!(target: "darkfid", "Failed starting miner task: {}", e),
  280. }
  281. },
  282. Error::MinerTaskStopped,
  283. ex.clone(),
  284. );
  285. task
  286. } else {
  287. let task = StoppableTask::new();
  288. task.clone().start(
  289. // Weird hack to prevent lifetimes hell
  290. async move { consensus_task(&darkfid).await },
  291. |res| async {
  292. match res {
  293. Ok(()) | Err(Error::ConsensusTaskStopped) => { /* Do nothing */ }
  294. Err(e) => error!(target: "darkfid", "Failed starting consensus task: {}", e),
  295. }
  296. },
  297. Error::ConsensusTaskStopped,
  298. ex.clone(),
  299. );
  300. task
  301. };
  302. // Signal handling for graceful termination.
  303. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  304. signals_handler.wait_termination(signals_task).await?;
  305. info!(target: "darkfid", "Caught termination signal, cleaning up and exiting...");
  306. info!(target: "darkfid", "Stopping JSON-RPC server...");
  307. rpc_task.stop().await;
  308. info!(target: "darkfid", "Stopping P2P network...");
  309. p2p.stop().await;
  310. info!(target: "darkfid", "Stopping consensus task...");
  311. consensus_task.stop().await;
  312. info!(target: "darkfid", "Flushing sled database...");
  313. let flushed_bytes = sled_db.flush_async().await?;
  314. info!(target: "darkfid", "Flushed {} bytes", flushed_bytes);
  315. Ok(())
  316. }