| use std::{io, time::Duration}; |
|
|
| use anyhow::{Context, Result}; |
| use futures::{AsyncReadExt, AsyncWriteExt, StreamExt}; |
| use libp2p::{multiaddr::Protocol, Multiaddr, PeerId, Stream, StreamProtocol}; |
| use libp2p_stream as stream; |
| use rand::RngCore; |
| use tracing::level_filters::LevelFilter; |
| use tracing_subscriber::EnvFilter; |
|
|
| const ECHO_PROTOCOL: StreamProtocol = StreamProtocol::new("/echo"); |
|
|
| #[tokio::main] |
| async fn main() -> Result<()> { |
| tracing_subscriber::fmt() |
| .with_env_filter( |
| EnvFilter::builder() |
| .with_default_directive(LevelFilter::INFO.into()) |
| .from_env()?, |
| ) |
| .init(); |
|
|
| let maybe_address = std::env::args() |
| .nth(1) |
| .map(|arg| arg.parse::<Multiaddr>()) |
| .transpose() |
| .context("Failed to parse argument as `Multiaddr`")?; |
|
|
| let mut swarm = libp2p::SwarmBuilder::with_new_identity() |
| .with_tokio() |
| .with_quic() |
| .with_behaviour(|_| stream::Behaviour::new())? |
| .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(10))) |
| .build(); |
|
|
| swarm.listen_on("/ip4/127.0.0.1/udp/0/quic-v1".parse()?)?; |
|
|
| let mut incoming_streams = swarm |
| .behaviour() |
| .new_control() |
| .accept(ECHO_PROTOCOL) |
| .unwrap(); |
|
|
| |
| |
| |
| |
| tokio::spawn(async move { |
| |
| |
| |
| |
|
|
| while let Some((peer, stream)) = incoming_streams.next().await { |
| match echo(stream).await { |
| Ok(n) => { |
| tracing::info!(%peer, "Echoed {n} bytes!"); |
| } |
| Err(e) => { |
| tracing::warn!(%peer, "Echo failed: {e}"); |
| continue; |
| } |
| }; |
| } |
| }); |
|
|
| |
| if let Some(address) = maybe_address { |
| let Some(Protocol::P2p(peer_id)) = address.iter().last() else { |
| anyhow::bail!("Provided address does not end in `/p2p`"); |
| }; |
|
|
| swarm.dial(address)?; |
|
|
| tokio::spawn(connection_handler(peer_id, swarm.behaviour().new_control())); |
| } |
|
|
| |
| loop { |
| let event = swarm.next().await.expect("never terminates"); |
|
|
| match event { |
| libp2p::swarm::SwarmEvent::NewListenAddr { address, .. } => { |
| let listen_address = address.with_p2p(*swarm.local_peer_id()).unwrap(); |
| tracing::info!(%listen_address); |
| } |
| event => tracing::trace!(?event), |
| } |
| } |
| } |
|
|
| |
| async fn connection_handler(peer: PeerId, mut control: stream::Control) { |
| loop { |
| tokio::time::sleep(Duration::from_secs(1)).await; |
|
|
| let stream = match control.open_stream(peer, ECHO_PROTOCOL).await { |
| Ok(stream) => stream, |
| Err(error @ stream::OpenStreamError::UnsupportedProtocol(_)) => { |
| tracing::info!(%peer, %error); |
| return; |
| } |
| Err(error) => { |
| |
| |
| tracing::debug!(%peer, %error); |
| continue; |
| } |
| }; |
|
|
| if let Err(e) = send(stream).await { |
| tracing::warn!(%peer, "Echo protocol failed: {e}"); |
| continue; |
| } |
|
|
| tracing::info!(%peer, "Echo complete!") |
| } |
| } |
|
|
| async fn echo(mut stream: Stream) -> io::Result<usize> { |
| let mut total = 0; |
|
|
| let mut buf = [0u8; 100]; |
|
|
| loop { |
| let read = stream.read(&mut buf).await?; |
| if read == 0 { |
| return Ok(total); |
| } |
|
|
| total += read; |
| stream.write_all(&buf[..read]).await?; |
| } |
| } |
|
|
| async fn send(mut stream: Stream) -> io::Result<()> { |
| let num_bytes = rand::random::<usize>() % 1000; |
|
|
| let mut bytes = vec![0; num_bytes]; |
| rand::thread_rng().fill_bytes(&mut bytes); |
|
|
| stream.write_all(&bytes).await?; |
|
|
| let mut buf = vec![0; num_bytes]; |
| stream.read_exact(&mut buf).await?; |
|
|
| if bytes != buf { |
| return Err(io::Error::new(io::ErrorKind::Other, "incorrect echo")); |
| } |
|
|
| stream.close().await?; |
|
|
| Ok(()) |
| } |
|
|