main.rs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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 log::{debug, error, info};
  19. use smol::{lock::Mutex, stream::StreamExt};
  20. use std::{collections::HashSet, sync::Arc};
  21. use url::Url;
  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. },
  29. system::{StoppableTask, StoppableTaskPtr},
  30. util::path::get_config_path,
  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. pub mod dchat_error;
  39. pub mod dchatmsg;
  40. pub mod protocol_dchat;
  41. pub mod rpc;
  42. const CONFIG_FILE: &str = "dchat_config.toml";
  43. const CONFIG_FILE_CONTENTS: &str = include_str!("../dchat_config.toml");
  44. // ANCHOR: args
  45. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  46. #[serde(default)]
  47. #[structopt(name = "dchat", about = cli_desc!())]
  48. struct Args {
  49. #[structopt(long, default_value = "tcp://127.0.0.1:51054")]
  50. /// RPC server listen address
  51. rpc_listen: Url,
  52. #[structopt(short, long)]
  53. /// Configuration file to use
  54. config: Option<String>,
  55. #[structopt(short, long)]
  56. /// Set log file to ouput into
  57. log: Option<String>,
  58. #[structopt(short, parse(from_occurrences))]
  59. /// Increase verbosity (-vvv supported)
  60. verbose: u8,
  61. /// P2P network settings
  62. #[structopt(flatten)]
  63. net: SettingsOpt,
  64. }
  65. // ANCHOR_END: args
  66. // ANCHOR: dchat
  67. struct Dchat {
  68. p2p: net::P2pPtr,
  69. recv_msgs: DchatMsgsBuffer,
  70. pub rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  71. pub dnet_sub: JsonSubscriber,
  72. }
  73. // ANCHOR_END: dchat
  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: main
  85. async_daemonize!(realmain);
  86. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  87. let cfg_path = get_config_path(args.config, CONFIG_FILE)?;
  88. let _toml_contents = std::fs::read_to_string(cfg_path)?;
  89. let p2p = net::P2p::new(args.net.into(), ex.clone()).await;
  90. // ANCHOR: dnet
  91. info!("Starting dnet subs task");
  92. let dnet_sub = JsonSubscriber::new("dnet.subscribe_events");
  93. let dnet_sub_ = dnet_sub.clone();
  94. let p2p_ = p2p.clone();
  95. let dnet_task = StoppableTask::new();
  96. dnet_task.clone().start(
  97. async move {
  98. let dnet_sub = p2p_.dnet_subscribe().await;
  99. loop {
  100. let event = dnet_sub.receive().await;
  101. debug!("Got dnet event: {:?}", event);
  102. dnet_sub_.notify(vec![event.into()].into()).await;
  103. }
  104. },
  105. |res| async {
  106. match res {
  107. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  108. Err(e) => panic!("{}", e),
  109. }
  110. },
  111. Error::DetachedTaskStopped,
  112. ex.clone(),
  113. );
  114. // ANCHOR_end: dnet
  115. // ANCHOR: rpc
  116. info!("Starting JSON-RPC server on port {}", args.rpc_listen);
  117. let msgs: DchatMsgsBuffer = Arc::new(Mutex::new(vec![DchatMsg { msg: String::new() }]));
  118. let rpc_connections = Mutex::new(HashSet::new());
  119. let dchat = Arc::new(Dchat::new(p2p.clone(), msgs.clone(), rpc_connections, dnet_sub));
  120. let _ex = ex.clone();
  121. let rpc_task = StoppableTask::new();
  122. rpc_task.clone().start(
  123. listen_and_serve(args.rpc_listen, dchat.clone(), None, ex.clone()),
  124. |res| async move {
  125. match res {
  126. Ok(()) | Err(Error::RpcServerStopped) => dchat.stop_connections().await,
  127. Err(e) => error!("Failed stopping JSON-RPC server: {}", e),
  128. }
  129. },
  130. Error::RpcServerStopped,
  131. ex.clone(),
  132. );
  133. // ANCHOR_end: rpc
  134. // ANCHOR: register_protocol
  135. info!("Registering Dchat protocol");
  136. let registry = p2p.protocol_registry();
  137. registry
  138. .register(!net::session::SESSION_SEED, move |channel, _p2p| {
  139. let msgs_ = msgs.clone();
  140. async move { ProtocolDchat::init(channel, msgs_).await }
  141. })
  142. .await;
  143. // ANCHOR_END: register_protocol
  144. // ANCHOR: p2p_start
  145. info!("Starting P2P network");
  146. p2p.clone().start().await?;
  147. // ANCHOR_END: p2p_start
  148. // ANCHOR: shutdown
  149. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  150. signals_handler.wait_termination(signals_task).await?;
  151. info!("Caught termination signal, cleaning up and exiting...");
  152. info!("Stopping P2P network");
  153. p2p.stop().await;
  154. info!("Stopping JSON-RPC server");
  155. rpc_task.stop().await;
  156. dnet_task.stop().await;
  157. info!("Shut down successfully");
  158. // ANCHOR_END: shutdown
  159. Ok(())
  160. }
  161. // ANCHOR_END: main