main.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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;
  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, default_value = "10")]
  114. /// Epoch duration, denominated by number of blocks/slots
  115. pub epoch_length: u64,
  116. #[structopt(long, default_value = "10")]
  117. /// PoS slot duration, in seconds
  118. pub slot_time: u64,
  119. #[structopt(long)]
  120. /// Whitelisted faucet public key (repeatable flag)
  121. pub faucet_pub: Vec<String>,
  122. #[structopt(long)]
  123. /// Participate in the consensus protocol
  124. pub consensus: bool,
  125. #[structopt(long)]
  126. /// Wallet address to receive consensus rewards
  127. pub recipient: Option<String>,
  128. #[structopt(long)]
  129. /// Skip syncing process and start node right away
  130. pub skip_sync: bool,
  131. #[structopt(long)]
  132. /// Enable testing mode for local testing
  133. pub testing_mode: bool,
  134. /// Syncing network settings
  135. #[structopt(flatten)]
  136. pub sync_net: SettingsOpt,
  137. /// Consensus network settings
  138. #[structopt(flatten)]
  139. pub consensus_net: SettingsOpt,
  140. }
  141. /// Daemon structure
  142. pub struct Darkfid {
  143. /// Syncing P2P network pointer
  144. sync_p2p: P2pPtr,
  145. /// Optional consensus P2P network pointer
  146. consensus_p2p: Option<P2pPtr>,
  147. /// Validator(node) pointer
  148. validator: ValidatorPtr,
  149. /// A map of various subscribers exporting live info from the blockchain
  150. subscribers: HashMap<&'static str, JsonSubscriber>,
  151. /// JSON-RPC connection tracker
  152. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  153. }
  154. impl Darkfid {
  155. pub async fn new(
  156. sync_p2p: P2pPtr,
  157. consensus_p2p: Option<P2pPtr>,
  158. validator: ValidatorPtr,
  159. subscribers: HashMap<&'static str, JsonSubscriber>,
  160. ) -> Self {
  161. Self {
  162. sync_p2p,
  163. consensus_p2p,
  164. validator,
  165. subscribers,
  166. rpc_connections: Mutex::new(HashSet::new()),
  167. }
  168. }
  169. }
  170. async_daemonize!(realmain);
  171. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  172. info!(target: "darkfid", "Initializing DarkFi node...");
  173. // Grab blockchain network configuration
  174. let (blockchain_config, genesis_block) = match args.network.as_str() {
  175. "localnet" => (args.localnet, GENESIS_BLOCK_LOCALNET),
  176. "testnet" => (args.testnet, GENESIS_BLOCK_TESTNET),
  177. "mainnet" => (args.mainnet, GENESIS_BLOCK_MAINNET),
  178. _ => {
  179. error!("Unsupported chain `{}`", args.network);
  180. return Err(Error::UnsupportedChain)
  181. }
  182. };
  183. if blockchain_config.testing_mode {
  184. info!(target: "darkfid", "Node is configured to run in testing mode!");
  185. }
  186. // Parse the genesis block
  187. let bytes = bs58::decode(&genesis_block.trim()).into_vec()?;
  188. let genesis_block: BlockInfo = deserialize(&bytes)?;
  189. // Initialize or open sled database
  190. let db_path = expand_path(&blockchain_config.database)?;
  191. let sled_db = sled::open(&db_path)?;
  192. // Initialize validator configuration
  193. let genesis_txs_total = genesis_txs_total(&genesis_block.txs)?;
  194. let time_keeper = TimeKeeper::new(
  195. genesis_block.header.timestamp,
  196. blockchain_config.epoch_length,
  197. blockchain_config.slot_time,
  198. 0,
  199. );
  200. let config = ValidatorConfig::new(
  201. time_keeper,
  202. blockchain_config.threshold,
  203. blockchain_config.pow_threads,
  204. blockchain_config.pow_target,
  205. genesis_block,
  206. genesis_txs_total,
  207. vec![],
  208. blockchain_config.testing_mode,
  209. );
  210. // Initialize validator
  211. let validator = Validator::new(&sled_db, config).await?;
  212. // Here we initialize various subscribers that can export live blockchain/consensus data.
  213. let mut subscribers = HashMap::new();
  214. subscribers.insert("blocks", JsonSubscriber::new("blockchain.subscribe_blocks"));
  215. subscribers.insert("txs", JsonSubscriber::new("blockchain.subscribe_txs"));
  216. if blockchain_config.consensus {
  217. subscribers.insert("proposals", JsonSubscriber::new("blockchain.subscribe_proposals"));
  218. }
  219. // Initialize syncing P2P network
  220. let sync_p2p =
  221. spawn_sync_p2p(&blockchain_config.sync_net.into(), &validator, &subscribers, ex.clone())
  222. .await;
  223. // Initialize consensus P2P network
  224. let consensus_p2p = if blockchain_config.consensus {
  225. Some(
  226. spawn_consensus_p2p(
  227. &blockchain_config.consensus_net.into(),
  228. &validator,
  229. &subscribers,
  230. ex.clone(),
  231. )
  232. .await,
  233. )
  234. } else {
  235. None
  236. };
  237. // Initialize node
  238. let darkfid =
  239. Darkfid::new(sync_p2p.clone(), consensus_p2p.clone(), validator.clone(), subscribers).await;
  240. let darkfid = Arc::new(darkfid);
  241. info!(target: "darkfid", "Node initialized successfully!");
  242. // JSON-RPC server
  243. info!(target: "darkfid", "Starting JSON-RPC server");
  244. // Here we create a task variable so we can manually close the
  245. // task later. P2P tasks don't need this since it has its own
  246. // stop() function to shut down, also terminating the task we
  247. // created for it.
  248. let rpc_task = StoppableTask::new();
  249. let darkfid_ = darkfid.clone();
  250. rpc_task.clone().start(
  251. listen_and_serve(args.rpc_listen, darkfid.clone(), None, ex.clone()),
  252. |res| async move {
  253. match res {
  254. Ok(()) | Err(Error::RpcServerStopped) => darkfid_.stop_connections().await,
  255. Err(e) => error!(target: "darkfid", "Failed starting sync JSON-RPC server: {}", e),
  256. }
  257. },
  258. Error::RpcServerStopped,
  259. ex.clone(),
  260. );
  261. info!(target: "darkfid", "Starting sync P2P network");
  262. sync_p2p.clone().start().await?;
  263. // Consensus protocol
  264. if blockchain_config.consensus {
  265. info!(target: "darkfid", "Starting consensus P2P network");
  266. let consensus_p2p = consensus_p2p.clone().unwrap();
  267. consensus_p2p.clone().start().await?;
  268. } else {
  269. info!(target: "darkfid", "Not starting consensus P2P network");
  270. }
  271. // Sync blockchain
  272. if !blockchain_config.skip_sync {
  273. sync_task(&darkfid).await?;
  274. } else {
  275. darkfid.validator.write().await.synced = true;
  276. }
  277. // Clean node pending transactions
  278. darkfid.validator.write().await.purge_pending_txs().await?;
  279. // Consensus protocol
  280. let (consensus_task, consensus_sender) = if blockchain_config.consensus {
  281. info!(target: "darkfid", "Starting consensus protocol task");
  282. // Grab rewards recipient public key(address)
  283. if blockchain_config.recipient.is_none() {
  284. return Err(Error::ParseFailed("Recipient address missing"))
  285. }
  286. let recipient = match PublicKey::from_str(&blockchain_config.recipient.unwrap()) {
  287. Ok(address) => address,
  288. Err(_) => return Err(Error::InvalidAddress),
  289. };
  290. let (sender, recvr) = smol::channel::bounded(1);
  291. let task = StoppableTask::new();
  292. task.clone().start(
  293. // Weird hack to prevent lifetimes hell
  294. async move { miner_task(&darkfid, &recipient, &recvr).await },
  295. |res| async {
  296. match res {
  297. Ok(()) | Err(Error::MinerTaskStopped) => { /* Do nothing */ }
  298. Err(e) => error!(target: "darkfid", "Failed starting miner task: {}", e),
  299. }
  300. },
  301. Error::MinerTaskStopped,
  302. ex.clone(),
  303. );
  304. (Some(task), Some(sender))
  305. } else {
  306. info!(target: "darkfid", "Not participating in consensus");
  307. (None, None)
  308. };
  309. // Signal handling for graceful termination.
  310. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  311. signals_handler.wait_termination(signals_task).await?;
  312. info!(target: "darkfid", "Caught termination signal, cleaning up and exiting...");
  313. info!(target: "darkfid", "Stopping JSON-RPC server...");
  314. rpc_task.stop().await;
  315. info!(target: "darkfid", "Stopping syncing P2P network...");
  316. sync_p2p.stop().await;
  317. if blockchain_config.consensus {
  318. info!(target: "darkfid", "Stopping consensus P2P network...");
  319. consensus_p2p.unwrap().stop().await;
  320. info!(target: "darkfid", "Stopping consensus task...");
  321. // Send signal to spawned miner threads to stop
  322. consensus_sender.unwrap().send(()).await?;
  323. consensus_task.unwrap().stop().await;
  324. }
  325. info!(target: "darkfid", "Flushing sled database...");
  326. let flushed_bytes = sled_db.flush_async().await?;
  327. info!(target: "darkfid", "Flushed {} bytes", flushed_bytes);
  328. Ok(())
  329. }