main.rs 9.8 KB

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