main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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::{debug, error, info, warn};
  6. use serde_derive::Deserialize;
  7. use serde_json::{json, Value};
  8. use std::{collections::HashSet, fs, path::PathBuf};
  9. use structopt::StructOpt;
  10. use structopt_toml::StructOptToml;
  11. use url::Url;
  12. use darkfi::{
  13. async_daemonize, cli_desc,
  14. dht::{waiting_for_response, Dht, DhtPtr},
  15. net,
  16. rpc::{
  17. jsonrpc::{
  18. ErrorCode::{InvalidParams, MethodNotFound},
  19. JsonError, JsonRequest, JsonResponse, JsonResult,
  20. },
  21. server::{listen_and_serve, RequestHandler},
  22. },
  23. util::{
  24. cli::{get_log_config, get_log_level, spawn_config},
  25. expand_path,
  26. path::get_config_path,
  27. serial::serialize,
  28. },
  29. Result,
  30. };
  31. mod error;
  32. use error::{server_error, RpcError};
  33. const CONFIG_FILE: &str = "fud_config.toml";
  34. const CONFIG_FILE_CONTENTS: &str = include_str!("../fud_config.toml");
  35. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  36. #[serde(default)]
  37. #[structopt(name = "fud", about = cli_desc!())]
  38. struct Args {
  39. #[structopt(short, long)]
  40. /// Configuration file to use
  41. config: Option<String>,
  42. #[structopt(long, default_value = "~/.config/darkfi/fud")]
  43. /// Path to the contents directory
  44. folder: String,
  45. #[structopt(long, default_value = "tcp://127.0.0.1:13336")]
  46. /// JSON-RPC listen URL
  47. rpc_listen: Url,
  48. #[structopt(long)]
  49. /// P2P accept addresses (repeatable flag)
  50. p2p_accept: Vec<Url>,
  51. #[structopt(long)]
  52. /// P2P external addresses (repeatable flag)
  53. p2p_external: Vec<Url>,
  54. #[structopt(long, default_value = "8")]
  55. /// Connection slots
  56. slots: u32,
  57. #[structopt(long)]
  58. /// Connect to seed (repeatable flag)
  59. seeds: Vec<Url>,
  60. #[structopt(long)]
  61. /// Connect to peer (repeatable flag)
  62. peers: Vec<Url>,
  63. #[structopt(short, parse(from_occurrences))]
  64. /// Increase verbosity (-vvv supported)
  65. verbose: u8,
  66. }
  67. /// Struct representing the daemon.
  68. pub struct Fud {
  69. /// Daemon dht state
  70. dht: DhtPtr,
  71. /// Path to the contents directory
  72. folder: PathBuf,
  73. }
  74. impl Fud {
  75. pub async fn new(dht: DhtPtr, folder: PathBuf) -> Result<Self> {
  76. Ok(Self { dht, folder })
  77. }
  78. /// Initialize fud dht state by reading the contents folder and generating
  79. /// the corresponding dht records.
  80. async fn init(&self) -> Result<()> {
  81. info!("Initializing fud dht state for folder: {:?}", self.folder);
  82. if !self.folder.exists() {
  83. fs::create_dir_all(&self.folder)?;
  84. }
  85. let entries = fs::read_dir(&self.folder).unwrap();
  86. {
  87. let mut lock = self.dht.write().await;
  88. // Sync lookup map with network
  89. if let Err(e) = lock.sync_lookup_map().await {
  90. error!("Failed to sync lookup map: {}", e);
  91. }
  92. for entry in entries {
  93. let e = entry.unwrap();
  94. let name = String::from(e.file_name().to_str().unwrap());
  95. info!("Entry: {}", name);
  96. let key_hash = blake3::hash(&serialize(&name));
  97. let value: Vec<u8> = std::fs::read(e.path()).unwrap();
  98. if let Err(e) = lock.insert(key_hash, value).await {
  99. error!("Failed to insert key: {}", e);
  100. }
  101. }
  102. }
  103. Ok(())
  104. }
  105. /// Signaling fud network that node goes offline.
  106. async fn disconnect(&self) -> Result<()> {
  107. debug!("Peer disconnecting, signaling network");
  108. {
  109. let mut lock = self.dht.write().await;
  110. let records = lock.map.clone();
  111. for key in records.keys() {
  112. let result = lock.remove(*key).await;
  113. match result {
  114. Ok(option) => match option {
  115. Some(k) => {
  116. debug!("Hash key removed: {}", k);
  117. }
  118. None => {
  119. warn!("Did not find key: {}", key);
  120. }
  121. },
  122. Err(e) => {
  123. error!("Failed to remove key: {}", e);
  124. }
  125. }
  126. }
  127. }
  128. Ok(())
  129. }
  130. // RPCAPI:
  131. // Returns all folder contents, with file changes.
  132. // --> {"jsonrpc": "2.0", "method": "list", "params": [], "id": 1}
  133. // <-- {"jsonrpc": "2.0", "result": "[[files],[new],[deleted]", "id": 1}
  134. pub async fn list(&self, id: Value, _params: &[Value]) -> JsonResult {
  135. let mut content = HashSet::new();
  136. let mut new = HashSet::new();
  137. let mut deleted = HashSet::new();
  138. let entries = fs::read_dir(&self.folder).unwrap();
  139. let records = self.dht.read().await.map.clone();
  140. let mut entries_hashes = HashSet::new();
  141. // We iterate files for new records
  142. for entry in entries {
  143. let e = entry.unwrap();
  144. let name = String::from(e.file_name().to_str().unwrap());
  145. let key_hash = blake3::hash(&serialize(&name));
  146. entries_hashes.insert(key_hash);
  147. if records.contains_key(&key_hash) {
  148. content.insert(name.clone());
  149. } else {
  150. new.insert(name);
  151. }
  152. }
  153. // We check records for removed files
  154. for key in records.keys() {
  155. if entries_hashes.contains(key) {
  156. continue
  157. }
  158. deleted.insert(key.to_string());
  159. }
  160. JsonResponse::new(json!((content, new, deleted)), id).into()
  161. }
  162. // RPCAPI:
  163. // Iterate contents folder and dht for potential changes.
  164. // --> {"jsonrpc": "2.0", "method": "sync", "params": [], "id": 1}
  165. // <-- {"jsonrpc": "2.0", "result": "true", "id": 1}
  166. pub async fn sync(&self, id: Value, _params: &[Value]) -> JsonResult {
  167. info!("Sync process started");
  168. let entries = fs::read_dir(&self.folder).unwrap();
  169. {
  170. let mut lock = self.dht.write().await;
  171. let records = lock.map.clone();
  172. let mut entries_hashes = HashSet::new();
  173. // We iterate files for new records
  174. for entry in entries {
  175. let e = entry.unwrap();
  176. let name = String::from(e.file_name().to_str().unwrap());
  177. info!("Entry: {}", name);
  178. let key_hash = blake3::hash(&serialize(&name));
  179. entries_hashes.insert(key_hash);
  180. if records.contains_key(&key_hash) {
  181. continue
  182. }
  183. let value: Vec<u8> = std::fs::read(e.path()).unwrap();
  184. if let Err(e) = lock.insert(key_hash, value).await {
  185. error!("Failed to insert key: {}", e);
  186. return server_error(RpcError::KeyInsertFail, id)
  187. }
  188. }
  189. // We check records for removed files
  190. let records = lock.map.clone();
  191. for key in records.keys() {
  192. if entries_hashes.contains(key) {
  193. continue
  194. }
  195. let result = lock.remove(*key).await;
  196. match result {
  197. Ok(option) => match option {
  198. Some(k) => {
  199. debug!("Hash key removed: {}", k);
  200. }
  201. None => {
  202. warn!("Did not find key: {}", key);
  203. }
  204. },
  205. Err(e) => {
  206. error!("Failed to remove key: {}", e);
  207. return server_error(RpcError::KeyRemoveFail, id)
  208. }
  209. }
  210. }
  211. }
  212. JsonResponse::new(json!(true), id).into()
  213. }
  214. // RPCAPI:
  215. // Checks if provided key exists and retrieve it from the local map or queries the network.
  216. // Returns key or not found message.
  217. // --> {"jsonrpc": "2.0", "method": "get", "params": ["name"], "id": 1}
  218. // <-- {"jsonrpc": "2.0", "result": "path", "id": 1}
  219. async fn get(&self, id: Value, params: &[Value]) -> JsonResult {
  220. if params.len() != 1 || !params[0].is_string() {
  221. return JsonError::new(InvalidParams, None, id).into()
  222. }
  223. let key = params[0].as_str().unwrap().to_string();
  224. let key_hash = blake3::hash(&serialize(&key));
  225. // We execute this sequence to prevent lock races between threads
  226. // Verify key exists
  227. let exists = self.dht.read().await.contains_key(key_hash.clone());
  228. if let None = exists {
  229. info!("Did not find key: {}", key);
  230. return server_error(RpcError::UnknownKey, id).into()
  231. }
  232. // Check if key is local or should query network
  233. let path = self.folder.join(key.clone());
  234. let local = exists.unwrap();
  235. if local {
  236. match self.dht.read().await.get(key_hash.clone()) {
  237. Some(_) => return JsonResponse::new(json!(path), id).into(),
  238. None => {
  239. info!("Did not find key: {}", key);
  240. return server_error(RpcError::UnknownKey, id).into()
  241. }
  242. }
  243. }
  244. info!("Key doesn't exist locally, querring network...");
  245. if let Err(e) = self.dht.read().await.request_key(key_hash).await {
  246. error!("Failed to query key: {}", e);
  247. return server_error(RpcError::QueryFailed, id).into()
  248. }
  249. info!("Waiting response...");
  250. match waiting_for_response(self.dht.clone()).await {
  251. Ok(response) => {
  252. match response {
  253. Some(resp) => {
  254. info!("Key found!");
  255. // Optionally, we insert the key to our local map
  256. if let Err(e) =
  257. self.dht.write().await.insert(resp.key, resp.value.clone()).await
  258. {
  259. error!("Failed to insert key: {}", e);
  260. return server_error(RpcError::KeyInsertFail, id)
  261. }
  262. if let Err(e) = std::fs::write(path.clone(), resp.value) {
  263. error!("Failed to generate file for key: {}", e);
  264. return server_error(RpcError::FileGenerationFail, id)
  265. }
  266. JsonResponse::new(json!(path), id).into()
  267. }
  268. None => {
  269. info!("Did not find key: {}", key);
  270. server_error(RpcError::UnknownKey, id).into()
  271. }
  272. }
  273. }
  274. Err(e) => {
  275. error!("Error while waiting network response: {}", e);
  276. server_error(RpcError::WaitingNetworkError, id).into()
  277. }
  278. }
  279. }
  280. // RPCAPI:
  281. // Replies to a ping method.
  282. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  283. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  284. async fn pong(&self, id: Value, _params: &[Value]) -> JsonResult {
  285. JsonResponse::new(json!("pong"), id).into()
  286. }
  287. // RPCAPI:
  288. // Retrieves P2P network information.
  289. // --> {"jsonrpc": "2.0", "method": "get_info", "params": [], "id": 42}
  290. // <-- {"jsonrpc": "2.0", result": {"nodeID": [], "nodeinfo": [], "id": 42}
  291. async fn get_info(&self, id: Value, _params: &[Value]) -> JsonResult {
  292. let resp = self.dht.read().await.p2p.get_info().await;
  293. JsonResponse::new(resp, id).into()
  294. }
  295. }
  296. #[async_trait]
  297. impl RequestHandler for Fud {
  298. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  299. if !req.params.is_array() {
  300. return JsonError::new(InvalidParams, None, req.id).into()
  301. }
  302. let params = req.params.as_array().unwrap();
  303. match req.method.as_str() {
  304. Some("list") => return self.list(req.id, params).await,
  305. Some("sync") => return self.sync(req.id, params).await,
  306. Some("get") => return self.get(req.id, params).await,
  307. Some("ping") => return self.pong(req.id, params).await,
  308. Some("get_info") => return self.get_info(req.id, params).await,
  309. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  310. }
  311. }
  312. }
  313. async_daemonize!(realmain);
  314. async fn realmain(args: Args, ex: Arc<Executor<'_>>) -> Result<()> {
  315. // We use this handler to block this function after detaching all
  316. // tasks, and to catch a shutdown signal, where we can clean up and
  317. // exit gracefully.
  318. let (signal, shutdown) = async_channel::bounded::<()>(1);
  319. ctrlc::set_handler(move || {
  320. async_std::task::block_on(signal.send(())).unwrap();
  321. })
  322. .unwrap();
  323. // P2P network
  324. let network_settings = net::Settings {
  325. inbound: args.p2p_accept,
  326. outbound_connections: args.slots,
  327. external_addr: args.p2p_external,
  328. peers: args.peers.clone(),
  329. seeds: args.seeds.clone(),
  330. ..Default::default()
  331. };
  332. let p2p = net::P2p::new(network_settings).await;
  333. // Initialize daemon dht
  334. let dht = Dht::new(None, p2p.clone(), shutdown.clone(), ex.clone()).await?;
  335. // Initialize daemon
  336. let folder = expand_path(&args.folder)?;
  337. let fud = Fud::new(dht.clone(), folder).await?;
  338. let fud = Arc::new(fud);
  339. // JSON-RPC server
  340. info!("Starting JSON-RPC server");
  341. ex.spawn(listen_and_serve(args.rpc_listen, fud.clone())).detach();
  342. info!("Starting sync P2P network");
  343. p2p.clone().start(ex.clone()).await?;
  344. let _ex = ex.clone();
  345. let _p2p = p2p.clone();
  346. ex.spawn(async move {
  347. if let Err(e) = _p2p.run(_ex).await {
  348. error!("Failed starting P2P network: {}", e);
  349. }
  350. })
  351. .detach();
  352. info!("Waiting for P2P outbound connections");
  353. p2p.wait_for_outbound(ex).await?;
  354. fud.init().await?;
  355. // Wait for SIGINT
  356. shutdown.recv().await?;
  357. print!("\r");
  358. info!("Caught termination signal, cleaning up and exiting...");
  359. fud.disconnect().await?;
  360. Ok(())
  361. }