main.rs 7.3 KB

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