main.rs 9.9 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, net,
  13. rpc::{
  14. jsonrpc::{
  15. ErrorCode::{InvalidParams, MethodNotFound},
  16. JsonError, JsonRequest, JsonResponse, JsonResult,
  17. },
  18. server::{listen_and_serve, RequestHandler},
  19. },
  20. util::{
  21. cli::{get_log_config, get_log_level, spawn_config},
  22. path::get_config_path,
  23. },
  24. Result,
  25. };
  26. mod error;
  27. use error::{server_error, RpcError};
  28. mod dht;
  29. use dht::{waiting_for_response, Dht, DhtPtr};
  30. mod messages;
  31. mod protocol;
  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 address
  46. p2p_accept: Option<Url>,
  47. #[structopt(long)]
  48. /// P2P external address
  49. p2p_external: Option<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. // We execute this sequence to prevent lock races between threads
  85. // Verify key exists
  86. let exists = self.dht.read().await.contains_key(key.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.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.clone()).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 value = params[1].to_string();
  148. if let Err(e) = self.dht.write().await.insert(key.clone(), value.as_bytes().to_vec()).await
  149. {
  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. // Check if key value pair existed and act accordingly
  165. let result = self.dht.write().await.remove(key.clone()).await;
  166. match result {
  167. Ok(option) => match option {
  168. Some(k) => {
  169. info!("Key removed: {}", k);
  170. JsonResponse::new(json!(k), id).into()
  171. }
  172. None => {
  173. info!("Did not find key: {}", key);
  174. server_error(RpcError::UnknownKey, id).into()
  175. }
  176. },
  177. Err(e) => {
  178. error!("Failed to remove key: {}", e);
  179. server_error(RpcError::KeyRemoveFail, id)
  180. }
  181. }
  182. }
  183. // RPCAPI:
  184. // Returns current local map.
  185. // --> {"jsonrpc": "2.0", "method": "map", "params": [], "id": 1}
  186. // <-- {"jsonrpc": "2.0", "result": "map", "id": 1}
  187. pub async fn map(&self, id: Value, _params: &[Value]) -> JsonResult {
  188. let map = self.dht.read().await.map.clone();
  189. JsonResponse::new(json!(map), id).into()
  190. }
  191. // RPCAPI:
  192. // Returns current lookup map.
  193. // --> {"jsonrpc": "2.0", "method": "lookup", "params": [], "id": 1}
  194. // <-- {"jsonrpc": "2.0", "result": "lookup", "id": 1}
  195. pub async fn lookup(&self, id: Value, _params: &[Value]) -> JsonResult {
  196. let lookup = self.dht.read().await.lookup.clone();
  197. JsonResponse::new(json!(lookup), id).into()
  198. }
  199. }
  200. #[async_trait]
  201. impl RequestHandler for Dhtd {
  202. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  203. if !req.params.is_array() {
  204. return JsonError::new(InvalidParams, None, req.id).into()
  205. }
  206. let params = req.params.as_array().unwrap();
  207. match req.method.as_str() {
  208. Some("get") => return self.get(req.id, params).await,
  209. Some("insert") => return self.insert(req.id, params).await,
  210. Some("remove") => return self.remove(req.id, params).await,
  211. Some("map") => return self.map(req.id, params).await,
  212. Some("lookup") => return self.lookup(req.id, params).await,
  213. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  214. }
  215. }
  216. }
  217. async_daemonize!(realmain);
  218. async fn realmain(args: Args, ex: Arc<Executor<'_>>) -> Result<()> {
  219. // We use this handler to block this function after detaching all
  220. // tasks, and to catch a shutdown signal, where we can clean up and
  221. // exit gracefully.
  222. let (signal, shutdown) = async_channel::bounded::<()>(1);
  223. ctrlc_async::set_async_handler(async move {
  224. signal.send(()).await.unwrap();
  225. })
  226. .unwrap();
  227. // P2P network
  228. let network_settings = net::Settings {
  229. inbound: args.p2p_accept,
  230. outbound_connections: args.slots,
  231. external_addr: args.p2p_external,
  232. peers: args.p2p_seed.clone(),
  233. seeds: args.p2p_seed.clone(),
  234. ..Default::default()
  235. };
  236. let p2p = net::P2p::new(network_settings).await;
  237. // Initialize daemon dht
  238. let dht = Dht::new(None, p2p.clone(), shutdown.clone(), ex.clone()).await?;
  239. // Initialize daemon
  240. let dhtd = Dhtd::new(dht.clone()).await?;
  241. let dhtd = Arc::new(dhtd);
  242. // JSON-RPC server
  243. info!("Starting JSON-RPC server");
  244. ex.spawn(listen_and_serve(args.rpc_listen, dhtd.clone())).detach();
  245. info!("Starting sync P2P network");
  246. p2p.clone().start(ex.clone()).await?;
  247. let _ex = ex.clone();
  248. let _p2p = p2p.clone();
  249. ex.spawn(async move {
  250. if let Err(e) = _p2p.run(_ex).await {
  251. error!("Failed starting P2P network: {}", e);
  252. }
  253. })
  254. .detach();
  255. // Wait for SIGINT
  256. shutdown.recv().await?;
  257. print!("\r");
  258. info!("Caught termination signal, cleaning up and exiting...");
  259. Ok(())
  260. }