main.rs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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::fmt;
  19. use async_std::sync::{Arc, Mutex};
  20. use log::{info, warn};
  21. use rand::rngs::OsRng;
  22. use smol::channel::Receiver;
  23. use structopt_toml::StructOptToml;
  24. use darkfi::{
  25. async_daemonize, net,
  26. rpc::server::listen_and_serve,
  27. system::{Subscriber, SubscriberPtr},
  28. util::{file::save_json_file, path::expand_path},
  29. Result,
  30. };
  31. pub mod buffers;
  32. pub mod crypto;
  33. pub mod irc;
  34. pub mod model;
  35. pub mod privmsg;
  36. pub mod protocol_privmsg;
  37. pub mod protocol_privmsg2;
  38. pub mod rpc;
  39. pub mod settings;
  40. pub mod view;
  41. use crate::{
  42. buffers::SeenIds,
  43. irc::IrcServer,
  44. privmsg::Privmsg,
  45. protocol_privmsg::ProtocolPrivmsg,
  46. rpc::JsonRpcInterface,
  47. settings::{Args, ChannelInfo, CONFIG_FILE, CONFIG_FILE_CONTENTS},
  48. };
  49. #[derive(serde::Serialize)]
  50. struct KeyPair {
  51. private_key: String,
  52. public_key: String,
  53. }
  54. impl fmt::Display for KeyPair {
  55. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  56. write!(f, "Public key: {}\nPrivate key: {}", self.public_key, self.private_key)
  57. }
  58. }
  59. struct Ircd {
  60. notify_clients: SubscriberPtr<Privmsg>,
  61. }
  62. impl Ircd {
  63. fn new() -> Self {
  64. let notify_clients = Subscriber::new();
  65. Self { notify_clients }
  66. }
  67. async fn start(
  68. &self,
  69. settings: &Args,
  70. seen: Arc<Mutex<SeenIds>>,
  71. p2p: net::P2pPtr,
  72. p2p_receiver: Receiver<Privmsg>,
  73. executor: Arc<smol::Executor<'_>>,
  74. ) -> Result<()> {
  75. let notify_clients = self.notify_clients.clone();
  76. executor
  77. .spawn(async move {
  78. while let Ok(msg) = p2p_receiver.recv().await {
  79. notify_clients.notify(msg).await;
  80. }
  81. })
  82. .detach();
  83. let irc_server = IrcServer::new(
  84. settings.clone(),
  85. seen.clone(),
  86. p2p.clone(),
  87. self.notify_clients.clone(),
  88. )
  89. .await?;
  90. let executor_cloned = executor.clone();
  91. executor
  92. .spawn(async move {
  93. irc_server.start(executor_cloned.clone()).await.unwrap();
  94. })
  95. .detach();
  96. Ok(())
  97. }
  98. }
  99. async_daemonize!(realmain);
  100. async fn realmain(settings: Args, executor: Arc<smol::Executor<'_>>) -> Result<()> {
  101. let seen = Arc::new(Mutex::new(SeenIds::new()));
  102. if settings.gen_secret {
  103. let secret_key = crypto_box::SecretKey::generate(&mut OsRng);
  104. let encoded = bs58::encode(secret_key.as_bytes());
  105. println!("{}", encoded.into_string());
  106. return Ok(())
  107. }
  108. if settings.gen_keypair {
  109. let secret_key = crypto_box::SecretKey::generate(&mut OsRng);
  110. let pub_key = secret_key.public_key();
  111. let prv_encoded = bs58::encode(secret_key.as_bytes()).into_string();
  112. let pub_encoded = bs58::encode(pub_key.as_bytes()).into_string();
  113. let kp = KeyPair { private_key: prv_encoded, public_key: pub_encoded };
  114. if settings.output.is_some() {
  115. let datastore = expand_path(&settings.output.unwrap())?;
  116. save_json_file(&datastore, &kp)?;
  117. } else {
  118. println!("Generated KeyPair:\n{}", kp);
  119. }
  120. return Ok(())
  121. }
  122. if settings.secret.is_some() {
  123. let secret = settings.secret.clone().unwrap();
  124. let bytes: [u8; 32] = bs58::decode(secret).into_vec()?.try_into().unwrap();
  125. let secret = crypto_box::SecretKey::from(bytes);
  126. let pubkey = secret.public_key();
  127. let pub_encoded = bs58::encode(pubkey.as_bytes()).into_string();
  128. if settings.output.is_some() {
  129. let datastore = expand_path(&settings.output.unwrap())?;
  130. save_json_file(&datastore, &pub_encoded)?;
  131. } else {
  132. println!("Public key recoverd: {}", pub_encoded);
  133. }
  134. return Ok(())
  135. }
  136. //
  137. // P2p setup
  138. //
  139. let mut net_settings = settings.net.clone();
  140. net_settings.app_version = Some(option_env!("CARGO_PKG_VERSION").unwrap_or("").to_string());
  141. let (p2p_send_channel, p2p_recv_channel) = smol::channel::unbounded::<Privmsg>();
  142. let p2p = net::P2p::new(net_settings.into()).await;
  143. let p2p2 = p2p.clone();
  144. let registry = p2p.protocol_registry();
  145. let seen_c = seen.clone();
  146. registry
  147. .register(net::SESSION_ALL, move |channel, p2p| {
  148. let sender = p2p_send_channel.clone();
  149. let seen = seen_c.clone();
  150. async move { ProtocolPrivmsg::init(channel, sender, p2p, seen).await }
  151. })
  152. .await;
  153. p2p.clone().start(executor.clone()).await?;
  154. let executor_cloned = executor.clone();
  155. executor_cloned.spawn(p2p.clone().run(executor.clone())).detach();
  156. // RPC interface
  157. let rpc_listen_addr = settings.rpc_listen.clone();
  158. let rpc_interface =
  159. Arc::new(JsonRpcInterface { addr: rpc_listen_addr.clone(), p2p: p2p.clone() });
  160. let _ex = executor.clone();
  161. executor
  162. .spawn(async move { listen_and_serve(rpc_listen_addr, rpc_interface, _ex).await })
  163. .detach();
  164. //
  165. // IRC instance
  166. //
  167. let ircd = Ircd::new();
  168. ircd.start(&settings, seen, p2p, p2p_recv_channel, executor.clone()).await?;
  169. // Run once receive exit signal
  170. let (signal, shutdown) = smol::channel::bounded::<()>(1);
  171. ctrlc::set_handler(move || {
  172. warn!(target: "ircd", "ircd start Exit Signal");
  173. // cleaning up tasks running in the background
  174. async_std::task::block_on(signal.send(())).unwrap();
  175. })
  176. .unwrap();
  177. // Wait for SIGINT
  178. shutdown.recv().await?;
  179. print!("\r");
  180. info!("Caught termination signal, cleaning up and exiting...");
  181. p2p2.stop().await;
  182. Ok(())
  183. }