main.rs 10 KB

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