main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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::RpcClient,
  34. jsonrpc::JsonSubscriber,
  35. server::{listen_and_serve, RequestHandler},
  36. },
  37. system::{StoppableTask, StoppableTaskPtr},
  38. util::{path::expand_path, time::TimeKeeper},
  39. validator::{utils::genesis_txs_total, 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::{miner_task, sync_task};
  55. /// P2P net protocols
  56. mod proto;
  57. /// Utility functions
  58. mod utils;
  59. use utils::{spawn_consensus_p2p, spawn_sync_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(long, default_value = "tcp://127.0.0.1:8340")]
  76. /// JSON-RPC listen URL
  77. rpc_listen: Url,
  78. #[structopt(long, default_value = "testnet")]
  79. /// Blockchain network to use
  80. network: String,
  81. #[structopt(flatten)]
  82. /// Localnet blockchain network configuration
  83. localnet: BlockchainNetwork,
  84. #[structopt(flatten)]
  85. /// Testnet blockchain network configuration
  86. testnet: BlockchainNetwork,
  87. #[structopt(flatten)]
  88. /// Mainnet blockchain network configuration
  89. mainnet: BlockchainNetwork,
  90. #[structopt(short, long)]
  91. /// Set log file to ouput into
  92. log: Option<String>,
  93. #[structopt(short, parse(from_occurrences))]
  94. /// Increase verbosity (-vvv supported)
  95. verbose: u8,
  96. }
  97. /// Defines a blockchain network configuration.
  98. /// Default values correspond to a local network.
  99. #[derive(Clone, Debug, serde::Deserialize, structopt::StructOpt, structopt_toml::StructOptToml)]
  100. #[structopt()]
  101. pub struct BlockchainNetwork {
  102. #[structopt(long, default_value = "~/.local/darkfi/darkfid_blockchain_localnet")]
  103. /// Path to blockchain database
  104. pub database: String,
  105. #[structopt(long, default_value = "3")]
  106. /// Finalization threshold, denominated by number of blocks
  107. pub threshold: usize,
  108. #[structopt(long, default_value = "tcp://127.0.0.1:28467")]
  109. /// minerd JSON-RPC endpoint
  110. pub minerd_endpoint: Url,
  111. #[structopt(long, default_value = "10")]
  112. /// PoW block production target, in seconds
  113. pub pow_target: usize,
  114. #[structopt(long)]
  115. /// Optional fixed PoW difficulty, used for testing
  116. pub pow_fixed_difficulty: Option<usize>,
  117. #[structopt(long, default_value = "10")]
  118. /// Epoch duration, denominated by number of blocks/slots
  119. pub epoch_length: u64,
  120. #[structopt(long, default_value = "10")]
  121. /// PoS slot duration, in seconds
  122. pub slot_time: u64,
  123. #[structopt(long)]
  124. /// Whitelisted faucet public key (repeatable flag)
  125. pub faucet_pub: Vec<String>,
  126. #[structopt(long)]
  127. /// Participate in the consensus protocol
  128. pub consensus: bool,
  129. #[structopt(long)]
  130. /// Wallet address to receive consensus rewards
  131. pub recipient: Option<String>,
  132. #[structopt(long)]
  133. /// Skip syncing process and start node right away
  134. pub skip_sync: bool,
  135. #[structopt(long)]
  136. /// Enable PoS testing mode for local testing
  137. pub pos_testing_mode: bool,
  138. /// Syncing network settings
  139. #[structopt(flatten)]
  140. pub sync_net: SettingsOpt,
  141. /// Consensus network settings
  142. #[structopt(flatten)]
  143. pub consensus_net: SettingsOpt,
  144. }
  145. /// Daemon structure
  146. pub struct Darkfid {
  147. /// Syncing P2P network pointer
  148. sync_p2p: P2pPtr,
  149. /// Optional consensus P2P network pointer
  150. consensus_p2p: Option<P2pPtr>,
  151. /// Validator(node) pointer
  152. validator: ValidatorPtr,
  153. /// A map of various subscribers exporting live info from the blockchain
  154. subscribers: HashMap<&'static str, JsonSubscriber>,
  155. /// JSON-RPC connection tracker
  156. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  157. /// JSON-RPC client to execute requests to the miner daemon
  158. rpc_client: Option<RpcClient>,
  159. }
  160. impl Darkfid {
  161. pub async fn new(
  162. sync_p2p: P2pPtr,
  163. consensus_p2p: Option<P2pPtr>,
  164. validator: ValidatorPtr,
  165. subscribers: HashMap<&'static str, JsonSubscriber>,
  166. rpc_client: Option<RpcClient>,
  167. ) -> Self {
  168. Self {
  169. sync_p2p,
  170. consensus_p2p,
  171. validator,
  172. subscribers,
  173. rpc_connections: Mutex::new(HashSet::new()),
  174. rpc_client,
  175. }
  176. }
  177. }
  178. async_daemonize!(realmain);
  179. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  180. info!(target: "darkfid", "Initializing DarkFi node...");
  181. // Grab blockchain network configuration
  182. let (blockchain_config, genesis_block) = match args.network.as_str() {
  183. "localnet" => (args.localnet, GENESIS_BLOCK_LOCALNET),
  184. "testnet" => (args.testnet, GENESIS_BLOCK_TESTNET),
  185. "mainnet" => (args.mainnet, GENESIS_BLOCK_MAINNET),
  186. _ => {
  187. error!("Unsupported chain `{}`", args.network);
  188. return Err(Error::UnsupportedChain)
  189. }
  190. };
  191. if blockchain_config.pos_testing_mode {
  192. info!(target: "darkfid", "Node is configured to run in PoS testing mode!");
  193. }
  194. // Parse the genesis block
  195. let bytes = bs58::decode(&genesis_block.trim()).into_vec()?;
  196. let genesis_block: BlockInfo = deserialize_async(&bytes).await?;
  197. // Initialize or open sled database
  198. let db_path = expand_path(&blockchain_config.database)?;
  199. let sled_db = sled::open(&db_path)?;
  200. // Initialize validator configuration
  201. let genesis_txs_total = genesis_txs_total(&genesis_block.txs).await?;
  202. let time_keeper = TimeKeeper::new(
  203. genesis_block.header.timestamp,
  204. blockchain_config.epoch_length,
  205. blockchain_config.slot_time,
  206. 0,
  207. );
  208. let pow_fixed_difficulty = if let Some(diff) = blockchain_config.pow_fixed_difficulty {
  209. info!(target: "darkfid", "Node is configured to run with fixed PoW difficulty: {}", diff);
  210. Some(diff.into())
  211. } else {
  212. None
  213. };
  214. let config = ValidatorConfig::new(
  215. time_keeper,
  216. blockchain_config.threshold,
  217. blockchain_config.pow_target,
  218. pow_fixed_difficulty,
  219. genesis_block,
  220. genesis_txs_total,
  221. vec![],
  222. blockchain_config.pos_testing_mode,
  223. false, // TODO: Make configurable
  224. );
  225. // Initialize validator
  226. let validator = Validator::new(&sled_db, config).await?;
  227. // Here we initialize various subscribers that can export live blockchain/consensus data.
  228. let mut subscribers = HashMap::new();
  229. subscribers.insert("blocks", JsonSubscriber::new("blockchain.subscribe_blocks"));
  230. subscribers.insert("txs", JsonSubscriber::new("blockchain.subscribe_txs"));
  231. if blockchain_config.consensus {
  232. subscribers.insert("proposals", JsonSubscriber::new("blockchain.subscribe_proposals"));
  233. }
  234. // Initialize syncing P2P network
  235. let sync_p2p =
  236. spawn_sync_p2p(&blockchain_config.sync_net.into(), &validator, &subscribers, ex.clone())
  237. .await;
  238. // Initialize consensus P2P network
  239. let (consensus_p2p, rpc_client) = if blockchain_config.consensus {
  240. let Ok(rpc_client) = RpcClient::new(blockchain_config.minerd_endpoint, ex.clone()).await
  241. else {
  242. error!(target: "darkfid", "Failed to initialize miner daemon rpc client, check if minerd is running");
  243. return Err(Error::RpcClientStopped)
  244. };
  245. (
  246. Some(
  247. spawn_consensus_p2p(
  248. &blockchain_config.consensus_net.into(),
  249. &validator,
  250. &subscribers,
  251. ex.clone(),
  252. )
  253. .await,
  254. ),
  255. Some(rpc_client),
  256. )
  257. } else {
  258. (None, None)
  259. };
  260. // Initialize node
  261. let darkfid = Darkfid::new(
  262. sync_p2p.clone(),
  263. consensus_p2p.clone(),
  264. validator.clone(),
  265. subscribers,
  266. rpc_client,
  267. )
  268. .await;
  269. let darkfid = Arc::new(darkfid);
  270. info!(target: "darkfid", "Node initialized successfully!");
  271. // Pinging minerd daemon to verify it listens
  272. if blockchain_config.consensus {
  273. if let Err(e) = darkfid.ping_miner_daemon().await {
  274. error!(target: "darkfid", "Failed to ping miner daemon: {}", e);
  275. return Err(Error::RpcClientStopped)
  276. }
  277. }
  278. // JSON-RPC server
  279. info!(target: "darkfid", "Starting JSON-RPC server");
  280. // Here we create a task variable so we can manually close the
  281. // task later. P2P tasks don't need this since it has its own
  282. // stop() function to shut down, also terminating the task we
  283. // created for it.
  284. let rpc_task = StoppableTask::new();
  285. let darkfid_ = darkfid.clone();
  286. rpc_task.clone().start(
  287. listen_and_serve(args.rpc_listen, darkfid.clone(), None, ex.clone()),
  288. |res| async move {
  289. match res {
  290. Ok(()) | Err(Error::RpcServerStopped) => darkfid_.stop_connections().await,
  291. Err(e) => error!(target: "darkfid", "Failed starting sync JSON-RPC server: {}", e),
  292. }
  293. },
  294. Error::RpcServerStopped,
  295. ex.clone(),
  296. );
  297. info!(target: "darkfid", "Starting sync P2P network");
  298. sync_p2p.clone().start().await?;
  299. // Consensus protocol
  300. if blockchain_config.consensus {
  301. info!(target: "darkfid", "Starting consensus P2P network");
  302. let consensus_p2p = consensus_p2p.clone().unwrap();
  303. consensus_p2p.clone().start().await?;
  304. } else {
  305. info!(target: "darkfid", "Not starting consensus P2P network");
  306. }
  307. // Sync blockchain
  308. if !blockchain_config.skip_sync {
  309. sync_task(&darkfid).await?;
  310. } else {
  311. *darkfid.validator.synced.write().await = true;
  312. }
  313. // Clean node pending transactions
  314. darkfid.validator.purge_pending_txs().await?;
  315. // Consensus protocol
  316. let consensus_task = if blockchain_config.consensus {
  317. info!(target: "darkfid", "Starting consensus protocol task");
  318. // Grab rewards recipient public key(address)
  319. if blockchain_config.recipient.is_none() {
  320. return Err(Error::ParseFailed("Recipient address missing"))
  321. }
  322. let recipient = match PublicKey::from_str(&blockchain_config.recipient.unwrap()) {
  323. Ok(address) => address,
  324. Err(_) => return Err(Error::InvalidAddress),
  325. };
  326. let task = StoppableTask::new();
  327. task.clone().start(
  328. // Weird hack to prevent lifetimes hell
  329. async move { miner_task(&darkfid, &recipient).await },
  330. |res| async {
  331. match res {
  332. Ok(()) | Err(Error::MinerTaskStopped) => { /* Do nothing */ }
  333. Err(e) => error!(target: "darkfid", "Failed starting miner task: {}", e),
  334. }
  335. },
  336. Error::MinerTaskStopped,
  337. ex.clone(),
  338. );
  339. Some(task)
  340. } else {
  341. info!(target: "darkfid", "Not participating in consensus");
  342. None
  343. };
  344. // Signal handling for graceful termination.
  345. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  346. signals_handler.wait_termination(signals_task).await?;
  347. info!(target: "darkfid", "Caught termination signal, cleaning up and exiting...");
  348. info!(target: "darkfid", "Stopping JSON-RPC server...");
  349. rpc_task.stop().await;
  350. info!(target: "darkfid", "Stopping syncing P2P network...");
  351. sync_p2p.stop().await;
  352. if blockchain_config.consensus {
  353. info!(target: "darkfid", "Stopping consensus P2P network...");
  354. consensus_p2p.unwrap().stop().await;
  355. info!(target: "darkfid", "Stopping consensus task...");
  356. consensus_task.unwrap().stop().await;
  357. }
  358. info!(target: "darkfid", "Flushing sled database...");
  359. let flushed_bytes = sled_db.flush_async().await?;
  360. info!(target: "darkfid", "Flushed {} bytes", flushed_bytes);
  361. Ok(())
  362. }