main.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 async_executor::Executor;
  19. use async_std::sync::Arc;
  20. use async_trait::async_trait;
  21. use futures_lite::future;
  22. use log::{error, info};
  23. use serde_derive::Deserialize;
  24. use serde_json::{json, Value};
  25. use structopt::StructOpt;
  26. use structopt_toml::StructOptToml;
  27. use url::Url;
  28. use darkfi::{
  29. async_daemonize, cli_desc,
  30. dht::{waiting_for_response, Dht, DhtPtr},
  31. net,
  32. rpc::{
  33. jsonrpc::{
  34. ErrorCode::{InvalidParams, MethodNotFound},
  35. JsonError, JsonRequest, JsonResponse, JsonResult,
  36. },
  37. server::{listen_and_serve, RequestHandler},
  38. },
  39. util::{
  40. cli::{get_log_config, get_log_level, spawn_config},
  41. path::get_config_path,
  42. serial::serialize,
  43. expand_path,
  44. },
  45. Result,
  46. };
  47. mod error;
  48. use error::{server_error, RpcError};
  49. const CONFIG_FILE: &str = "dhtd_config.toml";
  50. const CONFIG_FILE_CONTENTS: &str = include_str!("../dhtd_config.toml");
  51. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  52. #[serde(default)]
  53. #[structopt(name = "dhtd", about = cli_desc!())]
  54. struct Args {
  55. #[structopt(short, long)]
  56. /// Configuration file to use
  57. config: Option<String>,
  58. #[structopt(long, default_value = "tcp://127.0.0.1:9540")]
  59. /// JSON-RPC listen URL
  60. rpc_listen: Url,
  61. #[structopt(long)]
  62. /// P2P accept addresses (repeatable flag)
  63. p2p_accept: Vec<Url>,
  64. #[structopt(long)]
  65. /// P2P external addresses (repeatable flag)
  66. p2p_external: Vec<Url>,
  67. #[structopt(long, default_value = "8")]
  68. /// Connection slots
  69. slots: u32,
  70. #[structopt(long)]
  71. /// Connect to seed (repeatable flag)
  72. p2p_seed: Vec<Url>,
  73. #[structopt(long)]
  74. /// Connect to peer (repeatable flag)
  75. p2p_peer: Vec<Url>,
  76. #[structopt(short, parse(from_occurrences))]
  77. /// Increase verbosity (-vvv supported)
  78. verbose: u8,
  79. }
  80. /// Struct representing DHT daemon.
  81. /// This example/temp-impl stores String data.
  82. /// In final version everything will be in bytes (Vec<u8).
  83. pub struct Dhtd {
  84. /// Daemon dht state
  85. dht: DhtPtr,
  86. }
  87. impl Dhtd {
  88. pub async fn new(dht: DhtPtr) -> Result<Self> {
  89. Ok(Self { dht })
  90. }
  91. // RPCAPI:
  92. // Checks if provided key exists and retrieve it from the local map or queries the network.
  93. // Returns key value or not found message.
  94. // --> {"jsonrpc": "2.0", "method": "get", "params": ["key"], "id": 1}
  95. // <-- {"jsonrpc": "2.0", "result": "value", "id": 1}
  96. async fn get(&self, id: Value, params: &[Value]) -> JsonResult {
  97. if params.len() != 1 || !params[0].is_string() {
  98. return JsonError::new(InvalidParams, None, id).into()
  99. }
  100. let key = params[0].to_string();
  101. let key_hash = blake3::hash(&serialize(&key));
  102. // We execute this sequence to prevent lock races between threads
  103. // Verify key exists
  104. let exists = self.dht.read().await.contains_key(key_hash.clone());
  105. if let None = exists {
  106. info!("Did not find key: {}", key);
  107. return server_error(RpcError::UnknownKey, id).into()
  108. }
  109. // Check if key is local or shoud query network
  110. let local = exists.unwrap();
  111. if local {
  112. return match self.dht.read().await.get(key_hash.clone()) {
  113. Some(value) => {
  114. let string = std::str::from_utf8(&value).unwrap().to_string();
  115. JsonResponse::new(json!((key, string)), id).into()
  116. }
  117. None => {
  118. info!("Did not find key: {}", key);
  119. server_error(RpcError::UnknownKey, id).into()
  120. }
  121. }
  122. }
  123. info!("Key doesn't exist locally, querring network...");
  124. if let Err(e) = self.dht.read().await.request_key(key_hash).await {
  125. error!("Failed to query key: {}", e);
  126. return server_error(RpcError::QueryFailed, id).into()
  127. }
  128. info!("Waiting response...");
  129. match waiting_for_response(self.dht.clone()).await {
  130. Ok(response) => {
  131. match response {
  132. Some(resp) => {
  133. info!("Key found!");
  134. // Optionally, we insert the key to our local map
  135. if let Err(e) =
  136. self.dht.write().await.insert(resp.key, resp.value.clone()).await
  137. {
  138. error!("Failed to insert key: {}", e);
  139. return server_error(RpcError::KeyInsertFail, id)
  140. }
  141. let string = std::str::from_utf8(&resp.value).unwrap().to_string();
  142. JsonResponse::new(json!((key, string)), id).into()
  143. }
  144. None => {
  145. info!("Did not find key: {}", key);
  146. server_error(RpcError::UnknownKey, id).into()
  147. }
  148. }
  149. }
  150. Err(e) => {
  151. error!("Error while waiting network response: {}", e);
  152. server_error(RpcError::WaitingNetworkError, id).into()
  153. }
  154. }
  155. }
  156. // RPCAPI:
  157. // Insert key value pair in dht.
  158. // --> {"jsonrpc": "2.0", "method": "insert", "params": ["key", "value"], "id": 1}
  159. // <-- {"jsonrpc": "2.0", "result": "(key, value)", "id": 1}
  160. async fn insert(&self, id: Value, params: &[Value]) -> JsonResult {
  161. if params.len() != 2 || !params[0].is_string() || !params[1].is_string() {
  162. return JsonError::new(InvalidParams, None, id).into()
  163. }
  164. let key = params[0].to_string();
  165. let key_hash = blake3::hash(&serialize(&key));
  166. let value = params[1].to_string();
  167. if let Err(e) = self.dht.write().await.insert(key_hash, value.as_bytes().to_vec()).await {
  168. error!("Failed to insert key: {}", e);
  169. return server_error(RpcError::KeyInsertFail, id)
  170. }
  171. JsonResponse::new(json!((key, value)), id).into()
  172. }
  173. // RPCAPI:
  174. // Remove key value pair from local map.
  175. // --> {"jsonrpc": "2.0", "method": "remove", "params": ["key"], "id": 1}
  176. // <-- {"jsonrpc": "2.0", "result": "key", "id": 1}
  177. async fn remove(&self, id: Value, params: &[Value]) -> JsonResult {
  178. if params.len() != 1 || !params[0].is_string() {
  179. return JsonError::new(InvalidParams, None, id).into()
  180. }
  181. let key = params[0].to_string();
  182. let key_hash = blake3::hash(&serialize(&key));
  183. // Check if key value pair existed and act accordingly
  184. let result = self.dht.write().await.remove(key_hash).await;
  185. match result {
  186. Ok(option) => match option {
  187. Some(k) => {
  188. info!("Hash key removed: {}", k);
  189. JsonResponse::new(json!(k.to_string()), id).into()
  190. }
  191. None => {
  192. info!("Did not find key: {}", key);
  193. server_error(RpcError::UnknownKey, id).into()
  194. }
  195. },
  196. Err(e) => {
  197. error!("Failed to remove key: {}", e);
  198. server_error(RpcError::KeyRemoveFail, id)
  199. }
  200. }
  201. }
  202. // RPCAPI:
  203. // Returns current local map.
  204. // --> {"jsonrpc": "2.0", "method": "map", "params": [], "id": 1}
  205. // <-- {"jsonrpc": "2.0", "result": "map", "id": 1}
  206. pub async fn map(&self, id: Value, _params: &[Value]) -> JsonResult {
  207. let map = self.dht.read().await.map.clone();
  208. let map_string = format!("{:#?}", map);
  209. JsonResponse::new(json!(map_string), id).into()
  210. }
  211. // RPCAPI:
  212. // Returns current lookup map.
  213. // --> {"jsonrpc": "2.0", "method": "lookup", "params": [], "id": 1}
  214. // <-- {"jsonrpc": "2.0", "result": "lookup", "id": 1}
  215. pub async fn lookup(&self, id: Value, _params: &[Value]) -> JsonResult {
  216. let lookup = self.dht.read().await.lookup.clone();
  217. let lookup_string = format!("{:#?}", lookup);
  218. JsonResponse::new(json!(lookup_string), id).into()
  219. }
  220. }
  221. #[async_trait]
  222. impl RequestHandler for Dhtd {
  223. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  224. if !req.params.is_array() {
  225. return JsonError::new(InvalidParams, None, req.id).into()
  226. }
  227. let params = req.params.as_array().unwrap();
  228. return match req.method.as_str() {
  229. Some("get") => self.get(req.id, params).await,
  230. Some("insert") => self.insert(req.id, params).await,
  231. Some("remove") => self.remove(req.id, params).await,
  232. Some("map") => self.map(req.id, params).await,
  233. Some("lookup") => self.lookup(req.id, params).await,
  234. Some(_) | None => JsonError::new(MethodNotFound, None, req.id).into(),
  235. }
  236. }
  237. }
  238. async_daemonize!(realmain);
  239. async fn realmain(args: Args, ex: Arc<Executor<'_>>) -> Result<()> {
  240. // We use this handler to block this function after detaching all
  241. // tasks, and to catch a shutdown signal, where we can clean up and
  242. // exit gracefully.
  243. let (signal, shutdown) = async_channel::bounded::<()>(1);
  244. ctrlc::set_handler(move || {
  245. async_std::task::block_on(signal.send(())).unwrap();
  246. })
  247. .unwrap();
  248. // P2P network
  249. let network_settings = net::Settings {
  250. inbound: args.p2p_accept,
  251. outbound_connections: args.slots,
  252. external_addr: args.p2p_external,
  253. peers: args.p2p_seed.clone(),
  254. seeds: args.p2p_seed.clone(),
  255. ..Default::default()
  256. };
  257. let p2p = net::P2p::new(network_settings).await;
  258. // Initialize daemon dht
  259. let dht = Dht::new(None, p2p.clone(), shutdown.clone(), ex.clone()).await?;
  260. // Initialize daemon
  261. let dhtd = Dhtd::new(dht.clone()).await?;
  262. let dhtd = Arc::new(dhtd);
  263. // JSON-RPC server
  264. info!("Starting JSON-RPC server");
  265. let _ex = ex.clone();
  266. ex.spawn(listen_and_serve(args.rpc_listen, dhtd.clone(), _ex)).detach();
  267. info!("Starting sync P2P network");
  268. p2p.clone().start(ex.clone()).await?;
  269. let _ex = ex.clone();
  270. let _p2p = p2p.clone();
  271. ex.spawn(async move {
  272. if let Err(e) = _p2p.run(_ex).await {
  273. error!("Failed starting P2P network: {}", e);
  274. }
  275. })
  276. .detach();
  277. // Wait for SIGINT
  278. shutdown.recv().await?;
  279. print!("\r");
  280. info!("Caught termination signal, cleaning up and exiting...");
  281. Ok(())
  282. }