main.rs 10 KB

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