main.rs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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. // ANCHOR: imports
  19. use smol::{lock::Mutex, stream::StreamExt};
  20. use std::{collections::HashSet, sync::Arc};
  21. use tracing::{debug, error, info};
  22. use darkfi::{
  23. async_daemonize, cli_desc, net,
  24. net::settings::SettingsOpt,
  25. rpc::{
  26. jsonrpc::JsonSubscriber,
  27. server::{listen_and_serve, RequestHandler},
  28. settings::{RpcSettings, RpcSettingsOpt},
  29. },
  30. system::{StoppableTask, StoppableTaskPtr},
  31. Error, Result,
  32. };
  33. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  34. use crate::{
  35. dchatmsg::{DchatMsg, DchatMsgsBuffer},
  36. protocol_dchat::ProtocolDchat,
  37. };
  38. // ANCHOR_END: imports
  39. pub mod dchat_error;
  40. pub mod dchatmsg;
  41. pub mod protocol_dchat;
  42. pub mod rpc;
  43. const CONFIG_FILE: &str = "dchatd_config.toml";
  44. const CONFIG_FILE_CONTENTS: &str = include_str!("../dchatd_config.toml");
  45. // ANCHOR: args
  46. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  47. #[serde(default)]
  48. #[structopt(name = "dchat", about = cli_desc!())]
  49. struct Args {
  50. #[structopt(flatten)]
  51. /// JSON-RPC settings
  52. rpc: RpcSettingsOpt,
  53. #[structopt(short, long)]
  54. /// Configuration file to use
  55. config: Option<String>,
  56. #[structopt(short, long)]
  57. /// Set log file to ouput into
  58. log: Option<String>,
  59. #[structopt(short, parse(from_occurrences))]
  60. /// Increase verbosity (-vvv supported)
  61. verbose: u8,
  62. #[structopt(flatten)]
  63. /// P2P network settings
  64. net: SettingsOpt,
  65. }
  66. // ANCHOR_END: args
  67. // ANCHOR: dchat
  68. struct Dchat {
  69. p2p: net::P2pPtr,
  70. recv_msgs: DchatMsgsBuffer,
  71. pub rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  72. pub dnet_sub: JsonSubscriber,
  73. }
  74. impl Dchat {
  75. fn new(
  76. p2p: net::P2pPtr,
  77. recv_msgs: DchatMsgsBuffer,
  78. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  79. dnet_sub: JsonSubscriber,
  80. ) -> Self {
  81. Self { p2p, recv_msgs, rpc_connections, dnet_sub }
  82. }
  83. }
  84. // ANCHOR_END: dchat
  85. // ANCHOR: main
  86. async_daemonize!(realmain);
  87. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  88. let p2p_settings: net::Settings =
  89. (env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), args.net).try_into()?;
  90. let p2p = net::P2p::new(p2p_settings, ex.clone()).await?;
  91. // ANCHOR: dnet
  92. info!("Starting dnet subs task");
  93. let dnet_sub = JsonSubscriber::new("dnet.subscribe_events");
  94. let dnet_sub_ = dnet_sub.clone();
  95. let p2p_ = p2p.clone();
  96. let dnet_task = StoppableTask::new();
  97. dnet_task.clone().start(
  98. async move {
  99. let dnet_sub = p2p_.dnet_subscribe().await;
  100. loop {
  101. let event = dnet_sub.receive().await;
  102. debug!("Got dnet event: {event:?}");
  103. dnet_sub_.notify(vec![event.into()].into()).await;
  104. }
  105. },
  106. |res| async {
  107. match res {
  108. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  109. Err(e) => panic!("{e}"),
  110. }
  111. },
  112. Error::DetachedTaskStopped,
  113. ex.clone(),
  114. );
  115. // ANCHOR_end: dnet
  116. // ANCHOR: rpc
  117. let rpc_settings: RpcSettings = args.rpc.into();
  118. info!("Starting JSON-RPC server on port {}", rpc_settings.listen);
  119. let msgs: DchatMsgsBuffer = Arc::new(Mutex::new(vec![DchatMsg { msg: String::new() }]));
  120. let rpc_connections = Mutex::new(HashSet::new());
  121. let dchat = Arc::new(Dchat::new(p2p.clone(), msgs.clone(), rpc_connections, dnet_sub));
  122. let _ex = ex.clone();
  123. let rpc_task = StoppableTask::new();
  124. rpc_task.clone().start(
  125. listen_and_serve(rpc_settings, dchat.clone(), None, ex.clone()),
  126. |res| async move {
  127. match res {
  128. Ok(()) | Err(Error::RpcServerStopped) => dchat.stop_connections().await,
  129. Err(e) => error!("Failed stopping JSON-RPC server: {e}"),
  130. }
  131. },
  132. Error::RpcServerStopped,
  133. ex.clone(),
  134. );
  135. // ANCHOR_end: rpc
  136. // ANCHOR: register_protocol
  137. info!("Registering Dchat protocol");
  138. let registry = p2p.protocol_registry();
  139. registry
  140. .register(net::session::SESSION_DEFAULT, move |channel, _p2p| {
  141. let msgs_ = msgs.clone();
  142. async move { ProtocolDchat::init(channel, msgs_).await }
  143. })
  144. .await;
  145. // ANCHOR_END: register_protocol
  146. // ANCHOR: p2p_start
  147. info!("Starting P2P network");
  148. p2p.clone().start().await?;
  149. // ANCHOR_END: p2p_start
  150. // ANCHOR: shutdown
  151. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  152. signals_handler.wait_termination(signals_task).await?;
  153. info!("Caught termination signal, cleaning up and exiting...");
  154. info!("Stopping JSON-RPC server");
  155. rpc_task.stop().await;
  156. info!("Stopping dnet tasks");
  157. dnet_task.stop().await;
  158. info!("Stopping P2P network");
  159. p2p.stop().await;
  160. info!("Shut down successfully");
  161. // ANCHOR_END: shutdown
  162. Ok(())
  163. }
  164. // ANCHOR_END: main