main.rs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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 async_std::{
  19. stream::StreamExt,
  20. sync::{Arc, Mutex},
  21. task,
  22. };
  23. use irc::ClientSubMsg;
  24. use log::{debug, error, info, warn};
  25. use rand::rngs::OsRng;
  26. use signal_hook::consts::{SIGHUP, SIGINT, SIGQUIT, SIGTERM};
  27. use signal_hook_async_std::Signals;
  28. use structopt_toml::StructOptToml;
  29. use darkfi::{
  30. async_daemonize,
  31. event_graph::{
  32. events_queue::EventsQueue,
  33. model::Model,
  34. protocol_event::{ProtocolEvent, Seen},
  35. view::View,
  36. },
  37. net,
  38. rpc::server::listen_and_serve,
  39. system::{Subscriber, SubscriberPtr},
  40. util::{file::save_json_file, path::expand_path},
  41. Result,
  42. };
  43. pub mod crypto;
  44. pub mod irc;
  45. pub mod privmsg;
  46. pub mod rpc;
  47. pub mod settings;
  48. use crate::{
  49. crypto::KeyPair,
  50. irc::{IrcConfig, IrcServer},
  51. privmsg::PrivMsgEvent,
  52. rpc::JsonRpcInterface,
  53. settings::{Args, ChannelInfo, CONFIG_FILE, CONFIG_FILE_CONTENTS},
  54. };
  55. async_daemonize!(realmain);
  56. async fn realmain(settings: Args, executor: Arc<smol::Executor<'_>>) -> Result<()> {
  57. // Signal handling for config reload and graceful termination.
  58. let clients_subscriptions = Subscriber::new();
  59. let signals = Signals::new([SIGHUP, SIGTERM, SIGINT, SIGQUIT])?;
  60. let handle = signals.handle();
  61. let (term_tx, term_rx) = smol::channel::bounded::<()>(1);
  62. let signals_task = task::spawn(handle_signals(signals, term_tx, clients_subscriptions.clone()));
  63. ////////////////////
  64. // Generate new keypair and exit
  65. ////////////////////
  66. if settings.gen_keypair {
  67. let secret_key = crypto_box::SecretKey::generate(&mut OsRng);
  68. let pub_key = secret_key.public_key();
  69. let prv_encoded = bs58::encode(secret_key.as_bytes()).into_string();
  70. let pub_encoded = bs58::encode(pub_key.as_bytes()).into_string();
  71. let kp = KeyPair { private_key: prv_encoded, public_key: pub_encoded };
  72. if settings.output.is_some() {
  73. let datastore = expand_path(&settings.output.unwrap())?;
  74. save_json_file(&datastore, &kp)?;
  75. } else {
  76. println!("Generated KeyPair:\n{}", kp);
  77. }
  78. return Ok(())
  79. }
  80. ////////////////////
  81. // Initialize the base structures
  82. ////////////////////
  83. let events_queue = EventsQueue::<PrivMsgEvent>::new();
  84. let model = Arc::new(Mutex::new(Model::new(events_queue.clone())));
  85. let view = Arc::new(Mutex::new(View::new(events_queue)));
  86. let model_clone = model.clone();
  87. ////////////////////
  88. // P2p setup
  89. ////////////////////
  90. // Buffers
  91. let seen_event = Seen::new();
  92. let seen_inv = Seen::new();
  93. // Check the version
  94. let mut net_settings = settings.net.clone();
  95. net_settings.app_version = Some(option_env!("CARGO_PKG_VERSION").unwrap_or("").to_string());
  96. // New p2p
  97. let p2p = net::P2p::new(net_settings.into()).await;
  98. let p2p2 = p2p.clone();
  99. // Register the protocol_event
  100. let registry = p2p.protocol_registry();
  101. registry
  102. .register(net::SESSION_ALL, move |channel, p2p| {
  103. let seen_event = seen_event.clone();
  104. let seen_inv = seen_inv.clone();
  105. let model = model.clone();
  106. async move { ProtocolEvent::init(channel, p2p, model, seen_event, seen_inv).await }
  107. })
  108. .await;
  109. // Start
  110. p2p.clone().start(executor.clone()).await?;
  111. // Run
  112. let executor_cloned = executor.clone();
  113. executor_cloned.spawn(p2p.clone().run(executor.clone())).detach();
  114. ////////////////////
  115. // RPC interface setup
  116. ////////////////////
  117. let rpc_listen_addr = settings.rpc_listen.clone();
  118. let rpc_interface =
  119. Arc::new(JsonRpcInterface { addr: rpc_listen_addr.clone(), p2p: p2p.clone() });
  120. let _ex = executor.clone();
  121. executor
  122. .spawn(async move { listen_and_serve(rpc_listen_addr, rpc_interface, _ex).await })
  123. .detach();
  124. ////////////////////
  125. // IRC server
  126. ////////////////////
  127. // New irc server
  128. let irc_server = IrcServer::new(
  129. settings.clone(),
  130. p2p.clone(),
  131. model_clone,
  132. view.clone(),
  133. clients_subscriptions,
  134. )
  135. .await?;
  136. // Start the irc server and detach it
  137. let executor_cloned = executor.clone();
  138. executor_cloned.spawn(async move { irc_server.start(executor.clone()).await }).detach();
  139. ////////////////////
  140. // Wait for termination signal
  141. ////////////////////
  142. term_rx.recv().await?;
  143. print!("\r");
  144. info!("Caught termination signal, cleaning up and exiting...");
  145. handle.close();
  146. signals_task.await?;
  147. // stop p2p
  148. p2p2.stop().await;
  149. Ok(())
  150. }
  151. async fn handle_signals(
  152. mut signals: Signals,
  153. term_tx: smol::channel::Sender<()>,
  154. subscriber: SubscriberPtr<ClientSubMsg>,
  155. ) -> Result<()> {
  156. debug!("Started signal handler");
  157. while let Some(signal) = signals.next().await {
  158. match signal {
  159. SIGHUP => {
  160. let args = Args::from_args_with_toml("").unwrap();
  161. let cfg_path = darkfi::util::path::get_config_path(args.config, CONFIG_FILE)?;
  162. darkfi::util::cli::spawn_config(&cfg_path, CONFIG_FILE_CONTENTS.as_bytes())?;
  163. let args = Args::from_args_with_toml(&std::fs::read_to_string(cfg_path)?);
  164. if args.is_err() {
  165. error!("Error parsing the config file");
  166. continue
  167. }
  168. let new_config = IrcConfig::new(&args.unwrap())?;
  169. subscriber.notify(ClientSubMsg::Config(new_config)).await;
  170. }
  171. SIGTERM | SIGINT | SIGQUIT => {
  172. term_tx.send(()).await?;
  173. }
  174. _ => warn!("Unsupported signal"),
  175. }
  176. }
  177. Ok(())
  178. }