main.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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 clap::{Parser, Subcommand};
  19. use log::error;
  20. use simplelog::{ColorChoice, TermLogger, TerminalMode};
  21. use smol::lock::RwLock;
  22. use std::{
  23. collections::HashMap,
  24. io::{stdout, Write},
  25. sync::Arc,
  26. };
  27. use termcolor::{Color, ColorSpec, StandardStream, WriteColor};
  28. use url::Url;
  29. use darkfi::{
  30. cli_desc,
  31. rpc::{
  32. client::RpcClient,
  33. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResult},
  34. util::JsonValue,
  35. },
  36. system::{ExecutorPtr, Publisher, StoppableTask},
  37. util::cli::{get_log_config, get_log_level},
  38. Error, Result,
  39. };
  40. #[derive(Parser)]
  41. #[clap(name = "fu", about = cli_desc!(), version)]
  42. #[clap(arg_required_else_help(true))]
  43. struct Args {
  44. #[clap(short, action = clap::ArgAction::Count)]
  45. /// Increase verbosity (-vvv supported)
  46. verbose: u8,
  47. #[clap(short, long, default_value = "tcp://127.0.0.1:13336")]
  48. /// fud JSON-RPC endpoint
  49. endpoint: Url,
  50. #[clap(subcommand)]
  51. command: Subcmd,
  52. }
  53. #[derive(Subcommand)]
  54. enum Subcmd {
  55. /// Retrieve provided file name from the fud network
  56. Get {
  57. /// File hash
  58. file: String,
  59. /// File name
  60. name: Option<String>,
  61. },
  62. /// Put a file onto the fud network
  63. Put {
  64. /// File name
  65. file: String,
  66. },
  67. /// Watch
  68. Watch {},
  69. /// Remove a resource from fud
  70. Rm {
  71. /// Resource hash
  72. hash: String,
  73. },
  74. /// Get the current node buckets
  75. ListBuckets {},
  76. /// Get the router state
  77. ListSeeders {},
  78. }
  79. struct Fu {
  80. pub rpc_client: Arc<RpcClient>,
  81. pub endpoint: Url,
  82. }
  83. impl Fu {
  84. async fn get(
  85. &self,
  86. file_hash: String,
  87. file_name: Option<String>,
  88. ex: ExecutorPtr,
  89. ) -> Result<()> {
  90. let publisher = Publisher::new();
  91. let subscription = Arc::new(publisher.clone().subscribe().await);
  92. let subscriber_task = StoppableTask::new();
  93. let file_hash_ = file_hash.clone();
  94. let publisher_ = publisher.clone();
  95. let rpc_client_ = self.rpc_client.clone();
  96. subscriber_task.clone().start(
  97. async move {
  98. let req = JsonRequest::new("subscribe", JsonValue::Array(vec![]));
  99. rpc_client_.subscribe(req, publisher).await
  100. },
  101. move |res| async move {
  102. match res {
  103. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  104. Err(e) => {
  105. error!("{}", e);
  106. publisher_
  107. .notify(JsonResult::Error(JsonError::new(
  108. ErrorCode::InternalError,
  109. None,
  110. 0,
  111. )))
  112. .await;
  113. }
  114. }
  115. },
  116. Error::DetachedTaskStopped,
  117. ex.clone(),
  118. );
  119. let progress_bar_width = 20;
  120. let print_progress_bar = |info: &HashMap<String, JsonValue>| {
  121. let resource =
  122. info.get("resource").unwrap().get::<HashMap<String, JsonValue>>().unwrap();
  123. let chunks_downloaded =
  124. *resource.get("chunks_downloaded").unwrap().get::<f64>().unwrap() as usize;
  125. let chunks_total =
  126. *resource.get("chunks_total").unwrap().get::<f64>().unwrap() as usize;
  127. let status = match resource.get("status").unwrap().get::<String>().unwrap().as_str() {
  128. "seeding" => "done",
  129. s => s,
  130. };
  131. let completed = if chunks_total > 0 {
  132. (chunks_downloaded as f64 / chunks_total as f64 * progress_bar_width as f64)
  133. as usize
  134. } else {
  135. 0
  136. };
  137. let remaining = progress_bar_width - completed;
  138. let bar = "=".repeat(completed) + &" ".repeat(remaining);
  139. print!("\x1B[2K\r[{}] {}/{} chunks | {}", bar, chunks_downloaded, chunks_total, status);
  140. stdout().flush().unwrap();
  141. };
  142. let req = JsonRequest::new(
  143. "get",
  144. JsonValue::Array(vec![
  145. JsonValue::String(file_hash_.clone()),
  146. JsonValue::String(file_name.unwrap_or_default()),
  147. ]),
  148. );
  149. // Create a RPC client to send the `get` request
  150. let rpc_client_getter = RpcClient::new(self.endpoint.clone(), ex.clone()).await?;
  151. let _ = rpc_client_getter.request(req).await?;
  152. loop {
  153. match subscription.receive().await {
  154. JsonResult::Notification(n) => {
  155. let params = n.params.get::<HashMap<String, JsonValue>>().unwrap();
  156. let info =
  157. params.get("info").unwrap().get::<HashMap<String, JsonValue>>().unwrap();
  158. let hash = info.get("file_hash").unwrap().get::<String>().unwrap();
  159. if *hash != file_hash_ {
  160. continue;
  161. }
  162. match params.get("event").unwrap().get::<String>().unwrap().as_str() {
  163. "download_started" |
  164. "file_download_completed" |
  165. "chunk_download_completed" => {
  166. print_progress_bar(info);
  167. }
  168. "download_completed" => {
  169. let file_path = info.get("file_path").unwrap().get::<String>().unwrap();
  170. print_progress_bar(info);
  171. println!("\nDownload completed:\n{}", file_path);
  172. return Ok(());
  173. }
  174. "file_not_found" => {
  175. println!();
  176. return Err(Error::Custom(format!("Could not find file {}", file_hash)));
  177. }
  178. "chunk_not_found" => {
  179. // A seeder does not have a chunk we are looking for,
  180. // we will try another seeder so there is nothing to do
  181. }
  182. "missing_chunks" => {
  183. // We tried all seeders and some chunks are still missing
  184. println!();
  185. return Err(Error::Custom("Missing chunks".to_string()));
  186. }
  187. "download_error" => {
  188. // An error that caused the download to be unsuccessful
  189. println!();
  190. return Err(Error::Custom(
  191. info.get("error").unwrap().get::<String>().unwrap().to_string(),
  192. ));
  193. }
  194. _ => {}
  195. }
  196. }
  197. JsonResult::Error(e) => {
  198. return Err(Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}")))
  199. }
  200. x => {
  201. return Err(Error::UnexpectedJsonRpc(format!(
  202. "Got unexpected data from JSON-RPC: {x:?}"
  203. )))
  204. }
  205. }
  206. }
  207. }
  208. async fn put(&self, file: String) -> Result<()> {
  209. let req = JsonRequest::new("put", JsonValue::Array(vec![JsonValue::String(file)]));
  210. let rep = self.rpc_client.request(req).await?;
  211. match rep {
  212. JsonValue::String(file_id) => {
  213. println!("{}", file_id);
  214. Ok(())
  215. }
  216. _ => Err(Error::ParseFailed("File ID is not a string")),
  217. }
  218. }
  219. async fn list_buckets(&self) -> Result<()> {
  220. let req = JsonRequest::new("list_buckets", JsonValue::Array(vec![]));
  221. let rep = self.rpc_client.request(req).await?;
  222. let buckets: Vec<JsonValue> = rep.try_into().unwrap();
  223. let mut empty = true;
  224. for (bucket_i, bucket) in buckets.into_iter().enumerate() {
  225. let nodes: Vec<JsonValue> = bucket.try_into().unwrap();
  226. if nodes.is_empty() {
  227. continue
  228. }
  229. empty = false;
  230. println!("Bucket {}", bucket_i);
  231. for n in nodes.clone() {
  232. let node: Vec<JsonValue> = n.try_into().unwrap();
  233. let node_id: JsonValue = node[0].clone();
  234. let addresses: Vec<JsonValue> = node[1].clone().try_into().unwrap();
  235. let mut addrs: Vec<String> = vec![];
  236. for addr in addresses {
  237. addrs.push(addr.try_into().unwrap())
  238. }
  239. println!("\t{}: {}", node_id.stringify().unwrap(), addrs.join(", "));
  240. }
  241. }
  242. if empty {
  243. println!("All buckets are empty");
  244. }
  245. Ok(())
  246. }
  247. async fn list_seeders(&self) -> Result<()> {
  248. let req = JsonRequest::new("list_seeders", JsonValue::Array(vec![]));
  249. let rep = self.rpc_client.request(req).await?;
  250. let files: HashMap<String, JsonValue> = rep["seeders"].clone().try_into().unwrap();
  251. if files.is_empty() {
  252. println!("No known seeders");
  253. } else {
  254. for (file_hash, node_ids) in files {
  255. println!("{}", file_hash);
  256. let node_ids: Vec<JsonValue> = node_ids.try_into().unwrap();
  257. for node_id in node_ids {
  258. let node_id: String = node_id.try_into().unwrap();
  259. println!("\t{}", node_id);
  260. }
  261. }
  262. }
  263. Ok(())
  264. }
  265. async fn watch(&self, ex: ExecutorPtr) -> Result<()> {
  266. let req = JsonRequest::new("list_resources", JsonValue::Array(vec![]));
  267. let rep = self.rpc_client.request(req).await?;
  268. let resources_json: Vec<JsonValue> = rep.clone().try_into().unwrap();
  269. let resources: Arc<RwLock<Vec<HashMap<String, JsonValue>>>> = Arc::new(RwLock::new(vec![]));
  270. let publisher = Publisher::new();
  271. let subscription = Arc::new(publisher.clone().subscribe().await);
  272. let subscriber_task = StoppableTask::new();
  273. let publisher_ = publisher.clone();
  274. let rpc_client_ = self.rpc_client.clone();
  275. subscriber_task.clone().start(
  276. async move {
  277. let req = JsonRequest::new("subscribe", JsonValue::Array(vec![]));
  278. rpc_client_.subscribe(req, publisher).await
  279. },
  280. move |res| async move {
  281. match res {
  282. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  283. Err(e) => {
  284. error!("{}", e);
  285. publisher_
  286. .notify(JsonResult::Error(JsonError::new(
  287. ErrorCode::InternalError,
  288. None,
  289. 0,
  290. )))
  291. .await;
  292. }
  293. }
  294. },
  295. Error::DetachedTaskStopped,
  296. ex,
  297. );
  298. let mut tstdout = StandardStream::stdout(ColorChoice::Auto);
  299. let mut update_resource = async |resource: &HashMap<String, JsonValue>| {
  300. let hash = resource.get("hash").unwrap().get::<String>().unwrap();
  301. let mut resources_write = resources.write().await;
  302. let i = match resources_write
  303. .iter()
  304. .position(|r| r.get("hash").unwrap().get::<String>().unwrap() == hash)
  305. {
  306. Some(i) => {
  307. resources_write.remove(i);
  308. resources_write.insert(i, resource.clone());
  309. i
  310. }
  311. None => {
  312. resources_write.push(resource.clone());
  313. resources_write.len() - 1
  314. }
  315. };
  316. // Move the cursor to the i-th line and clear it
  317. print!("\x1b[{};1H\x1B[2K", i + 2);
  318. let hash = resource.get("hash").unwrap().get::<String>().unwrap();
  319. print!("\r{:>44} ", hash,);
  320. let status = resource.get("status").unwrap().get::<String>().unwrap();
  321. tstdout
  322. .set_color(
  323. ColorSpec::new()
  324. .set_fg(match status.as_str() {
  325. "downloading" => Some(Color::Blue),
  326. "seeding" => Some(Color::Green),
  327. "discovering" => Some(Color::Magenta),
  328. "incomplete" => Some(Color::Red),
  329. _ => None,
  330. })
  331. .set_bold(true),
  332. )
  333. .unwrap();
  334. print!("{:>11} ", status,);
  335. tstdout.reset().unwrap();
  336. let chunks_downloaded =
  337. *resource.get("chunks_downloaded").unwrap().get::<f64>().unwrap() as usize;
  338. let chunks_total =
  339. *resource.get("chunks_total").unwrap().get::<f64>().unwrap() as usize;
  340. match chunks_total {
  341. 0 => {
  342. print!("{:>5.1} {:>9}", 0.0, format!("{}/?", chunks_downloaded));
  343. }
  344. _ => {
  345. let percent = chunks_downloaded as f64 / chunks_total as f64 * 100.0;
  346. print!(
  347. "{:>5.1} {:>9}",
  348. percent,
  349. format!("{}/{}", chunks_downloaded, chunks_total)
  350. );
  351. }
  352. };
  353. println!();
  354. // Move the cursor to end
  355. print!("\x1b[{};1H", resources_write.len() + 2);
  356. stdout().flush().unwrap();
  357. };
  358. let print_begin = async || {
  359. // Clear
  360. print!("\x1B[2J\x1B[1;1H");
  361. // Print column headers
  362. println!("\x1b[4m{:>44} {:>11} {:>5} {:>9}\x1b[0m", "Hash", "Status", "%", "Chunks");
  363. };
  364. print_begin().await;
  365. if resources_json.is_empty() {
  366. println!("No known resources");
  367. } else {
  368. for resource in resources_json.iter() {
  369. let resource = resource.get::<HashMap<String, JsonValue>>().unwrap();
  370. update_resource(resource).await;
  371. }
  372. }
  373. loop {
  374. match subscription.receive().await {
  375. JsonResult::Notification(n) => {
  376. let params = n.params.get::<HashMap<String, JsonValue>>().unwrap();
  377. let info =
  378. params.get("info").unwrap().get::<HashMap<String, JsonValue>>().unwrap();
  379. match params.get("event").unwrap().get::<String>().unwrap().as_str() {
  380. "download_started" |
  381. "file_download_completed" |
  382. "chunk_download_completed" |
  383. "download_completed" |
  384. "missing_chunks" |
  385. "file_not_found" => {
  386. let resource = info
  387. .get("resource")
  388. .unwrap()
  389. .get::<HashMap<String, JsonValue>>()
  390. .unwrap();
  391. update_resource(resource).await;
  392. }
  393. "resource_removed" => {
  394. {
  395. let hash = info.get("file_hash").unwrap().get::<String>().unwrap();
  396. let mut resources_write = resources.write().await;
  397. let i = resources_write.iter().position(|r| {
  398. r.get("hash").unwrap().get::<String>().unwrap() == hash
  399. });
  400. if let Some(i) = i {
  401. resources_write.remove(i);
  402. }
  403. }
  404. let r = resources.read().await.clone();
  405. print_begin().await;
  406. for resource in r.iter() {
  407. update_resource(resource).await;
  408. }
  409. }
  410. "download_error" => {
  411. // An error that caused the download to be unsuccessful
  412. }
  413. _ => {}
  414. }
  415. }
  416. JsonResult::Error(e) => {
  417. return Err(Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}")))
  418. }
  419. x => {
  420. return Err(Error::UnexpectedJsonRpc(format!(
  421. "Got unexpected data from JSON-RPC: {x:?}"
  422. )))
  423. }
  424. }
  425. }
  426. }
  427. async fn remove(&self, hash: String) -> Result<()> {
  428. let req = JsonRequest::new("remove", JsonValue::Array(vec![JsonValue::String(hash)]));
  429. self.rpc_client.request(req).await?;
  430. Ok(())
  431. }
  432. }
  433. fn main() -> Result<()> {
  434. let args = Args::parse();
  435. let log_level = get_log_level(args.verbose);
  436. let log_config = get_log_config(args.verbose);
  437. TermLogger::init(log_level, log_config, TerminalMode::Mixed, ColorChoice::Auto)?;
  438. let ex = Arc::new(smol::Executor::new());
  439. smol::block_on(async {
  440. ex.run(async {
  441. let rpc_client = Arc::new(RpcClient::new(args.endpoint.clone(), ex.clone()).await?);
  442. let fu = Fu { rpc_client, endpoint: args.endpoint.clone() };
  443. match args.command {
  444. Subcmd::Get { file, name } => fu.get(file, name, ex.clone()).await,
  445. Subcmd::Put { file } => fu.put(file).await,
  446. Subcmd::Watch {} => fu.watch(ex.clone()).await,
  447. Subcmd::Rm { hash } => fu.remove(hash).await,
  448. Subcmd::ListBuckets {} => fu.list_buckets().await,
  449. Subcmd::ListSeeders {} => fu.list_seeders().await,
  450. }?;
  451. Ok(())
  452. })
  453. .await
  454. })
  455. }