main.rs 9.7 KB

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