main.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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::time::TimeKeeper,
  38. validator::{utils::genesis_txs_total, Validator, ValidatorConfig, ValidatorPtr},
  39. Error, Result,
  40. };
  41. use darkfi_contract_test_harness::vks;
  42. use darkfi_sdk::crypto::PublicKey;
  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. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  62. #[serde(default)]
  63. #[structopt(name = "darkfid", about = cli_desc!())]
  64. struct Args {
  65. #[structopt(short, long)]
  66. /// Configuration file to use
  67. config: Option<String>,
  68. #[structopt(long, default_value = "tcp://127.0.0.1:8340")]
  69. /// JSON-RPC listen URL
  70. rpc_listen: Url,
  71. #[structopt(long)]
  72. /// Participate in the consensus protocol
  73. consensus: bool,
  74. #[structopt(long)]
  75. /// Wallet address to receive consensus rewards
  76. recipient: Option<String>,
  77. #[structopt(long)]
  78. /// Skip syncing process and start node right away
  79. skip_sync: bool,
  80. /// Syncing network settings
  81. #[structopt(flatten)]
  82. sync_net: SettingsOpt,
  83. /// Consensus network settings
  84. #[structopt(flatten)]
  85. consensus_net: SettingsOpt,
  86. #[structopt(long)]
  87. /// Enable testing mode for local testing
  88. testing_mode: bool,
  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. /// Daemon structure
  97. pub struct Darkfid {
  98. /// Syncing P2P network pointer
  99. sync_p2p: P2pPtr,
  100. /// Optional consensus P2P network pointer
  101. consensus_p2p: Option<P2pPtr>,
  102. /// Validator(node) pointer
  103. validator: ValidatorPtr,
  104. /// A map of various subscribers exporting live info from the blockchain
  105. subscribers: HashMap<&'static str, JsonSubscriber>,
  106. /// JSON-RPC connection tracker
  107. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  108. }
  109. impl Darkfid {
  110. pub async fn new(
  111. sync_p2p: P2pPtr,
  112. consensus_p2p: Option<P2pPtr>,
  113. validator: ValidatorPtr,
  114. subscribers: HashMap<&'static str, JsonSubscriber>,
  115. ) -> Self {
  116. Self {
  117. sync_p2p,
  118. consensus_p2p,
  119. validator,
  120. subscribers,
  121. rpc_connections: Mutex::new(HashSet::new()),
  122. }
  123. }
  124. }
  125. async_daemonize!(realmain);
  126. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  127. info!(target: "darkfid", "Initializing DarkFi node...");
  128. if args.testing_mode {
  129. info!(target: "darkfid", "Node is configured to run in testing mode!");
  130. }
  131. // NOTE: everything is dummy for now
  132. // FIXME: The VKS should only ever have to be generated on initial run.
  133. // Do not use the precompiles for actual production code.
  134. // Initialize or open sled database
  135. let sled_db = sled::Config::new().temporary(true).open()?;
  136. let (_, vks) = vks::read_or_gen_vks_and_pks()?;
  137. vks::inject(&sled_db, &vks)?;
  138. // Initialize validator configuration
  139. let genesis_block = BlockInfo::default();
  140. let genesis_txs_total = genesis_txs_total(&genesis_block.txs)?;
  141. let time_keeper = TimeKeeper::new(genesis_block.header.timestamp, 10, 90, 0);
  142. // TODO: add miner threads arg
  143. let config = ValidatorConfig::new(
  144. time_keeper,
  145. Some(40),
  146. genesis_block,
  147. genesis_txs_total,
  148. vec![],
  149. args.testing_mode,
  150. );
  151. // Initialize validator
  152. let validator = Validator::new(&sled_db, config).await?;
  153. // Here we initialize various subscribers that can export live blockchain/consensus data.
  154. let mut subscribers = HashMap::new();
  155. subscribers.insert("blocks", JsonSubscriber::new("blockchain.subscribe_blocks"));
  156. subscribers.insert("txs", JsonSubscriber::new("blockchain.subscribe_txs"));
  157. if args.consensus {
  158. subscribers.insert("proposals", JsonSubscriber::new("blockchain.subscribe_proposals"));
  159. }
  160. // Initialize syncing P2P network
  161. let sync_p2p =
  162. spawn_sync_p2p(&args.sync_net.into(), &validator, &subscribers, ex.clone()).await;
  163. // Initialize consensus P2P network
  164. let consensus_p2p = if args.consensus {
  165. Some(
  166. spawn_consensus_p2p(&args.consensus_net.into(), &validator, &subscribers, ex.clone())
  167. .await,
  168. )
  169. } else {
  170. None
  171. };
  172. // Initialize node
  173. let darkfid =
  174. Darkfid::new(sync_p2p.clone(), consensus_p2p.clone(), validator.clone(), subscribers).await;
  175. let darkfid = Arc::new(darkfid);
  176. info!(target: "darkfid", "Node initialized successfully!");
  177. // JSON-RPC server
  178. info!(target: "darkfid", "Starting JSON-RPC server");
  179. // Here we create a task variable so we can manually close the
  180. // task later. P2P tasks don't need this since it has its own
  181. // stop() function to shut down, also terminating the task we
  182. // created for it.
  183. let rpc_task = StoppableTask::new();
  184. let darkfid_ = darkfid.clone();
  185. rpc_task.clone().start(
  186. listen_and_serve(args.rpc_listen, darkfid.clone(), None, ex.clone()),
  187. |res| async move {
  188. match res {
  189. Ok(()) | Err(Error::RpcServerStopped) => darkfid_.stop_connections().await,
  190. Err(e) => error!(target: "darkfid", "Failed starting sync JSON-RPC server: {}", e),
  191. }
  192. },
  193. Error::RpcServerStopped,
  194. ex.clone(),
  195. );
  196. info!(target: "darkfid", "Starting sync P2P network");
  197. sync_p2p.clone().start().await?;
  198. // Consensus protocol
  199. if args.consensus {
  200. info!(target: "darkfid", "Starting consensus P2P network");
  201. let consensus_p2p = consensus_p2p.clone().unwrap();
  202. consensus_p2p.clone().start().await?;
  203. } else {
  204. info!(target: "darkfid", "Not starting consensus P2P network");
  205. }
  206. // Sync blockchain
  207. if !args.skip_sync {
  208. sync_task(&darkfid).await?;
  209. } else {
  210. darkfid.validator.write().await.synced = true;
  211. }
  212. // Clean node pending transactions
  213. darkfid.validator.write().await.purge_pending_txs().await?;
  214. // Consensus protocol
  215. let (consensus_task, consensus_sender) = if args.consensus {
  216. info!(target: "darkfid", "Starting consensus protocol task");
  217. // Grab rewards recipient public key(address)
  218. if args.recipient.is_none() {
  219. return Err(Error::ParseFailed("Recipient address missing"))
  220. }
  221. let recipient = match PublicKey::from_str(&args.recipient.unwrap()) {
  222. Ok(address) => address,
  223. Err(_) => return Err(Error::InvalidAddress),
  224. };
  225. let (sender, recvr) = smol::channel::bounded(1);
  226. let task = StoppableTask::new();
  227. task.clone().start(
  228. // Weird hack to prevent lifetimes hell
  229. async move { miner_task(&darkfid, &recipient, &recvr).await },
  230. |res| async {
  231. match res {
  232. Ok(()) | Err(Error::MinerTaskStopped) => { /* Do nothing */ }
  233. Err(e) => error!(target: "darkfid", "Failed starting miner task: {}", e),
  234. }
  235. },
  236. Error::MinerTaskStopped,
  237. ex.clone(),
  238. );
  239. (Some(task), Some(sender))
  240. } else {
  241. info!(target: "darkfid", "Not participating in consensus");
  242. (None, None)
  243. };
  244. // Signal handling for graceful termination.
  245. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  246. signals_handler.wait_termination(signals_task).await?;
  247. info!(target: "darkfid", "Caught termination signal, cleaning up and exiting...");
  248. info!(target: "darkfid", "Stopping JSON-RPC server...");
  249. rpc_task.stop().await;
  250. info!(target: "darkfid", "Stopping syncing P2P network...");
  251. sync_p2p.stop().await;
  252. if args.consensus {
  253. info!(target: "darkfid", "Stopping consensus P2P network...");
  254. consensus_p2p.unwrap().stop().await;
  255. info!(target: "darkfid", "Stopping consensus task...");
  256. // Send signal to spawned miner threads to stop
  257. consensus_sender.unwrap().send(()).await?;
  258. consensus_task.unwrap().stop().await;
  259. }
  260. info!(target: "darkfid", "Flushing sled database...");
  261. let flushed_bytes = sled_db.flush_async().await?;
  262. info!(target: "darkfid", "Flushed {} bytes", flushed_bytes);
  263. Ok(())
  264. }