diff --git a/Cargo.toml b/Cargo.toml index 16f7ff70..5aa12dc4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,3 +29,8 @@ futures = "0.3.29" [features] async = ["flume/async"] default = ["async"] + +[[example]] +name = "async_get_immutable" +path = "examples/async/get_immutable.rs" +required-features = ["async"] diff --git a/examples/README.md b/examples/README.md index eea5fffa..f2278856 100644 --- a/examples/README.md +++ b/examples/README.md @@ -35,3 +35,9 @@ cargo run --example put_mutable <64 bytes hex secret_key> ```sh cargo run --example get_mutable <40 bytes hex target from put_mutable> ````` + +## Async Get Mutable + +```sh +cargo run --example async_get_mutable <40 bytes hex target from put_mutable> +````` diff --git a/examples/async/get_immutable.rs b/examples/async/get_immutable.rs new file mode 100644 index 00000000..c82528f1 --- /dev/null +++ b/examples/async/get_immutable.rs @@ -0,0 +1,67 @@ +use std::{str::FromStr, time::Instant}; + +use mainline::{Dht, Id}; + +use clap::Parser; + +#[derive(Parser)] +#[command(author, version, about, long_about = None)] +struct Cli { + /// Immutable data sha1 hash to lookup. + target: String, +} + +async fn async_main() { + let cli = Cli::parse(); + + let target_parse_result: Result = Id::from_str(cli.target.as_str()); + + match target_parse_result { + Ok(infohash) => { + let dht = Dht::default().as_async(); + + let start = Instant::now(); + + println!("\nLooking up immutable data: {} ...\n", cli.target); + + let response = &mut dht.get_immutable(infohash).await; + + if let Some(res) = response.next_async().await { + println!( + "Got result in {:?} seconds\n", + start.elapsed().as_secs_f32() + ); + + // No need to stream responses, just print the first result, since + // all immutable data items are guaranteed to be the same. + + match String::from_utf8(res.value.to_vec()) { + Ok(string) => { + println!("Got immutable data: {:?} | from: {:?}", string, res.from); + } + Err(_) => { + println!("Got immutable data: {:?} | from: {:?}", res.value, res.from); + } + }; + } + + println!( + "\nVisited {:?} nodes, found {:?} closest nodes", + response.visited, + &response.closest_nodes.len() + ); + + println!( + "\nQuery exhausted in {:?} seconds", + start.elapsed().as_secs_f32(), + ); + } + Err(err) => { + println!("Error: {}", err) + } + }; +} + +fn main() { + futures::executor::block_on(async_main()); +} diff --git a/src/lib.rs b/src/lib.rs index 7438754e..6e5b3517 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ //! Rust implementation of read-only BitTorrent Mainline DHT client. // Public modules +#[cfg(feature = "async")] pub mod async_dht; pub mod common; pub mod dht;