main.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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::{collections::HashSet, sync::Arc};
  19. use darkfi::{
  20. async_daemonize, cli_desc,
  21. event_graph::{proto::ProtocolEventGraph, EventGraph, EventGraphPtr},
  22. net::{session::SESSION_DEFAULT, settings::SettingsOpt, P2p, P2pPtr},
  23. rpc::{
  24. jsonrpc::JsonSubscriber,
  25. server::{listen_and_serve, RequestHandler},
  26. },
  27. system::{sleep, StoppableTask, StoppableTaskPtr},
  28. util::path::{expand_path, get_config_path},
  29. Error, Result,
  30. };
  31. use log::{debug, error, info};
  32. use rand::rngs::OsRng;
  33. use smol::{fs, lock::Mutex, stream::StreamExt, Executor};
  34. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  35. use url::Url;
  36. const CONFIG_FILE: &str = "darkirc_config.toml";
  37. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkirc_config.toml");
  38. /// IRC server and client handler implementation
  39. mod irc;
  40. use irc::server::IrcServer;
  41. /// Cryptography utilities
  42. mod crypto;
  43. // RLN
  44. //mod rln;
  45. /// JSON-RPC methods
  46. mod rpc;
  47. /// Settings utilities
  48. mod settings;
  49. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  50. #[serde(default)]
  51. #[structopt(name = "darkirc", about = cli_desc!())]
  52. struct Args {
  53. #[structopt(short, parse(from_occurrences))]
  54. /// Increase verbosity (-vvv supported)
  55. verbose: u8,
  56. #[structopt(short, long)]
  57. /// Configuration file to use
  58. config: Option<String>,
  59. #[structopt(long)]
  60. /// Set log file output
  61. log: Option<String>,
  62. #[structopt(long, default_value = "tcp://127.0.0.1:26660")]
  63. /// RPC server listen address
  64. rpc_listen: Url,
  65. #[structopt(long, default_value = "tcp://127.0.0.1:6667")]
  66. /// IRC server listen address
  67. irc_listen: Url,
  68. /// Optional TLS certificate file path if `irc_listen` uses TLS
  69. irc_tls_cert: Option<String>,
  70. /// Optional TLS certificate key file path if `irc_listen` uses TLS
  71. irc_tls_secret: Option<String>,
  72. #[structopt(short, long, default_value = "~/.local/darkfi/darkirc_db")]
  73. /// Datastore (DB) path
  74. datastore: String,
  75. /// Generate a new NaCl keypair and exit
  76. #[structopt(long)]
  77. gen_chacha_keypair: bool,
  78. /// Generate a new encrypted channel NaCl secret and exit
  79. #[structopt(long)]
  80. gen_channel_secret: bool,
  81. /// Recover NaCl public key from a secret key
  82. #[structopt(long)]
  83. get_chacha_pubkey: Option<String>,
  84. /// Flag to skip syncing the DAG (no history).
  85. #[structopt(long)]
  86. skip_dag_sync: bool,
  87. /// Number of attempts to sync the DAG.
  88. #[structopt(long, default_value = "5")]
  89. sync_attempts: u8,
  90. /// Number of seconds to wait before trying again if sync fails.
  91. #[structopt(long, default_value = "10")]
  92. sync_timeout: u8,
  93. /// P2P network settings
  94. #[structopt(flatten)]
  95. net: SettingsOpt,
  96. }
  97. pub struct DarkIrc {
  98. /// P2P network pointer
  99. p2p: P2pPtr,
  100. /// Sled DB (also used in event_graph and for RLN)
  101. sled: sled::Db,
  102. /// Event Graph instance
  103. event_graph: EventGraphPtr,
  104. /// JSON-RPC connection tracker
  105. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  106. /// dnet JSON-RPC subscriber
  107. dnet_sub: JsonSubscriber,
  108. /// deg JSON-RPC subscriber
  109. deg_sub: JsonSubscriber,
  110. }
  111. impl DarkIrc {
  112. fn new(
  113. p2p: P2pPtr,
  114. sled: sled::Db,
  115. event_graph: EventGraphPtr,
  116. dnet_sub: JsonSubscriber,
  117. deg_sub: JsonSubscriber,
  118. ) -> Self {
  119. Self {
  120. p2p,
  121. sled,
  122. event_graph,
  123. rpc_connections: Mutex::new(HashSet::new()),
  124. dnet_sub,
  125. deg_sub,
  126. }
  127. }
  128. }
  129. async_daemonize!(realmain);
  130. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  131. if args.gen_chacha_keypair {
  132. let secret = crypto_box::SecretKey::generate(&mut OsRng);
  133. let public = secret.public_key();
  134. let secret = bs58::encode(secret.to_bytes()).into_string();
  135. let public = bs58::encode(public.to_bytes()).into_string();
  136. println!("Place this in your config file:\n");
  137. println!("[crypto]");
  138. println!("#dm_chacha_public = \"{}\"", public);
  139. println!("dm_chacha_secret = \"{}\"", secret);
  140. return Ok(())
  141. }
  142. if args.gen_channel_secret {
  143. let secret = crypto_box::SecretKey::generate(&mut OsRng);
  144. let secret = bs58::encode(secret.to_bytes()).into_string();
  145. println!("Place this in your config file:\n");
  146. println!("[channel.\"#yourchannelname\"]");
  147. println!("secret = \"{}\"", secret);
  148. return Ok(())
  149. }
  150. if let Some(chacha_secret) = args.get_chacha_pubkey {
  151. let bytes = match bs58::decode(chacha_secret).into_vec() {
  152. Ok(v) => v,
  153. Err(e) => {
  154. println!("Error: {}", e);
  155. return Err(Error::ParseFailed("Secret key parsing failed"))
  156. }
  157. };
  158. if bytes.len() != 32 {
  159. return Err(Error::ParseFailed("Decoded base58 is not 32 bytes long"))
  160. }
  161. let secret: [u8; 32] = bytes.try_into().unwrap();
  162. let secret = crypto_box::SecretKey::from(secret);
  163. println!("{}", bs58::encode(secret.public_key().to_bytes()).into_string());
  164. return Ok(())
  165. }
  166. info!("Initializing DarkIRC node");
  167. // Create datastore path if not there already.
  168. let datastore = expand_path(&args.datastore)?;
  169. fs::create_dir_all(&datastore).await?;
  170. info!("Instantiating event DAG");
  171. let sled_db = sled::open(datastore)?;
  172. let mut p2p_settings: darkfi::net::Settings = args.net.into();
  173. p2p_settings.app_version = semver::Version::parse(env!("CARGO_PKG_VERSION")).unwrap();
  174. let p2p = P2p::new(p2p_settings, ex.clone()).await;
  175. let event_graph =
  176. EventGraph::new(p2p.clone(), sled_db.clone(), "darkirc_dag", 1, ex.clone()).await?;
  177. info!("Registering EventGraph P2P protocol");
  178. let event_graph_ = Arc::clone(&event_graph);
  179. let registry = p2p.protocol_registry();
  180. registry
  181. .register(SESSION_DEFAULT, move |channel, _| {
  182. let event_graph_ = event_graph_.clone();
  183. async move { ProtocolEventGraph::init(event_graph_, channel).await.unwrap() }
  184. })
  185. .await;
  186. info!("Starting dnet subs task");
  187. let dnet_sub = JsonSubscriber::new("dnet.subscribe_events");
  188. let dnet_sub_ = dnet_sub.clone();
  189. let p2p_ = p2p.clone();
  190. let dnet_task = StoppableTask::new();
  191. dnet_task.clone().start(
  192. async move {
  193. let dnet_sub = p2p_.dnet_subscribe().await;
  194. loop {
  195. let event = dnet_sub.receive().await;
  196. debug!("Got dnet event: {:?}", event);
  197. dnet_sub_.notify(vec![event.into()].into()).await;
  198. }
  199. },
  200. |res| async {
  201. match res {
  202. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  203. Err(e) => panic!("{}", e),
  204. }
  205. },
  206. Error::DetachedTaskStopped,
  207. ex.clone(),
  208. );
  209. info!("Starting deg subs task");
  210. let deg_sub = JsonSubscriber::new("deg.subscribe_events");
  211. let deg_sub_ = deg_sub.clone();
  212. let event_graph_ = event_graph.clone();
  213. let deg_task = StoppableTask::new();
  214. deg_task.clone().start(
  215. async move {
  216. let deg_sub = event_graph_.deg_subscribe().await;
  217. loop {
  218. let event = deg_sub.receive().await;
  219. debug!("Got deg event: {:?}", event);
  220. deg_sub_.notify(vec![event.into()].into()).await;
  221. }
  222. },
  223. |res| async {
  224. match res {
  225. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  226. Err(e) => panic!("{}", e),
  227. }
  228. },
  229. Error::DetachedTaskStopped,
  230. ex.clone(),
  231. );
  232. info!("Starting JSON-RPC server");
  233. let darkirc = Arc::new(DarkIrc::new(
  234. p2p.clone(),
  235. sled_db.clone(),
  236. event_graph.clone(),
  237. dnet_sub,
  238. deg_sub,
  239. ));
  240. let darkirc_ = Arc::clone(&darkirc);
  241. let rpc_task = StoppableTask::new();
  242. rpc_task.clone().start(
  243. listen_and_serve(args.rpc_listen, darkirc.clone(), None, ex.clone()),
  244. |res| async move {
  245. match res {
  246. Ok(()) | Err(Error::RpcServerStopped) => darkirc_.stop_connections().await,
  247. Err(e) => error!("Failed stopping JSON-RPC server: {}", e),
  248. }
  249. },
  250. Error::RpcServerStopped,
  251. ex.clone(),
  252. );
  253. info!("Starting IRC server");
  254. let config_path = get_config_path(args.config, CONFIG_FILE)?;
  255. let irc_server = IrcServer::new(
  256. darkirc.clone(),
  257. args.irc_listen,
  258. args.irc_tls_cert,
  259. args.irc_tls_secret,
  260. config_path,
  261. )
  262. .await?;
  263. let irc_task = StoppableTask::new();
  264. let ex_ = ex.clone();
  265. irc_task.clone().start(
  266. irc_server.clone().listen(ex_),
  267. |res| async move {
  268. match res {
  269. Ok(()) | Err(Error::DetachedTaskStopped) => { /* TODO: */ }
  270. Err(e) => error!("Failed stopping IRC server: {}", e),
  271. }
  272. },
  273. Error::DetachedTaskStopped,
  274. ex.clone(),
  275. );
  276. info!("Starting P2P network");
  277. p2p.clone().start().await?;
  278. info!("Waiting for some P2P connections...");
  279. sleep(5).await;
  280. // We'll attempt to sync {sync_attempts} times
  281. if !args.skip_dag_sync {
  282. for i in 1..=args.sync_attempts {
  283. info!("Syncing event DAG (attempt #{})", i);
  284. match event_graph.dag_sync().await {
  285. Ok(()) => break,
  286. Err(e) => {
  287. if i == args.sync_attempts {
  288. error!("Failed syncing DAG. Exiting.");
  289. p2p.stop().await;
  290. return Err(Error::DagSyncFailed)
  291. } else {
  292. // TODO: Maybe at this point we should prune or something?
  293. // TODO: Or maybe just tell the user to delete the DAG from FS.
  294. error!("Failed syncing DAG ({}), retrying in {}s...", e, args.sync_timeout);
  295. sleep(args.sync_timeout.into()).await;
  296. }
  297. }
  298. }
  299. }
  300. } else {
  301. *event_graph.synced.write().await = true;
  302. }
  303. // Signal handling for graceful termination.
  304. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  305. signals_handler.wait_termination(signals_task).await?;
  306. info!("Caught termination signal, cleaning up and exiting...");
  307. info!("Stopping P2P network");
  308. p2p.stop().await;
  309. info!("Stopping JSON-RPC server");
  310. rpc_task.stop().await;
  311. dnet_task.stop().await;
  312. deg_task.stop().await;
  313. info!("Stopping IRC server");
  314. irc_task.stop().await;
  315. info!("Flushing sled database...");
  316. let flushed_bytes = sled_db.flush_async().await?;
  317. info!("Flushed {} bytes", flushed_bytes);
  318. info!("Shut down successfully");
  319. Ok(())
  320. }