main.rs 21 KB

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