main.rs 11 KB

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