evgrd.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. use darkfi::{
  19. async_daemonize, cli_desc,
  20. event_graph::{self, proto::ProtocolEventGraph, EventGraph, EventGraphPtr},
  21. net::{
  22. session::SESSION_DEFAULT,
  23. settings::SettingsOpt as NetSettingsOpt,
  24. transport::{Listener, PtListener, PtStream},
  25. P2p, P2pPtr,
  26. },
  27. rpc::{
  28. jsonrpc::JsonSubscriber,
  29. server::{listen_and_serve, RequestHandler},
  30. },
  31. system::{sleep, Publisher, PublisherPtr, StoppableTask, StoppableTaskPtr},
  32. util::path::{expand_path, get_config_path},
  33. Error, Result,
  34. };
  35. use darkfi_serial::{
  36. async_trait, deserialize_async, serialize_async, AsyncDecodable, AsyncEncodable, Encodable,
  37. SerialDecodable, SerialEncodable,
  38. };
  39. use futures::FutureExt;
  40. use log::{debug, error, info};
  41. use rand::rngs::OsRng;
  42. use sled_overlay::sled;
  43. use smol::{fs, lock::Mutex, stream::StreamExt, Executor};
  44. use std::{
  45. collections::HashSet,
  46. path::PathBuf,
  47. sync::{Arc, Mutex as SyncMutex},
  48. };
  49. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  50. use url::Url;
  51. use evgrd::{FetchEventsMessage, VersionMessage, MSG_EVENT, MSG_FETCHEVENTS};
  52. mod rpc;
  53. const CONFIG_FILE: &str = "evgrd.toml";
  54. const CONFIG_FILE_CONTENTS: &str = include_str!("../evgrd.toml");
  55. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  56. #[serde(default)]
  57. #[structopt(name = "evgrd", about = cli_desc!())]
  58. struct Args {
  59. #[structopt(short, parse(from_occurrences))]
  60. /// Increase verbosity (-vvv supported)
  61. verbose: u8,
  62. #[structopt(short, long)]
  63. /// Configuration file to use
  64. config: Option<String>,
  65. #[structopt(long)]
  66. /// Set log file output
  67. log: Option<String>,
  68. #[structopt(long, default_value = "tcp://127.0.0.1:5588")]
  69. /// RPC server listen address
  70. daemon_listen: Url,
  71. #[structopt(long, default_value = "tcp://127.0.0.1:26690")]
  72. /// JSON-RPC server listen address
  73. json_rpc_listen: Url,
  74. #[structopt(short, long, default_value = "~/.local/darkfi/evgrd_db")]
  75. /// Datastore (DB) path
  76. datastore: String,
  77. #[structopt(short, long, default_value = "~/.local/darkfi/replayed_evgrd_db")]
  78. /// Replay logs (DB) path
  79. replay_datastore: String,
  80. /// Flag to store Sled DB instructions
  81. #[structopt(long)]
  82. replay_mode: bool,
  83. /// Flag to skip syncing the DAG (no history).
  84. #[structopt(long)]
  85. skip_dag_sync: bool,
  86. /// Number of attempts to sync the DAG.
  87. #[structopt(long, default_value = "5")]
  88. sync_attempts: u8,
  89. /// Number of seconds to wait before trying again if sync fails.
  90. #[structopt(long, default_value = "10")]
  91. sync_timeout: u8,
  92. /// P2P network settings
  93. #[structopt(flatten)]
  94. net: NetSettingsOpt,
  95. }
  96. pub struct Daemon {
  97. /// P2P network pointer
  98. p2p: P2pPtr,
  99. ///// Sled DB (also used in event_graph and for RLN)
  100. //sled: sled::Db,
  101. /// Event Graph instance
  102. event_graph: EventGraphPtr,
  103. /// JSON-RPC connection tracker
  104. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  105. /// dnet JSON-RPC subscriber
  106. dnet_sub: JsonSubscriber,
  107. /// deg JSON-RPC subscriber
  108. deg_sub: JsonSubscriber,
  109. /// Replay logs (DB) path
  110. replay_datastore: PathBuf,
  111. }
  112. impl Daemon {
  113. fn new(
  114. p2p: P2pPtr,
  115. //sled: sled::Db,
  116. event_graph: EventGraphPtr,
  117. dnet_sub: JsonSubscriber,
  118. deg_sub: JsonSubscriber,
  119. replay_datastore: PathBuf,
  120. ) -> Self {
  121. Self {
  122. p2p,
  123. //sled,
  124. event_graph,
  125. rpc_connections: Mutex::new(HashSet::new()),
  126. dnet_sub,
  127. deg_sub,
  128. replay_datastore,
  129. }
  130. }
  131. }
  132. async fn rpc_serve(
  133. listener: Box<dyn PtListener>,
  134. daemon: Arc<Daemon>,
  135. ex: Arc<Executor<'_>>,
  136. ) -> Result<()> {
  137. loop {
  138. match listener.next().await {
  139. Ok((stream, url)) => {
  140. info!(target: "evgrd", "Accepted connection from {url}");
  141. ex.spawn(handle_connect(stream, daemon.clone(), ex.clone())).detach();
  142. }
  143. // Errors we didn't handle above:
  144. Err(e) => {
  145. error!(
  146. target: "evgrd",
  147. "Unhandled listener.next() error: {}", e,
  148. );
  149. continue
  150. }
  151. }
  152. }
  153. Ok(())
  154. }
  155. async fn handle_connect(
  156. mut stream: Box<dyn PtStream>,
  157. daemon: Arc<Daemon>,
  158. ex: Arc<Executor<'_>>,
  159. ) -> Result<()> {
  160. let client_version = VersionMessage::decode_async(&mut stream).await?;
  161. info!(target: "evgrd", "Client version: {}", client_version.protocol_version);
  162. let version = VersionMessage::new();
  163. version.encode_async(&mut stream).await?;
  164. let event_sub = daemon.event_graph.event_pub.clone().subscribe().await;
  165. loop {
  166. futures::select! {
  167. ev = event_sub.receive().fuse() => {
  168. MSG_EVENT.encode_async(&mut stream).await?;
  169. ev.encode_async(&mut stream).await?;
  170. }
  171. msg_type = u8::decode_async(&mut stream).fuse() => {
  172. let msg_type = msg_type?;
  173. if msg_type != MSG_FETCHEVENTS {
  174. error!(target: "evgrd", "Connection received invalid msg_type: {msg_type}");
  175. return Err(Error::MalformedPacket)
  176. }
  177. let fetchevs = FetchEventsMessage::decode_async(&mut stream).await?;
  178. info!(target: "evgrd", "Fetching events {fetchevs:?}");
  179. // Now do your thing with the daemon and get missing tips
  180. // Then send them like this:
  181. // for ev in evs {
  182. // MSG_EVENT.encode_async(&mut stream).await?;
  183. // ev.encode_async(&mut stream).await?;
  184. // }
  185. }
  186. }
  187. }
  188. Ok(())
  189. }
  190. async_daemonize!(realmain);
  191. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  192. info!("Starting evgrd node");
  193. // Create datastore path if not there already.
  194. let datastore = expand_path(&args.datastore)?;
  195. fs::create_dir_all(&datastore).await?;
  196. let replay_datastore = expand_path(&args.replay_datastore)?;
  197. let replay_mode = args.replay_mode;
  198. info!("Instantiating event DAG");
  199. let sled_db = sled::open(datastore)?;
  200. let mut p2p_settings: darkfi::net::Settings = args.net.into();
  201. p2p_settings.app_version = semver::Version::parse(env!("CARGO_PKG_VERSION")).unwrap();
  202. let p2p = P2p::new(p2p_settings, ex.clone()).await?;
  203. let event_graph = EventGraph::new(
  204. p2p.clone(),
  205. sled_db.clone(),
  206. replay_datastore.clone(),
  207. replay_mode,
  208. "darkirc_dag",
  209. 1,
  210. ex.clone(),
  211. )
  212. .await?;
  213. let prune_task = event_graph.prune_task.get().unwrap();
  214. info!("Registering EventGraph P2P protocol");
  215. let event_graph_ = Arc::clone(&event_graph);
  216. let registry = p2p.protocol_registry();
  217. registry
  218. .register(SESSION_DEFAULT, move |channel, _| {
  219. let event_graph_ = event_graph_.clone();
  220. async move { ProtocolEventGraph::init(event_graph_, channel).await.unwrap() }
  221. })
  222. .await;
  223. info!("Starting dnet subs task");
  224. let dnet_sub = JsonSubscriber::new("dnet.subscribe_events");
  225. let dnet_sub_ = dnet_sub.clone();
  226. let p2p_ = p2p.clone();
  227. let dnet_task = StoppableTask::new();
  228. dnet_task.clone().start(
  229. async move {
  230. let dnet_sub = p2p_.dnet_subscribe().await;
  231. loop {
  232. let event = dnet_sub.receive().await;
  233. debug!("Got dnet event: {:?}", event);
  234. dnet_sub_.notify(vec![event.into()].into()).await;
  235. }
  236. },
  237. |res| async {
  238. match res {
  239. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  240. Err(e) => panic!("{}", e),
  241. }
  242. },
  243. Error::DetachedTaskStopped,
  244. ex.clone(),
  245. );
  246. info!("Starting deg subs task");
  247. let deg_sub = JsonSubscriber::new("deg.subscribe_events");
  248. let deg_sub_ = deg_sub.clone();
  249. let event_graph_ = event_graph.clone();
  250. let deg_task = StoppableTask::new();
  251. deg_task.clone().start(
  252. async move {
  253. let deg_sub = event_graph_.deg_subscribe().await;
  254. loop {
  255. let event = deg_sub.receive().await;
  256. debug!("Got deg event: {:?}", event);
  257. deg_sub_.notify(vec![event.into()].into()).await;
  258. }
  259. },
  260. |res| async {
  261. match res {
  262. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  263. Err(e) => panic!("{}", e),
  264. }
  265. },
  266. Error::DetachedTaskStopped,
  267. ex.clone(),
  268. );
  269. info!("Starting JSON-RPC server");
  270. let daemon = Arc::new(Daemon::new(
  271. p2p.clone(),
  272. //sled_db.clone(),
  273. event_graph.clone(),
  274. dnet_sub,
  275. deg_sub,
  276. replay_datastore.clone(),
  277. ));
  278. // Used for deg and dnet
  279. let daemon_ = daemon.clone();
  280. let rpc_task = StoppableTask::new();
  281. rpc_task.clone().start(
  282. listen_and_serve(args.json_rpc_listen, daemon.clone(), None, ex.clone()),
  283. |res| async move {
  284. match res {
  285. Ok(()) | Err(Error::RpcServerStopped) => daemon_.stop_connections().await,
  286. Err(e) => error!("Failed stopping JSON-RPC server: {}", e),
  287. }
  288. },
  289. Error::RpcServerStopped,
  290. ex.clone(),
  291. );
  292. info!("Starting evgrd server");
  293. let listener = Listener::new(args.daemon_listen, None).await?;
  294. let ptlistener = listener.listen().await?;
  295. let rpc_task = StoppableTask::new();
  296. rpc_task.clone().start(
  297. rpc_serve(ptlistener, daemon.clone(), ex.clone()),
  298. |res| async move {
  299. match res {
  300. Ok(()) => panic!("Acceptor task should never complete without error status"),
  301. //Err(Error::RpcServerStopped) => daemon_.stop_connections().await,
  302. Err(e) => error!("Failed stopping RPC server: {}", e),
  303. }
  304. },
  305. Error::RpcServerStopped,
  306. ex.clone(),
  307. );
  308. info!("Starting P2P network");
  309. p2p.clone().start().await?;
  310. info!("Waiting for some P2P connections...");
  311. sleep(5).await;
  312. // We'll attempt to sync {sync_attempts} times
  313. if !args.skip_dag_sync {
  314. for i in 1..=args.sync_attempts {
  315. info!("Syncing event DAG (attempt #{})", i);
  316. match event_graph.dag_sync().await {
  317. Ok(()) => break,
  318. Err(e) => {
  319. if i == args.sync_attempts {
  320. error!("Failed syncing DAG. Exiting.");
  321. p2p.stop().await;
  322. return Err(Error::DagSyncFailed)
  323. } else {
  324. // TODO: Maybe at this point we should prune or something?
  325. // TODO: Or maybe just tell the user to delete the DAG from FS.
  326. error!("Failed syncing DAG ({}), retrying in {}s...", e, args.sync_timeout);
  327. sleep(args.sync_timeout.into()).await;
  328. }
  329. }
  330. }
  331. }
  332. } else {
  333. *event_graph.synced.write().await = true;
  334. }
  335. // Signal handling for graceful termination.
  336. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  337. signals_handler.wait_termination(signals_task).await?;
  338. info!("Caught termination signal, cleaning up and exiting...");
  339. info!("Stopping P2P network");
  340. p2p.stop().await;
  341. info!("Stopping RPC server");
  342. rpc_task.stop().await;
  343. dnet_task.stop().await;
  344. deg_task.stop().await;
  345. info!("Stopping IRC server");
  346. prune_task.stop().await;
  347. info!("Flushing sled database...");
  348. let flushed_bytes = sled_db.flush_async().await?;
  349. info!("Flushed {} bytes", flushed_bytes);
  350. info!("Shut down successfully");
  351. Ok(())
  352. }