main.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 std::sync::{Arc, OnceLock};
  19. use darkfi::{
  20. async_daemonize, cli_desc,
  21. event_graph::{proto::ProtocolEventGraph, EventGraph, EventGraphPtr, NULL_ID},
  22. net::{settings::SettingsOpt, P2p, SESSION_ALL},
  23. rpc::{
  24. jsonrpc::JsonSubscriber,
  25. server::{listen_and_serve, RequestHandler},
  26. },
  27. system::{sleep, StoppableTask},
  28. util::path::expand_path,
  29. Error, Result,
  30. };
  31. use log::{debug, error, info};
  32. use smol::{lock::RwLock, stream::StreamExt};
  33. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  34. use url::Url;
  35. mod rpc;
  36. use rpc::JsonRpcInterface;
  37. const CONFIG_FILE: &str = "genev_config.toml";
  38. const CONFIG_FILE_CONTENTS: &str = include_str!("../genev_config.toml");
  39. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  40. #[serde(default)]
  41. #[structopt(name = "genev", about = cli_desc!())]
  42. struct Args {
  43. #[structopt(short, long)]
  44. /// Configuration file to use
  45. config: Option<String>,
  46. /// JSON-RPC listen URL
  47. #[structopt(long = "rpc", default_value = "tcp://127.0.0.1:28880")]
  48. pub rpc_listen: Url,
  49. #[structopt(flatten)]
  50. pub net: SettingsOpt,
  51. /// Sets Datastore Path
  52. #[structopt(long, default_value = "~/.local/darkfi/genev_db")]
  53. pub datastore: String,
  54. #[structopt(short, long)]
  55. /// Set log file to ouput into
  56. log: Option<String>,
  57. #[structopt(long)]
  58. pub skip_dag_sync: bool,
  59. #[structopt(short, parse(from_occurrences))]
  60. /// Increase verbosity (-vvv supported)
  61. verbose: u8,
  62. }
  63. async fn start_sync_loop(
  64. event_graph: EventGraphPtr,
  65. last_sent: RwLock<blake3::Hash>,
  66. seen: OnceLock<sled::Tree>,
  67. ) -> Result<()> {
  68. let incoming = event_graph.event_sub.clone().subscribe().await;
  69. let seen_events = seen.get().unwrap();
  70. loop {
  71. let event = incoming.receive().await;
  72. let event_id = event.id();
  73. if *last_sent.read().await == event_id {
  74. continue
  75. }
  76. if seen_events.contains_key(event_id.as_bytes()).unwrap() {
  77. continue
  78. }
  79. debug!("new event: {:?}", event);
  80. }
  81. }
  82. async_daemonize!(realmain);
  83. async fn realmain(settings: Args, executor: Arc<smol::Executor<'static>>) -> Result<()> {
  84. ////////////////////
  85. // Initialize the base structures
  86. ////////////////////
  87. info!("Instantiating event DAG");
  88. // Create datastore path if not there already.
  89. let datastore_path = expand_path(&settings.datastore)?;
  90. let sled_db = sled::open(datastore_path.clone())?;
  91. let p2p = P2p::new(settings.net.into(), executor.clone()).await;
  92. let event_graph =
  93. EventGraph::new(p2p.clone(), sled_db.clone(), "genevd_dag", 1, executor.clone()).await?;
  94. info!("Registering EventGraph P2P protocol");
  95. let event_graph_ = Arc::clone(&event_graph);
  96. let registry = p2p.protocol_registry();
  97. registry
  98. .register(SESSION_ALL, move |channel, _| {
  99. let event_graph_ = event_graph_.clone();
  100. async move { ProtocolEventGraph::init(event_graph_, channel).await.unwrap() }
  101. })
  102. .await;
  103. // Run
  104. info!(target: "genevd", "Starting P2P network");
  105. p2p.clone().start().await?;
  106. info!(target: "genevd", "Waiting for some P2P connections...");
  107. sleep(5).await;
  108. // We'll attempt to sync 5 times
  109. if !settings.skip_dag_sync {
  110. for i in 1..=6 {
  111. info!("Syncing event DAG (attempt #{})", i);
  112. match event_graph.dag_sync().await {
  113. Ok(()) => break,
  114. Err(e) => {
  115. if i == 6 {
  116. error!("Failed syncing DAG. Exiting.");
  117. p2p.stop().await;
  118. return Err(Error::DagSyncFailed)
  119. } else {
  120. // TODO: Maybe at this point we should prune or something?
  121. // TODO: Or maybe just tell the user to delete the DAG from FS.
  122. error!("Failed syncing DAG ({}), retrying in 10s...", e);
  123. sleep(10).await;
  124. }
  125. }
  126. }
  127. }
  128. } else {
  129. *event_graph.synced.write().await = true;
  130. }
  131. ////////////////////
  132. // Listner
  133. ////////////////////
  134. let last_sent = RwLock::new(NULL_ID);
  135. let seen = OnceLock::new();
  136. seen.set(sled_db.open_tree("genevdb").unwrap()).unwrap();
  137. info!(target: "genevd", "Starting sync loop task");
  138. let sync_loop_task = StoppableTask::new();
  139. sync_loop_task.clone().start(
  140. start_sync_loop(event_graph.clone(), last_sent, seen.clone()),
  141. |res| async {
  142. match res {
  143. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  144. Err(e) => error!(target: "genevd", "Failed starting sync loop task: {}", e),
  145. }
  146. },
  147. Error::DetachedTaskStopped,
  148. executor.clone(),
  149. );
  150. info!("Starting dnet subs task");
  151. let dnet_sub = JsonSubscriber::new("dnet.subscribe_events");
  152. let dnet_sub_ = dnet_sub.clone();
  153. let p2p_ = p2p.clone();
  154. let dnet_task = StoppableTask::new();
  155. dnet_task.clone().start(
  156. async move {
  157. let dnet_sub = p2p_.dnet_subscribe().await;
  158. loop {
  159. let event = dnet_sub.receive().await;
  160. debug!("Got dnet event: {:?}", event);
  161. dnet_sub_.notify(vec![event.into()].into()).await;
  162. }
  163. },
  164. |res| async {
  165. match res {
  166. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  167. Err(e) => panic!("{}", e),
  168. }
  169. },
  170. Error::DetachedTaskStopped,
  171. executor.clone(),
  172. );
  173. info!("Starting deg subs task");
  174. let deg_sub = JsonSubscriber::new("deg.subscribe_events");
  175. let deg_sub_ = deg_sub.clone();
  176. let event_graph_ = event_graph.clone();
  177. let deg_task = StoppableTask::new();
  178. deg_task.clone().start(
  179. async move {
  180. let deg_sub = event_graph_.deg_subscribe().await;
  181. loop {
  182. let event = deg_sub.receive().await;
  183. debug!("Got deg event: {:?}", event);
  184. deg_sub_.notify(vec![event.into()].into()).await;
  185. }
  186. },
  187. |res| async {
  188. match res {
  189. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  190. Err(e) => panic!("{}", e),
  191. }
  192. },
  193. Error::DetachedTaskStopped,
  194. executor.clone(),
  195. );
  196. //
  197. // RPC interface
  198. //
  199. let rpc_interface = Arc::new(JsonRpcInterface::new(
  200. "Alolymous".to_string(),
  201. event_graph.clone(),
  202. p2p.clone(),
  203. dnet_sub,
  204. deg_sub,
  205. ));
  206. let rpc_task = StoppableTask::new();
  207. let rpc_interface_ = rpc_interface.clone();
  208. rpc_task.clone().start(
  209. listen_and_serve(settings.rpc_listen, rpc_interface, None, executor.clone()),
  210. |res| async move {
  211. match res {
  212. Ok(()) | Err(Error::RpcServerStopped) => rpc_interface_.stop_connections().await,
  213. Err(e) => error!(target: "genevd", "Failed starting JSON-RPC server: {}", e),
  214. }
  215. },
  216. Error::RpcServerStopped,
  217. executor.clone(),
  218. );
  219. // Signal handling for graceful termination.
  220. let (signals_handler, signals_task) = SignalHandler::new(executor)?;
  221. signals_handler.wait_termination(signals_task).await?;
  222. info!("Caught termination signal, cleaning up and exiting...");
  223. info!(target: "genevd", "Stopping JSON-RPC server...");
  224. rpc_task.stop().await;
  225. info!(target: "genevd", "Stopping Debugging tasks...");
  226. dnet_task.stop().await;
  227. deg_task.stop().await;
  228. info!(target: "genevd", "Stopping sync loop task...");
  229. sync_loop_task.stop().await;
  230. // stop p2p
  231. p2p.stop().await;
  232. Ok(())
  233. }