main.rs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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 log::{debug, error, info};
  20. use smol::{lock::Mutex, stream::StreamExt};
  21. use std::{collections::HashSet, sync::Arc};
  22. use url::Url;
  23. use darkfi::{
  24. async_daemonize, cli_desc, net,
  25. net::settings::SettingsOpt,
  26. rpc::{
  27. jsonrpc::JsonSubscriber,
  28. server::{listen_and_serve, RequestHandler},
  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(long, default_value = "tcp://127.0.0.1:51054")]
  51. /// RPC server listen address
  52. rpc_listen: Url,
  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. /// P2P network settings
  63. #[structopt(flatten)]
  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 = net::P2p::new(args.net.into(), ex.clone()).await;
  89. // ANCHOR: dnet
  90. info!("Starting dnet subs task");
  91. let dnet_sub = JsonSubscriber::new("dnet.subscribe_events");
  92. let dnet_sub_ = dnet_sub.clone();
  93. let p2p_ = p2p.clone();
  94. let dnet_task = StoppableTask::new();
  95. dnet_task.clone().start(
  96. async move {
  97. let dnet_sub = p2p_.dnet_subscribe().await;
  98. loop {
  99. let event = dnet_sub.receive().await;
  100. debug!("Got dnet event: {:?}", event);
  101. dnet_sub_.notify(vec![event.into()].into()).await;
  102. }
  103. },
  104. |res| async {
  105. match res {
  106. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  107. Err(e) => panic!("{}", e),
  108. }
  109. },
  110. Error::DetachedTaskStopped,
  111. ex.clone(),
  112. );
  113. // ANCHOR_end: dnet
  114. // ANCHOR: rpc
  115. info!("Starting JSON-RPC server on port {}", args.rpc_listen);
  116. let msgs: DchatMsgsBuffer = Arc::new(Mutex::new(vec![DchatMsg { msg: String::new() }]));
  117. let rpc_connections = Mutex::new(HashSet::new());
  118. let dchat = Arc::new(Dchat::new(p2p.clone(), msgs.clone(), rpc_connections, dnet_sub));
  119. let _ex = ex.clone();
  120. let rpc_task = StoppableTask::new();
  121. rpc_task.clone().start(
  122. listen_and_serve(args.rpc_listen, dchat.clone(), None, ex.clone()),
  123. |res| async move {
  124. match res {
  125. Ok(()) | Err(Error::RpcServerStopped) => dchat.stop_connections().await,
  126. Err(e) => error!("Failed stopping JSON-RPC server: {}", e),
  127. }
  128. },
  129. Error::RpcServerStopped,
  130. ex.clone(),
  131. );
  132. // ANCHOR_end: rpc
  133. // ANCHOR: register_protocol
  134. info!("Registering Dchat protocol");
  135. let registry = p2p.protocol_registry();
  136. registry
  137. .register(net::session::SESSION_DEFAULT, move |channel, _p2p| {
  138. let msgs_ = msgs.clone();
  139. async move { ProtocolDchat::init(channel, msgs_).await }
  140. })
  141. .await;
  142. // ANCHOR_END: register_protocol
  143. // ANCHOR: p2p_start
  144. info!("Starting P2P network");
  145. p2p.clone().start().await?;
  146. // ANCHOR_END: p2p_start
  147. // ANCHOR: shutdown
  148. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  149. signals_handler.wait_termination(signals_task).await?;
  150. info!("Caught termination signal, cleaning up and exiting...");
  151. info!("Stopping JSON-RPC server");
  152. rpc_task.stop().await;
  153. info!("Stopping dnet tasks");
  154. dnet_task.stop().await;
  155. info!("Stopping P2P network");
  156. p2p.stop().await;
  157. info!("Shut down successfully");
  158. // ANCHOR_END: shutdown
  159. Ok(())
  160. }
  161. // ANCHOR_END: main