main.rs 5.8 KB

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