main.rs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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, info};
  26. use rand::rngs::OsRng;
  27. use structopt_toml::StructOptToml;
  28. use darkfi::{
  29. async_daemonize,
  30. event_graph::{
  31. events_queue::EventsQueue,
  32. model::{Model, ModelPtr},
  33. protocol_event::{ProtocolEvent, Seen},
  34. view::View,
  35. },
  36. net,
  37. rpc::server::listen_and_serve,
  38. system::{Subscriber, SubscriberPtr},
  39. util::{async_util::sleep, file::save_json_file, path::expand_path, time::Timestamp},
  40. Result,
  41. };
  42. pub mod crypto;
  43. pub mod irc;
  44. pub mod privmsg;
  45. pub mod rpc;
  46. pub mod settings;
  47. use crate::{
  48. crypto::KeyPair,
  49. irc::{IrcConfig, IrcServer},
  50. privmsg::PrivMsgEvent,
  51. rpc::JsonRpcInterface,
  52. settings::{Args, ChannelInfo, CONFIG_FILE, CONFIG_FILE_CONTENTS},
  53. };
  54. async fn parse_signals(
  55. sighup_sub: SubscriberPtr<Args>,
  56. client_sub: SubscriberPtr<ClientSubMsg>,
  57. ) -> Result<()> {
  58. debug!("Started signal parsing handler");
  59. let subscription = sighup_sub.subscribe().await;
  60. loop {
  61. let args = subscription.receive().await;
  62. let new_config = IrcConfig::new(&args)?;
  63. client_sub.notify(ClientSubMsg::Config(new_config)).await;
  64. }
  65. }
  66. async fn reset_root(model: ModelPtr<PrivMsgEvent>) {
  67. loop {
  68. let now = Utc::now();
  69. // clocks are valid, safe to unwrap
  70. let next_midnight = (now + Duration::days(1)).date_naive().and_hms_opt(0, 0, 0).unwrap();
  71. let duration = next_midnight.signed_duration_since(now.naive_utc()).to_std().unwrap();
  72. // make sure the root is the same as everyone else's at
  73. // startup by passing today's date 00:00 AM UTC as
  74. // timestamp to root_event
  75. let now_datetime = now.date_naive().and_hms_opt(0, 0, 0).unwrap();
  76. let timestamp = now_datetime.timestamp() as u64;
  77. model.lock().await.reset_root(Timestamp(timestamp));
  78. sleep(duration.as_secs()).await;
  79. info!("Resetting root");
  80. }
  81. }
  82. async_daemonize!(realmain);
  83. async fn realmain(settings: Args, executor: Arc<smol::Executor<'_>>) -> Result<()> {
  84. // Signal handling for config reload and graceful termination.
  85. let (signals_handler, signals_task) = SignalHandler::new()?;
  86. let client_sub = Subscriber::new();
  87. task::spawn(parse_signals(signals_handler.sighup_sub.clone(), client_sub.clone()));
  88. ////////////////////
  89. // Generate new keypair and exit
  90. ////////////////////
  91. if settings.gen_keypair {
  92. let secret_key = crypto_box::SecretKey::generate(&mut OsRng);
  93. let public_key = secret_key.public_key();
  94. let secret = bs58::encode(secret_key.to_bytes()).into_string();
  95. let public = bs58::encode(public_key.as_bytes()).into_string();
  96. let kp = KeyPair { secret, public };
  97. if settings.output.is_some() {
  98. let datastore = expand_path(&settings.output.unwrap())?;
  99. save_json_file(&datastore, &kp, false)?;
  100. } else {
  101. println!("Generated keypair:\n{}", kp);
  102. }
  103. return Ok(())
  104. }
  105. if settings.gen_secret {
  106. let secret_key = crypto_box::SecretKey::generate(&mut OsRng);
  107. let encoded = bs58::encode(secret_key.to_bytes());
  108. println!("{}", encoded.into_string());
  109. return Ok(())
  110. }
  111. ////////////////////
  112. // Initialize the base structures
  113. ////////////////////
  114. let events_queue = EventsQueue::<PrivMsgEvent>::new();
  115. let model = Arc::new(Mutex::new(Model::new(events_queue.clone())));
  116. let view = Arc::new(Mutex::new(View::new(events_queue)));
  117. let model_clone = model.clone();
  118. let model_clone2 = model.clone();
  119. ////////////////////
  120. // P2p setup
  121. ////////////////////
  122. // Buffers
  123. let seen_event = Seen::new();
  124. let seen_inv = Seen::new();
  125. // Check the version
  126. let net_settings = settings.net.clone();
  127. // New p2p
  128. let p2p = net::P2p::new(net_settings.into()).await;
  129. let p2p2 = p2p.clone();
  130. // Register the protocol_event
  131. let registry = p2p.protocol_registry();
  132. registry
  133. .register(net::SESSION_ALL, move |channel, p2p| {
  134. let seen_event = seen_event.clone();
  135. let seen_inv = seen_inv.clone();
  136. let model = model.clone();
  137. async move { ProtocolEvent::init(channel, p2p, model, seen_event, seen_inv).await }
  138. })
  139. .await;
  140. // Start
  141. p2p.clone().start(executor.clone()).await?;
  142. // Run
  143. let executor_cloned = executor.clone();
  144. executor_cloned.spawn(p2p.clone().run(executor.clone())).detach();
  145. ////////////////////
  146. // RPC interface setup
  147. ////////////////////
  148. let rpc_listen_addr = settings.rpc_listen.clone();
  149. let rpc_interface =
  150. Arc::new(JsonRpcInterface { addr: rpc_listen_addr.clone(), p2p: p2p.clone() });
  151. let _ex = executor.clone();
  152. executor
  153. .spawn(async move { listen_and_serve(rpc_listen_addr, rpc_interface, _ex).await })
  154. .detach();
  155. ////////////////////
  156. // IRC server
  157. ////////////////////
  158. // New irc server
  159. let irc_server =
  160. IrcServer::new(settings.clone(), p2p.clone(), model_clone, view.clone(), client_sub)
  161. .await?;
  162. // Start the irc server and detach it
  163. let executor_cloned = executor.clone();
  164. executor.spawn(async move { irc_server.start(executor_cloned).await }).detach();
  165. // Reset root task
  166. executor.spawn(async move { reset_root(model_clone2).await }).detach();
  167. // Wait for termination signal
  168. signals_handler.wait_termination(signals_task).await?;
  169. info!("Caught termination signal, cleaning up and exiting...");
  170. // stop p2p
  171. p2p2.stop().await;
  172. Ok(())
  173. }