main.rs 13 KB

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