evgrd.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. path::PathBuf,
  46. sync::{Arc, Mutex as SyncMutex},
  47. };
  48. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  49. use url::Url;
  50. use evgrd::{FetchEventsMessage, VersionMessage, MSG_EVENT, MSG_FETCHEVENTS};
  51. const CONFIG_FILE: &str = "evgrd.toml";
  52. const CONFIG_FILE_CONTENTS: &str = include_str!("../evgrd.toml");
  53. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  54. #[serde(default)]
  55. #[structopt(name = "evgrd", about = cli_desc!())]
  56. struct Args {
  57. #[structopt(short, parse(from_occurrences))]
  58. /// Increase verbosity (-vvv supported)
  59. verbose: u8,
  60. #[structopt(short, long)]
  61. /// Configuration file to use
  62. config: Option<String>,
  63. #[structopt(long)]
  64. /// Set log file output
  65. log: Option<String>,
  66. #[structopt(long, default_value = "tcp://127.0.0.1:5588")]
  67. /// RPC server listen address
  68. rpc_listen: Url,
  69. #[structopt(short, long, default_value = "~/.local/darkfi/evgrd_db")]
  70. /// Datastore (DB) path
  71. datastore: String,
  72. #[structopt(short, long, default_value = "~/.local/darkfi/replayed_evgrd_db")]
  73. /// Replay logs (DB) path
  74. replay_datastore: String,
  75. /// Flag to store Sled DB instructions
  76. #[structopt(long)]
  77. replay_mode: bool,
  78. /// Flag to skip syncing the DAG (no history).
  79. #[structopt(long)]
  80. skip_dag_sync: bool,
  81. /// Number of attempts to sync the DAG.
  82. #[structopt(long, default_value = "5")]
  83. sync_attempts: u8,
  84. /// Number of seconds to wait before trying again if sync fails.
  85. #[structopt(long, default_value = "10")]
  86. sync_timeout: u8,
  87. /// P2P network settings
  88. #[structopt(flatten)]
  89. net: NetSettingsOpt,
  90. }
  91. pub struct Daemon {
  92. ///// P2P network pointer
  93. //p2p: P2pPtr,
  94. ///// Sled DB (also used in event_graph and for RLN)
  95. //sled: sled::Db,
  96. ///// Event Graph instance
  97. //event_graph: EventGraphPtr,
  98. ///// JSON-RPC connection tracker
  99. //rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  100. ///// dnet JSON-RPC subscriber
  101. //dnet_sub: JsonSubscriber,
  102. ///// deg JSON-RPC subscriber
  103. //deg_sub: JsonSubscriber,
  104. ///// Replay logs (DB) path
  105. //replay_datastore: PathBuf,
  106. /// New events publisher
  107. events_pub: PublisherPtr<event_graph::Event>,
  108. }
  109. impl Daemon {
  110. fn new(
  111. //p2p: P2pPtr,
  112. //sled: sled::Db,
  113. //event_graph: EventGraphPtr,
  114. //dnet_sub: JsonSubscriber,
  115. //deg_sub: JsonSubscriber,
  116. //replay_datastore: PathBuf,
  117. events_pub: PublisherPtr<event_graph::Event>,
  118. ) -> Self {
  119. Self {
  120. //p2p,
  121. //sled,
  122. //event_graph,
  123. //rpc_connections: Mutex::new(HashSet::new()),
  124. //dnet_sub,
  125. //deg_sub,
  126. //replay_datastore,
  127. events_pub,
  128. }
  129. }
  130. }
  131. async fn rpc_serve(
  132. listener: Box<dyn PtListener>,
  133. daemon: Arc<Daemon>,
  134. ex: Arc<Executor<'_>>,
  135. ) -> Result<()> {
  136. loop {
  137. match listener.next().await {
  138. Ok((stream, url)) => {
  139. info!(target: "evgrd", "Accepted connection from {url}");
  140. ex.spawn(handle_connect(stream, daemon.clone(), ex.clone())).detach();
  141. }
  142. // Errors we didn't handle above:
  143. Err(e) => {
  144. error!(
  145. target: "evgrd",
  146. "Unhandled listener.next() error: {}", e,
  147. );
  148. continue
  149. }
  150. }
  151. }
  152. Ok(())
  153. }
  154. async fn handle_connect(
  155. mut stream: Box<dyn PtStream>,
  156. daemon: Arc<Daemon>,
  157. ex: Arc<Executor<'_>>,
  158. ) -> Result<()> {
  159. let client_version = VersionMessage::decode_async(&mut stream).await?;
  160. info!(target: "evgrd", "Client version: {}", client_version.protocol_version);
  161. let version = VersionMessage::new();
  162. version.encode_async(&mut stream).await?;
  163. let event_sub = daemon.events_pub.clone().subscribe().await;
  164. loop {
  165. futures::select! {
  166. ev = event_sub.receive().fuse() => {
  167. MSG_EVENT.encode_async(&mut stream).await?;
  168. ev.encode_async(&mut stream).await?;
  169. }
  170. msg_type = u8::decode_async(&mut stream).fuse() => {
  171. let msg_type = msg_type?;
  172. if msg_type != MSG_FETCHEVENTS {
  173. error!(target: "evgrd", "Connection received invalid msg_type: {msg_type}");
  174. return Err(Error::MalformedPacket)
  175. }
  176. let fetchevs = FetchEventsMessage::decode_async(&mut stream).await?;
  177. info!(target: "evgrd", "Fetching events {fetchevs:?}");
  178. // Now do your thing with the daemon and get missing tips
  179. // Then send them like this:
  180. // for ev in evs {
  181. // MSG_EVENT.encode_async(&mut stream).await?;
  182. // ev.encode_async(&mut stream).await?;
  183. // }
  184. }
  185. }
  186. }
  187. Ok(())
  188. }
  189. async_daemonize!(realmain);
  190. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  191. info!("Starting evgrd node");
  192. /*
  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. */
  270. // New events are published here
  271. let events_pub = Publisher::new();
  272. info!("Starting JSON-RPC server");
  273. let daemon = Arc::new(Daemon::new(
  274. //p2p.clone(),
  275. //sled_db.clone(),
  276. //event_graph.clone(),
  277. //dnet_sub,
  278. //deg_sub,
  279. //replay_datastore.clone(),
  280. events_pub,
  281. ));
  282. let listener = Listener::new(args.rpc_listen, None).await?;
  283. let ptlistener = listener.listen().await?;
  284. let rpc_task = StoppableTask::new();
  285. rpc_task.clone().start(
  286. rpc_serve(ptlistener, daemon.clone(), ex.clone()),
  287. |res| async move {
  288. match res {
  289. Ok(()) => panic!("Acceptor task should never complete without error status"),
  290. //Err(Error::RpcServerStopped) => daemon_.stop_connections().await,
  291. Err(e) => error!("Failed stopping RPC server: {}", e),
  292. }
  293. },
  294. Error::RpcServerStopped,
  295. ex.clone(),
  296. );
  297. /*
  298. info!("Starting P2P network");
  299. p2p.clone().start().await?;
  300. */
  301. info!("Waiting for some P2P connections...");
  302. sleep(5).await;
  303. /*
  304. // We'll attempt to sync {sync_attempts} times
  305. if !args.skip_dag_sync {
  306. for i in 1..=args.sync_attempts {
  307. info!("Syncing event DAG (attempt #{})", i);
  308. match event_graph.dag_sync().await {
  309. Ok(()) => break,
  310. Err(e) => {
  311. if i == args.sync_attempts {
  312. error!("Failed syncing DAG. Exiting.");
  313. p2p.stop().await;
  314. return Err(Error::DagSyncFailed)
  315. } else {
  316. // TODO: Maybe at this point we should prune or something?
  317. // TODO: Or maybe just tell the user to delete the DAG from FS.
  318. error!("Failed syncing DAG ({}), retrying in {}s...", e, args.sync_timeout);
  319. sleep(args.sync_timeout.into()).await;
  320. }
  321. }
  322. }
  323. }
  324. } else {
  325. *event_graph.synced.write().await = true;
  326. }
  327. */
  328. // Signal handling for graceful termination.
  329. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  330. signals_handler.wait_termination(signals_task).await?;
  331. info!("Caught termination signal, cleaning up and exiting...");
  332. /*
  333. info!("Stopping P2P network");
  334. p2p.stop().await;
  335. */
  336. info!("Stopping RPC server");
  337. rpc_task.stop().await;
  338. /*
  339. dnet_task.stop().await;
  340. deg_task.stop().await;
  341. info!("Stopping IRC server");
  342. prune_task.stop().await;
  343. info!("Flushing sled database...");
  344. let flushed_bytes = sled_db.flush_async().await?;
  345. info!("Flushed {} bytes", flushed_bytes);
  346. info!("Shut down successfully");
  347. */
  348. Ok(())
  349. }