main.rs 6.2 KB

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