diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5f199225e9b..6dc794e9138 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -225,7 +225,7 @@ jobs: fail-fast: false matrix: rust-version: [ - 1.83.0, # current stable + 1.85.0, # current stable beta, ] steps: diff --git a/Cargo.lock b/Cargo.lock index a419878cc46..822e50ee7b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "addr2line" diff --git a/Cargo.toml b/Cargo.toml index 98d9c88ee0e..28b0d13acac 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,8 +70,8 @@ members = [ resolver = "2" [workspace.package] -rust-version = "1.83.0" -edition = "2021" +rust-version = "1.85.0" +edition = "2024" [workspace.dependencies] libp2p = { version = "0.55.1", path = "libp2p" } diff --git a/core/src/either.rs b/core/src/either.rs index aa0340a46bf..7dc9d92d875 100644 --- a/core/src/either.rs +++ b/core/src/either.rs @@ -28,9 +28,9 @@ use futures::prelude::*; use pin_project::pin_project; use crate::{ + Multiaddr, muxing::{StreamMuxer, StreamMuxerEvent}, transport::{DialOpts, ListenerId, Transport, TransportError, TransportEvent}, - Multiaddr, }; impl StreamMuxer for future::Either diff --git a/core/src/lib.rs b/core/src/lib.rs index bbe42adc26a..a1e05207720 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -36,7 +36,7 @@ mod proto { include!("generated/mod.rs"); pub use self::{ envelope_proto::*, - peer_record_proto::{mod_PeerRecord::*, PeerRecord}, + peer_record_proto::{PeerRecord, mod_PeerRecord::*}, }; } diff --git a/core/src/muxing.rs b/core/src/muxing.rs index 60062f899f9..c749436764b 100644 --- a/core/src/muxing.rs +++ b/core/src/muxing.rs @@ -53,8 +53,8 @@ use std::{future::Future, pin::Pin}; use futures::{ - task::{Context, Poll}, AsyncRead, AsyncWrite, + task::{Context, Poll}, }; use multiaddr::Multiaddr; diff --git a/core/src/peer_record.rs b/core/src/peer_record.rs index 9c6b7f73f05..7ed38316ee3 100644 --- a/core/src/peer_record.rs +++ b/core/src/peer_record.rs @@ -2,7 +2,7 @@ use libp2p_identity::{Keypair, PeerId, SigningError}; use quick_protobuf::{BytesReader, Writer}; use web_time::SystemTime; -use crate::{proto, signed_envelope, signed_envelope::SignedEnvelope, DecodeError, Multiaddr}; +use crate::{DecodeError, Multiaddr, proto, signed_envelope, signed_envelope::SignedEnvelope}; const PAYLOAD_TYPE: &str = "/libp2p/routing-state-record"; const DOMAIN_SEP: &str = "libp2p-routing-state"; diff --git a/core/src/signed_envelope.rs b/core/src/signed_envelope.rs index 9a08c6d3d34..08808e4cad0 100644 --- a/core/src/signed_envelope.rs +++ b/core/src/signed_envelope.rs @@ -4,7 +4,7 @@ use libp2p_identity::{Keypair, PublicKey, SigningError}; use quick_protobuf::{BytesReader, Writer}; use unsigned_varint::encode::usize_buffer; -use crate::{proto, DecodeError}; +use crate::{DecodeError, proto}; /// A signed envelope contains an arbitrary byte string payload, a signature of the payload, and the /// public key that can be used to verify the signature. diff --git a/core/src/transport/and_then.rs b/core/src/transport/and_then.rs index 5d2b7d91553..27bd3161fde 100644 --- a/core/src/transport/and_then.rs +++ b/core/src/transport/and_then.rs @@ -175,7 +175,7 @@ where Poll::Ready(Ok(v)) => Poll::Ready(Ok(v)), Poll::Ready(Err(err)) => return Poll::Ready(Err(Either::Right(err))), Poll::Pending => Poll::Pending, - } + }; } }; diff --git a/core/src/transport/choice.rs b/core/src/transport/choice.rs index 251091f2008..22be6b8d9af 100644 --- a/core/src/transport/choice.rs +++ b/core/src/transport/choice.rs @@ -120,7 +120,7 @@ where addr } Err(TransportError::Other(err)) => { - return Err(TransportError::Other(Either::Left(err))) + return Err(TransportError::Other(Either::Left(err))); } }; @@ -140,7 +140,7 @@ where addr } Err(TransportError::Other(err)) => { - return Err(TransportError::Other(Either::Right(err))) + return Err(TransportError::Other(Either::Right(err))); } }; @@ -154,13 +154,13 @@ where let this = self.project(); match this.0.poll(cx) { Poll::Ready(ev) => { - return Poll::Ready(ev.map_upgrade(EitherFuture::First).map_err(Either::Left)) + return Poll::Ready(ev.map_upgrade(EitherFuture::First).map_err(Either::Left)); } Poll::Pending => {} } match this.1.poll(cx) { Poll::Ready(ev) => { - return Poll::Ready(ev.map_upgrade(EitherFuture::Second).map_err(Either::Right)) + return Poll::Ready(ev.map_upgrade(EitherFuture::Second).map_err(Either::Right)); } Poll::Pending => {} } diff --git a/core/src/transport/dummy.rs b/core/src/transport/dummy.rs index 85c5815fd37..b7db070adc0 100644 --- a/core/src/transport/dummy.rs +++ b/core/src/transport/dummy.rs @@ -26,8 +26,8 @@ use futures::{ }; use crate::{ - transport::{DialOpts, ListenerId, Transport, TransportError, TransportEvent}, Multiaddr, + transport::{DialOpts, ListenerId, Transport, TransportError, TransportEvent}, }; /// Implementation of `Transport` that doesn't support any multiaddr. diff --git a/core/src/transport/memory.rs b/core/src/transport/memory.rs index 6c809c7a996..7e7cdf21715 100644 --- a/core/src/transport/memory.rs +++ b/core/src/transport/memory.rs @@ -19,7 +19,7 @@ // DEALINGS IN THE SOFTWARE. use std::{ - collections::{hash_map::Entry, VecDeque}, + collections::{VecDeque, hash_map::Entry}, error, fmt, io, num::NonZeroU64, pin::Pin, @@ -406,7 +406,7 @@ impl Drop for Chan { #[cfg(test)] mod tests { use super::*; - use crate::{transport::PortUse, Endpoint}; + use crate::{Endpoint, transport::PortUse}; #[test] fn parse_memory_addr_works() { @@ -463,21 +463,27 @@ mod tests { let listener_id_3 = ListenerId::next(); transport.listen_on(listener_id_3, addr_2.clone()).unwrap(); - assert!(transport - .listen_on(ListenerId::next(), addr_1.clone()) - .is_err()); - assert!(transport - .listen_on(ListenerId::next(), addr_2.clone()) - .is_err()); + assert!( + transport + .listen_on(ListenerId::next(), addr_1.clone()) + .is_err() + ); + assert!( + transport + .listen_on(ListenerId::next(), addr_2.clone()) + .is_err() + ); assert!( transport.remove_listener(listener_id_2), "Listener doesn't exist." ); assert!(transport.listen_on(ListenerId::next(), addr_1).is_ok()); - assert!(transport - .listen_on(ListenerId::next(), addr_2.clone()) - .is_err()); + assert!( + transport + .listen_on(ListenerId::next(), addr_2.clone()) + .is_err() + ); assert!( transport.remove_listener(listener_id_3), @@ -489,30 +495,34 @@ mod tests { #[test] fn port_not_in_use() { let mut transport = MemoryTransport::default(); - assert!(transport - .dial( - "/memory/810172461024613".parse().unwrap(), - DialOpts { - role: Endpoint::Dialer, - port_use: PortUse::New - } - ) - .is_err()); + assert!( + transport + .dial( + "/memory/810172461024613".parse().unwrap(), + DialOpts { + role: Endpoint::Dialer, + port_use: PortUse::New + } + ) + .is_err() + ); transport .listen_on( ListenerId::next(), "/memory/810172461024613".parse().unwrap(), ) .unwrap(); - assert!(transport - .dial( - "/memory/810172461024613".parse().unwrap(), - DialOpts { - role: Endpoint::Dialer, - port_use: PortUse::New - } - ) - .is_ok()); + assert!( + transport + .dial( + "/memory/810172461024613".parse().unwrap(), + DialOpts { + role: Endpoint::Dialer, + port_use: PortUse::New + } + ) + .is_ok() + ); } #[test] diff --git a/core/src/transport/timeout.rs b/core/src/transport/timeout.rs index ce494216279..c7ccc9c7fc9 100644 --- a/core/src/transport/timeout.rs +++ b/core/src/transport/timeout.rs @@ -35,8 +35,8 @@ use futures::prelude::*; use futures_timer::Delay; use crate::{ - transport::{DialOpts, ListenerId, TransportError, TransportEvent}, Multiaddr, Transport, + transport::{DialOpts, ListenerId, TransportError, TransportEvent}, }; /// A `TransportTimeout` is a `Transport` that wraps another `Transport` and adds diff --git a/core/src/transport/upgrade.rs b/core/src/transport/upgrade.rs index df0038c3cf5..0bd8f56308b 100644 --- a/core/src/transport/upgrade.rs +++ b/core/src/transport/upgrade.rs @@ -34,17 +34,17 @@ use multiaddr::Multiaddr; pub use crate::upgrade::Version; use crate::{ + Negotiated, connection::ConnectedPoint, muxing::{StreamMuxer, StreamMuxerBox}, transport::{ - and_then::AndThen, boxed::boxed, timeout::TransportTimeout, DialOpts, ListenerId, - Transport, TransportError, TransportEvent, + DialOpts, ListenerId, Transport, TransportError, TransportEvent, and_then::AndThen, + boxed::boxed, timeout::TransportTimeout, }, upgrade::{ - self, apply_inbound, apply_outbound, InboundConnectionUpgrade, InboundUpgradeApply, - OutboundConnectionUpgrade, OutboundUpgradeApply, UpgradeError, + self, InboundConnectionUpgrade, InboundUpgradeApply, OutboundConnectionUpgrade, + OutboundUpgradeApply, UpgradeError, apply_inbound, apply_outbound, }, - Negotiated, }; /// A `Builder` facilitates upgrading of a [`Transport`] for use with @@ -506,9 +506,10 @@ where loop { this.upgrade = match this.upgrade { future::Either::Left(ref mut up) => { - let (i, c) = match ready!(TryFuture::try_poll(this.future.as_mut(), cx) - .map_err(TransportUpgradeError::Transport)) - { + let (i, c) = match ready!( + TryFuture::try_poll(this.future.as_mut(), cx) + .map_err(TransportUpgradeError::Transport) + ) { Ok(v) => v, Err(err) => return Poll::Ready(Err(err)), }; @@ -565,9 +566,10 @@ where loop { this.upgrade = match this.upgrade { future::Either::Left(ref mut up) => { - let (i, c) = match ready!(TryFuture::try_poll(this.future.as_mut(), cx) - .map_err(TransportUpgradeError::Transport)) - { + let (i, c) = match ready!( + TryFuture::try_poll(this.future.as_mut(), cx) + .map_err(TransportUpgradeError::Transport) + ) { Ok(v) => v, Err(err) => return Poll::Ready(Err(err)), }; @@ -577,9 +579,10 @@ where future::Either::Right((i, apply_inbound(c, u))) } future::Either::Right((i, ref mut up)) => { - let d = match ready!(TryFuture::try_poll(Pin::new(up), cx) - .map_err(TransportUpgradeError::Upgrade)) - { + let d = match ready!( + TryFuture::try_poll(Pin::new(up), cx) + .map_err(TransportUpgradeError::Upgrade) + ) { Ok(v) => v, Err(err) => return Poll::Ready(Err(err)), }; diff --git a/core/src/upgrade.rs b/core/src/upgrade.rs index 93039705938..dc08201f88d 100644 --- a/core/src/upgrade.rs +++ b/core/src/upgrade.rs @@ -65,7 +65,7 @@ mod ready; mod select; pub(crate) use apply::{ - apply, apply_inbound, apply_outbound, InboundUpgradeApply, OutboundUpgradeApply, + InboundUpgradeApply, OutboundUpgradeApply, apply, apply_inbound, apply_outbound, }; pub(crate) use error::UpgradeError; use futures::future::Future; diff --git a/core/src/upgrade/apply.rs b/core/src/upgrade/apply.rs index 9e090267b0c..248237f5ef7 100644 --- a/core/src/upgrade/apply.rs +++ b/core/src/upgrade/apply.rs @@ -29,9 +29,9 @@ pub(crate) use multistream_select::Version; use multistream_select::{DialerSelectFuture, ListenerSelectFuture}; use crate::{ + Negotiated, connection::ConnectedPoint, upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade, UpgradeError}, - Negotiated, }; // TODO: Still needed? diff --git a/core/tests/transport_upgrade.rs b/core/tests/transport_upgrade.rs index 82a17877f9c..e833d7c0b91 100644 --- a/core/tests/transport_upgrade.rs +++ b/core/tests/transport_upgrade.rs @@ -22,9 +22,9 @@ use std::{io, pin::Pin}; use futures::prelude::*; use libp2p_core::{ + Endpoint, transport::{DialOpts, ListenerId, MemoryTransport, PortUse, Transport}, upgrade::{self, InboundConnectionUpgrade, OutboundConnectionUpgrade, UpgradeInfo}, - Endpoint, }; use libp2p_identity as identity; use libp2p_mplex::Config; diff --git a/examples/autonat/src/bin/autonat_client.rs b/examples/autonat/src/bin/autonat_client.rs index 5c739d723f0..3bdb86279ad 100644 --- a/examples/autonat/src/bin/autonat_client.rs +++ b/examples/autonat/src/bin/autonat_client.rs @@ -25,11 +25,11 @@ use std::{error::Error, net::Ipv4Addr, time::Duration}; use clap::Parser; use futures::StreamExt; use libp2p::{ - autonat, - core::{multiaddr::Protocol, Multiaddr}, + PeerId, autonat, + core::{Multiaddr, multiaddr::Protocol}, identify, identity, noise, swarm::{NetworkBehaviour, SwarmEvent}, - tcp, yamux, PeerId, + tcp, yamux, }; use tracing_subscriber::EnvFilter; diff --git a/examples/autonat/src/bin/autonat_server.rs b/examples/autonat/src/bin/autonat_server.rs index 2d867a1b7a2..bcc74b8951e 100644 --- a/examples/autonat/src/bin/autonat_server.rs +++ b/examples/autonat/src/bin/autonat_server.rs @@ -26,7 +26,7 @@ use clap::Parser; use futures::StreamExt; use libp2p::{ autonat, - core::{multiaddr::Protocol, Multiaddr}, + core::{Multiaddr, multiaddr::Protocol}, identify, identity, noise, swarm::{NetworkBehaviour, SwarmEvent}, tcp, yamux, diff --git a/examples/autonatv2/src/bin/autonatv2_client.rs b/examples/autonatv2/src/bin/autonatv2_client.rs index 3ee42370cda..4f4c4b408e3 100644 --- a/examples/autonatv2/src/bin/autonatv2_client.rs +++ b/examples/autonatv2/src/bin/autonatv2_client.rs @@ -2,13 +2,13 @@ use std::{error::Error, net::Ipv4Addr, time::Duration}; use clap::Parser; use libp2p::{ - autonat, + Multiaddr, SwarmBuilder, autonat, futures::StreamExt, identify, identity, multiaddr::Protocol, noise, - swarm::{dial_opts::DialOpts, NetworkBehaviour, SwarmEvent}, - tcp, yamux, Multiaddr, SwarmBuilder, + swarm::{NetworkBehaviour, SwarmEvent, dial_opts::DialOpts}, + tcp, yamux, }; use rand::rngs::OsRng; use tracing_subscriber::EnvFilter; @@ -73,7 +73,9 @@ async fn main() -> Result<(), Box> { bytes_sent, result: Ok(()), })) => { - println!("Tested {tested_addr} with {server}. Sent {bytes_sent} bytes for verification. Everything Ok and verified."); + println!( + "Tested {tested_addr} with {server}. Sent {bytes_sent} bytes for verification. Everything Ok and verified." + ); } SwarmEvent::Behaviour(BehaviourEvent::Autonat(autonat::v2::client::Event { server, @@ -81,7 +83,9 @@ async fn main() -> Result<(), Box> { bytes_sent, result: Err(e), })) => { - println!("Tested {tested_addr} with {server}. Sent {bytes_sent} bytes for verification. Failed with {e:?}."); + println!( + "Tested {tested_addr} with {server}. Sent {bytes_sent} bytes for verification. Failed with {e:?}." + ); } SwarmEvent::ExternalAddrConfirmed { address } => { println!("External address confirmed: {address}"); diff --git a/examples/autonatv2/src/bin/autonatv2_server.rs b/examples/autonatv2/src/bin/autonatv2_server.rs index 849ed3b3b0a..59e4e4d9518 100644 --- a/examples/autonatv2/src/bin/autonatv2_server.rs +++ b/examples/autonatv2/src/bin/autonatv2_server.rs @@ -3,13 +3,13 @@ use std::{error::Error, net::Ipv4Addr, time::Duration}; use cfg_if::cfg_if; use clap::Parser; use libp2p::{ - autonat, + Multiaddr, SwarmBuilder, autonat, futures::StreamExt, identify, identity, multiaddr::Protocol, noise, swarm::{NetworkBehaviour, SwarmEvent}, - tcp, yamux, Multiaddr, SwarmBuilder, + tcp, yamux, }; use rand::rngs::OsRng; diff --git a/examples/browser-webrtc/src/main.rs b/examples/browser-webrtc/src/main.rs index 52222dc882b..87741a4a65a 100644 --- a/examples/browser-webrtc/src/main.rs +++ b/examples/browser-webrtc/src/main.rs @@ -4,15 +4,15 @@ use std::net::{Ipv4Addr, SocketAddr}; use anyhow::Result; use axum::{ + Router, extract::{Path, State}, - http::{header::CONTENT_TYPE, Method, StatusCode}, + http::{Method, StatusCode, header::CONTENT_TYPE}, response::{Html, IntoResponse}, routing::get, - Router, }; use futures::StreamExt; use libp2p::{ - core::{muxing::StreamMuxerBox, Transport}, + core::{Transport, muxing::StreamMuxerBox}, multiaddr::{Multiaddr, Protocol}, ping, swarm::SwarmEvent, diff --git a/examples/dcutr/src/main.rs b/examples/dcutr/src/main.rs index 3f403d534e7..6d7e54b883f 100644 --- a/examples/dcutr/src/main.rs +++ b/examples/dcutr/src/main.rs @@ -25,10 +25,11 @@ use std::{error::Error, str::FromStr}; use clap::Parser; use futures::{executor::block_on, future::FutureExt, stream::StreamExt}; use libp2p::{ + PeerId, core::multiaddr::{Multiaddr, Protocol}, dcutr, identify, identity, noise, ping, relay, swarm::{NetworkBehaviour, SwarmEvent}, - tcp, yamux, PeerId, + tcp, yamux, }; use tracing_subscriber::EnvFilter; diff --git a/examples/distributed-key-value-store/src/main.rs b/examples/distributed-key-value-store/src/main.rs index 3522c84c720..d8e84713a3f 100644 --- a/examples/distributed-key-value-store/src/main.rs +++ b/examples/distributed-key-value-store/src/main.rs @@ -25,7 +25,7 @@ use std::error::Error; use futures::stream::StreamExt; use libp2p::{ kad, - kad::{store::MemoryStore, Mode}, + kad::{Mode, store::MemoryStore}, mdns, noise, swarm::{NetworkBehaviour, SwarmEvent}, tcp, yamux, diff --git a/examples/file-sharing/src/main.rs b/examples/file-sharing/src/main.rs index 1e3b80a330c..2533d382e4a 100644 --- a/examples/file-sharing/src/main.rs +++ b/examples/file-sharing/src/main.rs @@ -25,7 +25,7 @@ mod network; use std::{error::Error, io::Write, path::PathBuf}; use clap::Parser; -use futures::{prelude::*, StreamExt}; +use futures::{StreamExt, prelude::*}; use libp2p::{core::Multiaddr, multiaddr::Protocol}; use tokio::task::spawn; use tracing_subscriber::EnvFilter; diff --git a/examples/file-sharing/src/network.rs b/examples/file-sharing/src/network.rs index 409255ee9ec..f69656e0c87 100644 --- a/examples/file-sharing/src/network.rs +++ b/examples/file-sharing/src/network.rs @@ -1,22 +1,23 @@ use std::{ - collections::{hash_map, HashMap, HashSet}, + collections::{HashMap, HashSet, hash_map}, error::Error, time::Duration, }; use futures::{ + StreamExt, channel::{mpsc, oneshot}, prelude::*, - StreamExt, }; use libp2p::{ + PeerId, StreamProtocol, core::Multiaddr, identity, kad, multiaddr::Protocol, noise, request_response::{self, OutboundRequestId, ProtocolSupport, ResponseChannel}, swarm::{NetworkBehaviour, Swarm, SwarmEvent}, - tcp, yamux, PeerId, StreamProtocol, + tcp, yamux, }; use serde::{Deserialize, Serialize}; diff --git a/examples/ipfs-kad/src/main.rs b/examples/ipfs-kad/src/main.rs index 8d9a289bdd1..57a34d7a29b 100644 --- a/examples/ipfs-kad/src/main.rs +++ b/examples/ipfs-kad/src/main.rs @@ -26,14 +26,15 @@ use std::{ time::{Duration, Instant}, }; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use clap::Parser; use futures::StreamExt; use libp2p::{ + PeerId, bytes::BufMut, identity, kad, noise, swarm::{StreamProtocol, SwarmEvent}, - tcp, yamux, PeerId, + tcp, yamux, }; use tracing_subscriber::EnvFilter; diff --git a/examples/ipfs-private/src/main.rs b/examples/ipfs-private/src/main.rs index 6d8f9beb75d..9c3b5e30e2f 100644 --- a/examples/ipfs-private/src/main.rs +++ b/examples/ipfs-private/src/main.rs @@ -25,13 +25,14 @@ use std::{env, error::Error, fs, path::Path, str::FromStr}; use either::Either; use futures::prelude::*; use libp2p::{ + Multiaddr, Transport, core::transport::upgrade::Version, gossipsub, identify, multiaddr::Protocol, noise, ping, pnet::{PnetConfig, PreSharedKey}, swarm::{NetworkBehaviour, SwarmEvent}, - tcp, yamux, Multiaddr, Transport, + tcp, yamux, }; use tokio::{io, io::AsyncBufReadExt, select}; use tracing_subscriber::EnvFilter; diff --git a/examples/metrics/src/http_service.rs b/examples/metrics/src/http_service.rs index f1485832d86..35a1aa33d31 100644 --- a/examples/metrics/src/http_service.rs +++ b/examples/metrics/src/http_service.rs @@ -23,7 +23,7 @@ use std::{ sync::{Arc, Mutex}, }; -use axum::{extract::State, http::StatusCode, response::IntoResponse, routing::get, Router}; +use axum::{Router, extract::State, http::StatusCode, response::IntoResponse, routing::get}; use prometheus_client::{encoding::text::encode, registry::Registry}; use tokio::net::TcpListener; diff --git a/examples/metrics/src/main.rs b/examples/metrics/src/main.rs index 6f6e9d08e31..0802d24c17c 100644 --- a/examples/metrics/src/main.rs +++ b/examples/metrics/src/main.rs @@ -31,11 +31,11 @@ use libp2p::{ swarm::{NetworkBehaviour, SwarmEvent}, tcp, yamux, }; -use opentelemetry::{trace::TracerProvider as _, KeyValue}; +use opentelemetry::{KeyValue, trace::TracerProvider as _}; use opentelemetry_otlp::SpanExporter; use opentelemetry_sdk::{runtime, trace::TracerProvider}; use prometheus_client::registry::Registry; -use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer}; +use tracing_subscriber::{EnvFilter, Layer, layer::SubscriberExt, util::SubscriberInitExt}; mod http_service; diff --git a/examples/ping/src/main.rs b/examples/ping/src/main.rs index 565ef057c0d..6411b65d063 100644 --- a/examples/ping/src/main.rs +++ b/examples/ping/src/main.rs @@ -23,7 +23,7 @@ use std::{error::Error, time::Duration}; use futures::prelude::*; -use libp2p::{noise, ping, swarm::SwarmEvent, tcp, yamux, Multiaddr}; +use libp2p::{Multiaddr, noise, ping, swarm::SwarmEvent, tcp, yamux}; use tracing_subscriber::EnvFilter; #[tokio::main] diff --git a/examples/relay-server/src/main.rs b/examples/relay-server/src/main.rs index b7868418fb0..72c4d6c627f 100644 --- a/examples/relay-server/src/main.rs +++ b/examples/relay-server/src/main.rs @@ -29,7 +29,7 @@ use std::{ use clap::Parser; use futures::StreamExt; use libp2p::{ - core::{multiaddr::Protocol, Multiaddr}, + core::{Multiaddr, multiaddr::Protocol}, identify, identity, noise, ping, relay, swarm::{NetworkBehaviour, SwarmEvent}, tcp, yamux, diff --git a/examples/rendezvous/src/bin/rzv-discover.rs b/examples/rendezvous/src/bin/rzv-discover.rs index bdf9aeafdab..d9a52724aa0 100644 --- a/examples/rendezvous/src/bin/rzv-discover.rs +++ b/examples/rendezvous/src/bin/rzv-discover.rs @@ -22,10 +22,11 @@ use std::{error::Error, time::Duration}; use futures::StreamExt; use libp2p::{ + Multiaddr, multiaddr::Protocol, noise, ping, rendezvous, swarm::{NetworkBehaviour, SwarmEvent}, - tcp, yamux, Multiaddr, + tcp, yamux, }; use tracing_subscriber::EnvFilter; diff --git a/examples/rendezvous/src/bin/rzv-identify.rs b/examples/rendezvous/src/bin/rzv-identify.rs index 00e94627292..5e1bdcfefc2 100644 --- a/examples/rendezvous/src/bin/rzv-identify.rs +++ b/examples/rendezvous/src/bin/rzv-identify.rs @@ -22,9 +22,9 @@ use std::time::Duration; use futures::StreamExt; use libp2p::{ - identify, noise, ping, rendezvous, + Multiaddr, identify, noise, ping, rendezvous, swarm::{NetworkBehaviour, SwarmEvent}, - tcp, yamux, Multiaddr, + tcp, yamux, }; use tracing_subscriber::EnvFilter; diff --git a/examples/rendezvous/src/bin/rzv-register.rs b/examples/rendezvous/src/bin/rzv-register.rs index f70eda5d55e..0179519b99e 100644 --- a/examples/rendezvous/src/bin/rzv-register.rs +++ b/examples/rendezvous/src/bin/rzv-register.rs @@ -22,9 +22,9 @@ use std::time::Duration; use futures::StreamExt; use libp2p::{ - noise, ping, rendezvous, + Multiaddr, noise, ping, rendezvous, swarm::{NetworkBehaviour, SwarmEvent}, - tcp, yamux, Multiaddr, + tcp, yamux, }; use tracing_subscriber::EnvFilter; diff --git a/examples/stream/src/main.rs b/examples/stream/src/main.rs index 71d2d2fcc76..fc5d8a0cf4c 100644 --- a/examples/stream/src/main.rs +++ b/examples/stream/src/main.rs @@ -2,7 +2,7 @@ use std::{io, time::Duration}; use anyhow::{Context, Result}; use futures::{AsyncReadExt, AsyncWriteExt, StreamExt}; -use libp2p::{multiaddr::Protocol, Multiaddr, PeerId, Stream, StreamProtocol}; +use libp2p::{Multiaddr, PeerId, Stream, StreamProtocol, multiaddr::Protocol}; use libp2p_stream as stream; use rand::RngCore; use tracing::level_filters::LevelFilter; diff --git a/examples/upnp/src/main.rs b/examples/upnp/src/main.rs index 19de8d773ae..27cbae1883c 100644 --- a/examples/upnp/src/main.rs +++ b/examples/upnp/src/main.rs @@ -23,7 +23,7 @@ use std::error::Error; use futures::prelude::*; -use libp2p::{noise, swarm::SwarmEvent, upnp, yamux, Multiaddr}; +use libp2p::{Multiaddr, noise, swarm::SwarmEvent, upnp, yamux}; use tracing_subscriber::EnvFilter; #[tokio::main] @@ -65,7 +65,9 @@ async fn main() -> Result<(), Box> { break; } SwarmEvent::Behaviour(upnp::Event::NonRoutableGateway) => { - println!("Gateway is not exposed directly to the public Internet, i.e. it itself has a private IP address."); + println!( + "Gateway is not exposed directly to the public Internet, i.e. it itself has a private IP address." + ); break; } _ => {} diff --git a/hole-punching-tests/src/main.rs b/hole-punching-tests/src/main.rs index bc5a1bae4f5..d386ba33d4c 100644 --- a/hole-punching-tests/src/main.rs +++ b/hole-punching-tests/src/main.rs @@ -30,13 +30,14 @@ use anyhow::{Context, Result}; use either::Either; use futures::stream::StreamExt; use libp2p::{ + Swarm, core::{ multiaddr::{Multiaddr, Protocol}, transport::ListenerId, }, dcutr, identify, noise, ping, relay, - swarm::{dial_opts::DialOpts, ConnectionId, NetworkBehaviour, SwarmEvent}, - tcp, yamux, Swarm, + swarm::{ConnectionId, NetworkBehaviour, SwarmEvent, dial_opts::DialOpts}, + tcp, yamux, }; use redis::AsyncCommands; diff --git a/identity/Cargo.toml b/identity/Cargo.toml index 67f2b3f459d..62e40a9653e 100644 --- a/identity/Cargo.toml +++ b/identity/Cargo.toml @@ -1,9 +1,9 @@ [package] name = "libp2p-identity" version = "0.2.10" -edition = "2021" # MUST NOT inherit from workspace because we don't want to publish breaking changes to `libp2p-identity`. +edition = "2024" description = "Data structures and algorithms for identifying peers in libp2p." -rust-version = "1.73.0" # MUST NOT inherit from workspace because we don't want to publish breaking changes to `libp2p-identity`. +rust-version = "1.85.0" # MUST NOT inherit from workspace because we don't want to publish breaking changes to `libp2p-identity`. license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" keywords = ["peer-to-peer", "libp2p", "networking", "cryptography"] diff --git a/identity/benches/peer_id.rs b/identity/benches/peer_id.rs index 358778e221e..5a81a384c94 100644 --- a/identity/benches/peer_id.rs +++ b/identity/benches/peer_id.rs @@ -18,7 +18,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, black_box, criterion_group, criterion_main}; use libp2p_identity::{Keypair, PeerId}; fn from_bytes(c: &mut Criterion) { diff --git a/identity/src/ecdsa.rs b/identity/src/ecdsa.rs index 11cdaced795..a46e77d90cc 100644 --- a/identity/src/ecdsa.rs +++ b/identity/src/ecdsa.rs @@ -24,11 +24,11 @@ use core::{cmp, fmt, hash}; use std::convert::Infallible; use p256::{ + EncodedPoint, ecdsa::{ - signature::{Signer, Verifier}, Signature, SigningKey, VerifyingKey, + signature::{Signer, Verifier}, }, - EncodedPoint, }; use sec1::{DecodeEcPrivateKey, EncodeEcPrivateKey}; use zeroize::Zeroize; diff --git a/identity/src/keypair.rs b/identity/src/keypair.rs index a1bbba00fa9..aafd5aeaed7 100644 --- a/identity/src/keypair.rs +++ b/identity/src/keypair.rs @@ -55,8 +55,8 @@ use crate::rsa; #[cfg(feature = "secp256k1")] use crate::secp256k1; use crate::{ - error::{DecodingError, SigningError}, KeyType, + error::{DecodingError, SigningError}, }; /// Identity keypair of a node. diff --git a/identity/src/peer_id.rs b/identity/src/peer_id.rs index 7f6d1f44eab..8d2c364ff58 100644 --- a/identity/src/peer_id.rs +++ b/identity/src/peer_id.rs @@ -106,7 +106,7 @@ impl PeerId { /// This is useful for randomly walking on a DHT, or for testing purposes. #[cfg(feature = "rand")] pub fn random() -> PeerId { - let peer_id = rand::thread_rng().gen::<[u8; 32]>(); + let peer_id = rand::thread_rng().r#gen::<[u8; 32]>(); PeerId { multihash: Multihash::wrap(0x0, &peer_id).expect("The digest size is never too large"), } diff --git a/identity/src/rsa.rs b/identity/src/rsa.rs index 00c4b65a3bc..ea03c7d38b2 100644 --- a/identity/src/rsa.rs +++ b/identity/src/rsa.rs @@ -23,12 +23,12 @@ use std::{fmt, sync::Arc}; use asn1_der::{ - typed::{DerDecodable, DerEncodable, DerTypeView, Sequence}, Asn1DerError, Asn1DerErrorVariant, DerObject, Sink, VecBacking, + typed::{DerDecodable, DerEncodable, DerTypeView, Sequence}, }; use ring::{ rand::SystemRandom, - signature::{self, KeyPair, RsaKeyPair, RSA_PKCS1_2048_8192_SHA256, RSA_PKCS1_SHA256}, + signature::{self, KeyPair, RSA_PKCS1_2048_8192_SHA256, RSA_PKCS1_SHA256, RsaKeyPair}, }; use zeroize::Zeroize; diff --git a/interop-tests/src/arch.rs b/interop-tests/src/arch.rs index 88c4c5767de..89330487d39 100644 --- a/interop-tests/src/arch.rs +++ b/interop-tests/src/arch.rs @@ -1,16 +1,16 @@ // Native re-exports #[cfg(not(target_arch = "wasm32"))] -pub(crate) use native::{build_swarm, init_logger, sleep, Instant, RedisClient}; +pub(crate) use native::{Instant, RedisClient, build_swarm, init_logger, sleep}; // Wasm re-exports #[cfg(target_arch = "wasm32")] -pub(crate) use wasm::{build_swarm, init_logger, sleep, Instant, RedisClient}; +pub(crate) use wasm::{Instant, RedisClient, build_swarm, init_logger, sleep}; #[cfg(not(target_arch = "wasm32"))] pub(crate) mod native { use std::time::Duration; - use anyhow::{bail, Context, Result}; - use futures::{future::BoxFuture, FutureExt}; + use anyhow::{Context, Result, bail}; + use futures::{FutureExt, future::BoxFuture}; use libp2p::{ identity::Keypair, noise, @@ -179,14 +179,15 @@ pub(crate) mod native { pub(crate) mod wasm { use std::time::Duration; - use anyhow::{bail, Context, Result}; + use anyhow::{Context, Result, bail}; use futures::future::{BoxFuture, FutureExt}; use libp2p::{ + Transport as _, core::upgrade::Version, identity::Keypair, noise, swarm::{NetworkBehaviour, Swarm}, - websocket_websys, webtransport_websys, yamux, Transport as _, + websocket_websys, webtransport_websys, yamux, }; use libp2p_mplex as mplex; use libp2p_webrtc_websys as webrtc_websys; diff --git a/interop-tests/src/bin/wasm_ping.rs b/interop-tests/src/bin/wasm_ping.rs index 7730b869456..502d2f31e36 100644 --- a/interop-tests/src/bin/wasm_ping.rs +++ b/interop-tests/src/bin/wasm_ping.rs @@ -2,13 +2,13 @@ use std::{future::IntoFuture, process::Stdio, time::Duration}; -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use axum::{ + Json, Router, extract::State, - http::{header, StatusCode, Uri}, + http::{StatusCode, Uri, header}, response::{Html, IntoResponse, Response}, routing::{get, post}, - Json, Router, }; use interop_tests::{BlpopRequest, Report}; use redis::{AsyncCommands, Client}; @@ -20,7 +20,7 @@ use tokio::{ sync::mpsc, }; use tower_http::{cors::CorsLayer, trace::TraceLayer}; -use tracing_subscriber::{fmt, prelude::*, EnvFilter}; +use tracing_subscriber::{EnvFilter, fmt, prelude::*}; mod config; diff --git a/interop-tests/src/lib.rs b/interop-tests/src/lib.rs index a16dc4b8228..d5fcad5f53a 100644 --- a/interop-tests/src/lib.rs +++ b/interop-tests/src/lib.rs @@ -1,20 +1,19 @@ use std::{str::FromStr, time::Duration}; -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use futures::{FutureExt, StreamExt}; use libp2p::{ - identify, + Multiaddr, identify, identity::Keypair, ping, swarm::{NetworkBehaviour, SwarmEvent}, - Multiaddr, }; #[cfg(target_arch = "wasm32")] use wasm_bindgen::prelude::*; mod arch; -use arch::{build_swarm, init_logger, Instant, RedisClient}; +use arch::{Instant, RedisClient, build_swarm, init_logger}; pub async fn run_test( transport: &str, diff --git a/libp2p/src/bandwidth.rs b/libp2p/src/bandwidth.rs index ac668e26b3f..08391551ea7 100644 --- a/libp2p/src/bandwidth.rs +++ b/libp2p/src/bandwidth.rs @@ -25,8 +25,8 @@ use std::{ io, pin::Pin, sync::{ - atomic::{AtomicU64, Ordering}, Arc, + atomic::{AtomicU64, Ordering}, }, task::{Context, Poll}, }; diff --git a/libp2p/src/builder/phase.rs b/libp2p/src/builder/phase.rs index f8f1672f952..f48d3b959db 100644 --- a/libp2p/src/builder/phase.rs +++ b/libp2p/src/builder/phase.rs @@ -20,7 +20,7 @@ pub use behaviour::BehaviourError; use behaviour::*; use build::*; use dns::*; -use libp2p_core::{muxing::StreamMuxerBox, Transport}; +use libp2p_core::{Transport, muxing::StreamMuxerBox}; use libp2p_identity::Keypair; pub use other_transport::TransportError; use other_transport::*; @@ -34,7 +34,7 @@ pub use websocket::WebsocketError; use websocket::*; use super::{ - select_muxer::SelectMuxerUpgrade, select_security::SelectSecurityUpgrade, SwarmBuilder, + SwarmBuilder, select_muxer::SelectMuxerUpgrade, select_security::SelectSecurityUpgrade, }; #[allow(unreachable_pub)] diff --git a/libp2p/src/builder/phase/bandwidth_logging.rs b/libp2p/src/builder/phase/bandwidth_logging.rs index f24df5f3df5..80f3a028fbf 100644 --- a/libp2p/src/builder/phase/bandwidth_logging.rs +++ b/libp2p/src/builder/phase/bandwidth_logging.rs @@ -3,7 +3,7 @@ use std::{marker::PhantomData, sync::Arc}; use super::*; #[allow(deprecated)] use crate::bandwidth::BandwidthSinks; -use crate::{transport_ext::TransportExt, SwarmBuilder}; +use crate::{SwarmBuilder, transport_ext::TransportExt}; pub struct BandwidthLoggingPhase { pub(crate) relay_behaviour: R, diff --git a/libp2p/src/builder/phase/bandwidth_metrics.rs b/libp2p/src/builder/phase/bandwidth_metrics.rs index ddd292c140e..de4cf11a287 100644 --- a/libp2p/src/builder/phase/bandwidth_metrics.rs +++ b/libp2p/src/builder/phase/bandwidth_metrics.rs @@ -3,7 +3,7 @@ use std::{marker::PhantomData, sync::Arc}; use super::*; #[allow(deprecated)] use crate::bandwidth::BandwidthSinks; -use crate::{transport_ext::TransportExt, SwarmBuilder}; +use crate::{SwarmBuilder, transport_ext::TransportExt}; pub struct BandwidthMetricsPhase { pub(crate) relay_behaviour: R, diff --git a/libp2p/src/builder/phase/build.rs b/libp2p/src/builder/phase/build.rs index d3138cb8b8d..8708f85a2bf 100644 --- a/libp2p/src/builder/phase/build.rs +++ b/libp2p/src/builder/phase/build.rs @@ -1,6 +1,6 @@ use std::time::Duration; -use libp2p_core::{transport::timeout::TransportTimeout, Transport}; +use libp2p_core::{Transport, transport::timeout::TransportTimeout}; use libp2p_swarm::Swarm; #[allow(unused_imports)] diff --git a/libp2p/src/builder/phase/other_transport.rs b/libp2p/src/builder/phase/other_transport.rs index c3b951c8c75..7abd9dfae4b 100644 --- a/libp2p/src/builder/phase/other_transport.rs +++ b/libp2p/src/builder/phase/other_transport.rs @@ -1,18 +1,18 @@ use std::{convert::Infallible, marker::PhantomData, sync::Arc}; +#[cfg(feature = "relay")] +use libp2p_core::{Negotiated, UpgradeInfo}; use libp2p_core::{ - upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}, Transport, + upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}, }; #[cfg(feature = "relay")] -use libp2p_core::{Negotiated, UpgradeInfo}; -#[cfg(feature = "relay")] use libp2p_identity::PeerId; use super::*; +use crate::SwarmBuilder; #[allow(deprecated)] use crate::bandwidth::BandwidthSinks; -use crate::SwarmBuilder; pub struct OtherTransportPhase { pub(crate) transport: T, diff --git a/libp2p/src/builder/phase/relay.rs b/libp2p/src/builder/phase/relay.rs index 33dbf1fb54c..59f87444a05 100644 --- a/libp2p/src/builder/phase/relay.rs +++ b/libp2p/src/builder/phase/relay.rs @@ -1,10 +1,10 @@ use std::marker::PhantomData; +#[cfg(feature = "relay")] +use libp2p_core::Transport; #[cfg(feature = "relay")] use libp2p_core::muxing::StreamMuxerBox; use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}; -#[cfg(feature = "relay")] -use libp2p_core::Transport; #[cfg(any(feature = "relay", feature = "websocket"))] use libp2p_core::{InboundUpgrade, Negotiated, OutboundUpgrade, StreamMuxer, UpgradeInfo}; #[cfg(feature = "relay")] diff --git a/libp2p/src/builder/phase/tcp.rs b/libp2p/src/builder/phase/tcp.rs index f38f52441e5..fd5ee0c7f39 100644 --- a/libp2p/src/builder/phase/tcp.rs +++ b/libp2p/src/builder/phase/tcp.rs @@ -1,18 +1,18 @@ use std::marker::PhantomData; +#[cfg(all(feature = "websocket", not(target_arch = "wasm32")))] +use libp2p_core::Transport; #[cfg(all( not(target_arch = "wasm32"), any(feature = "tcp", feature = "websocket") ))] use libp2p_core::muxing::{StreamMuxer, StreamMuxerBox}; -#[cfg(all(feature = "websocket", not(target_arch = "wasm32")))] -use libp2p_core::Transport; #[cfg(all( not(target_arch = "wasm32"), any(feature = "tcp", feature = "websocket") ))] use libp2p_core::{ - upgrade::InboundConnectionUpgrade, upgrade::OutboundConnectionUpgrade, Negotiated, UpgradeInfo, + Negotiated, UpgradeInfo, upgrade::InboundConnectionUpgrade, upgrade::OutboundConnectionUpgrade, }; use super::*; diff --git a/libp2p/src/builder/phase/websocket.rs b/libp2p/src/builder/phase/websocket.rs index bb9c0da7fff..af0635f2ef6 100644 --- a/libp2p/src/builder/phase/websocket.rs +++ b/libp2p/src/builder/phase/websocket.rs @@ -1,10 +1,10 @@ use std::marker::PhantomData; +#[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))] +use libp2p_core::Transport; #[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))] use libp2p_core::muxing::{StreamMuxer, StreamMuxerBox}; use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}; -#[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))] -use libp2p_core::Transport; #[cfg(any( all(not(target_arch = "wasm32"), feature = "websocket"), feature = "relay" diff --git a/libp2p/src/builder/select_muxer.rs b/libp2p/src/builder/select_muxer.rs index 93ae0547269..0c3aed8b9d6 100644 --- a/libp2p/src/builder/select_muxer.rs +++ b/libp2p/src/builder/select_muxer.rs @@ -25,9 +25,9 @@ use std::iter::{Chain, Map}; use either::Either; use futures::future; use libp2p_core::{ + UpgradeInfo, either::EitherFuture, upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}, - UpgradeInfo, }; #[derive(Debug, Clone)] diff --git a/libp2p/src/builder/select_security.rs b/libp2p/src/builder/select_security.rs index 1ed760feb1b..297491313d9 100644 --- a/libp2p/src/builder/select_security.rs +++ b/libp2p/src/builder/select_security.rs @@ -24,7 +24,7 @@ use std::iter::{Chain, Map}; use either::Either; -use futures::{future, future::MapOk, TryFutureExt}; +use futures::{TryFutureExt, future, future::MapOk}; use libp2p_core::{ either::EitherFuture, upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade, UpgradeInfo}, diff --git a/libp2p/src/lib.rs b/libp2p/src/lib.rs index 1814bb4fcbb..aab268a0487 100644 --- a/libp2p/src/lib.rs +++ b/libp2p/src/lib.rs @@ -166,11 +166,11 @@ pub use self::{ TransportError as TransportBuilderError, }, core::{ + Transport, transport::TransportError, upgrade::{InboundUpgrade, OutboundUpgrade}, - Transport, }, - multiaddr::{multiaddr as build_multiaddr, Multiaddr}, + multiaddr::{Multiaddr, multiaddr as build_multiaddr}, swarm::Swarm, transport_ext::TransportExt, }; diff --git a/libp2p/src/transport_ext.rs b/libp2p/src/transport_ext.rs index 0ed5b816903..e13c2630c94 100644 --- a/libp2p/src/transport_ext.rs +++ b/libp2p/src/transport_ext.rs @@ -27,11 +27,11 @@ use libp2p_identity::PeerId; #[allow(deprecated)] use crate::bandwidth::{BandwidthLogging, BandwidthSinks}; use crate::{ + Transport, core::{ muxing::{StreamMuxer, StreamMuxerBox}, transport::Boxed, }, - Transport, }; /// Trait automatically implemented on all objects that implement `Transport`. Provides some @@ -46,7 +46,7 @@ pub trait TransportExt: Transport { /// # Example /// /// ``` - /// use libp2p::{core::upgrade, identity, Transport, TransportExt}; + /// use libp2p::{Transport, TransportExt, core::upgrade, identity}; /// use libp2p_noise as noise; /// use libp2p_tcp as tcp; /// use libp2p_yamux as yamux; diff --git a/libp2p/src/tutorials/ping.rs b/libp2p/src/tutorials/ping.rs index 41f1f54b6c2..e039a438094 100644 --- a/libp2p/src/tutorials/ping.rs +++ b/libp2p/src/tutorials/ping.rs @@ -52,7 +52,7 @@ //! [package] //! name = "rust-libp2p-tutorial" //! version = "0.1.0" -//! edition = "2021" +//! edition = "2024" //! //! [dependencies] //! libp2p = { version = "0.54", features = ["noise", "ping", "tcp", "tokio", "yamux"] } @@ -270,7 +270,7 @@ //! ```rust //! use std::{error::Error, time::Duration}; //! -//! use libp2p::{noise, ping, tcp, yamux, Multiaddr}; +//! use libp2p::{Multiaddr, noise, ping, tcp, yamux}; //! use tracing_subscriber::EnvFilter; //! //! #[tokio::main] @@ -318,7 +318,7 @@ //! use std::{error::Error, time::Duration}; //! //! use futures::prelude::*; -//! use libp2p::{noise, ping, swarm::SwarmEvent, tcp, yamux, Multiaddr}; +//! use libp2p::{Multiaddr, noise, ping, swarm::SwarmEvent, tcp, yamux}; //! use tracing_subscriber::EnvFilter; //! //! #[tokio::main] diff --git a/misc/allow-block-list/src/lib.rs b/misc/allow-block-list/src/lib.rs index 5e177e69c47..3bf1b010de8 100644 --- a/misc/allow-block-list/src/lib.rs +++ b/misc/allow-block-list/src/lib.rs @@ -68,11 +68,11 @@ use std::{ task::{Context, Poll, Waker}, }; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ - dummy, CloseConnection, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, - THandlerInEvent, THandlerOutEvent, ToSwarm, + CloseConnection, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, + THandlerInEvent, THandlerOutEvent, ToSwarm, dummy, }; /// A [`NetworkBehaviour`] that can act as an allow or block list. @@ -298,7 +298,7 @@ where #[cfg(test)] mod tests { - use libp2p_swarm::{dial_opts::DialOpts, DialError, ListenError, Swarm, SwarmEvent}; + use libp2p_swarm::{DialError, ListenError, Swarm, SwarmEvent, dial_opts::DialOpts}; use libp2p_swarm_test::SwarmExt; use super::*; @@ -363,14 +363,18 @@ mod tests { dialer.behaviour_mut().block_peer(*listener.local_peer_id()); let ( - [SwarmEvent::ConnectionClosed { - peer_id: closed_dialer_peer, - .. - }], - [SwarmEvent::ConnectionClosed { - peer_id: closed_listener_peer, - .. - }], + [ + SwarmEvent::ConnectionClosed { + peer_id: closed_dialer_peer, + .. + }, + ], + [ + SwarmEvent::ConnectionClosed { + peer_id: closed_listener_peer, + .. + }, + ], ) = libp2p_swarm_test::drive(&mut dialer, &mut listener).await else { panic!("unexpected events") @@ -426,20 +430,25 @@ mod tests { .unwrap(); let ( - [SwarmEvent::OutgoingConnectionError { - error: - DialError::Denied { - cause: outgoing_cause, - }, - .. - }], - [_, SwarmEvent::IncomingConnectionError { - error: - ListenError::Denied { - cause: incoming_cause, - }, - .. - }], + [ + SwarmEvent::OutgoingConnectionError { + error: + DialError::Denied { + cause: outgoing_cause, + }, + .. + }, + ], + [ + _, + SwarmEvent::IncomingConnectionError { + error: + ListenError::Denied { + cause: incoming_cause, + }, + .. + }, + ], ) = libp2p_swarm_test::drive(&mut dialer, &mut listener).await else { panic!("unexpected events") @@ -462,14 +471,18 @@ mod tests { .behaviour_mut() .disallow_peer(*listener.local_peer_id()); let ( - [SwarmEvent::ConnectionClosed { - peer_id: closed_dialer_peer, - .. - }], - [SwarmEvent::ConnectionClosed { - peer_id: closed_listener_peer, - .. - }], + [ + SwarmEvent::ConnectionClosed { + peer_id: closed_dialer_peer, + .. + }, + ], + [ + SwarmEvent::ConnectionClosed { + peer_id: closed_listener_peer, + .. + }, + ], ) = libp2p_swarm_test::drive(&mut dialer, &mut listener).await else { panic!("unexpected events") diff --git a/misc/connection-limits/src/lib.rs b/misc/connection-limits/src/lib.rs index b0666c705cb..414be7809fb 100644 --- a/misc/connection-limits/src/lib.rs +++ b/misc/connection-limits/src/lib.rs @@ -25,12 +25,13 @@ use std::{ task::{Context, Poll}, }; -use libp2p_core::{transport::PortUse, ConnectedPoint, Endpoint, Multiaddr}; +use libp2p_core::{ConnectedPoint, Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ - behaviour::{ConnectionEstablished, DialFailure, ListenFailure}, - dummy, ConnectionClosed, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, + ConnectionClosed, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + behaviour::{ConnectionEstablished, DialFailure, ListenFailure}, + dummy, }; /// A [`NetworkBehaviour`] that enforces a set of [`ConnectionLimits`]. @@ -401,9 +402,9 @@ impl NetworkBehaviour for Behaviour { #[cfg(test)] mod tests { use libp2p_swarm::{ + DialError, ListenError, Swarm, SwarmEvent, behaviour::toggle::Toggle, dial_opts::{DialOpts, PeerCondition}, - DialError, ListenError, Swarm, SwarmEvent, }; use libp2p_swarm_test::SwarmExt; use quickcheck::*; diff --git a/misc/keygen/src/main.rs b/misc/keygen/src/main.rs index 9f258be56d4..69bf12d983b 100644 --- a/misc/keygen/src/main.rs +++ b/misc/keygen/src/main.rs @@ -63,10 +63,10 @@ fn main() -> Result<(), Box> { let peer_id = keypair.public().into(); assert_eq!( - PeerId::from_str(&config.identity.peer_id)?, - peer_id, - "Expect peer id derived from private key and peer id retrieved from config to match." - ); + PeerId::from_str(&config.identity.peer_id)?, + peer_id, + "Expect peer id derived from private key and peer id retrieved from config to match." + ); (peer_id, keypair) } @@ -96,12 +96,14 @@ fn main() -> Result<(), Box> { let prefix = prefix.clone(); let tx = tx.clone(); - thread::spawn(move || loop { - let keypair = identity::Keypair::generate_ed25519(); - let peer_id = keypair.public().to_peer_id(); - let base58 = peer_id.to_base58(); - if base58[8..].starts_with(&prefix) { - tx.send((peer_id, keypair)).expect("to send"); + thread::spawn(move || { + loop { + let keypair = identity::Keypair::generate_ed25519(); + let peer_id = keypair.public().to_peer_id(); + let base58 = peer_id.to_base58(); + if base58[8..].starts_with(&prefix) { + tx.send((peer_id, keypair)).expect("to send"); + } } }); } diff --git a/misc/memory-connection-limits/src/lib.rs b/misc/memory-connection-limits/src/lib.rs index 7905e39ac18..0ef52394cb0 100644 --- a/misc/memory-connection-limits/src/lib.rs +++ b/misc/memory-connection-limits/src/lib.rs @@ -25,11 +25,11 @@ use std::{ time::{Duration, Instant}, }; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ - dummy, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, THandlerInEvent, - THandlerOutEvent, ToSwarm, + ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, THandlerInEvent, + THandlerOutEvent, ToSwarm, dummy, }; use sysinfo::MemoryRefreshKind; @@ -228,8 +228,7 @@ impl fmt::Display for MemoryUsageLimitExceeded { write!( f, "process physical memory usage limit exceeded: process memory: {} bytes, max allowed: {} bytes", - self.process_physical_memory_bytes, - self.max_allowed_bytes, + self.process_physical_memory_bytes, self.max_allowed_bytes, ) } } diff --git a/misc/memory-connection-limits/tests/max_bytes.rs b/misc/memory-connection-limits/tests/max_bytes.rs index e82ad67d076..e1d5c68225e 100644 --- a/misc/memory-connection-limits/tests/max_bytes.rs +++ b/misc/memory-connection-limits/tests/max_bytes.rs @@ -25,7 +25,7 @@ use std::time::Duration; use libp2p_core::Multiaddr; use libp2p_identity::PeerId; use libp2p_memory_connection_limits::*; -use libp2p_swarm::{dial_opts::DialOpts, DialError, Swarm}; +use libp2p_swarm::{DialError, Swarm, dial_opts::DialOpts}; use libp2p_swarm_test::SwarmExt; use util::*; @@ -70,7 +70,7 @@ fn max_bytes() { } std::thread::sleep(Duration::from_millis(100)); // Memory stats are only updated every 100ms internally, ensure they are up-to-date when we try - // to exceed it. + // to exceed it. match network .dial( diff --git a/misc/memory-connection-limits/tests/max_percentage.rs b/misc/memory-connection-limits/tests/max_percentage.rs index bdadad437b8..16d13d28767 100644 --- a/misc/memory-connection-limits/tests/max_percentage.rs +++ b/misc/memory-connection-limits/tests/max_percentage.rs @@ -26,8 +26,8 @@ use libp2p_core::Multiaddr; use libp2p_identity::PeerId; use libp2p_memory_connection_limits::*; use libp2p_swarm::{ - dial_opts::{DialOpts, PeerCondition}, DialError, Swarm, + dial_opts::{DialOpts, PeerCondition}, }; use libp2p_swarm_test::SwarmExt; use sysinfo::{MemoryRefreshKind, RefreshKind}; diff --git a/misc/memory-connection-limits/tests/util/mod.rs b/misc/memory-connection-limits/tests/util/mod.rs index b73352334da..949daadcb60 100644 --- a/misc/memory-connection-limits/tests/util/mod.rs +++ b/misc/memory-connection-limits/tests/util/mod.rs @@ -23,11 +23,11 @@ use std::{ task::{Context, Poll}, }; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ - dummy, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, THandlerInEvent, - THandlerOutEvent, ToSwarm, + ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, THandlerInEvent, + THandlerOutEvent, ToSwarm, dummy, }; #[derive(libp2p_swarm_derive::NetworkBehaviour)] diff --git a/misc/metrics/src/bandwidth.rs b/misc/metrics/src/bandwidth.rs index b6308ed1b51..edbfaf4b60f 100644 --- a/misc/metrics/src/bandwidth.rs +++ b/misc/metrics/src/bandwidth.rs @@ -12,9 +12,9 @@ use futures::{ ready, }; use libp2p_core::{ + Multiaddr, muxing::{StreamMuxer, StreamMuxerEvent}, transport::{DialOpts, ListenerId, TransportError, TransportEvent}, - Multiaddr, }; use libp2p_identity::PeerId; use prometheus_client::{ diff --git a/misc/metrics/src/identify.rs b/misc/metrics/src/identify.rs index b16c6a56ccf..103df4097cf 100644 --- a/misc/metrics/src/identify.rs +++ b/misc/metrics/src/identify.rs @@ -28,7 +28,7 @@ use libp2p_swarm::StreamProtocol; use prometheus_client::{ collector::Collector, encoding::{DescriptorEncoder, EncodeMetric}, - metrics::{counter::Counter, gauge::ConstGauge, MetricType}, + metrics::{MetricType, counter::Counter, gauge::ConstGauge}, registry::Registry, }; diff --git a/misc/metrics/src/kad.rs b/misc/metrics/src/kad.rs index 0a2a8038511..30f9e9e9e49 100644 --- a/misc/metrics/src/kad.rs +++ b/misc/metrics/src/kad.rs @@ -23,7 +23,7 @@ use prometheus_client::{ metrics::{ counter::Counter, family::Family, - histogram::{exponential_buckets, Histogram}, + histogram::{Histogram, exponential_buckets}, }, registry::{Registry, Unit}, }; diff --git a/misc/metrics/src/ping.rs b/misc/metrics/src/ping.rs index ce653c72ea1..6c87049f57e 100644 --- a/misc/metrics/src/ping.rs +++ b/misc/metrics/src/ping.rs @@ -23,7 +23,7 @@ use prometheus_client::{ metrics::{ counter::Counter, family::Family, - histogram::{exponential_buckets, Histogram}, + histogram::{Histogram, exponential_buckets}, }, registry::{Registry, Unit}, }; diff --git a/misc/metrics/src/swarm.rs b/misc/metrics/src/swarm.rs index 6e95d082de6..c036f089029 100644 --- a/misc/metrics/src/swarm.rs +++ b/misc/metrics/src/swarm.rs @@ -29,7 +29,7 @@ use prometheus_client::{ metrics::{ counter::Counter, family::Family, - histogram::{exponential_buckets, Histogram}, + histogram::{Histogram, exponential_buckets}, }, registry::{Registry, Unit}, }; diff --git a/misc/multistream-select/src/dialer_select.rs b/misc/multistream-select/src/dialer_select.rs index 1d13e94910d..b23e370ad97 100644 --- a/misc/multistream-select/src/dialer_select.rs +++ b/misc/multistream-select/src/dialer_select.rs @@ -30,8 +30,8 @@ use std::{ use futures::prelude::*; use crate::{ - protocol::{HeaderLine, Message, MessageIO, Protocol, ProtocolError}, Negotiated, NegotiationError, Version, + protocol::{HeaderLine, Message, MessageIO, Protocol, ProtocolError}, }; /// Returns a `Future` that negotiates a protocol on the given I/O stream diff --git a/misc/multistream-select/src/length_delimited.rs b/misc/multistream-select/src/length_delimited.rs index 8062455de46..f4fe76ebed3 100644 --- a/misc/multistream-select/src/length_delimited.rs +++ b/misc/multistream-select/src/length_delimited.rs @@ -128,7 +128,7 @@ impl LengthDelimited { return Poll::Ready(Err(io::Error::new( io::ErrorKind::WriteZero, "Failed to write buffered frame.", - ))) + ))); } Poll::Ready(Ok(n)) => this.write_buffer.advance(n), Poll::Ready(Err(err)) => return Poll::Ready(Err(err)), @@ -198,7 +198,7 @@ where .poll_read(cx, &mut this.read_buffer[*pos..]) { Poll::Ready(Ok(0)) => { - return Poll::Ready(Some(Err(io::ErrorKind::UnexpectedEof.into()))) + return Poll::Ready(Some(Err(io::ErrorKind::UnexpectedEof.into()))); } Poll::Ready(Ok(n)) => *pos += n, Poll::Pending => return Poll::Pending, @@ -249,7 +249,7 @@ where return Err(io::Error::new( io::ErrorKind::InvalidData, "Maximum frame size exceeded.", - )) + )); } }; diff --git a/misc/multistream-select/src/lib.rs b/misc/multistream-select/src/lib.rs index 96432de6cb0..6ed100fb4a7 100644 --- a/misc/multistream-select/src/lib.rs +++ b/misc/multistream-select/src/lib.rs @@ -71,7 +71,7 @@ //! ```no_run //! use async_std::net::TcpStream; //! use futures::prelude::*; -//! use multistream_select::{dialer_select_proto, Version}; +//! use multistream_select::{Version, dialer_select_proto}; //! //! async_std::task::block_on(async move { //! let socket = TcpStream::connect("127.0.0.1:10333").await.unwrap(); @@ -95,8 +95,8 @@ mod negotiated; mod protocol; pub use self::{ - dialer_select::{dialer_select_proto, DialerSelectFuture}, - listener_select::{listener_select_proto, ListenerSelectFuture}, + dialer_select::{DialerSelectFuture, dialer_select_proto}, + listener_select::{ListenerSelectFuture, listener_select_proto}, negotiated::{Negotiated, NegotiatedComplete, NegotiationError}, protocol::ProtocolError, }; diff --git a/misc/multistream-select/src/listener_select.rs b/misc/multistream-select/src/listener_select.rs index cd5af72a9d0..7acd08ab09b 100644 --- a/misc/multistream-select/src/listener_select.rs +++ b/misc/multistream-select/src/listener_select.rs @@ -32,8 +32,8 @@ use futures::prelude::*; use smallvec::SmallVec; use crate::{ - protocol::{HeaderLine, Message, MessageIO, Protocol, ProtocolError}, Negotiated, NegotiationError, + protocol::{HeaderLine, Message, MessageIO, Protocol, ProtocolError}, }; /// Returns a `Future` that negotiates a protocol on the given I/O stream @@ -132,7 +132,7 @@ where *this.state = State::SendHeader { io } } Poll::Ready(Some(Ok(_))) => { - return Poll::Ready(Err(ProtocolError::InvalidMessage.into())) + return Poll::Ready(Err(ProtocolError::InvalidMessage.into())); } Poll::Ready(Some(Err(err))) => return Poll::Ready(Err(From::from(err))), // Treat EOF error as [`NegotiationError::Failed`], not as diff --git a/misc/multistream-select/src/negotiated.rs b/misc/multistream-select/src/negotiated.rs index 6693b3b5636..120cc4189da 100644 --- a/misc/multistream-select/src/negotiated.rs +++ b/misc/multistream-select/src/negotiated.rs @@ -309,10 +309,11 @@ where fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { // Ensure all data has been flushed, including optimistic multistream-select messages. - ready!(self - .as_mut() - .poll_flush(cx) - .map_err(Into::::into)?); + ready!( + self.as_mut() + .poll_flush(cx) + .map_err(Into::::into)? + ); // Continue with the shutdown of the underlying I/O stream. match self.project().state.project() { @@ -320,7 +321,9 @@ where StateProj::Expecting { io, .. } => { let close_poll = io.poll_close(cx); if let Poll::Ready(Ok(())) = close_poll { - tracing::debug!("Stream closed. Confirmation from remote for optimstic protocol negotiation still pending") + tracing::debug!( + "Stream closed. Confirmation from remote for optimstic protocol negotiation still pending" + ) } close_poll } diff --git a/misc/multistream-select/src/protocol.rs b/misc/multistream-select/src/protocol.rs index 9b015c3c502..a06755f8d04 100644 --- a/misc/multistream-select/src/protocol.rs +++ b/misc/multistream-select/src/protocol.rs @@ -37,8 +37,8 @@ use futures::{io::IoSlice, prelude::*, ready}; use unsigned_varint as uvi; use crate::{ - length_delimited::{LengthDelimited, LengthDelimitedReader}, Version, + length_delimited::{LengthDelimited, LengthDelimitedReader}, }; /// The maximum number of supported protocols that can be processed. diff --git a/misc/quick-protobuf-codec/benches/codec.rs b/misc/quick-protobuf-codec/benches/codec.rs index 0f6ce9469c5..e26b01582ea 100644 --- a/misc/quick-protobuf-codec/benches/codec.rs +++ b/misc/quick-protobuf-codec/benches/codec.rs @@ -1,7 +1,7 @@ use asynchronous_codec::Encoder; use bytes::BytesMut; -use criterion::{criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion}; -use quick_protobuf_codec::{proto, Codec}; +use criterion::{BatchSize, BenchmarkId, Criterion, criterion_group, criterion_main}; +use quick_protobuf_codec::{Codec, proto}; pub fn benchmark(c: &mut Criterion) { for size in [1000, 10_000, 100_000, 1_000_000, 10_000_000] { diff --git a/misc/quick-protobuf-codec/src/lib.rs b/misc/quick-protobuf-codec/src/lib.rs index 28b53946899..c3ca588ea74 100644 --- a/misc/quick-protobuf-codec/src/lib.rs +++ b/misc/quick-protobuf-codec/src/lib.rs @@ -185,7 +185,7 @@ mod tests { use std::error::Error; use asynchronous_codec::FramedRead; - use futures::{io::Cursor, FutureExt, StreamExt}; + use futures::{FutureExt, StreamExt, io::Cursor}; use quickcheck::{Arbitrary, Gen, QuickCheck}; use super::*; diff --git a/misc/quick-protobuf-codec/tests/large_message.rs b/misc/quick-protobuf-codec/tests/large_message.rs index a434d3ce17f..c3d25897ee6 100644 --- a/misc/quick-protobuf-codec/tests/large_message.rs +++ b/misc/quick-protobuf-codec/tests/large_message.rs @@ -1,6 +1,6 @@ use asynchronous_codec::Encoder; use bytes::BytesMut; -use quick_protobuf_codec::{proto, Codec}; +use quick_protobuf_codec::{Codec, proto}; #[test] fn encode_large_message() { diff --git a/misc/rw-stream-sink/src/lib.rs b/misc/rw-stream-sink/src/lib.rs index 5fdf1987252..9b35351df54 100644 --- a/misc/rw-stream-sink/src/lib.rs +++ b/misc/rw-stream-sink/src/lib.rs @@ -71,7 +71,7 @@ where // Grab the item to copy from. let item_to_copy = loop { - if let Some(ref mut i) = this.current_item { + if let Some(i) = this.current_item { if i.position() < i.get_ref().as_ref().len() as u64 { break i; } diff --git a/misc/server/src/behaviour.rs b/misc/server/src/behaviour.rs index 230d62a2ef3..5ffe4fe4517 100644 --- a/misc/server/src/behaviour.rs +++ b/misc/server/src/behaviour.rs @@ -1,9 +1,8 @@ use std::{str::FromStr, time::Duration}; use libp2p::{ - autonat, identify, identity, kad, ping, relay, - swarm::{behaviour::toggle::Toggle, NetworkBehaviour, StreamProtocol}, - Multiaddr, PeerId, + Multiaddr, PeerId, autonat, identify, identity, kad, ping, relay, + swarm::{NetworkBehaviour, StreamProtocol, behaviour::toggle::Toggle}, }; const BOOTNODES: [&str; 4] = [ diff --git a/misc/server/src/http_service.rs b/misc/server/src/http_service.rs index 87a8adb94e0..126275b489e 100644 --- a/misc/server/src/http_service.rs +++ b/misc/server/src/http_service.rs @@ -23,7 +23,7 @@ use std::{ sync::{Arc, Mutex}, }; -use axum::{extract::State, http::StatusCode, response::IntoResponse, routing::get, Router}; +use axum::{Router, extract::State, http::StatusCode, response::IntoResponse, routing::get}; use prometheus_client::{encoding::text::encode, registry::Registry}; use tokio::net::TcpListener; diff --git a/misc/webrtc-utils/src/lib.rs b/misc/webrtc-utils/src/lib.rs index c744634de30..060e69a299e 100644 --- a/misc/webrtc-utils/src/lib.rs +++ b/misc/webrtc-utils/src/lib.rs @@ -1,7 +1,7 @@ mod proto { #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub use self::webrtc::pb::{mod_Message::Flag, Message}; + pub use self::webrtc::pb::{Message, mod_Message::Flag}; } mod fingerprint; @@ -11,5 +11,5 @@ mod stream; mod transport; pub use fingerprint::{Fingerprint, SHA256}; -pub use stream::{DropListener, Stream, MAX_MSG_LEN}; +pub use stream::{DropListener, MAX_MSG_LEN, Stream}; pub use transport::parse_webrtc_dial_addr; diff --git a/misc/webrtc-utils/src/noise.rs b/misc/webrtc-utils/src/noise.rs index 705db7f4697..bcb5102120f 100644 --- a/misc/webrtc-utils/src/noise.rs +++ b/misc/webrtc-utils/src/noise.rs @@ -20,8 +20,8 @@ use futures::{AsyncRead, AsyncWrite, AsyncWriteExt}; use libp2p_core::{ - upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}, UpgradeInfo, + upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}, }; use libp2p_identity as identity; use libp2p_identity::PeerId; @@ -106,7 +106,13 @@ mod tests { let prologue1 = noise_prologue(a, b); let prologue2 = noise_prologue(b, a); - assert_eq!(hex::encode(prologue1), "6c69627032702d7765627274632d6e6f6973653a12203e79af40d6059617a0d83b83a52ce73b0c1f37a72c6043ad2969e2351bdca870122030fc9f469c207419dfdd0aab5f27a86c973c94e40548db9375cca2e915973b99"); - assert_eq!(hex::encode(prologue2), "6c69627032702d7765627274632d6e6f6973653a122030fc9f469c207419dfdd0aab5f27a86c973c94e40548db9375cca2e915973b9912203e79af40d6059617a0d83b83a52ce73b0c1f37a72c6043ad2969e2351bdca870"); + assert_eq!( + hex::encode(prologue1), + "6c69627032702d7765627274632d6e6f6973653a12203e79af40d6059617a0d83b83a52ce73b0c1f37a72c6043ad2969e2351bdca870122030fc9f469c207419dfdd0aab5f27a86c973c94e40548db9375cca2e915973b99" + ); + assert_eq!( + hex::encode(prologue2), + "6c69627032702d7765627274632d6e6f6973653a122030fc9f469c207419dfdd0aab5f27a86c973c94e40548db9375cca2e915973b9912203e79af40d6059617a0d83b83a52ce73b0c1f37a72c6043ad2969e2351bdca870" + ); } } diff --git a/misc/webrtc-utils/src/sdp.rs b/misc/webrtc-utils/src/sdp.rs index 96a07f5db95..2be0ed76f29 100644 --- a/misc/webrtc-utils/src/sdp.rs +++ b/misc/webrtc-utils/src/sdp.rs @@ -20,7 +20,7 @@ // DEALINGS IN THE SOFTWARE. use std::net::{IpAddr, SocketAddr}; -use rand::{distributions::Alphanumeric, thread_rng, Rng}; +use rand::{Rng, distributions::Alphanumeric, thread_rng}; use serde::Serialize; use tinytemplate::TinyTemplate; diff --git a/misc/webrtc-utils/src/stream/drop_listener.rs b/misc/webrtc-utils/src/stream/drop_listener.rs index ea3f19d2f57..def6757b298 100644 --- a/misc/webrtc-utils/src/stream/drop_listener.rs +++ b/misc/webrtc-utils/src/stream/drop_listener.rs @@ -26,8 +26,8 @@ use std::{ }; use futures::{ - channel::{oneshot, oneshot::Canceled}, AsyncRead, AsyncWrite, FutureExt, SinkExt, + channel::{oneshot, oneshot::Canceled}, }; use crate::{ diff --git a/misc/webrtc-utils/src/stream/state.rs b/misc/webrtc-utils/src/stream/state.rs index 006c1610d00..fa0c2b59b01 100644 --- a/misc/webrtc-utils/src/stream/state.rs +++ b/misc/webrtc-utils/src/stream/state.rs @@ -257,7 +257,7 @@ impl State { write_closed: true, .. } | State::BothClosed { reset: false } => { - return Err(io::ErrorKind::BrokenPipe.into()) + return Err(io::ErrorKind::BrokenPipe.into()); } State::ClosingRead { @@ -267,11 +267,11 @@ impl State { return Err(io::Error::new( io::ErrorKind::Other, "cannot close read half while closing write half", - )) + )); } State::BothClosed { reset: true } => { - return Err(io::ErrorKind::ConnectionReset.into()) + return Err(io::ErrorKind::ConnectionReset.into()); } } } @@ -302,7 +302,7 @@ impl State { read_closed: true, .. } | State::BothClosed { reset: false } => { - return Err(io::ErrorKind::BrokenPipe.into()) + return Err(io::ErrorKind::BrokenPipe.into()); } State::ClosingWrite { @@ -311,11 +311,11 @@ impl State { return Err(io::Error::new( io::ErrorKind::Other, "cannot close write half while closing read half", - )) + )); } State::BothClosed { reset: true } => { - return Err(io::ErrorKind::ConnectionReset.into()) + return Err(io::ErrorKind::ConnectionReset.into()); } } } diff --git a/misc/webrtc-utils/src/transport.rs b/misc/webrtc-utils/src/transport.rs index 60b1934082f..6fc4429e4be 100644 --- a/misc/webrtc-utils/src/transport.rs +++ b/misc/webrtc-utils/src/transport.rs @@ -1,6 +1,6 @@ use std::net::{IpAddr, SocketAddr}; -use libp2p_core::{multiaddr::Protocol, Multiaddr}; +use libp2p_core::{Multiaddr, multiaddr::Protocol}; use crate::fingerprint::Fingerprint; diff --git a/muxers/mplex/benches/split_send_size.rs b/muxers/mplex/benches/split_send_size.rs index cd8de8cc02d..c2b225a90fd 100644 --- a/muxers/mplex/benches/split_send_size.rs +++ b/muxers/mplex/benches/split_send_size.rs @@ -24,15 +24,15 @@ use std::{pin::Pin, time::Duration}; use async_std::task; -use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput}; +use criterion::{Criterion, Throughput, black_box, criterion_group, criterion_main}; use futures::{ channel::oneshot, future::{join, poll_fn}, prelude::*, }; use libp2p_core::{ - multiaddr::multiaddr, muxing, muxing::StreamMuxerExt, transport, transport::ListenerId, - upgrade, Endpoint, Multiaddr, Transport, + Endpoint, Multiaddr, Transport, multiaddr::multiaddr, muxing, muxing::StreamMuxerExt, + transport, transport::ListenerId, upgrade, }; use libp2p_identity as identity; use libp2p_identity::PeerId; diff --git a/muxers/mplex/src/io.rs b/muxers/mplex/src/io.rs index 14adff92989..3aaf8f5526b 100644 --- a/muxers/mplex/src/io.rs +++ b/muxers/mplex/src/io.rs @@ -33,15 +33,15 @@ use futures::{ prelude::*, ready, stream::Fuse, - task::{waker_ref, ArcWake, AtomicWaker, WakerRef}, + task::{ArcWake, AtomicWaker, WakerRef, waker_ref}, }; use nohash_hasher::{IntMap, IntSet}; use parking_lot::Mutex; use smallvec::SmallVec; use crate::{ - codec::{Codec, Frame, LocalStreamId, RemoteStreamId}, Config, MaxBufferBehaviour, + codec::{Codec, Frame, LocalStreamId, RemoteStreamId}, }; /// A connection identifier. /// @@ -392,10 +392,10 @@ where // Check if the stream is open for writing. match self.substreams.get(&id) { None | Some(SubstreamState::Reset { .. }) => { - return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())) + return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); } Some(SubstreamState::SendClosed { .. }) | Some(SubstreamState::Closed { .. }) => { - return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) + return Poll::Ready(Err(io::ErrorKind::WriteZero.into())); } Some(SubstreamState::Open { .. }) | Some(SubstreamState::RecvClosed { .. }) => { // Substream is writeable. Continue. @@ -479,7 +479,7 @@ where // Read the next frame. match ready!(self.poll_read_frame(cx, Some(id)))? { Frame::Data { data, stream_id } if stream_id.into_local() == id => { - return Poll::Ready(Ok(Some(data))) + return Poll::Ready(Ok(Some(data))); } Frame::Data { stream_id, data } => { // The data frame is for a different stream than the one diff --git a/muxers/test-harness/src/lib.rs b/muxers/test-harness/src/lib.rs index 489d476f158..6b5865f831f 100644 --- a/muxers/test-harness/src/lib.rs +++ b/muxers/test-harness/src/lib.rs @@ -7,11 +7,11 @@ use std::{ time::Duration, }; -use futures::{future, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, Stream, StreamExt}; +use futures::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, Stream, StreamExt, future}; use libp2p_core::{ + StreamMuxer, UpgradeInfo, muxing::StreamMuxerExt, upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}, - StreamMuxer, UpgradeInfo, }; use crate::future::{BoxFuture, Either, FutureExt}; diff --git a/protocols/autonat/src/v1.rs b/protocols/autonat/src/v1.rs index 4de601c5df5..98d793f4d89 100644 --- a/protocols/autonat/src/v1.rs +++ b/protocols/autonat/src/v1.rs @@ -36,11 +36,11 @@ pub use self::{ Behaviour, Config, Event, InboundProbeError, InboundProbeEvent, NatStatus, OutboundProbeError, OutboundProbeEvent, ProbeId, }, - protocol::{ResponseError, DEFAULT_PROTOCOL_NAME}, + protocol::{DEFAULT_PROTOCOL_NAME, ResponseError}, }; pub(crate) mod proto { #![allow(unreachable_pub)] include!("v1/generated/mod.rs"); - pub(crate) use self::structs::{mod_Message::*, Message}; + pub(crate) use self::structs::{Message, mod_Message::*}; } diff --git a/protocols/autonat/src/v1/behaviour.rs b/protocols/autonat/src/v1/behaviour.rs index 24ec1b13be7..0d13299c290 100644 --- a/protocols/autonat/src/v1/behaviour.rs +++ b/protocols/autonat/src/v1/behaviour.rs @@ -33,21 +33,21 @@ pub use as_client::{OutboundProbeError, OutboundProbeEvent}; use as_server::AsServer; pub use as_server::{InboundProbeError, InboundProbeEvent}; use futures_timer::Delay; -use libp2p_core::{multiaddr::Protocol, transport::PortUse, ConnectedPoint, Endpoint, Multiaddr}; +use libp2p_core::{ConnectedPoint, Endpoint, Multiaddr, multiaddr::Protocol, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_request_response::{ self as request_response, InboundRequestId, OutboundRequestId, ProtocolSupport, ResponseChannel, }; use libp2p_swarm::{ - behaviour::{AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}, ConnectionDenied, ConnectionId, ListenAddresses, NetworkBehaviour, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + behaviour::{AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}, }; use web_time::Instant; use crate::{ - protocol::{AutoNatCodec, DialRequest, DialResponse, ResponseError}, DEFAULT_PROTOCOL_NAME, + protocol::{AutoNatCodec, DialRequest, DialResponse, ResponseError}, }; /// Config for the [`Behaviour`]. diff --git a/protocols/autonat/src/v1/behaviour/as_server.rs b/protocols/autonat/src/v1/behaviour/as_server.rs index 32b4120c552..109ddaa4a7c 100644 --- a/protocols/autonat/src/v1/behaviour/as_server.rs +++ b/protocols/autonat/src/v1/behaviour/as_server.rs @@ -22,14 +22,14 @@ use std::{ num::NonZeroU8, }; -use libp2p_core::{multiaddr::Protocol, Multiaddr}; +use libp2p_core::{Multiaddr, multiaddr::Protocol}; use libp2p_identity::PeerId; use libp2p_request_response::{ self as request_response, InboundFailure, InboundRequestId, ResponseChannel, }; use libp2p_swarm::{ - dial_opts::{DialOpts, PeerCondition}, ConnectionId, DialError, ToSwarm, + dial_opts::{DialOpts, PeerCondition}, }; use web_time::Instant; diff --git a/protocols/autonat/src/v1/protocol.rs b/protocols/autonat/src/v1/protocol.rs index 6aa0c99167b..251a8d8d755 100644 --- a/protocols/autonat/src/v1/protocol.rs +++ b/protocols/autonat/src/v1/protocol.rs @@ -23,8 +23,8 @@ use std::io; use async_trait::async_trait; use asynchronous_codec::{FramedRead, FramedWrite}; use futures::{ - io::{AsyncRead, AsyncWrite}, SinkExt, StreamExt, + io::{AsyncRead, AsyncWrite}, }; use libp2p_core::Multiaddr; use libp2p_identity::PeerId; diff --git a/protocols/autonat/src/v2/client/behaviour.rs b/protocols/autonat/src/v2/client/behaviour.rs index 8e238fc9be4..1d7f11e960f 100644 --- a/protocols/autonat/src/v2/client/behaviour.rs +++ b/protocols/autonat/src/v2/client/behaviour.rs @@ -8,11 +8,12 @@ use std::{ use either::Either; use futures::FutureExt; use futures_timer::Delay; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ - behaviour::ConnectionEstablished, ConnectionClosed, ConnectionDenied, ConnectionHandler, - ConnectionId, FromSwarm, NetworkBehaviour, NewExternalAddrCandidate, NotifyHandler, ToSwarm, + ConnectionClosed, ConnectionDenied, ConnectionHandler, ConnectionId, FromSwarm, + NetworkBehaviour, NewExternalAddrCandidate, NotifyHandler, ToSwarm, + behaviour::ConnectionEstablished, }; use rand::prelude::*; use rand_core::OsRng; @@ -21,7 +22,7 @@ use super::handler::{ dial_back::{self, IncomingNonce}, dial_request, }; -use crate::v2::{protocol::DialRequest, Nonce}; +use crate::v2::{Nonce, protocol::DialRequest}; #[derive(Debug, Clone, Copy)] pub struct Config { @@ -293,7 +294,7 @@ where return; }; - let nonce = self.rng.gen(); + let nonce = self.rng.r#gen(); self.address_candidates .get_mut(&addr) .expect("only emit candidates") @@ -314,7 +315,7 @@ where /// /// More frequently reported candidates are considered to more likely be external addresses and /// thus tested first. - fn untested_candidates(&self) -> impl Iterator { + fn untested_candidates(&self) -> impl Iterator + use { let mut entries = self .address_candidates .iter() diff --git a/protocols/autonat/src/v2/client/handler/dial_back.rs b/protocols/autonat/src/v2/client/handler/dial_back.rs index 3fd3cf0b5ed..13dc24305d7 100644 --- a/protocols/autonat/src/v2/client/handler/dial_back.rs +++ b/protocols/autonat/src/v2/client/handler/dial_back.rs @@ -9,11 +9,11 @@ use futures::channel::oneshot; use futures_bounded::StreamSet; use libp2p_core::upgrade::{DeniedUpgrade, ReadyUpgrade}; use libp2p_swarm::{ - handler::{ConnectionEvent, FullyNegotiatedInbound, ListenUpgradeError}, ConnectionHandler, ConnectionHandlerEvent, StreamProtocol, SubstreamProtocol, + handler::{ConnectionEvent, FullyNegotiatedInbound, ListenUpgradeError}, }; -use crate::v2::{protocol, Nonce, DIAL_BACK_PROTOCOL}; +use crate::v2::{DIAL_BACK_PROTOCOL, Nonce, protocol}; pub struct Handler { inbound: StreamSet>, diff --git a/protocols/autonat/src/v2/client/handler/dial_request.rs b/protocols/autonat/src/v2/client/handler/dial_request.rs index 3da96a1d01f..bd3d7d78b93 100644 --- a/protocols/autonat/src/v2/client/handler/dial_request.rs +++ b/protocols/autonat/src/v2/client/handler/dial_request.rs @@ -7,28 +7,28 @@ use std::{ time::Duration, }; -use futures::{channel::oneshot, AsyncWrite}; +use futures::{AsyncWrite, channel::oneshot}; use futures_bounded::FuturesMap; use libp2p_core::{ - upgrade::{DeniedUpgrade, ReadyUpgrade}, Multiaddr, + upgrade::{DeniedUpgrade, ReadyUpgrade}, }; use libp2p_swarm::{ + ConnectionHandler, ConnectionHandlerEvent, Stream, StreamProtocol, StreamUpgradeError, + SubstreamProtocol, handler::{ ConnectionEvent, DialUpgradeError, FullyNegotiatedOutbound, OutboundUpgradeSend, ProtocolsChange, }, - ConnectionHandler, ConnectionHandlerEvent, Stream, StreamProtocol, StreamUpgradeError, - SubstreamProtocol, }; use crate::v2::{ - generated::structs::{mod_DialResponse::ResponseStatus, DialStatus}, + DIAL_REQUEST_PROTOCOL, Nonce, + generated::structs::{DialStatus, mod_DialResponse::ResponseStatus}, protocol::{ - Coder, DialDataRequest, DialDataResponse, DialRequest, Response, - DATA_FIELD_LEN_UPPER_BOUND, DATA_LEN_LOWER_BOUND, DATA_LEN_UPPER_BOUND, + Coder, DATA_FIELD_LEN_UPPER_BOUND, DATA_LEN_LOWER_BOUND, DATA_LEN_UPPER_BOUND, + DialDataRequest, DialDataResponse, DialRequest, Response, }, - Nonce, DIAL_REQUEST_PROTOCOL, }; #[derive(Debug)] @@ -137,7 +137,7 @@ impl ConnectionHandler for Handler { Poll::Ready((nonce, Ok(outcome))) => { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( ToBehaviour::TestOutcome { nonce, outcome }, - )) + )); } Poll::Ready((nonce, Err(_))) => { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( @@ -268,19 +268,19 @@ async fn start_stream_handle( return Err(Error::Io(io::Error::new( io::ErrorKind::Other, "server rejected request", - ))) + ))); } ResponseStatus::E_DIAL_REFUSED => { return Err(Error::Io(io::Error::new( io::ErrorKind::Other, "server refused dial", - ))) + ))); } ResponseStatus::E_INTERNAL_ERROR => { return Err(Error::Io(io::Error::new( io::ErrorKind::Other, "server encountered internal error", - ))) + ))); } ResponseStatus::OK => {} } @@ -296,21 +296,21 @@ async fn start_stream_handle( return Err(Error::Io(io::Error::new( io::ErrorKind::InvalidInput, "unexpected message", - ))) + ))); } DialStatus::E_DIAL_ERROR => { return Err(Error::AddressNotReachable { address: tested_address, bytes_sent, error: DialBackError::NoConnection, - }) + }); } DialStatus::E_DIAL_BACK_ERROR => { return Err(Error::AddressNotReachable { address: tested_address, bytes_sent, error: DialBackError::StreamFailed, - }) + }); } DialStatus::OK => {} } diff --git a/protocols/autonat/src/v2/protocol.rs b/protocols/autonat/src/v2/protocol.rs index 70f9f8c37af..b5a4dabdda9 100644 --- a/protocols/autonat/src/v2/protocol.rs +++ b/protocols/autonat/src/v2/protocol.rs @@ -8,7 +8,7 @@ use libp2p_core::Multiaddr; use quick_protobuf_codec::Codec; use rand::Rng; -use crate::v2::{generated::structs as proto, Nonce}; +use crate::v2::{Nonce, generated::structs as proto}; const REQUEST_MAX_SIZE: usize = 4104; pub(super) const DATA_LEN_LOWER_BOUND: usize = 30_000u32 as usize; @@ -310,7 +310,7 @@ pub(crate) async fn recv_dial_back_response( #[cfg(test)] mod tests { use crate::v2::generated::structs::{ - mod_Message::OneOfmsg, DialDataResponse as GenDialDataResponse, Message, + DialDataResponse as GenDialDataResponse, Message, mod_Message::OneOfmsg, }; #[test] diff --git a/protocols/autonat/src/v2/server/behaviour.rs b/protocols/autonat/src/v2/server/behaviour.rs index 856d46a25c1..90ee71dec4e 100644 --- a/protocols/autonat/src/v2/server/behaviour.rs +++ b/protocols/autonat/src/v2/server/behaviour.rs @@ -5,19 +5,19 @@ use std::{ }; use either::Either; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ + ConnectionDenied, ConnectionHandler, ConnectionId, DialFailure, FromSwarm, NetworkBehaviour, + ToSwarm, dial_opts::{DialOpts, PeerCondition}, - dummy, ConnectionDenied, ConnectionHandler, ConnectionId, DialFailure, FromSwarm, - NetworkBehaviour, ToSwarm, + dummy, }; use rand_core::{OsRng, RngCore}; use crate::v2::server::handler::{ - dial_back, + Handler, dial_back, dial_request::{self, DialBackCommand, DialBackStatus}, - Handler, }; pub struct Behaviour diff --git a/protocols/autonat/src/v2/server/handler/dial_back.rs b/protocols/autonat/src/v2/server/handler/dial_back.rs index 8adb33509ef..1e6df244916 100644 --- a/protocols/autonat/src/v2/server/handler/dial_back.rs +++ b/protocols/autonat/src/v2/server/handler/dial_back.rs @@ -9,15 +9,15 @@ use futures::{AsyncRead, AsyncWrite}; use futures_bounded::FuturesSet; use libp2p_core::upgrade::{DeniedUpgrade, ReadyUpgrade}; use libp2p_swarm::{ - handler::{ConnectionEvent, DialUpgradeError, FullyNegotiatedOutbound}, ConnectionHandler, ConnectionHandlerEvent, StreamProtocol, StreamUpgradeError, SubstreamProtocol, + handler::{ConnectionEvent, DialUpgradeError, FullyNegotiatedOutbound}, }; use super::dial_request::{DialBackCommand, DialBackStatus as DialBackRes}; use crate::v2::{ - protocol::{dial_back, recv_dial_back_response}, DIAL_BACK_PROTOCOL, + protocol::{dial_back, recv_dial_back_response}, }; pub(crate) type ToBehaviour = io::Result<()>; diff --git a/protocols/autonat/src/v2/server/handler/dial_request.rs b/protocols/autonat/src/v2/server/handler/dial_request.rs index 14e5189af49..08e5b81b33e 100644 --- a/protocols/autonat/src/v2/server/handler/dial_request.rs +++ b/protocols/autonat/src/v2/server/handler/dial_request.rs @@ -7,26 +7,26 @@ use std::{ use either::Either; use futures::{ - channel::{mpsc, oneshot}, AsyncRead, AsyncWrite, SinkExt, StreamExt, + channel::{mpsc, oneshot}, }; use futures_bounded::FuturesSet; use libp2p_core::{ - upgrade::{DeniedUpgrade, ReadyUpgrade}, Multiaddr, + upgrade::{DeniedUpgrade, ReadyUpgrade}, }; use libp2p_identity::PeerId; use libp2p_swarm::{ - handler::{ConnectionEvent, FullyNegotiatedInbound, ListenUpgradeError}, ConnectionHandler, ConnectionHandlerEvent, StreamProtocol, SubstreamProtocol, + handler::{ConnectionEvent, FullyNegotiatedInbound, ListenUpgradeError}, }; use rand_core::RngCore; use crate::v2::{ - generated::structs::{mod_DialResponse::ResponseStatus, DialStatus}, + DIAL_REQUEST_PROTOCOL, Nonce, + generated::structs::{DialStatus, mod_DialResponse::ResponseStatus}, protocol::{Coder, DialDataRequest, DialRequest, DialResponse, Request, Response}, server::behaviour::Event, - Nonce, DIAL_REQUEST_PROTOCOL, }; #[derive(Debug, PartialEq)] diff --git a/protocols/autonat/tests/autonatv2.rs b/protocols/autonat/tests/autonatv2.rs index 49866a9adb5..e39fb4715bc 100644 --- a/protocols/autonat/tests/autonatv2.rs +++ b/protocols/autonat/tests/autonatv2.rs @@ -4,7 +4,7 @@ use libp2p_autonat::v2::{ client::{self, Config}, server, }; -use libp2p_core::{multiaddr::Protocol, transport::TransportError, Multiaddr}; +use libp2p_core::{Multiaddr, multiaddr::Protocol, transport::TransportError}; use libp2p_swarm::{ DialError, FromSwarm, NetworkBehaviour, NewExternalAddrCandidate, Swarm, SwarmEvent, }; diff --git a/protocols/autonat/tests/test_server.rs b/protocols/autonat/tests/test_server.rs index 944c4301b20..0f14be4e44f 100644 --- a/protocols/autonat/tests/test_server.rs +++ b/protocols/autonat/tests/test_server.rs @@ -23,7 +23,7 @@ use std::{num::NonZeroU32, time::Duration}; use libp2p_autonat::{ Behaviour, Config, Event, InboundProbeError, InboundProbeEvent, ResponseError, }; -use libp2p_core::{multiaddr::Protocol, ConnectedPoint, Endpoint, Multiaddr}; +use libp2p_core::{ConnectedPoint, Endpoint, Multiaddr, multiaddr::Protocol}; use libp2p_identity::PeerId; use libp2p_swarm::{DialError, Swarm, SwarmEvent}; use libp2p_swarm_test::SwarmExt as _; diff --git a/protocols/dcutr/src/behaviour.rs b/protocols/dcutr/src/behaviour.rs index 4985527aca2..2b26b07e5e3 100644 --- a/protocols/dcutr/src/behaviour.rs +++ b/protocols/dcutr/src/behaviour.rs @@ -29,14 +29,15 @@ use std::{ use either::Either; use libp2p_core::{ - connection::ConnectedPoint, multiaddr::Protocol, transport::PortUse, Endpoint, Multiaddr, + Endpoint, Multiaddr, connection::ConnectedPoint, multiaddr::Protocol, transport::PortUse, }; use libp2p_identity::PeerId; use libp2p_swarm::{ + ConnectionDenied, ConnectionHandler, ConnectionId, NetworkBehaviour, NewExternalAddrCandidate, + NotifyHandler, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, behaviour::{ConnectionClosed, DialFailure, FromSwarm}, dial_opts::{self, DialOpts}, - dummy, ConnectionDenied, ConnectionHandler, ConnectionId, NetworkBehaviour, - NewExternalAddrCandidate, NotifyHandler, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + dummy, }; use lru::LruCache; use thiserror::Error; @@ -221,7 +222,7 @@ impl NetworkBehaviour for Behaviour { }, self.observed_addresses(), ))); // TODO: We could make two `handler::relayed::Handler` here, one inbound one - // outbound. + // outbound. } self.direct_connections diff --git a/protocols/dcutr/src/handler/relayed.rs b/protocols/dcutr/src/handler/relayed.rs index af84d8fe9b1..a4eadd6698d 100644 --- a/protocols/dcutr/src/handler/relayed.rs +++ b/protocols/dcutr/src/handler/relayed.rs @@ -30,21 +30,21 @@ use std::{ use either::Either; use futures::future; use libp2p_core::{ + ConnectedPoint, multiaddr::Multiaddr, upgrade::{DeniedUpgrade, ReadyUpgrade}, - ConnectedPoint, }; use libp2p_swarm::{ + ConnectionHandler, ConnectionHandlerEvent, StreamProtocol, StreamUpgradeError, + SubstreamProtocol, handler::{ ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, ListenUpgradeError, }, - ConnectionHandler, ConnectionHandlerEvent, StreamProtocol, StreamUpgradeError, - SubstreamProtocol, }; use protocol::{inbound, outbound}; -use crate::{behaviour::MAX_NUMBER_OF_UPGRADE_ATTEMPTS, protocol, PROTOCOL_NAME}; +use crate::{PROTOCOL_NAME, behaviour::MAX_NUMBER_OF_UPGRADE_ATTEMPTS, protocol}; #[derive(Debug)] pub enum Command { @@ -237,19 +237,19 @@ impl ConnectionHandler for Handler { Event::InboundConnectNegotiated { remote_addrs: addresses, }, - )) + )); } Poll::Ready(Ok(Err(error))) => { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( Event::InboundConnectFailed { error }, - )) + )); } Poll::Ready(Err(futures_bounded::Timeout { .. })) => { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( Event::InboundConnectFailed { error: inbound::Error::Io(io::ErrorKind::TimedOut.into()), }, - )) + )); } Poll::Pending => {} } @@ -260,19 +260,19 @@ impl ConnectionHandler for Handler { Event::OutboundConnectNegotiated { remote_addrs: addresses, }, - )) + )); } Poll::Ready(Ok(Err(error))) => { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( Event::OutboundConnectFailed { error }, - )) + )); } Poll::Ready(Err(futures_bounded::Timeout { .. })) => { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( Event::OutboundConnectFailed { error: outbound::Error::Io(io::ErrorKind::TimedOut.into()), }, - )) + )); } Poll::Pending => {} } diff --git a/protocols/dcutr/src/lib.rs b/protocols/dcutr/src/lib.rs index 7c5d28aba19..a6911c1aeda 100644 --- a/protocols/dcutr/src/lib.rs +++ b/protocols/dcutr/src/lib.rs @@ -30,7 +30,7 @@ mod protocol; mod proto { #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub(crate) use self::holepunch::pb::{mod_HolePunch::*, HolePunch}; + pub(crate) use self::holepunch::pb::{HolePunch, mod_HolePunch::*}; } pub use behaviour::{Behaviour, Error, Event}; diff --git a/protocols/dcutr/src/protocol/inbound.rs b/protocols/dcutr/src/protocol/inbound.rs index c5209930ca2..969212765c8 100644 --- a/protocols/dcutr/src/protocol/inbound.rs +++ b/protocols/dcutr/src/protocol/inbound.rs @@ -22,7 +22,7 @@ use std::io; use asynchronous_codec::Framed; use futures::prelude::*; -use libp2p_core::{multiaddr::Protocol, Multiaddr}; +use libp2p_core::{Multiaddr, multiaddr::Protocol}; use libp2p_swarm::Stream; use thiserror::Error; diff --git a/protocols/dcutr/src/protocol/outbound.rs b/protocols/dcutr/src/protocol/outbound.rs index cdd3d5fbf0b..5c45ca97156 100644 --- a/protocols/dcutr/src/protocol/outbound.rs +++ b/protocols/dcutr/src/protocol/outbound.rs @@ -23,12 +23,12 @@ use std::io; use asynchronous_codec::Framed; use futures::prelude::*; use futures_timer::Delay; -use libp2p_core::{multiaddr::Protocol, Multiaddr}; +use libp2p_core::{Multiaddr, multiaddr::Protocol}; use libp2p_swarm::Stream; use thiserror::Error; use web_time::Instant; -use crate::{proto, PROTOCOL_NAME}; +use crate::{PROTOCOL_NAME, proto}; pub(crate) async fn handshake( stream: Stream, diff --git a/protocols/dcutr/tests/lib.rs b/protocols/dcutr/tests/lib.rs index a35c9a50cfe..9f378aa6a4a 100644 --- a/protocols/dcutr/tests/lib.rs +++ b/protocols/dcutr/tests/lib.rs @@ -22,7 +22,7 @@ use std::time::Duration; use libp2p_core::{ multiaddr::{Multiaddr, Protocol}, - transport::{upgrade::Version, MemoryTransport, Transport}, + transport::{MemoryTransport, Transport, upgrade::Version}, }; use libp2p_dcutr as dcutr; use libp2p_identify as identify; diff --git a/protocols/floodsub/src/layer.rs b/protocols/floodsub/src/layer.rs index dfadbe4e0e4..bd991700f9a 100644 --- a/protocols/floodsub/src/layer.rs +++ b/protocols/floodsub/src/layer.rs @@ -20,8 +20,8 @@ use std::{ collections::{ - hash_map::{DefaultHasher, HashMap}, VecDeque, + hash_map::{DefaultHasher, HashMap}, }, iter, task::{Context, Poll}, @@ -30,23 +30,23 @@ use std::{ use bytes::Bytes; use cuckoofilter::{CuckooError, CuckooFilter}; use fnv::FnvHashSet; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ - behaviour::{ConnectionClosed, ConnectionEstablished, FromSwarm}, - dial_opts::DialOpts, CloseConnection, ConnectionDenied, ConnectionId, NetworkBehaviour, NotifyHandler, OneShotHandler, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + behaviour::{ConnectionClosed, ConnectionEstablished, FromSwarm}, + dial_opts::DialOpts, }; use smallvec::SmallVec; use crate::{ + Config, protocol::{ FloodsubMessage, FloodsubProtocol, FloodsubRpc, FloodsubSubscription, FloodsubSubscriptionAction, }, topic::Topic, - Config, }; #[deprecated = "Use `Behaviour` instead."] diff --git a/protocols/floodsub/src/lib.rs b/protocols/floodsub/src/lib.rs index ec4e2cf1b30..2a527dbfbbd 100644 --- a/protocols/floodsub/src/lib.rs +++ b/protocols/floodsub/src/lib.rs @@ -32,7 +32,7 @@ mod topic; mod proto { #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub(crate) use self::floodsub::pb::{mod_RPC::SubOpts, Message, RPC}; + pub(crate) use self::floodsub::pb::{Message, RPC, mod_RPC::SubOpts}; } #[allow(deprecated)] diff --git a/protocols/floodsub/src/protocol.rs b/protocols/floodsub/src/protocol.rs index 69cfcbd9dc7..58a93fcb2ce 100644 --- a/protocols/floodsub/src/protocol.rs +++ b/protocols/floodsub/src/protocol.rs @@ -23,8 +23,8 @@ use std::{io, iter, pin::Pin}; use asynchronous_codec::Framed; use bytes::Bytes; use futures::{ - io::{AsyncRead, AsyncWrite}, Future, SinkExt, StreamExt, + io::{AsyncRead, AsyncWrite}, }; use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}; use libp2p_identity::PeerId; diff --git a/protocols/gossipsub/src/backoff.rs b/protocols/gossipsub/src/backoff.rs index ee600d22098..0b18e3c63eb 100644 --- a/protocols/gossipsub/src/backoff.rs +++ b/protocols/gossipsub/src/backoff.rs @@ -21,8 +21,8 @@ //! Data structure for efficiently storing known back-off's when pruning peers. use std::{ collections::{ - hash_map::{Entry, HashMap}, HashSet, + hash_map::{Entry, HashMap}, }, time::Duration, }; diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index 0e9e44b2ef5..8522e812811 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -19,7 +19,7 @@ // DEALINGS IN THE SOFTWARE. use std::{ - cmp::{max, Ordering, Ordering::Equal}, + cmp::{Ordering, Ordering::Equal, max}, collections::{BTreeSet, HashMap, HashSet, VecDeque}, fmt, fmt::Debug, @@ -32,16 +32,16 @@ use futures::FutureExt; use futures_timer::Delay; use hashlink::LinkedHashMap; use libp2p_core::{ + Endpoint, Multiaddr, multiaddr::Protocol::{Ip4, Ip6}, transport::PortUse, - Endpoint, Multiaddr, }; use libp2p_identity::{Keypair, PeerId}; use libp2p_swarm::{ - behaviour::{AddressChange, ConnectionClosed, ConnectionEstablished, FromSwarm}, - dial_opts::DialOpts, ConnectionDenied, ConnectionId, NetworkBehaviour, NotifyHandler, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + behaviour::{AddressChange, ConnectionClosed, ConnectionEstablished, FromSwarm}, + dial_opts::DialOpts, }; use prometheus_client::registry::Registry; use quick_protobuf::{MessageWrite, Writer}; @@ -49,6 +49,7 @@ use rand::{seq::SliceRandom, thread_rng}; use web_time::{Instant, SystemTime}; use crate::{ + FailedMessages, PublishError, SubscriptionError, TopicScoreParams, ValidationError, backoff::BackoffStorage, config::{Config, ValidationMode}, gossip_promises::GossipPromises, @@ -68,7 +69,6 @@ use crate::{ PeerConnections, PeerInfo, PeerKind, Prune, RawMessage, RpcOut, Subscription, SubscriptionAction, }, - FailedMessages, PublishError, SubscriptionError, TopicScoreParams, ValidationError, }; #[cfg(test)] @@ -2742,7 +2742,7 @@ where ) -> Result { match &mut self.publish_config { PublishConfig::Signing { - ref keypair, + keypair, author, inline_key, last_seq_no, @@ -2871,7 +2871,9 @@ where | RpcOut::Prune(_) | RpcOut::Subscribe(_) | RpcOut::Unsubscribe(_) => { - unreachable!("Channel for highpriority control messages is unbounded and should always be open.") + unreachable!( + "Channel for highpriority control messages is unbounded and should always be open." + ) } } @@ -3270,7 +3272,10 @@ where .max_messages_per_rpc() .is_some_and(|max_msg| count >= max_msg) { - tracing::warn!("Received more messages than permitted. Ignoring further messages. Processed: {}", count); + tracing::warn!( + "Received more messages than permitted. Ignoring further messages. Processed: {}", + count + ); break; } self.handle_received_message(raw_message, &propagation_source); @@ -3289,7 +3294,10 @@ where .max_messages_per_rpc() .is_some_and(|max_msg| count >= max_msg) { - tracing::warn!("Received more control messages than permitted. Ignoring further messages. Processed: {}", count); + tracing::warn!( + "Received more control messages than permitted. Ignoring further messages. Processed: {}", + count + ); break; } @@ -3519,11 +3527,15 @@ fn validate_config( match validation_mode { ValidationMode::Anonymous => { if authenticity.is_signing() { - return Err("Cannot enable message signing with an Anonymous validation mode. Consider changing either the ValidationMode or MessageAuthenticity"); + return Err( + "Cannot enable message signing with an Anonymous validation mode. Consider changing either the ValidationMode or MessageAuthenticity", + ); } if !authenticity.is_anonymous() { - return Err("Published messages contain an author but incoming messages with an author will be rejected. Consider adjusting the validation or privacy settings in the config"); + return Err( + "Published messages contain an author but incoming messages with an author will be rejected. Consider adjusting the validation or privacy settings in the config", + ); } } ValidationMode::Strict => { diff --git a/protocols/gossipsub/src/behaviour/tests.rs b/protocols/gossipsub/src/behaviour/tests.rs index ff69c243453..dcb34d81306 100644 --- a/protocols/gossipsub/src/behaviour/tests.rs +++ b/protocols/gossipsub/src/behaviour/tests.rs @@ -28,8 +28,8 @@ use rand::Rng; use super::*; use crate::{ - config::ConfigBuilder, rpc::Receiver, subscription_filter::WhitelistSubscriptionFilter, - types::Rpc, IdentTopic as Topic, + IdentTopic as Topic, config::ConfigBuilder, rpc::Receiver, + subscription_filter::WhitelistSubscriptionFilter, types::Rpc, }; #[derive(Default, Debug)] @@ -289,7 +289,7 @@ where role_override: Endpoint::Dialer, port_use: PortUse::Reuse, }; // this is not relevant - // peer_connections.connections should never be empty. + // peer_connections.connections should never be empty. let mut active_connections = peer_connections.connections.len(); for connection_id in peer_connections.connections.clone() { @@ -1964,11 +1964,13 @@ fn test_connect_to_px_peers_on_handle_prune() { assert_eq!(dials_set.len(), config.prune_peers()); // all dial peers must be in px - assert!(dials_set.is_subset( - &px.iter() - .map(|i| *i.peer_id.as_ref().unwrap()) - .collect::>() - )); + assert!( + dials_set.is_subset( + &px.iter() + .map(|i| *i.peer_id.as_ref().unwrap()) + .collect::>() + ) + ); } #[test] @@ -2821,21 +2823,25 @@ fn test_iwant_msg_from_peer_below_gossip_threshold_gets_ignored() { }); // the message got sent to p2 - assert!(sent_messages - .iter() - .map(|(peer_id, msg)| ( - peer_id, - gs.data_transform.inbound_transform(msg.clone()).unwrap() - )) - .any(|(peer_id, msg)| peer_id == &p2 && gs.config.message_id(&msg) == msg_id)); + assert!( + sent_messages + .iter() + .map(|(peer_id, msg)| ( + peer_id, + gs.data_transform.inbound_transform(msg.clone()).unwrap() + )) + .any(|(peer_id, msg)| peer_id == &p2 && gs.config.message_id(&msg) == msg_id) + ); // the message got not sent to p1 - assert!(sent_messages - .iter() - .map(|(peer_id, msg)| ( - peer_id, - gs.data_transform.inbound_transform(msg.clone()).unwrap() - )) - .all(|(peer_id, msg)| !(peer_id == &p1 && gs.config.message_id(&msg) == msg_id))); + assert!( + sent_messages + .iter() + .map(|(peer_id, msg)| ( + peer_id, + gs.data_transform.inbound_transform(msg.clone()).unwrap() + )) + .all(|(peer_id, msg)| !(peer_id == &p1 && gs.config.message_id(&msg) == msg_id)) + ); } #[test] @@ -3273,12 +3279,14 @@ fn test_keep_best_scoring_peers_on_oversubscription() { assert_eq!(gs.mesh[&topics[0]].len(), config.mesh_n()); // mesh contains retain_scores best peers - assert!(gs.mesh[&topics[0]].is_superset( - &peers[(n - config.retain_scores())..] - .iter() - .cloned() - .collect() - )); + assert!( + gs.mesh[&topics[0]].is_superset( + &peers[(n - config.retain_scores())..] + .iter() + .cloned() + .collect() + ) + ); } #[test] @@ -3353,7 +3361,7 @@ fn random_message(seq: &mut u64, topics: &[TopicHash]) -> RawMessage { *seq += 1; RawMessage { source: Some(PeerId::random()), - data: (0..rng.gen_range(10..30)).map(|_| rng.gen()).collect(), + data: (0..rng.gen_range(10..30)).map(|_| rng.r#gen()).collect(), sequence_number: Some(*seq), topic: topics[rng.gen_range(0..topics.len())].clone(), signature: None, @@ -6045,11 +6053,15 @@ fn test_priority_messages_are_always_sent() { let sender = Sender::new(2); let topic_hash = Topic::new("Test").hash(); // Fill the buffer with the first message. - assert!(sender - .send_message(RpcOut::Subscribe(topic_hash.clone())) - .is_ok()); - assert!(sender - .send_message(RpcOut::Subscribe(topic_hash.clone())) - .is_ok()); + assert!( + sender + .send_message(RpcOut::Subscribe(topic_hash.clone())) + .is_ok() + ); + assert!( + sender + .send_message(RpcOut::Subscribe(topic_hash.clone())) + .is_ok() + ); assert!(sender.send_message(RpcOut::Unsubscribe(topic_hash)).is_ok()); } diff --git a/protocols/gossipsub/src/config.rs b/protocols/gossipsub/src/config.rs index d524ed78cc0..d4b0cf85aab 100644 --- a/protocols/gossipsub/src/config.rs +++ b/protocols/gossipsub/src/config.rs @@ -25,7 +25,7 @@ use libp2p_swarm::StreamProtocol; use crate::{ error::ConfigBuilderError, - protocol::{ProtocolConfig, ProtocolId, FLOODSUB_PROTOCOL}, + protocol::{FLOODSUB_PROTOCOL, ProtocolConfig, ProtocolId}, types::{Message, MessageId, PeerKind}, }; @@ -958,7 +958,7 @@ mod test { use libp2p_core::UpgradeInfo; use super::*; - use crate::{topic::IdentityHash, Topic}; + use crate::{Topic, topic::IdentityHash}; #[test] fn create_config_with_message_id_as_plain_function() { diff --git a/protocols/gossipsub/src/error.rs b/protocols/gossipsub/src/error.rs index 03cf8601b02..598e3d9311b 100644 --- a/protocols/gossipsub/src/error.rs +++ b/protocols/gossipsub/src/error.rs @@ -150,9 +150,17 @@ impl std::fmt::Display for ConfigBuilderError { Self::MaxTransmissionSizeTooSmall => { write!(f, "Maximum transmission size is too small") } - Self::HistoryLengthTooSmall => write!(f, "History length less than history gossip length"), - Self::MeshParametersInvalid => write!(f, "The ineauality doesn't hold mesh_outbound_min <= mesh_n_low <= mesh_n <= mesh_n_high"), - Self::MeshOutboundInvalid => write!(f, "The inequality doesn't hold mesh_outbound_min <= self.config.mesh_n / 2"), + Self::HistoryLengthTooSmall => { + write!(f, "History length less than history gossip length") + } + Self::MeshParametersInvalid => write!( + f, + "The ineauality doesn't hold mesh_outbound_min <= mesh_n_low <= mesh_n <= mesh_n_high" + ), + Self::MeshOutboundInvalid => write!( + f, + "The inequality doesn't hold mesh_outbound_min <= self.config.mesh_n / 2" + ), Self::UnsubscribeBackoffIsZero => write!(f, "unsubscribe_backoff is zero"), Self::InvalidProtocol => write!(f, "Invalid protocol"), } diff --git a/protocols/gossipsub/src/gossip_promises.rs b/protocols/gossipsub/src/gossip_promises.rs index 284ba7cab01..a140102cc19 100644 --- a/protocols/gossipsub/src/gossip_promises.rs +++ b/protocols/gossipsub/src/gossip_promises.rs @@ -23,7 +23,7 @@ use std::collections::HashMap; use libp2p_identity::PeerId; use web_time::Instant; -use crate::{peer_score::RejectReason, MessageId, ValidationError}; +use crate::{MessageId, ValidationError, peer_score::RejectReason}; /// Tracks recently sent `IWANT` messages and checks if peers respond to them. #[derive(Default)] diff --git a/protocols/gossipsub/src/handler.rs b/protocols/gossipsub/src/handler.rs index 7dc15e97fc1..7077ad7ce01 100644 --- a/protocols/gossipsub/src/handler.rs +++ b/protocols/gossipsub/src/handler.rs @@ -24,23 +24,23 @@ use std::{ }; use asynchronous_codec::Framed; -use futures::{future::Either, prelude::*, StreamExt}; +use futures::{StreamExt, future::Either, prelude::*}; use libp2p_core::upgrade::DeniedUpgrade; use libp2p_swarm::{ + Stream, handler::{ ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, StreamUpgradeError, SubstreamProtocol, }, - Stream, }; use web_time::Instant; use crate::{ + ValidationError, protocol::{GossipsubCodec, ProtocolConfig}, rpc::Receiver, rpc_proto::proto, types::{PeerKind, RawMessage, Rpc, RpcOut}, - ValidationError, }; /// The event emitted by the Handler. This informs the behaviour of various events created diff --git a/protocols/gossipsub/src/lib.rs b/protocols/gossipsub/src/lib.rs index 87db1b771d1..b0fa3881c80 100644 --- a/protocols/gossipsub/src/lib.rs +++ b/protocols/gossipsub/src/lib.rs @@ -118,8 +118,8 @@ pub use self::{ error::{ConfigBuilderError, PublishError, SubscriptionError, ValidationError}, metrics::Config as MetricsConfig, peer_score::{ - score_parameter_decay, score_parameter_decay_with_base, PeerScoreParams, - PeerScoreThresholds, TopicScoreParams, + PeerScoreParams, PeerScoreThresholds, TopicScoreParams, score_parameter_decay, + score_parameter_decay_with_base, }, subscription_filter::{ AllowAllSubscriptionFilter, CallbackSubscriptionFilter, CombinedSubscriptionFilters, diff --git a/protocols/gossipsub/src/mcache.rs b/protocols/gossipsub/src/mcache.rs index 8ed71ea07f2..68b4f80b1d4 100644 --- a/protocols/gossipsub/src/mcache.rs +++ b/protocols/gossipsub/src/mcache.rs @@ -19,7 +19,7 @@ // DEALINGS IN THE SOFTWARE. use std::{ - collections::{hash_map::Entry, HashMap, HashSet}, + collections::{HashMap, HashSet, hash_map::Entry}, fmt, fmt::Debug, }; diff --git a/protocols/gossipsub/src/metrics.rs b/protocols/gossipsub/src/metrics.rs index 485bcd54eeb..645aecd1c9c 100644 --- a/protocols/gossipsub/src/metrics.rs +++ b/protocols/gossipsub/src/metrics.rs @@ -29,7 +29,7 @@ use prometheus_client::{ counter::Counter, family::{Family, MetricConstructor}, gauge::Gauge, - histogram::{linear_buckets, Histogram}, + histogram::{Histogram, linear_buckets}, }, registry::Registry, }; diff --git a/protocols/gossipsub/src/peer_score.rs b/protocols/gossipsub/src/peer_score.rs index 33573ebeacc..c121784a27a 100644 --- a/protocols/gossipsub/src/peer_score.rs +++ b/protocols/gossipsub/src/peer_score.rs @@ -21,7 +21,7 @@ //! Manages and stores the Scoring logic of a particular peer on the gossipsub behaviour. use std::{ - collections::{hash_map, HashMap, HashSet}, + collections::{HashMap, HashSet, hash_map}, net::IpAddr, time::Duration, }; @@ -30,15 +30,15 @@ use libp2p_identity::PeerId; use web_time::Instant; use crate::{ + MessageId, TopicHash, metrics::{Metrics, Penalty}, time_cache::TimeCache, - MessageId, TopicHash, }; mod params; pub use params::{ - score_parameter_decay, score_parameter_decay_with_base, PeerScoreParams, PeerScoreThresholds, - TopicScoreParams, + PeerScoreParams, PeerScoreThresholds, TopicScoreParams, score_parameter_decay, + score_parameter_decay_with_base, }; use crate::ValidationError; diff --git a/protocols/gossipsub/src/peer_score/tests.rs b/protocols/gossipsub/src/peer_score/tests.rs index 951f7084347..ecf4ee8d87f 100644 --- a/protocols/gossipsub/src/peer_score/tests.rs +++ b/protocols/gossipsub/src/peer_score/tests.rs @@ -20,7 +20,7 @@ /// A collection of unit tests mostly ported from the go implementation. use super::*; -use crate::{types::RawMessage, IdentTopic as Topic, Message}; +use crate::{IdentTopic as Topic, Message, types::RawMessage}; // estimates a value within variance fn within_variance(value: f64, expected: f64, variance: f64) -> bool { diff --git a/protocols/gossipsub/src/protocol.rs b/protocols/gossipsub/src/protocol.rs index 7ee6d5c8245..727a773489a 100644 --- a/protocols/gossipsub/src/protocol.rs +++ b/protocols/gossipsub/src/protocol.rs @@ -30,6 +30,7 @@ use libp2p_swarm::StreamProtocol; use quick_protobuf::Writer; use crate::{ + ValidationError, config::ValidationMode, handler::HandlerEvent, rpc_proto::proto, @@ -38,7 +39,6 @@ use crate::{ ControlAction, Graft, IDontWant, IHave, IWant, MessageId, PeerInfo, PeerKind, Prune, RawMessage, Rpc, Subscription, SubscriptionAction, }, - ValidationError, }; pub(crate) const SIGNING_PREFIX: &[u8] = b"libp2p-pubsub:"; @@ -283,7 +283,9 @@ impl Decoder for GossipsubCodec { ); invalid_kind = Some(ValidationError::SequenceNumberPresent); } else if message.from.is_some() { - tracing::warn!("Message dropped. Message source was non-empty and anonymous validation mode is set"); + tracing::warn!( + "Message dropped. Message source was non-empty and anonymous validation mode is set" + ); invalid_kind = Some(ValidationError::MessageSourcePresent); } } @@ -538,7 +540,7 @@ mod tests { use super::*; use crate::{ - config::Config, Behaviour, ConfigBuilder, IdentTopic as Topic, MessageAuthenticity, Version, + Behaviour, ConfigBuilder, IdentTopic as Topic, MessageAuthenticity, Version, config::Config, }; #[derive(Clone, Debug)] diff --git a/protocols/gossipsub/src/rpc.rs b/protocols/gossipsub/src/rpc.rs index 41b338267e9..d2eebb8e377 100644 --- a/protocols/gossipsub/src/rpc.rs +++ b/protocols/gossipsub/src/rpc.rs @@ -22,13 +22,13 @@ use std::{ future::Future, pin::Pin, sync::{ - atomic::{AtomicUsize, Ordering}, Arc, + atomic::{AtomicUsize, Ordering}, }, task::{Context, Poll}, }; -use futures::{stream::Peekable, Stream, StreamExt}; +use futures::{Stream, StreamExt, stream::Peekable}; use crate::types::RpcOut; @@ -126,7 +126,7 @@ impl Receiver { let priority = match self.priority.as_mut().poll_peek_mut(cx) { Poll::Ready(Some(RpcOut::Publish { message: _, - ref mut timeout, + timeout, })) => { if Pin::new(timeout).poll(cx).is_ready() { // Return the message. @@ -142,7 +142,7 @@ impl Receiver { let non_priority = match self.non_priority.as_mut().poll_peek_mut(cx) { Poll::Ready(Some(RpcOut::Forward { message: _, - ref mut timeout, + timeout, })) => { if Pin::new(timeout).poll(cx).is_ready() { // Return the message. diff --git a/protocols/gossipsub/src/rpc_proto.rs b/protocols/gossipsub/src/rpc_proto.rs index 2f6832a01a1..0bdb0e3ab11 100644 --- a/protocols/gossipsub/src/rpc_proto.rs +++ b/protocols/gossipsub/src/rpc_proto.rs @@ -30,7 +30,7 @@ mod test { use quick_protobuf::{BytesReader, MessageRead, MessageWrite, Writer}; use rand::Rng; - use crate::{rpc_proto::proto::compat, IdentTopic as Topic}; + use crate::{IdentTopic as Topic, rpc_proto::proto::compat}; #[test] fn test_multi_topic_message_compatibility() { @@ -39,27 +39,27 @@ mod test { let new_message1 = super::proto::Message { from: Some(PeerId::random().to_bytes()), - data: Some(rand::thread_rng().gen::<[u8; 32]>().to_vec()), - seqno: Some(rand::thread_rng().gen::<[u8; 8]>().to_vec()), + data: Some(rand::thread_rng().r#gen::<[u8; 32]>().to_vec()), + seqno: Some(rand::thread_rng().r#gen::<[u8; 8]>().to_vec()), topic: topic1.clone().into_string(), - signature: Some(rand::thread_rng().gen::<[u8; 32]>().to_vec()), - key: Some(rand::thread_rng().gen::<[u8; 32]>().to_vec()), + signature: Some(rand::thread_rng().r#gen::<[u8; 32]>().to_vec()), + key: Some(rand::thread_rng().r#gen::<[u8; 32]>().to_vec()), }; let old_message1 = compat::pb::Message { from: Some(PeerId::random().to_bytes()), - data: Some(rand::thread_rng().gen::<[u8; 32]>().to_vec()), - seqno: Some(rand::thread_rng().gen::<[u8; 8]>().to_vec()), + data: Some(rand::thread_rng().r#gen::<[u8; 32]>().to_vec()), + seqno: Some(rand::thread_rng().r#gen::<[u8; 8]>().to_vec()), topic_ids: vec![topic1.clone().into_string()], - signature: Some(rand::thread_rng().gen::<[u8; 32]>().to_vec()), - key: Some(rand::thread_rng().gen::<[u8; 32]>().to_vec()), + signature: Some(rand::thread_rng().r#gen::<[u8; 32]>().to_vec()), + key: Some(rand::thread_rng().r#gen::<[u8; 32]>().to_vec()), }; let old_message2 = compat::pb::Message { from: Some(PeerId::random().to_bytes()), - data: Some(rand::thread_rng().gen::<[u8; 32]>().to_vec()), - seqno: Some(rand::thread_rng().gen::<[u8; 8]>().to_vec()), + data: Some(rand::thread_rng().r#gen::<[u8; 32]>().to_vec()), + seqno: Some(rand::thread_rng().r#gen::<[u8; 8]>().to_vec()), topic_ids: vec![topic1.clone().into_string(), topic2.clone().into_string()], - signature: Some(rand::thread_rng().gen::<[u8; 32]>().to_vec()), - key: Some(rand::thread_rng().gen::<[u8; 32]>().to_vec()), + signature: Some(rand::thread_rng().r#gen::<[u8; 32]>().to_vec()), + key: Some(rand::thread_rng().r#gen::<[u8; 32]>().to_vec()), }; let mut new_message1b = Vec::with_capacity(new_message1.get_size()); diff --git a/protocols/gossipsub/src/subscription_filter.rs b/protocols/gossipsub/src/subscription_filter.rs index c051b6c333b..cf914ccb592 100644 --- a/protocols/gossipsub/src/subscription_filter.rs +++ b/protocols/gossipsub/src/subscription_filter.rs @@ -20,7 +20,7 @@ use std::collections::{BTreeSet, HashMap, HashSet}; -use crate::{types::Subscription, TopicHash}; +use crate::{TopicHash, types::Subscription}; pub trait TopicSubscriptionFilter { /// Returns true iff the topic is of interest and we can subscribe to it. diff --git a/protocols/gossipsub/src/time_cache.rs b/protocols/gossipsub/src/time_cache.rs index ace02606e88..06b2aed646e 100644 --- a/protocols/gossipsub/src/time_cache.rs +++ b/protocols/gossipsub/src/time_cache.rs @@ -22,11 +22,11 @@ use std::{ collections::{ + VecDeque, hash_map::{ self, Entry::{Occupied, Vacant}, }, - VecDeque, }, time::Duration, }; diff --git a/protocols/gossipsub/src/types.rs b/protocols/gossipsub/src/types.rs index 6681eca1d93..1a3ded07525 100644 --- a/protocols/gossipsub/src/types.rs +++ b/protocols/gossipsub/src/types.rs @@ -31,7 +31,7 @@ use quick_protobuf::MessageWrite; use serde::{Deserialize, Serialize}; use web_time::Instant; -use crate::{rpc::Sender, rpc_proto::proto, TopicHash}; +use crate::{TopicHash, rpc::Sender, rpc_proto::proto}; /// Messages that have expired while attempting to be sent to a peer. #[derive(Clone, Debug, Default)] diff --git a/protocols/gossipsub/tests/smoke.rs b/protocols/gossipsub/tests/smoke.rs index 85038665b4d..f46ba4e070d 100644 --- a/protocols/gossipsub/tests/smoke.rs +++ b/protocols/gossipsub/tests/smoke.rs @@ -21,15 +21,15 @@ use std::{task::Poll, time::Duration}; use futures::{ - stream::{FuturesUnordered, SelectAll}, StreamExt, + stream::{FuturesUnordered, SelectAll}, }; use libp2p_gossipsub as gossipsub; use libp2p_gossipsub::{MessageAuthenticity, ValidationMode}; use libp2p_swarm::Swarm; use libp2p_swarm_test::SwarmExt as _; use quickcheck::{QuickCheck, TestResult}; -use rand::{seq::SliceRandom, SeedableRng}; +use rand::{SeedableRng, seq::SliceRandom}; use tokio::{runtime::Runtime, time}; use tracing_subscriber::EnvFilter; @@ -96,10 +96,12 @@ impl Graph { /// Polls the graph until Poll::Pending is obtained, completing the underlying polls. async fn drain_events(&mut self) { - let fut = futures::future::poll_fn(|cx| loop { - match self.nodes.poll_next_unpin(cx) { - Poll::Ready(_) => {} - Poll::Pending => return Poll::Ready(()), + let fut = futures::future::poll_fn(|cx| { + loop { + match self.nodes.poll_next_unpin(cx) { + Poll::Ready(_) => {} + Poll::Pending => return Poll::Ready(()), + } } }); time::timeout(Duration::from_secs(10), fut).await.unwrap(); diff --git a/protocols/identify/src/behaviour.rs b/protocols/identify/src/behaviour.rs index 3a0a0898394..9cb9aac5782 100644 --- a/protocols/identify/src/behaviour.rs +++ b/protocols/identify/src/behaviour.rs @@ -19,7 +19,7 @@ // DEALINGS IN THE SOFTWARE. use std::{ - collections::{hash_map::Entry, HashMap, HashSet, VecDeque}, + collections::{HashMap, HashSet, VecDeque, hash_map::Entry}, num::NonZeroUsize, sync::Arc, task::{Context, Poll}, @@ -27,16 +27,16 @@ use std::{ }; use libp2p_core::{ + ConnectedPoint, Endpoint, Multiaddr, multiaddr::{self, Protocol}, transport::PortUse, - ConnectedPoint, Endpoint, Multiaddr, }; use libp2p_identity::{Keypair, PeerId, PublicKey}; use libp2p_swarm::{ + _address_translation, ConnectionDenied, ConnectionId, DialError, ExternalAddresses, + ListenAddresses, NetworkBehaviour, NotifyHandler, PeerAddresses, StreamUpgradeError, THandler, + THandlerInEvent, THandlerOutEvent, ToSwarm, behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}, - ConnectionDenied, ConnectionId, DialError, ExternalAddresses, ListenAddresses, - NetworkBehaviour, NotifyHandler, PeerAddresses, StreamUpgradeError, THandler, THandlerInEvent, - THandlerOutEvent, ToSwarm, _address_translation, }; use crate::{ diff --git a/protocols/identify/src/handler.rs b/protocols/identify/src/handler.rs index c2e31ae95f6..7b8757ecf30 100644 --- a/protocols/identify/src/handler.rs +++ b/protocols/identify/src/handler.rs @@ -30,25 +30,25 @@ use futures::prelude::*; use futures_bounded::Timeout; use futures_timer::Delay; use libp2p_core::{ - upgrade::{ReadyUpgrade, SelectUpgrade}, Multiaddr, + upgrade::{ReadyUpgrade, SelectUpgrade}, }; use libp2p_identity::PeerId; use libp2p_swarm::{ + ConnectionHandler, ConnectionHandlerEvent, StreamProtocol, StreamUpgradeError, + SubstreamProtocol, SupportedProtocols, handler::{ ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, ProtocolSupport, }, - ConnectionHandler, ConnectionHandlerEvent, StreamProtocol, StreamUpgradeError, - SubstreamProtocol, SupportedProtocols, }; use smallvec::SmallVec; use tracing::Level; use crate::{ + PROTOCOL_NAME, PUSH_PROTOCOL_NAME, behaviour::KeyType, protocol::{self, Info, PushInfo, UpgradeError}, - PROTOCOL_NAME, PUSH_PROTOCOL_NAME, }; const STREAM_TIMEOUT: Duration = Duration::from_secs(60); diff --git a/protocols/identify/src/lib.rs b/protocols/identify/src/lib.rs index 868ace87aeb..cbe01cb2813 100644 --- a/protocols/identify/src/lib.rs +++ b/protocols/identify/src/lib.rs @@ -43,7 +43,7 @@ pub use self::{ behaviour::{Behaviour, Config, Event}, - protocol::{Info, UpgradeError, PROTOCOL_NAME, PUSH_PROTOCOL_NAME}, + protocol::{Info, PROTOCOL_NAME, PUSH_PROTOCOL_NAME, UpgradeError}, }; mod behaviour; diff --git a/protocols/identify/src/protocol.rs b/protocols/identify/src/protocol.rs index 0fb4e32d357..c8753d93abf 100644 --- a/protocols/identify/src/protocol.rs +++ b/protocols/identify/src/protocol.rs @@ -22,7 +22,7 @@ use std::io; use asynchronous_codec::{FramedRead, FramedWrite}; use futures::prelude::*; -use libp2p_core::{multiaddr, Multiaddr, PeerRecord, SignedEnvelope}; +use libp2p_core::{Multiaddr, PeerRecord, SignedEnvelope, multiaddr}; use libp2p_identity as identity; use libp2p_identity::PublicKey; use libp2p_swarm::StreamProtocol; diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index 04ebe7d8174..5da6c13d447 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -32,14 +32,14 @@ use std::{ }; use fnv::FnvHashSet; -use libp2p_core::{transport::PortUse, ConnectedPoint, Endpoint, Multiaddr}; +use libp2p_core::{ConnectedPoint, Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ - behaviour::{AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}, - dial_opts::{self, DialOpts}, ConnectionDenied, ConnectionHandler, ConnectionId, DialError, ExternalAddresses, ListenAddresses, NetworkBehaviour, NotifyHandler, StreamProtocol, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + behaviour::{AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}, + dial_opts::{self, DialOpts}, }; use thiserror::Error; use tracing::Level; @@ -47,6 +47,7 @@ use web_time::Instant; pub use crate::query::QueryStats; use crate::{ + K_VALUE, addresses::Addresses, bootstrap, handler::{Handler, HandlerEvent, HandlerIn, RequestId}, @@ -56,11 +57,9 @@ use crate::{ protocol::{ConnectionType, KadPeer, ProtocolConfig}, query::{Query, QueryConfig, QueryId, QueryPool, QueryPoolState}, record::{ - self, + self, ProviderRecord, Record, store::{self, RecordStore}, - ProviderRecord, Record, }, - K_VALUE, }; /// `Behaviour` is a `NetworkBehaviour` that implements the libp2p @@ -1154,7 +1153,9 @@ where self.mode = match (self.external_addresses.as_slice(), self.mode) { ([], Mode::Server) => { - tracing::debug!("Switching to client-mode because we no longer have any confirmed external addresses"); + tracing::debug!( + "Switching to client-mode because we no longer have any confirmed external addresses" + ); Mode::Client } @@ -1168,7 +1169,9 @@ where let confirmed_external_addresses = to_comma_separated_list(confirmed_external_addresses); - tracing::debug!("Switching to server-mode assuming that one of [{confirmed_external_addresses}] is externally reachable"); + tracing::debug!( + "Switching to server-mode assuming that one of [{confirmed_external_addresses}] is externally reachable" + ); } Mode::Server @@ -2449,8 +2452,8 @@ where let stats = query.stats().clone(); if let QueryInfo::GetRecord { key, - ref mut step, - ref mut found_a_record, + step, + found_a_record, cache_candidates, } = &mut query.info { diff --git a/protocols/kad/src/behaviour/test.rs b/protocols/kad/src/behaviour/test.rs index 467865dd225..b94151521aa 100644 --- a/protocols/kad/src/behaviour/test.rs +++ b/protocols/kad/src/behaviour/test.rs @@ -23,22 +23,23 @@ use futures::{executor::block_on, future::poll_fn, prelude::*}; use futures_timer::Delay; use libp2p_core::{ - multiaddr::{multiaddr, Protocol}, + Transport, + multiaddr::{Protocol, multiaddr}, multihash::Multihash, transport::MemoryTransport, - upgrade, Transport, + upgrade, }; use libp2p_identity as identity; use libp2p_noise as noise; use libp2p_swarm::{self as swarm, Swarm, SwarmEvent}; use libp2p_yamux as yamux; use quickcheck::*; -use rand::{random, rngs::StdRng, thread_rng, Rng, SeedableRng}; +use rand::{Rng, SeedableRng, random, rngs::StdRng, thread_rng}; use super::*; use crate::{ - record::{store::MemoryStore, Key}, K_VALUE, PROTOCOL_NAME, SHA_256_MH, + record::{Key, store::MemoryStore}, }; type TestSwarm = Swarm>; @@ -137,7 +138,7 @@ fn build_fully_connected_nodes_with_config( } fn random_multihash() -> Multihash<64> { - Multihash::wrap(SHA_256_MH, &thread_rng().gen::<[u8; 32]>()).unwrap() + Multihash::wrap(SHA_256_MH, &thread_rng().r#gen::<[u8; 32]>()).unwrap() } #[derive(Clone, Debug)] @@ -169,7 +170,7 @@ fn bootstrap() { // triggering automatically. cfg.set_periodic_bootstrap_interval(None); cfg.set_automatic_bootstrap_throttle(None); - if rng.gen() { + if rng.r#gen() { cfg.disjoint_query_paths(true); } @@ -471,9 +472,17 @@ fn get_closest_with_different_num_results_inner(num_results: usize, replication_ }))) => { assert_eq!(&ok.key[..], search_target.to_bytes().as_slice()); if num_results > k_value { - assert_eq!(ok.peers.len(), k_value, "Failed with replication_factor: {replication_factor}, num_results: {num_results}"); + assert_eq!( + ok.peers.len(), + k_value, + "Failed with replication_factor: {replication_factor}, num_results: {num_results}" + ); } else { - assert_eq!(ok.peers.len(), num_results, "Failed with replication_factor: {replication_factor}, num_results: {num_results}"); + assert_eq!( + ok.peers.len(), + num_results, + "Failed with replication_factor: {replication_factor}, num_results: {num_results}" + ); } return Poll::Ready(()); @@ -568,7 +577,7 @@ fn put_record() { // triggering automatically. config.set_periodic_bootstrap_interval(None); config.set_automatic_bootstrap_throttle(None); - if rng.gen() { + if rng.r#gen() { config.disjoint_query_paths(true); } @@ -639,165 +648,168 @@ fn put_record() { // The accumulated results for one round of publishing. let mut results = Vec::new(); - block_on(poll_fn(move |ctx| loop { - // Poll all swarms until they are "Pending". - for swarm in &mut swarms { - loop { - match swarm.poll_next_unpin(ctx) { - Poll::Ready(Some(SwarmEvent::Behaviour( - Event::OutboundQueryProgressed { - id, - result: QueryResult::PutRecord(res), - stats, - step: index, - }, - ))) - | Poll::Ready(Some(SwarmEvent::Behaviour( - Event::OutboundQueryProgressed { - id, - result: QueryResult::RepublishRecord(res), - stats, - step: index, - }, - ))) => { - assert!(qids.is_empty() || qids.remove(&id)); - assert!(stats.duration().is_some()); - assert!(stats.num_successes() >= replication_factor.get() as u32); - assert!(stats.num_requests() >= stats.num_successes()); - assert_eq!(stats.num_failures(), 0); - assert_eq!(usize::from(index.count), 1); - assert!(index.last); - match res { - Err(e) => panic!("{e:?}"), - Ok(ok) => { - assert!(records.contains_key(&ok.key)); - let record = swarm.behaviour_mut().store.get(&ok.key).unwrap(); - results.push(record.into_owned()); + block_on(poll_fn(move |ctx| { + loop { + // Poll all swarms until they are "Pending". + for swarm in &mut swarms { + loop { + match swarm.poll_next_unpin(ctx) { + Poll::Ready(Some(SwarmEvent::Behaviour( + Event::OutboundQueryProgressed { + id, + result: QueryResult::PutRecord(res), + stats, + step: index, + }, + ))) + | Poll::Ready(Some(SwarmEvent::Behaviour( + Event::OutboundQueryProgressed { + id, + result: QueryResult::RepublishRecord(res), + stats, + step: index, + }, + ))) => { + assert!(qids.is_empty() || qids.remove(&id)); + assert!(stats.duration().is_some()); + assert!(stats.num_successes() >= replication_factor.get() as u32); + assert!(stats.num_requests() >= stats.num_successes()); + assert_eq!(stats.num_failures(), 0); + assert_eq!(usize::from(index.count), 1); + assert!(index.last); + match res { + Err(e) => panic!("{e:?}"), + Ok(ok) => { + assert!(records.contains_key(&ok.key)); + let record = + swarm.behaviour_mut().store.get(&ok.key).unwrap(); + results.push(record.into_owned()); + } } } - } - Poll::Ready(Some(SwarmEvent::Behaviour(Event::InboundRequest { - request: InboundRequest::PutRecord { record, .. }, - }))) => { - if !drop_records { - if let Some(record) = record { - assert_eq!( - swarm.behaviour().record_filtering, - StoreInserts::FilterBoth - ); - // Accept the record - swarm - .behaviour_mut() - .store_mut() - .put(record) - .expect("record is stored"); - } else { - assert_eq!( - swarm.behaviour().record_filtering, - StoreInserts::Unfiltered - ); + Poll::Ready(Some(SwarmEvent::Behaviour(Event::InboundRequest { + request: InboundRequest::PutRecord { record, .. }, + }))) => { + if !drop_records { + if let Some(record) = record { + assert_eq!( + swarm.behaviour().record_filtering, + StoreInserts::FilterBoth + ); + // Accept the record + swarm + .behaviour_mut() + .store_mut() + .put(record) + .expect("record is stored"); + } else { + assert_eq!( + swarm.behaviour().record_filtering, + StoreInserts::Unfiltered + ); + } } } + // Ignore any other event. + Poll::Ready(Some(_)) => (), + e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), + Poll::Pending => break, } - // Ignore any other event. - Poll::Ready(Some(_)) => (), - e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), - Poll::Pending => break, } } - } - // All swarms are Pending and not enough results have been collected - // so far, thus wait to be polled again for further progress. - if results.len() != records.len() { - return Poll::Pending; - } - - // Consume the results, checking that each record was replicated - // correctly to the closest peers to the key. - while let Some(r) = results.pop() { - let expected = records.get(&r.key).unwrap(); - - assert_eq!(r.key, expected.key); - assert_eq!(r.value, expected.value); - assert_eq!(r.expires, expected.expires); - assert_eq!(r.publisher, Some(*swarms[0].local_peer_id())); - - let key = kbucket::Key::new(r.key.clone()); - let mut expected = swarms - .iter() - .skip(1) - .map(Swarm::local_peer_id) - .cloned() - .collect::>(); - expected.sort_by(|id1, id2| { - kbucket::Key::from(*id1) - .distance(&key) - .cmp(&kbucket::Key::from(*id2).distance(&key)) - }); - - let expected = expected - .into_iter() - .take(replication_factor.get()) - .collect::>(); - - let actual = swarms - .iter() - .skip(1) - .filter_map(|swarm| { - if swarm.behaviour().store.get(key.preimage()).is_some() { - Some(*swarm.local_peer_id()) - } else { - None - } - }) - .collect::>(); - - if swarms[0].behaviour().record_filtering != StoreInserts::Unfiltered - && drop_records - { - assert_eq!(actual.len(), 0); - } else { - assert_eq!(actual.len(), replication_factor.get()); + // All swarms are Pending and not enough results have been collected + // so far, thus wait to be polled again for further progress. + if results.len() != records.len() { + return Poll::Pending; + } - let actual_not_expected = - actual.difference(&expected).collect::>(); - assert!( - actual_not_expected.is_empty(), - "Did not expect records to be stored on nodes {actual_not_expected:?}.", - ); + // Consume the results, checking that each record was replicated + // correctly to the closest peers to the key. + while let Some(r) = results.pop() { + let expected = records.get(&r.key).unwrap(); + + assert_eq!(r.key, expected.key); + assert_eq!(r.value, expected.value); + assert_eq!(r.expires, expected.expires); + assert_eq!(r.publisher, Some(*swarms[0].local_peer_id())); + + let key = kbucket::Key::new(r.key.clone()); + let mut expected = swarms + .iter() + .skip(1) + .map(Swarm::local_peer_id) + .cloned() + .collect::>(); + expected.sort_by(|id1, id2| { + kbucket::Key::from(*id1) + .distance(&key) + .cmp(&kbucket::Key::from(*id2).distance(&key)) + }); + + let expected = expected + .into_iter() + .take(replication_factor.get()) + .collect::>(); + + let actual = swarms + .iter() + .skip(1) + .filter_map(|swarm| { + if swarm.behaviour().store.get(key.preimage()).is_some() { + Some(*swarm.local_peer_id()) + } else { + None + } + }) + .collect::>(); + + if swarms[0].behaviour().record_filtering != StoreInserts::Unfiltered + && drop_records + { + assert_eq!(actual.len(), 0); + } else { + assert_eq!(actual.len(), replication_factor.get()); + + let actual_not_expected = + actual.difference(&expected).collect::>(); + assert!( + actual_not_expected.is_empty(), + "Did not expect records to be stored on nodes {actual_not_expected:?}.", + ); + + let expected_not_actual = + expected.difference(&actual).collect::>(); + assert!( + expected_not_actual.is_empty(), + "Expected record to be stored on nodes {expected_not_actual:?}.", + ); + } + } - let expected_not_actual = - expected.difference(&actual).collect::>(); - assert!( - expected_not_actual.is_empty(), - "Expected record to be stored on nodes {expected_not_actual:?}.", + if republished { + assert_eq!( + swarms[0].behaviour_mut().store.records().count(), + records.len() ); + assert_eq!(swarms[0].behaviour_mut().queries.size(), 0); + for k in records.keys() { + swarms[0].behaviour_mut().store.remove(k); + } + assert_eq!(swarms[0].behaviour_mut().store.records().count(), 0); + // All records have been republished, thus the test is complete. + return Poll::Ready(()); } - } - if republished { - assert_eq!( - swarms[0].behaviour_mut().store.records().count(), - records.len() - ); - assert_eq!(swarms[0].behaviour_mut().queries.size(), 0); - for k in records.keys() { - swarms[0].behaviour_mut().store.remove(k); - } - assert_eq!(swarms[0].behaviour_mut().store.records().count(), 0); - // All records have been republished, thus the test is complete. - return Poll::Ready(()); + // Tell the replication job to republish asap. + swarms[0] + .behaviour_mut() + .put_record_job + .as_mut() + .unwrap() + .asap(true); + republished = true; } - - // Tell the replication job to republish asap. - swarms[0] - .behaviour_mut() - .put_record_job - .as_mut() - .unwrap() - .asap(true); - republished = true; })) } @@ -941,7 +953,7 @@ fn add_provider() { // triggering automatically. config.set_periodic_bootstrap_interval(None); config.set_automatic_bootstrap_throttle(None); - if rng.gen() { + if rng.r#gen() { config.disjoint_query_paths(true); } @@ -987,125 +999,127 @@ fn add_provider() { qids.insert(qid); } - block_on(poll_fn(move |ctx| loop { - // Poll all swarms until they are "Pending". - for swarm in &mut swarms { - loop { - match swarm.poll_next_unpin(ctx) { - Poll::Ready(Some(SwarmEvent::Behaviour( - Event::OutboundQueryProgressed { - id, - result: QueryResult::StartProviding(res), - .. - }, - ))) - | Poll::Ready(Some(SwarmEvent::Behaviour( - Event::OutboundQueryProgressed { - id, - result: QueryResult::RepublishProvider(res), - .. - }, - ))) => { - assert!(qids.is_empty() || qids.remove(&id)); - match res { - Err(e) => panic!("{e:?}"), - Ok(ok) => { - assert!(keys.contains(&ok.key)); - results.push(ok.key); + block_on(poll_fn(move |ctx| { + loop { + // Poll all swarms until they are "Pending". + for swarm in &mut swarms { + loop { + match swarm.poll_next_unpin(ctx) { + Poll::Ready(Some(SwarmEvent::Behaviour( + Event::OutboundQueryProgressed { + id, + result: QueryResult::StartProviding(res), + .. + }, + ))) + | Poll::Ready(Some(SwarmEvent::Behaviour( + Event::OutboundQueryProgressed { + id, + result: QueryResult::RepublishProvider(res), + .. + }, + ))) => { + assert!(qids.is_empty() || qids.remove(&id)); + match res { + Err(e) => panic!("{e:?}"), + Ok(ok) => { + assert!(keys.contains(&ok.key)); + results.push(ok.key); + } } } + // Ignore any other event. + Poll::Ready(Some(_)) => (), + e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), + Poll::Pending => break, } - // Ignore any other event. - Poll::Ready(Some(_)) => (), - e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), - Poll::Pending => break, } } - } - - if results.len() == keys.len() { - // All requests have been sent for one round of publishing. - published = true - } - if !published { - // Still waiting for all requests to be sent for one round - // of publishing. - return Poll::Pending; - } - - // A round of publishing is complete. Consume the results, checking that - // each key was published to the `replication_factor` closest peers. - while let Some(key) = results.pop() { - // Collect the nodes that have a provider record for `key`. - let actual = swarms - .iter() - .skip(1) - .filter_map(|swarm| { - if swarm.behaviour().store.providers(&key).len() == 1 { - Some(*Swarm::local_peer_id(swarm)) - } else { - None - } - }) - .collect::>(); + if results.len() == keys.len() { + // All requests have been sent for one round of publishing. + published = true + } - if actual.len() != replication_factor.get() { - // Still waiting for some nodes to process the request. - results.push(key); + if !published { + // Still waiting for all requests to be sent for one round + // of publishing. return Poll::Pending; } - let mut expected = swarms - .iter() - .skip(1) - .map(Swarm::local_peer_id) - .cloned() - .collect::>(); - let kbucket_key = kbucket::Key::new(key); - expected.sort_by(|id1, id2| { - kbucket::Key::from(*id1) - .distance(&kbucket_key) - .cmp(&kbucket::Key::from(*id2).distance(&kbucket_key)) - }); - - let expected = expected - .into_iter() - .take(replication_factor.get()) - .collect::>(); - - assert_eq!(actual, expected); - } + // A round of publishing is complete. Consume the results, checking that + // each key was published to the `replication_factor` closest peers. + while let Some(key) = results.pop() { + // Collect the nodes that have a provider record for `key`. + let actual = swarms + .iter() + .skip(1) + .filter_map(|swarm| { + if swarm.behaviour().store.providers(&key).len() == 1 { + Some(*Swarm::local_peer_id(swarm)) + } else { + None + } + }) + .collect::>(); - // One round of publishing is complete. - assert!(results.is_empty()); - for swarm in &swarms { - assert_eq!(swarm.behaviour().queries.size(), 0); - } + if actual.len() != replication_factor.get() { + // Still waiting for some nodes to process the request. + results.push(key); + return Poll::Pending; + } - if republished { - assert_eq!( - swarms[0].behaviour_mut().store.provided().count(), - keys.len() - ); - for k in &keys { - swarms[0].behaviour_mut().stop_providing(k); + let mut expected = swarms + .iter() + .skip(1) + .map(Swarm::local_peer_id) + .cloned() + .collect::>(); + let kbucket_key = kbucket::Key::new(key); + expected.sort_by(|id1, id2| { + kbucket::Key::from(*id1) + .distance(&kbucket_key) + .cmp(&kbucket::Key::from(*id2).distance(&kbucket_key)) + }); + + let expected = expected + .into_iter() + .take(replication_factor.get()) + .collect::>(); + + assert_eq!(actual, expected); } - assert_eq!(swarms[0].behaviour_mut().store.provided().count(), 0); - // All records have been republished, thus the test is complete. - return Poll::Ready(()); - } - // Initiate the second round of publishing by telling the - // periodic provider job to run asap. - swarms[0] - .behaviour_mut() - .add_provider_job - .as_mut() - .unwrap() - .asap(); - published = false; - republished = true; + // One round of publishing is complete. + assert!(results.is_empty()); + for swarm in &swarms { + assert_eq!(swarm.behaviour().queries.size(), 0); + } + + if republished { + assert_eq!( + swarms[0].behaviour_mut().store.provided().count(), + keys.len() + ); + for k in &keys { + swarms[0].behaviour_mut().stop_providing(k); + } + assert_eq!(swarms[0].behaviour_mut().store.provided().count(), 0); + // All records have been republished, thus the test is complete. + return Poll::Ready(()); + } + + // Initiate the second round of publishing by telling the + // periodic provider job to run asap. + swarms[0] + .behaviour_mut() + .add_provider_job + .as_mut() + .unwrap() + .asap(); + published = false; + republished = true; + } })) } @@ -1176,7 +1190,7 @@ fn disjoint_query_does_not_finish_before_all_paths_did() { let mut bob = build_node(); let key = Key::from( - Multihash::<64>::wrap(SHA_256_MH, &thread_rng().gen::<[u8; 32]>()) + Multihash::<64>::wrap(SHA_256_MH, &thread_rng().r#gen::<[u8; 32]>()) .expect("32 array to fit into 64 byte multihash"), ); let record_bob = Record::new(key.clone(), b"bob".to_vec()); @@ -1393,15 +1407,17 @@ fn network_behaviour_on_address_change() { // At this point the remote is not yet known to support the // configured protocol name, so the peer is not yet in the // local routing table and hence no addresses are known. - assert!(kademlia - .handle_pending_outbound_connection( - connection_id, - Some(remote_peer_id), - &[], - Endpoint::Dialer - ) - .unwrap() - .is_empty()); + assert!( + kademlia + .handle_pending_outbound_connection( + connection_id, + Some(remote_peer_id), + &[], + Endpoint::Dialer + ) + .unwrap() + .is_empty() + ); // Mimic the connection handler confirming the protocol for // the test connection, so that the peer is added to the routing table. diff --git a/protocols/kad/src/bootstrap.rs b/protocols/kad/src/bootstrap.rs index 9fa5d17ab5d..1588838916e 100644 --- a/protocols/kad/src/bootstrap.rs +++ b/protocols/kad/src/bootstrap.rs @@ -241,9 +241,7 @@ mod tests { ); assert!( - tokio::time::timeout(MS_5 * 2, status.next()) - .await - .is_ok(), + tokio::time::timeout(MS_5 * 2, status.next()).await.is_ok(), "bootstrap to be triggered in less then the configured periodic delay because we connected to a new peer" ); } @@ -264,8 +262,8 @@ mod tests { } #[tokio::test] - async fn given_periodic_bootstrap_when_routing_table_updated_then_wont_bootstrap_until_next_interval( - ) { + async fn given_periodic_bootstrap_when_routing_table_updated_then_wont_bootstrap_until_next_interval() + { let mut status = Status::new(Some(MS_100), Some(MS_5)); status.trigger(); @@ -284,8 +282,8 @@ mod tests { } #[tokio::test] - async fn given_no_periodic_bootstrap_and_automatic_bootstrap_when_new_entry_then_will_bootstrap( - ) { + async fn given_no_periodic_bootstrap_and_automatic_bootstrap_when_new_entry_then_will_bootstrap() + { let mut status = Status::new(None, Some(Duration::ZERO)); status.trigger(); @@ -309,8 +307,8 @@ mod tests { } #[tokio::test] - async fn given_no_periodic_bootstrap_and_automatic_bootstrap_reset_throttle_when_multiple_peers( - ) { + async fn given_no_periodic_bootstrap_and_automatic_bootstrap_reset_throttle_when_multiple_peers() + { let mut status = Status::new(None, Some(MS_100)); status.trigger(); @@ -327,16 +325,14 @@ mod tests { Delay::new(MS_100 - MS_5).await; assert!( - tokio::time::timeout(MS_5*2, status.next()) - .await - .is_ok(), + tokio::time::timeout(MS_5 * 2, status.next()).await.is_ok(), "bootstrap to be triggered in the configured throttle delay because we connected to a new peer" ); } #[tokio::test] - async fn given_periodic_bootstrap_and_no_automatic_bootstrap_manually_triggering_prevent_periodic( - ) { + async fn given_periodic_bootstrap_and_no_automatic_bootstrap_manually_triggering_prevent_periodic() + { let mut status = Status::new(Some(MS_100), None); // first manually triggering diff --git a/protocols/kad/src/handler.rs b/protocols/kad/src/handler.rs index 48b91e7a0c9..2108a2a0edc 100644 --- a/protocols/kad/src/handler.rs +++ b/protocols/kad/src/handler.rs @@ -29,21 +29,21 @@ use std::{ use either::Either; use futures::{channel::oneshot, prelude::*, stream::SelectAll}; -use libp2p_core::{upgrade, ConnectedPoint}; +use libp2p_core::{ConnectedPoint, upgrade}; use libp2p_identity::PeerId; use libp2p_swarm::{ - handler::{ConnectionEvent, FullyNegotiatedInbound, FullyNegotiatedOutbound}, ConnectionHandler, ConnectionHandlerEvent, Stream, StreamUpgradeError, SubstreamProtocol, SupportedProtocols, + handler::{ConnectionEvent, FullyNegotiatedInbound, FullyNegotiatedOutbound}, }; use crate::{ + QueryId, behaviour::Mode, protocol::{ KadInStreamSink, KadOutStreamSink, KadPeer, KadRequestMsg, KadResponseMsg, ProtocolConfig, }, record::{self, Record}, - QueryId, }; const MAX_NUM_STREAMS: usize = 32; @@ -737,7 +737,7 @@ impl ConnectionHandler for Handler { Poll::Ready((Ok(Ok(Some(response))), query_id)) => { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( process_kad_response(response, query_id), - )) + )); } Poll::Ready((Ok(Ok(None)), _)) => { continue; @@ -748,7 +748,7 @@ impl ConnectionHandler for Handler { error: HandlerQueryErr::Io(e), query_id, }, - )) + )); } Poll::Ready((Err(_timeout), query_id)) => { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( @@ -756,7 +756,7 @@ impl ConnectionHandler for Handler { error: HandlerQueryErr::Io(io::ErrorKind::TimedOut.into()), query_id, }, - )) + )); } Poll::Pending => {} } @@ -823,7 +823,7 @@ fn compute_new_protocol_status( return ProtocolStatus { supported: now_supported, reported: false, - } + }; } Some(current) => current, }; diff --git a/protocols/kad/src/jobs.rs b/protocols/kad/src/jobs.rs index 56b3e080d96..09655976e6a 100644 --- a/protocols/kad/src/jobs.rs +++ b/protocols/kad/src/jobs.rs @@ -72,7 +72,7 @@ use futures_timer::Delay; use libp2p_identity::PeerId; use web_time::Instant; -use crate::record::{self, store::RecordStore, ProviderRecord, Record}; +use crate::record::{self, ProviderRecord, Record, store::RecordStore}; /// The maximum number of queries towards which background jobs /// are allowed to start new queries on an invocation of diff --git a/protocols/kad/src/kbucket.rs b/protocols/kad/src/kbucket.rs index f32c34e9bb7..9967c89c8e7 100644 --- a/protocols/kad/src/kbucket.rs +++ b/protocols/kad/src/kbucket.rs @@ -170,7 +170,7 @@ impl BucketIndex { let mut bytes = [0u8; 32]; let quot = self.0 / 8; for i in 0..quot { - bytes[31 - i] = rng.gen(); + bytes[31 - i] = rng.r#gen(); } let rem = (self.0 % 8) as u32; let lower = usize::pow(2, rem); diff --git a/protocols/kad/src/kbucket/bucket.rs b/protocols/kad/src/kbucket/bucket.rs index cbc6adf4d5c..b2a128deda7 100644 --- a/protocols/kad/src/kbucket/bucket.rs +++ b/protocols/kad/src/kbucket/bucket.rs @@ -226,7 +226,7 @@ where return None; } debug_assert!(self.first_connected_pos.is_none_or(|p| p > 0)); // (*) - // The pending node will be inserted. + // The pending node will be inserted. let inserted = pending.node.clone(); // A connected pending node goes at the end of the list for // the connected peers, removing the least-recently connected. @@ -260,7 +260,7 @@ where return Some(AppliedPending { inserted, evicted: None, - }) + }); } _ => unreachable!("Bucket is not full."), } diff --git a/protocols/kad/src/kbucket/entry.rs b/protocols/kad/src/kbucket/entry.rs index bdf8b9b5a18..32a3a86713f 100644 --- a/protocols/kad/src/kbucket/entry.rs +++ b/protocols/kad/src/kbucket/entry.rs @@ -21,7 +21,7 @@ //! The `Entry` API for querying and modifying the entries of a `KBucketsTable` //! representing the nodes participating in the Kademlia DHT. -pub(crate) use super::bucket::{AppliedPending, InsertResult, Node, K_VALUE}; +pub(crate) use super::bucket::{AppliedPending, InsertResult, K_VALUE, Node}; pub use super::key::*; use super::*; diff --git a/protocols/kad/src/kbucket/key.rs b/protocols/kad/src/kbucket/key.rs index 4080657d239..e5db79b89ea 100644 --- a/protocols/kad/src/kbucket/key.rs +++ b/protocols/kad/src/kbucket/key.rs @@ -27,8 +27,8 @@ use std::{ use libp2p_core::multihash::Multihash; use libp2p_identity::PeerId; use sha2::{ - digest::generic_array::{typenum::U32, GenericArray}, Digest, Sha256, + digest::generic_array::{GenericArray, typenum::U32}, }; use uint::*; diff --git a/protocols/kad/src/lib.rs b/protocols/kad/src/lib.rs index 5201832a2ba..e3009940bd1 100644 --- a/protocols/kad/src/lib.rs +++ b/protocols/kad/src/lib.rs @@ -49,8 +49,8 @@ mod proto { #![allow(unreachable_pub)] include!("generated/mod.rs"); pub use self::dht::pb::{ - mod_Message::{ConnectionType, MessageType, Peer}, Message, Record, + mod_Message::{ConnectionType, MessageType, Peer}, }; } @@ -72,7 +72,7 @@ pub use kbucket::{ use libp2p_swarm::StreamProtocol; pub use protocol::{ConnectionType, KadPeer}; pub use query::QueryId; -pub use record::{store, Key as RecordKey, ProviderRecord, Record}; +pub use record::{Key as RecordKey, ProviderRecord, Record, store}; /// The `k` parameter of the Kademlia specification. /// diff --git a/protocols/kad/src/protocol.rs b/protocols/kad/src/protocol.rs index 059b6ae6fd1..c39b4273eca 100644 --- a/protocols/kad/src/protocol.rs +++ b/protocols/kad/src/protocol.rs @@ -32,8 +32,8 @@ use asynchronous_codec::{Decoder, Encoder, Framed}; use bytes::BytesMut; use futures::prelude::*; use libp2p_core::{ - upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}, Multiaddr, + upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}, }; use libp2p_identity::PeerId; use libp2p_swarm::StreamProtocol; diff --git a/protocols/kad/src/query.rs b/protocols/kad/src/query.rs index 69257f73b26..ba92dcd354f 100644 --- a/protocols/kad/src/query.rs +++ b/protocols/kad/src/query.rs @@ -27,18 +27,18 @@ use fnv::FnvHashMap; use libp2p_core::Multiaddr; use libp2p_identity::PeerId; use peers::{ - closest::{disjoint::ClosestDisjointPeersIter, ClosestPeersIter, ClosestPeersIterConfig}, - fixed::FixedPeersIter, PeersIterState, + closest::{ClosestPeersIter, ClosestPeersIterConfig, disjoint::ClosestDisjointPeersIter}, + fixed::FixedPeersIter, }; use smallvec::SmallVec; use web_time::Instant; use crate::{ + ALPHA_VALUE, K_VALUE, QueryInfo, behaviour::PeerInfo, handler::HandlerIn, kbucket::{Key, KeyBytes}, - QueryInfo, ALPHA_VALUE, K_VALUE, }; /// A `QueryPool` provides an aggregate state machine for driving `Query`s to completion. diff --git a/protocols/kad/src/query/peers/closest.rs b/protocols/kad/src/query/peers/closest.rs index 2d1f91f050c..8e4a5e559da 100644 --- a/protocols/kad/src/query/peers/closest.rs +++ b/protocols/kad/src/query/peers/closest.rs @@ -28,8 +28,8 @@ use web_time::Instant; use super::*; use crate::{ - kbucket::{Distance, Key, KeyBytes}, ALPHA_VALUE, K_VALUE, + kbucket::{Distance, Key, KeyBytes}, }; pub(crate) mod disjoint; @@ -504,7 +504,7 @@ mod tests { use libp2p_core::multihash::Multihash; use quickcheck::*; - use rand::{rngs::StdRng, Rng, SeedableRng}; + use rand::{Rng, SeedableRng, rngs::StdRng}; use super::*; use crate::SHA_256_MH; @@ -512,7 +512,7 @@ mod tests { fn random_peers(n: usize, g: &mut R) -> Vec { (0..n) .map(|_| { - PeerId::from_multihash(Multihash::wrap(SHA_256_MH, &g.gen::<[u8; 32]>()).unwrap()) + PeerId::from_multihash(Multihash::wrap(SHA_256_MH, &g.r#gen::<[u8; 32]>()).unwrap()) .unwrap() }) .collect() diff --git a/protocols/kad/src/record.rs b/protocols/kad/src/record.rs index fea17f826a4..a6826b48198 100644 --- a/protocols/kad/src/record.rs +++ b/protocols/kad/src/record.rs @@ -28,7 +28,7 @@ use std::{ }; use bytes::Bytes; -use libp2p_core::{multihash::Multihash, Multiaddr}; +use libp2p_core::{Multiaddr, multihash::Multihash}; use libp2p_identity::PeerId; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; diff --git a/protocols/kad/src/record/store/memory.rs b/protocols/kad/src/record/store/memory.rs index 28f6a55044f..ed36f13b1f0 100644 --- a/protocols/kad/src/record/store/memory.rs +++ b/protocols/kad/src/record/store/memory.rs @@ -19,7 +19,7 @@ // DEALINGS IN THE SOFTWARE. use std::{ - collections::{hash_map, hash_set, HashMap, HashSet}, + collections::{HashMap, HashSet, hash_map, hash_set}, iter, }; @@ -218,7 +218,7 @@ mod tests { use crate::SHA_256_MH; fn random_multihash() -> Multihash<64> { - Multihash::wrap(SHA_256_MH, &rand::thread_rng().gen::<[u8; 32]>()).unwrap() + Multihash::wrap(SHA_256_MH, &rand::thread_rng().r#gen::<[u8; 32]>()).unwrap() } #[test] fn put_get_remove_record() { diff --git a/protocols/kad/tests/client_mode.rs b/protocols/kad/tests/client_mode.rs index d741299eb2c..9b49e433ac8 100644 --- a/protocols/kad/tests/client_mode.rs +++ b/protocols/kad/tests/client_mode.rs @@ -1,11 +1,11 @@ +use Event::*; +use MyBehaviourEvent::*; use libp2p_identify as identify; use libp2p_identity as identity; -use libp2p_kad::{store::MemoryStore, Behaviour, Config, Event, Mode}; +use libp2p_kad::{Behaviour, Config, Event, Mode, store::MemoryStore}; use libp2p_swarm::{Swarm, SwarmEvent}; use libp2p_swarm_test::SwarmExt; use tracing_subscriber::EnvFilter; -use Event::*; -use MyBehaviourEvent::*; #[tokio::test] async fn server_gets_added_to_routing_table_by_client() { @@ -56,8 +56,16 @@ async fn two_servers_add_each_other_to_routing_table() { match libp2p_swarm_test::drive(&mut server1, &mut server2).await { ( - [Identify(_), Identify(_), Kad(RoutingUpdated { peer: peer1, .. })] - | [Identify(_), Kad(RoutingUpdated { peer: peer1, .. }), Identify(_)], + [ + Identify(_), + Identify(_), + Kad(RoutingUpdated { peer: peer1, .. }), + ] + | [ + Identify(_), + Kad(RoutingUpdated { peer: peer1, .. }), + Identify(_), + ], [Identify(_), Identify(_)], ) => { assert_eq!(peer1, server2_peer_id); @@ -108,8 +116,14 @@ async fn adding_an_external_addresses_activates_server_mode_on_existing_connecti // table and triggers a mode change to Mode::Server. match libp2p_swarm_test::drive(&mut client, &mut server).await { ( - [Identify(identify::Event::Received { .. }), Kad(RoutingUpdated { peer: peer1, .. })], - [Kad(ModeChanged { new_mode }), Identify(identify::Event::Pushed { .. })], + [ + Identify(identify::Event::Received { .. }), + Kad(RoutingUpdated { peer: peer1, .. }), + ], + [ + Kad(ModeChanged { new_mode }), + Identify(identify::Event::Pushed { .. }), + ], ) => { assert_eq!(new_mode, Mode::Server); assert_eq!(peer1, server_peer_id); @@ -153,10 +167,11 @@ async fn set_client_to_server_mode() { assert_eq!(peer, server_peer_id); assert_eq!(peer_id, server_peer_id); - assert!(info - .protocols - .iter() - .all(|proto| libp2p_kad::PROTOCOL_NAME.ne(proto))); + assert!( + info.protocols + .iter() + .all(|proto| libp2p_kad::PROTOCOL_NAME.ne(proto)) + ); client.behaviour_mut().kad.set_mode(Some(Mode::Server)); @@ -169,10 +184,11 @@ async fn set_client_to_server_mode() { }) .await; - assert!(info - .protocols - .iter() - .any(|proto| libp2p_kad::PROTOCOL_NAME.eq(proto))); + assert!( + info.protocols + .iter() + .any(|proto| libp2p_kad::PROTOCOL_NAME.eq(proto)) + ); } #[derive(libp2p_swarm::NetworkBehaviour)] diff --git a/protocols/mdns/src/behaviour.rs b/protocols/mdns/src/behaviour.rs index 68e28cf3d63..c58dbcd37a2 100644 --- a/protocols/mdns/src/behaviour.rs +++ b/protocols/mdns/src/behaviour.rs @@ -25,8 +25,8 @@ mod timer; use std::{ cmp, collections::{ - hash_map::{Entry, HashMap}, VecDeque, + hash_map::{Entry, HashMap}, }, convert::Infallible, fmt, @@ -39,20 +39,20 @@ use std::{ time::Instant, }; -use futures::{channel::mpsc, Stream, StreamExt}; +use futures::{Stream, StreamExt, channel::mpsc}; use if_watch::IfEvent; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ - behaviour::FromSwarm, dummy, ConnectionDenied, ConnectionId, ListenAddresses, NetworkBehaviour, - THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + ConnectionDenied, ConnectionId, ListenAddresses, NetworkBehaviour, THandler, THandlerInEvent, + THandlerOutEvent, ToSwarm, behaviour::FromSwarm, dummy, }; use smallvec::SmallVec; use self::iface::InterfaceState; use crate::{ - behaviour::{socket::AsyncSocket, timer::Builder}, Config, + behaviour::{socket::AsyncSocket, timer::Builder}, }; /// An abstraction to allow for compatibility with various async runtimes. @@ -87,7 +87,7 @@ pub mod async_io { use if_watch::smol::IfWatcher; use super::Provider; - use crate::behaviour::{socket::asio::AsyncUdpSocket, timer::asio::AsyncTimer, Abort}; + use crate::behaviour::{Abort, socket::asio::AsyncUdpSocket, timer::asio::AsyncTimer}; #[doc(hidden)] pub enum AsyncIo {} @@ -125,7 +125,7 @@ pub mod tokio { use tokio::task::JoinHandle; use super::Provider; - use crate::behaviour::{socket::tokio::TokioUdpSocket, timer::tokio::TokioTimer, Abort}; + use crate::behaviour::{Abort, socket::tokio::TokioUdpSocket, timer::tokio::TokioTimer}; #[doc(hidden)] pub enum Tokio {} diff --git a/protocols/mdns/src/behaviour/iface.rs b/protocols/mdns/src/behaviour/iface.rs index 873bb8a307b..c4bba89e97e 100644 --- a/protocols/mdns/src/behaviour/iface.rs +++ b/protocols/mdns/src/behaviour/iface.rs @@ -32,7 +32,7 @@ use std::{ time::{Duration, Instant}, }; -use futures::{channel::mpsc, SinkExt, StreamExt}; +use futures::{SinkExt, StreamExt, channel::mpsc}; use libp2p_core::Multiaddr; use libp2p_identity::PeerId; use libp2p_swarm::ListenAddresses; @@ -43,8 +43,8 @@ use self::{ query::MdnsPacket, }; use crate::{ - behaviour::{socket::AsyncSocket, timer::Builder}, Config, + behaviour::{socket::AsyncSocket, timer::Builder}, }; /// Initial interval for starting probe diff --git a/protocols/mdns/src/behaviour/iface/dns.rs b/protocols/mdns/src/behaviour/iface/dns.rs index 35cba44f4af..9aa35905c81 100644 --- a/protocols/mdns/src/behaviour/iface/dns.rs +++ b/protocols/mdns/src/behaviour/iface/dns.rs @@ -24,7 +24,7 @@ use std::{borrow::Cow, cmp, error, fmt, str, time::Duration}; use libp2p_core::Multiaddr; use libp2p_identity::PeerId; -use rand::{distributions::Alphanumeric, thread_rng, Rng}; +use rand::{Rng, distributions::Alphanumeric, thread_rng}; use crate::{META_QUERY_SERVICE, SERVICE_NAME}; diff --git a/protocols/mdns/src/behaviour/iface/query.rs b/protocols/mdns/src/behaviour/iface/query.rs index a2a2c200b3b..9676bd5edc6 100644 --- a/protocols/mdns/src/behaviour/iface/query.rs +++ b/protocols/mdns/src/behaviour/iface/query.rs @@ -243,7 +243,7 @@ impl MdnsPeer { return None; } - if let RData::TXT(ref txt) = add_record.data() { + if let RData::TXT(txt) = add_record.data() { Some(txt) } else { None diff --git a/protocols/mdns/tests/use-async-std.rs b/protocols/mdns/tests/use-async-std.rs index df08b39af07..48f321d1821 100644 --- a/protocols/mdns/tests/use-async-std.rs +++ b/protocols/mdns/tests/use-async-std.rs @@ -21,7 +21,7 @@ use std::time::Duration; use futures::future::Either; -use libp2p_mdns::{async_io::Behaviour, Config, Event}; +use libp2p_mdns::{Config, Event, async_io::Behaviour}; use libp2p_swarm::{Swarm, SwarmEvent}; use libp2p_swarm_test::SwarmExt as _; use tracing_subscriber::EnvFilter; diff --git a/protocols/mdns/tests/use-tokio.rs b/protocols/mdns/tests/use-tokio.rs index 0ec90a52b90..c075cb42a0e 100644 --- a/protocols/mdns/tests/use-tokio.rs +++ b/protocols/mdns/tests/use-tokio.rs @@ -20,7 +20,7 @@ use std::time::Duration; use futures::future::Either; -use libp2p_mdns::{tokio::Behaviour, Config, Event}; +use libp2p_mdns::{Config, Event, tokio::Behaviour}; use libp2p_swarm::{Swarm, SwarmEvent}; use libp2p_swarm_test::SwarmExt as _; use tracing_subscriber::EnvFilter; diff --git a/protocols/perf/src/bin/perf.rs b/protocols/perf/src/bin/perf.rs index 506455f081a..803e1185139 100644 --- a/protocols/perf/src/bin/perf.rs +++ b/protocols/perf/src/bin/perf.rs @@ -20,16 +20,16 @@ use std::{net::SocketAddr, str::FromStr}; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use clap::Parser; use futures::StreamExt; use libp2p::{ - core::{multiaddr::Protocol, upgrade, Multiaddr}, + SwarmBuilder, + core::{Multiaddr, multiaddr::Protocol, upgrade}, identity::PeerId, swarm::{NetworkBehaviour, Swarm, SwarmEvent}, - SwarmBuilder, }; -use libp2p_perf::{client, server, Final, Intermediate, Run, RunParams, RunUpdate}; +use libp2p_perf::{Final, Intermediate, Run, RunParams, RunUpdate, client, server}; use serde::{Deserialize, Serialize}; use tracing_subscriber::EnvFilter; use web_time::{Duration, Instant}; diff --git a/protocols/perf/src/client/behaviour.rs b/protocols/perf/src/client/behaviour.rs index 86c85d61da9..c5a4355df24 100644 --- a/protocols/perf/src/client/behaviour.rs +++ b/protocols/perf/src/client/behaviour.rs @@ -25,15 +25,15 @@ use std::{ task::{Context, Poll}, }; -use libp2p_core::{transport::PortUse, Multiaddr}; +use libp2p_core::{Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ - derive_prelude::ConnectionEstablished, ConnectionClosed, ConnectionId, FromSwarm, - NetworkBehaviour, NotifyHandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + ConnectionClosed, ConnectionId, FromSwarm, NetworkBehaviour, NotifyHandler, THandlerInEvent, + THandlerOutEvent, ToSwarm, derive_prelude::ConnectionEstablished, }; use super::{RunError, RunId}; -use crate::{client::handler::Handler, RunParams, RunUpdate}; +use crate::{RunParams, RunUpdate, client::handler::Handler}; #[derive(Debug)] pub struct Event { diff --git a/protocols/perf/src/client/handler.rs b/protocols/perf/src/client/handler.rs index b45cdaa8208..619a391fd53 100644 --- a/protocols/perf/src/client/handler.rs +++ b/protocols/perf/src/client/handler.rs @@ -24,21 +24,21 @@ use std::{ }; use futures::{ - stream::{BoxStream, SelectAll}, StreamExt, + stream::{BoxStream, SelectAll}, }; use libp2p_core::upgrade::{DeniedUpgrade, ReadyUpgrade}; use libp2p_swarm::{ + ConnectionHandler, ConnectionHandlerEvent, StreamProtocol, SubstreamProtocol, handler::{ ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, ListenUpgradeError, }, - ConnectionHandler, ConnectionHandlerEvent, StreamProtocol, SubstreamProtocol, }; use crate::{ - client::{RunError, RunId}, RunParams, RunUpdate, + client::{RunError, RunId}, }; #[derive(Debug)] diff --git a/protocols/perf/src/protocol.rs b/protocols/perf/src/protocol.rs index c494761b8c8..ff2d070e7ac 100644 --- a/protocols/perf/src/protocol.rs +++ b/protocols/perf/src/protocol.rs @@ -21,8 +21,8 @@ use std::time::Duration; use futures::{ - future::{select, Either}, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, FutureExt, SinkExt, Stream, StreamExt, + future::{Either, select}, }; use futures_timer::Delay; use web_time::Instant; diff --git a/protocols/perf/src/server/behaviour.rs b/protocols/perf/src/server/behaviour.rs index 22466bfe56a..b3bccf9543e 100644 --- a/protocols/perf/src/server/behaviour.rs +++ b/protocols/perf/src/server/behaviour.rs @@ -31,7 +31,7 @@ use libp2p_swarm::{ ConnectionId, FromSwarm, NetworkBehaviour, THandlerInEvent, THandlerOutEvent, ToSwarm, }; -use crate::{server::handler::Handler, Run}; +use crate::{Run, server::handler::Handler}; #[derive(Debug)] pub struct Event { diff --git a/protocols/perf/src/server/handler.rs b/protocols/perf/src/server/handler.rs index 2748a5b6ad9..39048655071 100644 --- a/protocols/perf/src/server/handler.rs +++ b/protocols/perf/src/server/handler.rs @@ -26,11 +26,11 @@ use std::{ use futures::FutureExt; use libp2p_core::upgrade::{DeniedUpgrade, ReadyUpgrade}; use libp2p_swarm::{ + ConnectionHandler, ConnectionHandlerEvent, StreamProtocol, SubstreamProtocol, handler::{ ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, ListenUpgradeError, }, - ConnectionHandler, ConnectionHandlerEvent, StreamProtocol, SubstreamProtocol, }; use tracing::error; @@ -120,7 +120,7 @@ impl ConnectionHandler for Handler { loop { match self.inbound.poll_unpin(cx) { Poll::Ready(Ok(Ok(stats))) => { - return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(Event { stats })) + return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(Event { stats })); } Poll::Ready(Ok(Err(e))) => { error!("{e:?}"); diff --git a/protocols/perf/tests/lib.rs b/protocols/perf/tests/lib.rs index 017d475befd..b07674f1e7f 100644 --- a/protocols/perf/tests/lib.rs +++ b/protocols/perf/tests/lib.rs @@ -19,8 +19,9 @@ // DEALINGS IN THE SOFTWARE. use libp2p_perf::{ + RunParams, client::{self}, - server, RunParams, + server, }; use libp2p_swarm::{Swarm, SwarmEvent}; use libp2p_swarm_test::SwarmExt; diff --git a/protocols/ping/src/handler.rs b/protocols/ping/src/handler.rs index bc7c9d4e6bc..e1a27366687 100644 --- a/protocols/ping/src/handler.rs +++ b/protocols/ping/src/handler.rs @@ -34,12 +34,12 @@ use futures::{ use futures_timer::Delay; use libp2p_core::upgrade::ReadyUpgrade; use libp2p_swarm::{ - handler::{ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound}, ConnectionHandler, ConnectionHandlerEvent, Stream, StreamProtocol, StreamUpgradeError, SubstreamProtocol, + handler::{ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound}, }; -use crate::{protocol, PROTOCOL_NAME}; +use crate::{PROTOCOL_NAME, protocol}; /// The configuration for outbound pings. #[derive(Debug, Clone)] diff --git a/protocols/ping/src/lib.rs b/protocols/ping/src/lib.rs index d48bcbc98ab..a20aa636f71 100644 --- a/protocols/ping/src/lib.rs +++ b/protocols/ping/src/lib.rs @@ -62,11 +62,11 @@ use std::{ use handler::Handler; pub use handler::{Config, Failure}; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ - behaviour::FromSwarm, ConnectionDenied, ConnectionId, NetworkBehaviour, THandler, - THandlerInEvent, THandlerOutEvent, ToSwarm, + ConnectionDenied, ConnectionId, NetworkBehaviour, THandler, THandlerInEvent, THandlerOutEvent, + ToSwarm, behaviour::FromSwarm, }; pub use self::protocol::PROTOCOL_NAME; diff --git a/protocols/ping/src/protocol.rs b/protocols/ping/src/protocol.rs index 5e84f55e090..02dab4da66c 100644 --- a/protocols/ping/src/protocol.rs +++ b/protocols/ping/src/protocol.rs @@ -84,16 +84,16 @@ where mod tests { use futures::StreamExt; use libp2p_core::{ - multiaddr::multiaddr, - transport::{memory::MemoryTransport, DialOpts, ListenerId, PortUse, Transport}, Endpoint, + multiaddr::multiaddr, + transport::{DialOpts, ListenerId, PortUse, Transport, memory::MemoryTransport}, }; use super::*; #[tokio::test] async fn ping_pong() { - let mem_addr = multiaddr![Memory(thread_rng().gen::())]; + let mem_addr = multiaddr![Memory(thread_rng().r#gen::())]; let mut transport = MemoryTransport::new().boxed(); transport.listen_on(ListenerId::next(), mem_addr).unwrap(); diff --git a/protocols/ping/tests/ping.rs b/protocols/ping/tests/ping.rs index 210f9435e4a..561dc58635c 100644 --- a/protocols/ping/tests/ping.rs +++ b/protocols/ping/tests/ping.rs @@ -23,7 +23,7 @@ use std::{num::NonZeroU8, time::Duration}; use libp2p_ping as ping; -use libp2p_swarm::{dummy, Swarm, SwarmEvent}; +use libp2p_swarm::{Swarm, SwarmEvent, dummy}; use libp2p_swarm_test::SwarmExt; use quickcheck::*; diff --git a/protocols/relay/src/behaviour.rs b/protocols/relay/src/behaviour.rs index 9c768c6022d..98bd74c6ca5 100644 --- a/protocols/relay/src/behaviour.rs +++ b/protocols/relay/src/behaviour.rs @@ -23,7 +23,7 @@ pub(crate) mod handler; pub(crate) mod rate_limiter; use std::{ - collections::{hash_map, HashMap, HashSet, VecDeque}, + collections::{HashMap, HashSet, VecDeque, hash_map}, num::NonZeroU32, ops::Add, task::{Context, Poll}, @@ -31,12 +31,13 @@ use std::{ }; use either::Either; -use libp2p_core::{multiaddr::Protocol, transport::PortUse, ConnectedPoint, Endpoint, Multiaddr}; +use libp2p_core::{ConnectedPoint, Endpoint, Multiaddr, multiaddr::Protocol, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ + ConnectionDenied, ConnectionId, ExternalAddresses, NetworkBehaviour, NotifyHandler, THandler, + THandlerInEvent, THandlerOutEvent, ToSwarm, behaviour::{ConnectionClosed, FromSwarm}, - dummy, ConnectionDenied, ConnectionId, ExternalAddresses, NetworkBehaviour, NotifyHandler, - THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + dummy, }; use web_time::Instant; @@ -508,8 +509,7 @@ impl NetworkBehaviour for Behaviour { hash_map::Entry::Vacant(_) => { unreachable!( "Expect to track timed out reservation with peer {:?} on connection {:?}", - event_source, - connection, + event_source, connection, ); } } diff --git a/protocols/relay/src/behaviour/handler.rs b/protocols/relay/src/behaviour/handler.rs index fb80112e71c..2ec3d3e31fe 100644 --- a/protocols/relay/src/behaviour/handler.rs +++ b/protocols/relay/src/behaviour/handler.rs @@ -33,21 +33,21 @@ use futures::{ stream::{FuturesUnordered, StreamExt}, }; use futures_timer::Delay; -use libp2p_core::{upgrade::ReadyUpgrade, ConnectedPoint, Multiaddr}; +use libp2p_core::{ConnectedPoint, Multiaddr, upgrade::ReadyUpgrade}; use libp2p_identity::PeerId; use libp2p_swarm::{ - handler::{ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound}, ConnectionHandler, ConnectionHandlerEvent, ConnectionId, Stream, StreamProtocol, StreamUpgradeError, SubstreamProtocol, + handler::{ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound}, }; use web_time::Instant; use crate::{ + HOP_PROTOCOL_NAME, STOP_PROTOCOL_NAME, behaviour::CircuitId, copy_future::CopyFuture, proto, protocol::{inbound_hop, outbound_stop}, - HOP_PROTOCOL_NAME, STOP_PROTOCOL_NAME, }; const MAX_CONCURRENT_STREAMS_PER_CONNECTION: usize = 10; @@ -614,7 +614,7 @@ impl ConnectionHandler for Handler { dst_peer_id, error: None, }, - )) + )); } Err(e) => { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( @@ -623,7 +623,7 @@ impl ConnectionHandler for Handler { dst_peer_id, error: Some(e), }, - )) + )); } } } @@ -845,7 +845,7 @@ impl ConnectionHandler for Handler { Ok(()) => { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( Event::ReservationReqDenied {}, - )) + )); } Err(error) => { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( diff --git a/protocols/relay/src/copy_future.rs b/protocols/relay/src/copy_future.rs index ae7ef22d648..fc67b0c79c7 100644 --- a/protocols/relay/src/copy_future.rs +++ b/protocols/relay/src/copy_future.rs @@ -385,7 +385,8 @@ mod tests { "Expect `forward_data` to forward one read from the source to the wrapped destination." ); assert_eq!( - destination.get_ref().method_calls.as_slice(), &[], + destination.get_ref().method_calls.as_slice(), + &[], "Given that destination is wrapped with a `BufWrite`, the write doesn't (yet) make it to \ the destination. The source might have more data available, thus `forward_data` has not \ yet flushed.", @@ -399,7 +400,8 @@ mod tests { "Expect `forward_data` to forward one read from the source to the wrapped destination." ); assert_eq!( - destination.get_ref().method_calls.as_slice(), &[], + destination.get_ref().method_calls.as_slice(), + &[], "Given that destination is wrapped with a `BufWrite`, the write doesn't (yet) make it to \ the destination. The source might have more data available, thus `forward_data` has not \ yet flushed.", diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index dba07015765..75703e841fd 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -34,12 +34,12 @@ mod proto { include!("generated/mod.rs"); pub use self::message_v2::pb::mod_StopMessage::Type as StopMessageType; pub(crate) use self::message_v2::pb::{ - mod_HopMessage::Type as HopMessageType, HopMessage, Limit, Peer, Reservation, Status, - StopMessage, + HopMessage, Limit, Peer, Reservation, Status, StopMessage, + mod_HopMessage::Type as HopMessageType, }; } -pub use behaviour::{rate_limiter::RateLimiter, Behaviour, CircuitId, Config, Event}; +pub use behaviour::{Behaviour, CircuitId, Config, Event, rate_limiter::RateLimiter}; pub use protocol::{HOP_PROTOCOL_NAME, STOP_PROTOCOL_NAME}; /// Types related to the relay protocol inbound. @@ -64,7 +64,7 @@ pub mod outbound { /// Everything related to the relay protocol from a client's perspective. pub mod client { - pub use crate::priv_client::{new, transport::Transport, Behaviour, Connection, Event}; + pub use crate::priv_client::{Behaviour, Connection, Event, new, transport::Transport}; pub mod transport { pub use crate::priv_client::transport::Error; diff --git a/protocols/relay/src/multiaddr_ext.rs b/protocols/relay/src/multiaddr_ext.rs index 7c06eb7eab0..f9a1f71b4dc 100644 --- a/protocols/relay/src/multiaddr_ext.rs +++ b/protocols/relay/src/multiaddr_ext.rs @@ -1,4 +1,4 @@ -use libp2p_core::{multiaddr::Protocol, Multiaddr}; +use libp2p_core::{Multiaddr, multiaddr::Protocol}; pub(crate) trait MultiaddrExt { fn is_relayed(&self) -> bool; diff --git a/protocols/relay/src/priv_client.rs b/protocols/relay/src/priv_client.rs index 627c521320a..74bf2196f9a 100644 --- a/protocols/relay/src/priv_client.rs +++ b/protocols/relay/src/priv_client.rs @@ -24,7 +24,7 @@ pub(crate) mod handler; pub(crate) mod transport; use std::{ - collections::{hash_map, HashMap, VecDeque}, + collections::{HashMap, VecDeque, hash_map}, convert::Infallible, io::{Error, ErrorKind, IoSlice}, pin::Pin, @@ -40,13 +40,14 @@ use futures::{ ready, stream::StreamExt, }; -use libp2p_core::{multiaddr::Protocol, transport::PortUse, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, multiaddr::Protocol, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ + ConnectionDenied, ConnectionHandler, ConnectionId, DialFailure, NetworkBehaviour, + NotifyHandler, Stream, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, behaviour::{ConnectionClosed, ConnectionEstablished, FromSwarm}, dial_opts::DialOpts, - dummy, ConnectionDenied, ConnectionHandler, ConnectionId, DialFailure, NetworkBehaviour, - NotifyHandler, Stream, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + dummy, }; use transport::Transport; diff --git a/protocols/relay/src/priv_client/handler.rs b/protocols/relay/src/priv_client/handler.rs index 5f46dbf4460..3f5f3691b9b 100644 --- a/protocols/relay/src/priv_client/handler.rs +++ b/protocols/relay/src/priv_client/handler.rs @@ -31,21 +31,21 @@ use futures::{ future::FutureExt, }; use futures_timer::Delay; -use libp2p_core::{multiaddr::Protocol, upgrade::ReadyUpgrade, Multiaddr}; +use libp2p_core::{Multiaddr, multiaddr::Protocol, upgrade::ReadyUpgrade}; use libp2p_identity::PeerId; use libp2p_swarm::{ - handler::{ConnectionEvent, FullyNegotiatedInbound}, ConnectionHandler, ConnectionHandlerEvent, Stream, StreamProtocol, StreamUpgradeError, SubstreamProtocol, + handler::{ConnectionEvent, FullyNegotiatedInbound}, }; use crate::{ + HOP_PROTOCOL_NAME, STOP_PROTOCOL_NAME, client::Connection, priv_client, priv_client::{transport, transport::ToListenerMsg}, proto, protocol::{self, inbound_stop, outbound_hop}, - HOP_PROTOCOL_NAME, STOP_PROTOCOL_NAME, }; /// The maximum number of circuits being denied concurrently. diff --git a/protocols/relay/src/priv_client/transport.rs b/protocols/relay/src/priv_client/transport.rs index ed9faa946db..8de2a9afca1 100644 --- a/protocols/relay/src/priv_client/transport.rs +++ b/protocols/relay/src/priv_client/transport.rs @@ -27,7 +27,7 @@ use std::{ use futures::{ channel::{mpsc, oneshot}, - future::{ready, BoxFuture, FutureExt, Ready}, + future::{BoxFuture, FutureExt, Ready, ready}, sink::SinkExt, stream::{SelectAll, Stream, StreamExt}, }; @@ -39,13 +39,13 @@ use libp2p_identity::PeerId; use thiserror::Error; use crate::{ + RequestId, multiaddr_ext::MultiaddrExt, priv_client::Connection, protocol::{ outbound_hop, outbound_hop::{ConnectError, ReserveError}, }, - RequestId, }; /// A [`Transport`] enabling client relay capabilities. diff --git a/protocols/relay/src/protocol/outbound_hop.rs b/protocols/relay/src/protocol/outbound_hop.rs index 216c6d115bf..0b567ec7490 100644 --- a/protocols/relay/src/protocol/outbound_hop.rs +++ b/protocols/relay/src/protocol/outbound_hop.rs @@ -31,9 +31,8 @@ use thiserror::Error; use web_time::SystemTime; use crate::{ - proto, + HOP_PROTOCOL_NAME, proto, protocol::{Limit, MAX_MESSAGE_SIZE}, - HOP_PROTOCOL_NAME, }; #[derive(Debug, Error)] @@ -166,7 +165,7 @@ pub(crate) async fn make_reservation(stream: Stream) -> Result { return Err(ReserveError::Protocol(ProtocolViolation::UnexpectedStatus( s, - ))) + ))); } } diff --git a/protocols/relay/src/protocol/outbound_stop.rs b/protocols/relay/src/protocol/outbound_stop.rs index 272aa24eef6..0089d5bc384 100644 --- a/protocols/relay/src/protocol/outbound_stop.rs +++ b/protocols/relay/src/protocol/outbound_stop.rs @@ -27,7 +27,7 @@ use libp2p_identity::PeerId; use libp2p_swarm::Stream; use thiserror::Error; -use crate::{proto, protocol::MAX_MESSAGE_SIZE, STOP_PROTOCOL_NAME}; +use crate::{STOP_PROTOCOL_NAME, proto, protocol::MAX_MESSAGE_SIZE}; #[derive(Debug, Error)] pub enum Error { @@ -118,7 +118,7 @@ pub(crate) async fn connect( match type_pb { proto::StopMessageType::CONNECT => { - return Err(Error::Protocol(ProtocolViolation::UnexpectedTypeConnect)) + return Err(Error::Protocol(ProtocolViolation::UnexpectedTypeConnect)); } proto::StopMessageType::STATUS => {} } diff --git a/protocols/relay/tests/lib.rs b/protocols/relay/tests/lib.rs index 3181e60db74..4dd35c47ab8 100644 --- a/protocols/relay/tests/lib.rs +++ b/protocols/relay/tests/lib.rs @@ -30,7 +30,7 @@ use futures::{ use libp2p_core::{ multiaddr::{Multiaddr, Protocol}, muxing::StreamMuxerBox, - transport::{choice::OrTransport, Boxed, MemoryTransport, Transport}, + transport::{Boxed, MemoryTransport, Transport, choice::OrTransport}, upgrade, }; use libp2p_identity as identity; @@ -38,7 +38,7 @@ use libp2p_identity::PeerId; use libp2p_ping as ping; use libp2p_plaintext as plaintext; use libp2p_relay as relay; -use libp2p_swarm::{dial_opts::DialOpts, Config, DialError, NetworkBehaviour, Swarm, SwarmEvent}; +use libp2p_swarm::{Config, DialError, NetworkBehaviour, Swarm, SwarmEvent, dial_opts::DialOpts}; use libp2p_swarm_test::SwarmExt; use tracing_subscriber::EnvFilter; @@ -241,7 +241,7 @@ async fn connection_established_to( } if peer_id == relay_peer_id => {} SwarmEvent::ConnectionEstablished { peer_id, .. } if peer_id == relay_peer_id => {} SwarmEvent::Behaviour(ClientEvent::Ping(ping::Event { peer, .. })) if peer == other => { - break + break; } SwarmEvent::Behaviour(ClientEvent::Relay( relay::client::Event::OutboundCircuitEstablished { .. }, @@ -562,7 +562,7 @@ async fn wait_for_dial(client: &mut Swarm, remote: PeerId) -> bool { } if peer_id == remote => {} SwarmEvent::ConnectionEstablished { peer_id, .. } if peer_id == remote => return true, SwarmEvent::OutgoingConnectionError { peer_id, .. } if peer_id == Some(remote) => { - return false + return false; } SwarmEvent::Behaviour(ClientEvent::Ping(_)) => {} e => panic!("{e:?}"), diff --git a/protocols/rendezvous/src/client.rs b/protocols/rendezvous/src/client.rs index 086491bd2a6..b1fbf397ea0 100644 --- a/protocols/rendezvous/src/client.rs +++ b/protocols/rendezvous/src/client.rs @@ -29,7 +29,7 @@ use futures::{ future::{BoxFuture, FutureExt}, stream::{FuturesUnordered, StreamExt}, }; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr, PeerRecord}; +use libp2p_core::{Endpoint, Multiaddr, PeerRecord, transport::PortUse}; use libp2p_identity::{Keypair, PeerId, SigningError}; use libp2p_request_response::{OutboundRequestId, ProtocolSupport}; use libp2p_swarm::{ @@ -82,7 +82,7 @@ impl Behaviour { discovered_peers: Default::default(), registered_namespaces: Default::default(), expiring_registrations: FuturesUnordered::from_iter(vec![ - futures::future::pending().boxed() + futures::future::pending().boxed(), ]), external_addresses: Default::default(), } diff --git a/protocols/rendezvous/src/codec.rs b/protocols/rendezvous/src/codec.rs index 60f9f14f332..3bd13c12f63 100644 --- a/protocols/rendezvous/src/codec.rs +++ b/protocols/rendezvous/src/codec.rs @@ -23,7 +23,7 @@ use std::{fmt, io}; use async_trait::async_trait; use asynchronous_codec::{BytesMut, Decoder, Encoder, FramedRead, FramedWrite}; use futures::{AsyncRead, AsyncWrite, SinkExt, StreamExt}; -use libp2p_core::{peer_record, signed_envelope, PeerRecord, SignedEnvelope}; +use libp2p_core::{PeerRecord, SignedEnvelope, peer_record, signed_envelope}; use libp2p_swarm::StreamProtocol; use quick_protobuf_codec::Codec as ProtobufCodec; use rand::RngCore; @@ -639,7 +639,7 @@ pub struct UnmappableStatusCode(proto::ResponseStatus); mod proto { #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub(crate) use self::rendezvous::pb::{mod_Message::*, Message}; + pub(crate) use self::rendezvous::pb::{Message, mod_Message::*}; } #[cfg(test)] diff --git a/protocols/rendezvous/src/server.rs b/protocols/rendezvous/src/server.rs index 1be7220cfcb..bae513b86d6 100644 --- a/protocols/rendezvous/src/server.rs +++ b/protocols/rendezvous/src/server.rs @@ -21,23 +21,23 @@ use std::{ collections::{HashMap, HashSet}, iter, - task::{ready, Context, Poll}, + task::{Context, Poll, ready}, time::Duration, }; use bimap::BiMap; -use futures::{future::BoxFuture, stream::FuturesUnordered, FutureExt, StreamExt}; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr}; +use futures::{FutureExt, StreamExt, future::BoxFuture, stream::FuturesUnordered}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_request_response::ProtocolSupport; use libp2p_swarm::{ - behaviour::FromSwarm, ConnectionDenied, ConnectionId, NetworkBehaviour, THandler, - THandlerInEvent, THandlerOutEvent, ToSwarm, + ConnectionDenied, ConnectionId, NetworkBehaviour, THandler, THandlerInEvent, THandlerOutEvent, + ToSwarm, behaviour::FromSwarm, }; use crate::{ - codec::{Cookie, ErrorCode, Message, Namespace, NewRegistration, Registration, Ttl}, MAX_TTL, MIN_TTL, + codec::{Cookie, ErrorCode, Message, Namespace, NewRegistration, Registration, Ttl}, }; pub struct Behaviour { @@ -456,7 +456,7 @@ impl Registrations { (None, Some(_)) => return Err(CookieNamespaceMismatch), // discover for a namespace but cookie is for a different namespace? => bad (Some(namespace), Some(cookie_namespace)) if namespace != cookie_namespace => { - return Err(CookieNamespaceMismatch) + return Err(CookieNamespaceMismatch); } // every other combination is fine _ => {} diff --git a/protocols/rendezvous/tests/rendezvous.rs b/protocols/rendezvous/tests/rendezvous.rs index 09da179c691..6d8cf7aabd4 100644 --- a/protocols/rendezvous/tests/rendezvous.rs +++ b/protocols/rendezvous/tests/rendezvous.rs @@ -20,8 +20,8 @@ use std::time::Duration; -use futures::{stream::FuturesUnordered, StreamExt}; -use libp2p_core::{multiaddr::Protocol, Multiaddr}; +use futures::{StreamExt, stream::FuturesUnordered}; +use libp2p_core::{Multiaddr, multiaddr::Protocol}; use libp2p_identity as identity; use libp2p_rendezvous as rendezvous; use libp2p_rendezvous::client::RegisterError; @@ -45,11 +45,13 @@ async fn given_successful_registration_then_successful_discovery() { match libp2p_swarm_test::drive(&mut alice, &mut robert).await { ( - [rendezvous::client::Event::Registered { - rendezvous_node, - ttl, - namespace: register_node_namespace, - }], + [ + rendezvous::client::Event::Registered { + rendezvous_node, + ttl, + namespace: register_node_namespace, + }, + ], [rendezvous::server::Event::PeerRegistered { peer, registration }], ) => { assert_eq!(&peer, alice.local_peer_id()); @@ -69,11 +71,13 @@ async fn given_successful_registration_then_successful_discovery() { [rendezvous::client::Event::Discovered { registrations, .. }], [rendezvous::server::Event::DiscoverServed { .. }], ) => match registrations.as_slice() { - [rendezvous::Registration { - namespace: registered_namespace, - record, - ttl, - }] => { + [ + rendezvous::Registration { + namespace: registered_namespace, + record, + ttl, + }, + ] => { assert_eq!(*ttl, rendezvous::DEFAULT_TTL); assert_eq!(record.peer_id(), *alice.local_peer_id()); assert_eq!(*registered_namespace, namespace); @@ -324,9 +328,11 @@ async fn eve_cannot_register() { match libp2p_swarm_test::drive(&mut eve, &mut robert).await { ( - [rendezvous::client::Event::RegisterFailed { - error: err_code, .. - }], + [ + rendezvous::client::Event::RegisterFailed { + error: err_code, .. + }, + ], [rendezvous::server::Event::PeerNotRegistered { .. }], ) => { assert_eq!(err_code, rendezvous::ErrorCode::NotAuthorized); diff --git a/protocols/request-response/src/cbor.rs b/protocols/request-response/src/cbor.rs index f20fbfb5dff..d2defbe33c2 100644 --- a/protocols/request-response/src/cbor.rs +++ b/protocols/request-response/src/cbor.rs @@ -62,7 +62,7 @@ pub mod codec { use cbor4ii::core::error::DecodeError; use futures::prelude::*; use libp2p_swarm::StreamProtocol; - use serde::{de::DeserializeOwned, Serialize}; + use serde::{Serialize, de::DeserializeOwned}; pub struct Codec { /// Max request size in bytes. @@ -207,7 +207,7 @@ mod tests { use libp2p_swarm::StreamProtocol; use serde::{Deserialize, Serialize}; - use crate::{cbor::codec::Codec, Codec as _}; + use crate::{Codec as _, cbor::codec::Codec}; #[async_std::test] async fn test_codec() { diff --git a/protocols/request-response/src/handler.rs b/protocols/request-response/src/handler.rs index b7992abe9c8..a42a871f529 100644 --- a/protocols/request-response/src/handler.rs +++ b/protocols/request-response/src/handler.rs @@ -24,8 +24,8 @@ use std::{ collections::VecDeque, fmt, io, sync::{ - atomic::{AtomicU64, Ordering}, Arc, + atomic::{AtomicU64, Ordering}, }, task::{Context, Poll}, time::Duration, @@ -36,18 +36,18 @@ use futures::{ prelude::*, }; use libp2p_swarm::{ + SubstreamProtocol, handler::{ ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, ListenUpgradeError, StreamUpgradeError, }, - SubstreamProtocol, }; pub use protocol::ProtocolSupport; use smallvec::SmallVec; use crate::{ - codec::Codec, handler::protocol::Protocol, InboundRequestId, OutboundRequestId, - EMPTY_QUEUE_SHRINK_THRESHOLD, + EMPTY_QUEUE_SHRINK_THRESHOLD, InboundRequestId, OutboundRequestId, codec::Codec, + handler::protocol::Protocol, }; /// A connection handler for a request response [`Behaviour`](super::Behaviour) protocol. diff --git a/protocols/request-response/src/handler/protocol.rs b/protocols/request-response/src/handler/protocol.rs index a55faec2f16..809d680f0ed 100644 --- a/protocols/request-response/src/handler/protocol.rs +++ b/protocols/request-response/src/handler/protocol.rs @@ -25,7 +25,7 @@ use std::convert::Infallible; -use futures::future::{ready, Ready}; +use futures::future::{Ready, ready}; use libp2p_core::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}; use libp2p_swarm::Stream; use smallvec::SmallVec; diff --git a/protocols/request-response/src/json.rs b/protocols/request-response/src/json.rs index 4e55f1593e7..8f24fab7400 100644 --- a/protocols/request-response/src/json.rs +++ b/protocols/request-response/src/json.rs @@ -61,7 +61,7 @@ pub mod codec { use async_trait::async_trait; use futures::prelude::*; use libp2p_swarm::StreamProtocol; - use serde::{de::DeserializeOwned, Serialize}; + use serde::{Serialize, de::DeserializeOwned}; pub struct Codec { /// Max request size in bytes diff --git a/protocols/request-response/src/lib.rs b/protocols/request-response/src/lib.rs index 7fba089b04e..7b6a939976a 100644 --- a/protocols/request-response/src/lib.rs +++ b/protocols/request-response/src/lib.rs @@ -76,7 +76,7 @@ pub mod json; use std::{ collections::{HashMap, HashSet, VecDeque}, fmt, io, - sync::{atomic::AtomicU64, Arc}, + sync::{Arc, atomic::AtomicU64}, task::{Context, Poll}, time::Duration, }; @@ -85,13 +85,13 @@ pub use codec::Codec; use futures::channel::oneshot; use handler::Handler; pub use handler::ProtocolSupport; -use libp2p_core::{transport::PortUse, ConnectedPoint, Endpoint, Multiaddr}; +use libp2p_core::{ConnectedPoint, Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ - behaviour::{AddressChange, ConnectionClosed, DialFailure, FromSwarm}, - dial_opts::DialOpts, ConnectionDenied, ConnectionHandler, ConnectionId, NetworkBehaviour, NotifyHandler, PeerAddresses, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + behaviour::{AddressChange, ConnectionClosed, DialFailure, FromSwarm}, + dial_opts::DialOpts, }; use smallvec::SmallVec; @@ -879,7 +879,9 @@ where })); } None => { - tracing::debug!("Connection ({connection_id}) closed after `Event::Request` ({request_id}) has been emitted."); + tracing::debug!( + "Connection ({connection_id}) closed after `Event::Request` ({request_id}) has been emitted." + ); } }, handler::Event::ResponseSent(request_id) => { @@ -991,7 +993,9 @@ where })); } else { // This happens when `read_request` fails. - tracing::debug!("Inbound failure is reported for an unknown request_id ({request_id}): {error}"); + tracing::debug!( + "Inbound failure is reported for an unknown request_id ({request_id}): {error}" + ); } } } diff --git a/protocols/request-response/tests/error_reporting.rs b/protocols/request-response/tests/error_reporting.rs index 2108b6006c5..9fc544cc836 100644 --- a/protocols/request-response/tests/error_reporting.rs +++ b/protocols/request-response/tests/error_reporting.rs @@ -1,6 +1,6 @@ use std::{io, iter, pin::pin, time::Duration}; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use async_std::task::sleep; use async_trait::async_trait; use futures::prelude::*; diff --git a/protocols/request-response/tests/ping.rs b/protocols/request-response/tests/ping.rs index 94adedac2d7..18cc33be3b6 100644 --- a/protocols/request-response/tests/ping.rs +++ b/protocols/request-response/tests/ping.rs @@ -75,12 +75,16 @@ async fn is_response_outbound() { let request_id2 = swarm1.behaviour_mut().send_request(&offline_peer, ping); - assert!(!swarm1 - .behaviour() - .is_pending_outbound(&offline_peer, &request_id1)); - assert!(swarm1 - .behaviour() - .is_pending_outbound(&offline_peer, &request_id2)); + assert!( + !swarm1 + .behaviour() + .is_pending_outbound(&offline_peer, &request_id1) + ); + assert!( + swarm1 + .behaviour() + .is_pending_outbound(&offline_peer, &request_id2) + ); } /// Exercises a simple ping protocol. diff --git a/protocols/stream/src/behaviour.rs b/protocols/stream/src/behaviour.rs index e72af8fbfce..16360ac3eb0 100644 --- a/protocols/stream/src/behaviour.rs +++ b/protocols/stream/src/behaviour.rs @@ -4,19 +4,19 @@ use std::{ task::{Context, Poll}, }; -use futures::{channel::mpsc, StreamExt}; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr}; +use futures::{StreamExt, channel::mpsc}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use libp2p_swarm::{ - self as swarm, dial_opts::DialOpts, ConnectionDenied, ConnectionId, FromSwarm, - NetworkBehaviour, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + self as swarm, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, + THandlerInEvent, THandlerOutEvent, ToSwarm, dial_opts::DialOpts, }; use swarm::{ - behaviour::ConnectionEstablished, dial_opts::PeerCondition, ConnectionClosed, DialError, - DialFailure, + ConnectionClosed, DialError, DialFailure, behaviour::ConnectionEstablished, + dial_opts::PeerCondition, }; -use crate::{handler::Handler, shared::Shared, Control}; +use crate::{Control, handler::Handler, shared::Shared}; /// A generic behaviour for stream-oriented protocols. pub struct Behaviour { diff --git a/protocols/stream/src/control.rs b/protocols/stream/src/control.rs index 2149c6bca48..bea15778a18 100644 --- a/protocols/stream/src/control.rs +++ b/protocols/stream/src/control.rs @@ -7,13 +7,13 @@ use std::{ }; use futures::{ - channel::{mpsc, oneshot}, SinkExt as _, StreamExt as _, + channel::{mpsc, oneshot}, }; use libp2p_identity::PeerId; use libp2p_swarm::{Stream, StreamProtocol}; -use crate::{handler::NewStream, shared::Shared, AlreadyRegistered}; +use crate::{AlreadyRegistered, handler::NewStream, shared::Shared}; /// A (remote) control for opening new streams and registration of inbound protocols. /// diff --git a/protocols/stream/src/handler.rs b/protocols/stream/src/handler.rs index a0255c7cba6..10747ebae6d 100644 --- a/protocols/stream/src/handler.rs +++ b/protocols/stream/src/handler.rs @@ -6,17 +6,16 @@ use std::{ }; use futures::{ - channel::{mpsc, oneshot}, StreamExt as _, + channel::{mpsc, oneshot}, }; use libp2p_identity::PeerId; use libp2p_swarm::{ - self as swarm, + self as swarm, ConnectionHandler, Stream, StreamProtocol, handler::{ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound}, - ConnectionHandler, Stream, StreamProtocol, }; -use crate::{shared::Shared, upgrade::Upgrade, OpenStreamError}; +use crate::{OpenStreamError, shared::Shared, upgrade::Upgrade}; pub struct Handler { remote: PeerId, diff --git a/protocols/stream/src/shared.rs b/protocols/stream/src/shared.rs index 62d7b3cfe68..a01d388b879 100644 --- a/protocols/stream/src/shared.rs +++ b/protocols/stream/src/shared.rs @@ -1,5 +1,5 @@ use std::{ - collections::{hash_map::Entry, HashMap}, + collections::{HashMap, hash_map::Entry}, io, sync::{Arc, Mutex, MutexGuard}, }; @@ -9,7 +9,7 @@ use libp2p_identity::PeerId; use libp2p_swarm::{ConnectionId, Stream, StreamProtocol}; use rand::seq::IteratorRandom as _; -use crate::{handler::NewStream, AlreadyRegistered, IncomingStreams}; +use crate::{AlreadyRegistered, IncomingStreams, handler::NewStream}; pub(crate) struct Shared { /// Tracks the supported inbound protocols created via diff --git a/protocols/stream/src/upgrade.rs b/protocols/stream/src/upgrade.rs index bbe679f4a2c..69fa8d30ab1 100644 --- a/protocols/stream/src/upgrade.rs +++ b/protocols/stream/src/upgrade.rs @@ -1,6 +1,6 @@ use std::{ convert::Infallible, - future::{ready, Ready}, + future::{Ready, ready}, }; use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}; diff --git a/protocols/upnp/src/behaviour.rs b/protocols/upnp/src/behaviour.rs index a9db65e263a..3e06c38f177 100644 --- a/protocols/upnp/src/behaviour.rs +++ b/protocols/upnp/src/behaviour.rs @@ -32,20 +32,19 @@ use std::{ time::Duration, }; -use futures::{channel::oneshot, Future, StreamExt}; +use futures::{Future, StreamExt, channel::oneshot}; use futures_timer::Delay; use igd_next::PortMappingProtocol; use libp2p_core::{ - multiaddr, + Endpoint, Multiaddr, multiaddr, transport::{ListenerId, PortUse}, - Endpoint, Multiaddr, }; use libp2p_swarm::{ - derive_prelude::PeerId, dummy, ConnectionDenied, ConnectionId, ExpiredListenAddr, FromSwarm, - NetworkBehaviour, NewListenAddr, ToSwarm, + ConnectionDenied, ConnectionId, ExpiredListenAddr, FromSwarm, NetworkBehaviour, NewListenAddr, + ToSwarm, derive_prelude::PeerId, dummy, }; -use crate::tokio::{is_addr_global, Gateway}; +use crate::tokio::{Gateway, is_addr_global}; /// The duration in seconds of a port mapping on the gateway. const MAPPING_DURATION: u32 = 3600; @@ -298,7 +297,7 @@ impl NetworkBehaviour for Behaviour { MappingState::Inactive, ); } - GatewayState::Available(ref mut gateway) => { + GatewayState::Available(gateway) => { let mapping = Mapping { listener_id, protocol, @@ -340,7 +339,7 @@ impl NetworkBehaviour for Behaviour { listener_id, addr: _addr, }) => { - if let GatewayState::Available(ref mut gateway) = &mut self.state { + if let GatewayState::Available(gateway) = &mut self.state { if let Some((mapping, _state)) = self.mappings.remove_entry(&listener_id) { if let Err(err) = gateway .sender diff --git a/protocols/upnp/src/tokio.rs b/protocols/upnp/src/tokio.rs index 67ef52f9608..1fce2789cd5 100644 --- a/protocols/upnp/src/tokio.rs +++ b/protocols/upnp/src/tokio.rs @@ -21,8 +21,8 @@ use std::{error::Error, net::IpAddr}; use futures::{ - channel::{mpsc, oneshot}, SinkExt, StreamExt, + channel::{mpsc, oneshot}, }; use igd_next::SearchOptions; diff --git a/swarm-derive/src/lib.rs b/swarm-derive/src/lib.rs index 871f0b5815e..f18779d78aa 100644 --- a/swarm-derive/src/lib.rs +++ b/swarm-derive/src/lib.rs @@ -26,7 +26,7 @@ mod syn_ext; use heck::ToUpperCamelCase; use proc_macro::TokenStream; use quote::quote; -use syn::{parse_macro_input, punctuated::Punctuated, Data, DataStruct, DeriveInput, Meta, Token}; +use syn::{Data, DataStruct, DeriveInput, Meta, Token, parse_macro_input, punctuated::Punctuated}; use crate::syn_ext::RequireStrLit; diff --git a/swarm-test/src/lib.rs b/swarm-test/src/lib.rs index 0bc417dd8b1..6e7f16c0dda 100644 --- a/swarm-test/src/lib.rs +++ b/swarm-test/src/lib.rs @@ -22,14 +22,14 @@ use std::{fmt::Debug, future::IntoFuture, time::Duration}; use async_trait::async_trait; use futures::{ - future::{BoxFuture, Either}, FutureExt, StreamExt, + future::{BoxFuture, Either}, }; -use libp2p_core::{multiaddr::Protocol, Multiaddr}; +use libp2p_core::{Multiaddr, multiaddr::Protocol}; use libp2p_identity::PeerId; use libp2p_swarm::{ - dial_opts::{DialOpts, PeerCondition}, NetworkBehaviour, Swarm, SwarmEvent, + dial_opts::{DialOpts, PeerCondition}, }; /// An extension trait for [`Swarm`] that makes it @@ -228,7 +228,7 @@ where where Self: Sized, { - use libp2p_core::{transport::MemoryTransport, upgrade::Version, Transport as _}; + use libp2p_core::{Transport as _, transport::MemoryTransport, upgrade::Version}; use libp2p_identity::Keypair; let identity = Keypair::generate_ed25519(); @@ -255,7 +255,7 @@ where where Self: Sized, { - use libp2p_core::{transport::MemoryTransport, upgrade::Version, Transport as _}; + use libp2p_core::{Transport as _, transport::MemoryTransport, upgrade::Version}; use libp2p_identity::Keypair; let identity = Keypair::generate_ed25519(); diff --git a/swarm/benches/connection_handler.rs b/swarm/benches/connection_handler.rs index 3ae75288208..6d11fd1bc34 100644 --- a/swarm/benches/connection_handler.rs +++ b/swarm/benches/connection_handler.rs @@ -1,9 +1,9 @@ use std::{convert::Infallible, sync::atomic::AtomicUsize}; use async_std::stream::StreamExt; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use libp2p_core::{ - transport::MemoryTransport, InboundUpgrade, Multiaddr, OutboundUpgrade, Transport, UpgradeInfo, + InboundUpgrade, Multiaddr, OutboundUpgrade, Transport, UpgradeInfo, transport::MemoryTransport, }; use libp2p_identity::PeerId; use libp2p_swarm::{ConnectionHandler, NetworkBehaviour, StreamProtocol}; diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index 8c8c5998f67..a333851e892 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -28,17 +28,17 @@ use std::task::{Context, Poll}; pub use external_addresses::ExternalAddresses; use libp2p_core::{ - transport::{ListenerId, PortUse}, ConnectedPoint, Endpoint, Multiaddr, + transport::{ListenerId, PortUse}, }; use libp2p_identity::PeerId; pub use listen_addresses::ListenAddresses; pub use peer_addresses::PeerAddresses; use crate::{ - connection::ConnectionId, dial_opts::DialOpts, listen_opts::ListenOpts, ConnectionDenied, - ConnectionError, ConnectionHandler, DialError, ListenError, THandler, THandlerInEvent, - THandlerOutEvent, + ConnectionDenied, ConnectionError, ConnectionHandler, DialError, ListenError, THandler, + THandlerInEvent, THandlerOutEvent, connection::ConnectionId, dial_opts::DialOpts, + listen_opts::ListenOpts, }; /// A [`NetworkBehaviour`] defines the behaviour of the local node on the network. @@ -227,7 +227,7 @@ pub trait NetworkBehaviour: 'static { /// This API mimics the API of the `Stream` trait. The method may register the current task in /// order to wake it up at a later point in time. fn poll(&mut self, cx: &mut Context<'_>) - -> Poll>>; + -> Poll>>; } /// A command issued from a [`NetworkBehaviour`] for the [`Swarm`]. diff --git a/swarm/src/behaviour/either.rs b/swarm/src/behaviour/either.rs index b9a86e1b9d8..abc79eb137e 100644 --- a/swarm/src/behaviour/either.rs +++ b/swarm/src/behaviour/either.rs @@ -21,13 +21,13 @@ use std::task::{Context, Poll}; use either::Either; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse}; use libp2p_identity::PeerId; use crate::{ + ConnectionDenied, THandler, THandlerInEvent, THandlerOutEvent, behaviour::{self, NetworkBehaviour, ToSwarm}, connection::ConnectionId, - ConnectionDenied, THandler, THandlerInEvent, THandlerOutEvent, }; /// Implementation of [`NetworkBehaviour`] that can be either of two implementations. diff --git a/swarm/src/behaviour/peer_addresses.rs b/swarm/src/behaviour/peer_addresses.rs index 6069c270173..7654d2cd34b 100644 --- a/swarm/src/behaviour/peer_addresses.rs +++ b/swarm/src/behaviour/peer_addresses.rs @@ -4,7 +4,7 @@ use libp2p_core::Multiaddr; use libp2p_identity::PeerId; use lru::LruCache; -use crate::{behaviour::FromSwarm, DialError, DialFailure, NewExternalAddrOfPeer}; +use crate::{DialError, DialFailure, NewExternalAddrOfPeer, behaviour::FromSwarm}; /// Struct for tracking peers' external addresses of the [`Swarm`](crate::Swarm). #[derive(Debug)] @@ -99,7 +99,7 @@ mod tests { use libp2p_core::{ multiaddr::Protocol, - transport::{memory::MemoryTransportError, TransportError}, + transport::{TransportError, memory::MemoryTransportError}, }; use super::*; diff --git a/swarm/src/behaviour/toggle.rs b/swarm/src/behaviour/toggle.rs index 03cf062416f..3a30acccebb 100644 --- a/swarm/src/behaviour/toggle.rs +++ b/swarm/src/behaviour/toggle.rs @@ -22,10 +22,11 @@ use std::task::{Context, Poll}; use either::Either; use futures::future; -use libp2p_core::{transport::PortUse, upgrade::DeniedUpgrade, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse, upgrade::DeniedUpgrade}; use libp2p_identity::PeerId; use crate::{ + ConnectionDenied, NetworkBehaviour, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, behaviour::FromSwarm, connection::ConnectionId, handler::{ @@ -34,7 +35,6 @@ use crate::{ SubstreamProtocol, }, upgrade::SendWrapper, - ConnectionDenied, NetworkBehaviour, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, }; /// Implementation of `NetworkBehaviour` that can be either in the disabled or enabled state. diff --git a/swarm/src/connection.rs b/swarm/src/connection.rs index f0bac724942..85380e87ff6 100644 --- a/swarm/src/connection.rs +++ b/swarm/src/connection.rs @@ -37,22 +37,23 @@ use std::{ pub use error::ConnectionError; pub(crate) use error::{PendingInboundConnectionError, PendingOutboundConnectionError}; -use futures::{future::BoxFuture, stream, stream::FuturesUnordered, FutureExt, StreamExt}; +use futures::{FutureExt, StreamExt, future::BoxFuture, stream, stream::FuturesUnordered}; use futures_timer::Delay; use libp2p_core::{ + Endpoint, connection::ConnectedPoint, multiaddr::Multiaddr, muxing::{StreamMuxerBox, StreamMuxerEvent, StreamMuxerExt, SubstreamBox}, transport::PortUse, upgrade, upgrade::{NegotiationError, ProtocolError}, - Endpoint, }; use libp2p_identity::PeerId; pub use supported_protocols::SupportedProtocols; use web_time::Instant; use crate::{ + ConnectionHandlerEvent, Stream, StreamProtocol, StreamUpgradeError, SubstreamProtocol, handler::{ AddressChange, ConnectionEvent, ConnectionHandler, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, ListenUpgradeError, ProtocolSupport, @@ -60,7 +61,6 @@ use crate::{ }, stream::ActiveStreamCounter, upgrade::{InboundUpgradeSend, OutboundUpgradeSend}, - ConnectionHandlerEvent, Stream, StreamProtocol, StreamUpgradeError, SubstreamProtocol, }; static NEXT_CONNECTION_ID: AtomicUsize = AtomicUsize::new(1); @@ -392,7 +392,7 @@ where Shutdown::Asap => return Poll::Ready(Err(ConnectionError::KeepAliveTimeout)), Shutdown::Later(delay) => match Future::poll(Pin::new(delay), cx) { Poll::Ready(_) => { - return Poll::Ready(Err(ConnectionError::KeepAliveTimeout)) + return Poll::Ready(Err(ConnectionError::KeepAliveTimeout)); } Poll::Pending => {} }, @@ -653,7 +653,7 @@ impl Future for StreamUpgrade { .take() .expect("Future not to be polled again once ready."), Err(StreamUpgradeError::Timeout), - )) + )); } Poll::Pending => {} @@ -789,10 +789,10 @@ mod tests { time::Instant, }; - use futures::{future, AsyncRead, AsyncWrite}; + use futures::{AsyncRead, AsyncWrite, future}; use libp2p_core::{ - upgrade::{DeniedUpgrade, InboundUpgrade, OutboundUpgrade, UpgradeInfo}, StreamMuxer, + upgrade::{DeniedUpgrade, InboundUpgrade, OutboundUpgrade, UpgradeInfo}, }; use quickcheck::*; use tracing_subscriber::EnvFilter; diff --git a/swarm/src/connection/error.rs b/swarm/src/connection/error.rs index 6049849880f..8c59cd5ef36 100644 --- a/swarm/src/connection/error.rs +++ b/swarm/src/connection/error.rs @@ -20,7 +20,7 @@ use std::{fmt, io}; -use crate::{transport::TransportError, Multiaddr, PeerId}; +use crate::{Multiaddr, PeerId, transport::TransportError}; /// Errors that can occur in the context of an established `Connection`. #[derive(Debug)] diff --git a/swarm/src/connection/pool.rs b/swarm/src/connection/pool.rs index a0fcfa085af..1d2c2945959 100644 --- a/swarm/src/connection/pool.rs +++ b/swarm/src/connection/pool.rs @@ -31,7 +31,7 @@ use concurrent_dial::ConcurrentDial; use fnv::FnvHashMap; use futures::{ channel::{mpsc, oneshot}, - future::{poll_fn, BoxFuture, Either}, + future::{BoxFuture, Either, poll_fn}, prelude::*, ready, stream::{FuturesUnordered, SelectAll}, @@ -45,12 +45,12 @@ use tracing::Instrument; use web_time::{Duration, Instant}; use crate::{ + ConnectedPoint, ConnectionHandler, Executor, Multiaddr, PeerId, connection::{ Connected, Connection, ConnectionError, ConnectionId, IncomingInfo, PendingInboundConnectionError, PendingOutboundConnectionError, PendingPoint, }, transport::TransportError, - ConnectedPoint, ConnectionHandler, Executor, Multiaddr, PeerId, }; mod concurrent_dial; @@ -703,7 +703,9 @@ where peer: Some(peer), }) } - ConnectedPoint::Listener {.. } => unreachable!("There shouldn't be an expected PeerId on inbound connections."), + ConnectedPoint::Listener { .. } => unreachable!( + "There shouldn't be an expected PeerId on inbound connections." + ), }; } } diff --git a/swarm/src/connection/pool/concurrent_dial.rs b/swarm/src/connection/pool/concurrent_dial.rs index 99f0b385884..7682b2e0355 100644 --- a/swarm/src/connection/pool/concurrent_dial.rs +++ b/swarm/src/connection/pool/concurrent_dial.rs @@ -32,7 +32,7 @@ use futures::{ use libp2p_core::muxing::StreamMuxerBox; use libp2p_identity::PeerId; -use crate::{transport::TransportError, Multiaddr}; +use crate::{Multiaddr, transport::TransportError}; type Dial = BoxFuture< 'static, diff --git a/swarm/src/connection/pool/task.rs b/swarm/src/connection/pool/task.rs index c3f15e8ede7..846b81c0702 100644 --- a/swarm/src/connection/pool/task.rs +++ b/swarm/src/connection/pool/task.rs @@ -24,20 +24,20 @@ use std::{convert::Infallible, pin::Pin}; use futures::{ - channel::{mpsc, oneshot}, - future::{poll_fn, Either, Future}, SinkExt, StreamExt, + channel::{mpsc, oneshot}, + future::{Either, Future, poll_fn}, }; use libp2p_core::muxing::StreamMuxerBox; use super::concurrent_dial::ConcurrentDial; use crate::{ + ConnectionHandler, Multiaddr, PeerId, connection::{ self, ConnectionError, ConnectionId, PendingInboundConnectionError, PendingOutboundConnectionError, }, transport::TransportError, - ConnectionHandler, Multiaddr, PeerId, }; /// Commands that can be sent to a task driving an established connection. diff --git a/swarm/src/connection/supported_protocols.rs b/swarm/src/connection/supported_protocols.rs index c167bf88649..95aa6ca2fb6 100644 --- a/swarm/src/connection/supported_protocols.rs +++ b/swarm/src/connection/supported_protocols.rs @@ -1,6 +1,6 @@ use std::collections::HashSet; -use crate::{handler::ProtocolsChange, StreamProtocol}; +use crate::{StreamProtocol, handler::ProtocolsChange}; #[derive(Default, Clone, Debug)] pub struct SupportedProtocols { diff --git a/swarm/src/dial_opts.rs b/swarm/src/dial_opts.rs index f569a38df1c..f9358f47a5d 100644 --- a/swarm/src/dial_opts.rs +++ b/swarm/src/dial_opts.rs @@ -21,7 +21,7 @@ use std::num::NonZeroU8; -use libp2p_core::{connection::Endpoint, multiaddr::Protocol, transport::PortUse, Multiaddr}; +use libp2p_core::{Multiaddr, connection::Endpoint, multiaddr::Protocol, transport::PortUse}; use libp2p_identity::PeerId; use crate::ConnectionId; diff --git a/swarm/src/dummy.rs b/swarm/src/dummy.rs index e6f12b41d2c..2f4f1f2fb1b 100644 --- a/swarm/src/dummy.rs +++ b/swarm/src/dummy.rs @@ -3,15 +3,15 @@ use std::{ task::{Context, Poll}, }; -use libp2p_core::{transport::PortUse, upgrade::DeniedUpgrade, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse, upgrade::DeniedUpgrade}; use libp2p_identity::PeerId; use crate::{ + ConnectionDenied, ConnectionHandlerEvent, StreamUpgradeError, SubstreamProtocol, THandler, + THandlerInEvent, THandlerOutEvent, behaviour::{FromSwarm, NetworkBehaviour, ToSwarm}, connection::ConnectionId, handler::{ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound}, - ConnectionDenied, ConnectionHandlerEvent, StreamUpgradeError, SubstreamProtocol, THandler, - THandlerInEvent, THandlerOutEvent, }; /// Implementation of [`NetworkBehaviour`] that doesn't do anything. diff --git a/swarm/src/handler.rs b/swarm/src/handler.rs index 0e4d1f5a325..d58f2a6f692 100644 --- a/swarm/src/handler.rs +++ b/swarm/src/handler.rs @@ -63,7 +63,7 @@ pub use select::ConnectionHandlerSelect; use smallvec::SmallVec; pub use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper, UpgradeInfoSend}; -use crate::{connection::AsStrHashEq, StreamProtocol}; +use crate::{StreamProtocol, connection::AsStrHashEq}; /// A handler for a set of protocols used on a connection with a remote. /// diff --git a/swarm/src/handler/multi.rs b/swarm/src/handler/multi.rs index 73af1b1109e..84074cc6e3f 100644 --- a/swarm/src/handler/multi.rs +++ b/swarm/src/handler/multi.rs @@ -36,13 +36,13 @@ use futures::{future::BoxFuture, prelude::*, ready}; use rand::Rng; use crate::{ + Stream, handler::{ AddressChange, ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, ListenUpgradeError, SubstreamProtocol, }, upgrade::{InboundUpgradeSend, OutboundUpgradeSend, UpgradeInfoSend}, - Stream, }; /// A [`ConnectionHandler`] for multiple [`ConnectionHandler`]s of the same type. diff --git a/swarm/src/handler/one_shot.rs b/swarm/src/handler/one_shot.rs index c623008dd90..eba0a3a25a3 100644 --- a/swarm/src/handler/one_shot.rs +++ b/swarm/src/handler/one_shot.rs @@ -28,12 +28,12 @@ use std::{ use smallvec::SmallVec; use crate::{ + StreamUpgradeError, handler::{ ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, SubstreamProtocol, }, upgrade::{InboundUpgradeSend, OutboundUpgradeSend}, - StreamUpgradeError, }; /// A [`ConnectionHandler`] that opens a new substream for each request. @@ -228,9 +228,11 @@ mod tests { Default::default(), ); - block_on(poll_fn(|cx| loop { - if handler.poll(cx).is_pending() { - return Poll::Ready(()); + block_on(poll_fn(|cx| { + loop { + if handler.poll(cx).is_pending() { + return Poll::Ready(()); + } } })); diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index fb368bf975c..b240285cbc9 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -74,12 +74,14 @@ pub mod derive_prelude { pub use either::Either; pub use futures::prelude as futures; pub use libp2p_core::{ - transport::{ListenerId, PortUse}, ConnectedPoint, Endpoint, Multiaddr, + transport::{ListenerId, PortUse}, }; pub use libp2p_identity::PeerId; pub use crate::{ + ConnectionDenied, ConnectionHandler, ConnectionHandlerSelect, DialError, NetworkBehaviour, + THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, behaviour::{ AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredListenAddr, ExternalAddrConfirmed, ExternalAddrExpired, FromSwarm, ListenFailure, ListenerClosed, @@ -87,15 +89,13 @@ pub mod derive_prelude { NewListener, }, connection::ConnectionId, - ConnectionDenied, ConnectionHandler, ConnectionHandlerSelect, DialError, NetworkBehaviour, - THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, }; } use std::{ collections::{HashMap, HashSet, VecDeque}, error, fmt, io, - num::{NonZeroU32, NonZeroU8, NonZeroUsize}, + num::{NonZeroU8, NonZeroU32, NonZeroUsize}, pin::Pin, task::{Context, Poll}, time::Duration, @@ -107,10 +107,10 @@ pub use behaviour::{ ListenerClosed, ListenerError, NetworkBehaviour, NewExternalAddrCandidate, NewExternalAddrOfPeer, NewListenAddr, NotifyHandler, PeerAddresses, ToSwarm, }; -pub use connection::{pool::ConnectionCounters, ConnectionError, ConnectionId, SupportedProtocols}; +pub use connection::{ConnectionError, ConnectionId, SupportedProtocols, pool::ConnectionCounters}; use connection::{ - pool::{EstablishedConnection, Pool, PoolConfig, PoolEvent}, IncomingInfo, PendingInboundConnectionError, PendingOutboundConnectionError, + pool::{EstablishedConnection, Pool, PoolConfig, PoolEvent}, }; use dial_opts::{DialOpts, PeerCondition}; pub use executor::Executor; @@ -120,10 +120,10 @@ pub use handler::{ OneShotHandlerConfig, StreamUpgradeError, SubstreamProtocol, }; use libp2p_core::{ + Multiaddr, Transport, connection::ConnectedPoint, muxing::StreamMuxerBox, transport::{self, ListenerId, TransportError, TransportEvent}, - Multiaddr, Transport, }; use libp2p_identity::PeerId; #[cfg(feature = "macros")] @@ -636,11 +636,7 @@ where let was_connected = self.pool.is_connected(peer_id); self.pool.disconnect(peer_id); - if was_connected { - Ok(()) - } else { - Err(()) - } + if was_connected { Ok(()) } else { Err(()) } } /// Attempt to gracefully close a connection. @@ -1311,9 +1307,9 @@ fn notify_any( where TBehaviour: NetworkBehaviour, THandler: ConnectionHandler< - FromBehaviour = THandlerInEvent, - ToBehaviour = THandlerOutEvent, - >, + FromBehaviour = THandlerInEvent, + ToBehaviour = THandlerOutEvent, + >, { let mut pending = SmallVec::new(); let mut event = Some(event); // (1) @@ -1560,14 +1556,24 @@ impl fmt::Display for DialError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { DialError::NoAddresses => write!(f, "Dial error: no addresses for peer."), - DialError::LocalPeerId { address } => write!( + DialError::LocalPeerId { address } => { + write!(f, "Dial error: tried to dial local peer id at {address:?}.") + } + DialError::DialPeerConditionFalse(PeerCondition::Disconnected) => write!( + f, + "Dial error: dial condition was configured to only happen when disconnected (`PeerCondition::Disconnected`), but node is already connected, thus cancelling new dial." + ), + DialError::DialPeerConditionFalse(PeerCondition::NotDialing) => write!( f, - "Dial error: tried to dial local peer id at {address:?}." + "Dial error: dial condition was configured to only happen if there is currently no ongoing dialing attempt (`PeerCondition::NotDialing`), but a dial is in progress, thus cancelling new dial." ), - DialError::DialPeerConditionFalse(PeerCondition::Disconnected) => write!(f, "Dial error: dial condition was configured to only happen when disconnected (`PeerCondition::Disconnected`), but node is already connected, thus cancelling new dial."), - DialError::DialPeerConditionFalse(PeerCondition::NotDialing) => write!(f, "Dial error: dial condition was configured to only happen if there is currently no ongoing dialing attempt (`PeerCondition::NotDialing`), but a dial is in progress, thus cancelling new dial."), - DialError::DialPeerConditionFalse(PeerCondition::DisconnectedAndNotDialing) => write!(f, "Dial error: dial condition was configured to only happen when both disconnected (`PeerCondition::Disconnected`) and there is currently no ongoing dialing attempt (`PeerCondition::NotDialing`), but node is already connected or dial is in progress, thus cancelling new dial."), - DialError::DialPeerConditionFalse(PeerCondition::Always) => unreachable!("Dial peer condition is by definition true."), + DialError::DialPeerConditionFalse(PeerCondition::DisconnectedAndNotDialing) => write!( + f, + "Dial error: dial condition was configured to only happen when both disconnected (`PeerCondition::Disconnected`) and there is currently no ongoing dialing attempt (`PeerCondition::NotDialing`), but node is already connected or dial is in progress, thus cancelling new dial." + ), + DialError::DialPeerConditionFalse(PeerCondition::Always) => { + unreachable!("Dial peer condition is by definition true.") + } DialError::Aborted => write!( f, "Dial error: Pending connection attempt has been aborted." @@ -1766,7 +1772,7 @@ mod tests { multiaddr, multiaddr::multiaddr, transport, - transport::{memory::MemoryTransportError, TransportEvent}, + transport::{TransportEvent, memory::MemoryTransportError}, upgrade, }; use libp2p_identity as identity; @@ -1867,37 +1873,39 @@ mod tests { } let mut state = State::Connecting; - future::poll_fn(move |cx| loop { - let poll1 = Swarm::poll_next_event(Pin::new(&mut swarm1), cx); - let poll2 = Swarm::poll_next_event(Pin::new(&mut swarm2), cx); - match state { - State::Connecting => { - if swarms_connected(&swarm1, &swarm2, num_connections) { - if reconnected { - return Poll::Ready(()); + future::poll_fn(move |cx| { + loop { + let poll1 = Swarm::poll_next_event(Pin::new(&mut swarm1), cx); + let poll2 = Swarm::poll_next_event(Pin::new(&mut swarm2), cx); + match state { + State::Connecting => { + if swarms_connected(&swarm1, &swarm2, num_connections) { + if reconnected { + return Poll::Ready(()); + } + swarm2 + .disconnect_peer_id(swarm1_id) + .expect("Error disconnecting"); + state = State::Disconnecting; } - swarm2 - .disconnect_peer_id(swarm1_id) - .expect("Error disconnecting"); - state = State::Disconnecting; } - } - State::Disconnecting => { - if swarms_disconnected(&swarm1, &swarm2) { - if reconnected { - return Poll::Ready(()); - } - reconnected = true; - for _ in 0..num_connections { - swarm2.dial(addr1.clone()).unwrap(); + State::Disconnecting => { + if swarms_disconnected(&swarm1, &swarm2) { + if reconnected { + return Poll::Ready(()); + } + reconnected = true; + for _ in 0..num_connections { + swarm2.dial(addr1.clone()).unwrap(); + } + state = State::Connecting; } - state = State::Connecting; } } - } - if poll1.is_pending() && poll2.is_pending() { - return Poll::Pending; + if poll1.is_pending() && poll2.is_pending() { + return Poll::Pending; + } } }) .await @@ -1931,41 +1939,41 @@ mod tests { } let mut state = State::Connecting; - future::poll_fn(move |cx| loop { - let poll1 = Swarm::poll_next_event(Pin::new(&mut swarm1), cx); - let poll2 = Swarm::poll_next_event(Pin::new(&mut swarm2), cx); - match state { - State::Connecting => { - if swarms_connected(&swarm1, &swarm2, num_connections) { - if reconnected { - return Poll::Ready(()); + future::poll_fn(move |cx| { + loop { + let poll1 = Swarm::poll_next_event(Pin::new(&mut swarm1), cx); + let poll2 = Swarm::poll_next_event(Pin::new(&mut swarm2), cx); + match state { + State::Connecting => { + if swarms_connected(&swarm1, &swarm2, num_connections) { + if reconnected { + return Poll::Ready(()); + } + swarm2.behaviour.inner().next_action.replace( + ToSwarm::CloseConnection { + peer_id: swarm1_id, + connection: CloseConnection::All, + }, + ); + state = State::Disconnecting; + continue; } - swarm2 - .behaviour - .inner() - .next_action - .replace(ToSwarm::CloseConnection { - peer_id: swarm1_id, - connection: CloseConnection::All, - }); - state = State::Disconnecting; - continue; } - } - State::Disconnecting => { - if swarms_disconnected(&swarm1, &swarm2) { - reconnected = true; - for _ in 0..num_connections { - swarm2.dial(addr1.clone()).unwrap(); + State::Disconnecting => { + if swarms_disconnected(&swarm1, &swarm2) { + reconnected = true; + for _ in 0..num_connections { + swarm2.dial(addr1.clone()).unwrap(); + } + state = State::Connecting; + continue; } - state = State::Connecting; - continue; } } - } - if poll1.is_pending() && poll2.is_pending() { - return Poll::Pending; + if poll1.is_pending() && poll2.is_pending() { + return Poll::Pending; + } } }) .await @@ -1999,49 +2007,56 @@ mod tests { let mut state = State::Connecting; let mut disconnected_conn_id = None; - future::poll_fn(move |cx| loop { - let poll1 = Swarm::poll_next_event(Pin::new(&mut swarm1), cx); - let poll2 = Swarm::poll_next_event(Pin::new(&mut swarm2), cx); - match state { - State::Connecting => { - if swarms_connected(&swarm1, &swarm2, num_connections) { - disconnected_conn_id = { - let conn_id = - swarm2.behaviour.on_connection_established[num_connections / 2].1; - swarm2.behaviour.inner().next_action.replace( - ToSwarm::CloseConnection { - peer_id: swarm1_id, - connection: CloseConnection::One(conn_id), - }, - ); - Some(conn_id) - }; - state = State::Disconnecting; + future::poll_fn(move |cx| { + loop { + let poll1 = Swarm::poll_next_event(Pin::new(&mut swarm1), cx); + let poll2 = Swarm::poll_next_event(Pin::new(&mut swarm2), cx); + match state { + State::Connecting => { + if swarms_connected(&swarm1, &swarm2, num_connections) { + disconnected_conn_id = { + let conn_id = swarm2.behaviour.on_connection_established + [num_connections / 2] + .1; + swarm2.behaviour.inner().next_action.replace( + ToSwarm::CloseConnection { + peer_id: swarm1_id, + connection: CloseConnection::One(conn_id), + }, + ); + Some(conn_id) + }; + state = State::Disconnecting; + } } - } - State::Disconnecting => { - for s in &[&swarm1, &swarm2] { - assert!(s - .behaviour - .on_connection_closed + State::Disconnecting => { + for s in &[&swarm1, &swarm2] { + assert!( + s.behaviour + .on_connection_closed + .iter() + .all(|(.., remaining_conns)| *remaining_conns > 0) + ); + assert_eq!( + s.behaviour.on_connection_established.len(), + num_connections + ); + s.behaviour.assert_connected(num_connections, 1); + } + if [&swarm1, &swarm2] .iter() - .all(|(.., remaining_conns)| *remaining_conns > 0)); - assert_eq!(s.behaviour.on_connection_established.len(), num_connections); - s.behaviour.assert_connected(num_connections, 1); - } - if [&swarm1, &swarm2] - .iter() - .all(|s| s.behaviour.on_connection_closed.len() == 1) - { - let conn_id = swarm2.behaviour.on_connection_closed[0].1; - assert_eq!(Some(conn_id), disconnected_conn_id); - return Poll::Ready(()); + .all(|s| s.behaviour.on_connection_closed.len() == 1) + { + let conn_id = swarm2.behaviour.on_connection_closed[0].1; + assert_eq!(Some(conn_id), disconnected_conn_id); + return Poll::Ready(()); + } } } - } - if poll1.is_pending() && poll2.is_pending() { - return Poll::Pending; + if poll1.is_pending() && poll2.is_pending() { + return Poll::Pending; + } } }) .await @@ -2344,6 +2359,9 @@ mod tests { // Unfortunately, we have some "empty" errors // that lead to multiple colons without text but that is the best we can do. - assert_eq!("Failed to negotiate transport protocol(s): [(/ip4/127.0.0.1/tcp/80: : No listener on the given port.)]", string) + assert_eq!( + "Failed to negotiate transport protocol(s): [(/ip4/127.0.0.1/tcp/80: : No listener on the given port.)]", + string + ) } } diff --git a/swarm/src/stream.rs b/swarm/src/stream.rs index d3936cb557a..caa4e56bd27 100644 --- a/swarm/src/stream.rs +++ b/swarm/src/stream.rs @@ -6,7 +6,7 @@ use std::{ }; use futures::{AsyncRead, AsyncWrite}; -use libp2p_core::{muxing::SubstreamBox, Negotiated}; +use libp2p_core::{Negotiated, muxing::SubstreamBox}; /// Counter for the number of active streams on a connection. #[derive(Debug, Clone)] diff --git a/swarm/src/test.rs b/swarm/src/test.rs index 250960fbcca..e4db91add7e 100644 --- a/swarm/src/test.rs +++ b/swarm/src/test.rs @@ -24,20 +24,20 @@ use std::{ }; use libp2p_core::{ + ConnectedPoint, Endpoint, multiaddr::Multiaddr, transport::{ListenerId, PortUse}, - ConnectedPoint, Endpoint, }; use libp2p_identity::PeerId; use crate::{ + ConnectionDenied, ConnectionHandler, ConnectionId, NetworkBehaviour, THandler, THandlerInEvent, + THandlerOutEvent, ToSwarm, behaviour::{ ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredListenAddr, ExternalAddrExpired, FromSwarm, ListenerClosed, ListenerError, NewExternalAddrCandidate, NewListenAddr, NewListener, }, - ConnectionDenied, ConnectionHandler, ConnectionId, NetworkBehaviour, THandler, THandlerInEvent, - THandlerOutEvent, ToSwarm, }; /// A `MockBehaviour` is a `NetworkBehaviour` that allows for diff --git a/swarm/src/translation.rs b/swarm/src/translation.rs index baa80c907b5..233a33be2eb 100644 --- a/swarm/src/translation.rs +++ b/swarm/src/translation.rs @@ -18,7 +18,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use libp2p_core::{multiaddr::Protocol, Multiaddr}; +use libp2p_core::{Multiaddr, multiaddr::Protocol}; /// Perform IP address translation. /// diff --git a/swarm/tests/connection_close.rs b/swarm/tests/connection_close.rs index 0d95626b2f0..e6b0eea11b0 100644 --- a/swarm/tests/connection_close.rs +++ b/swarm/tests/connection_close.rs @@ -3,12 +3,12 @@ use std::{ task::{Context, Poll}, }; -use libp2p_core::{transport::PortUse, upgrade::DeniedUpgrade, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse, upgrade::DeniedUpgrade}; use libp2p_identity::PeerId; use libp2p_swarm::{ - handler::ConnectionEvent, ConnectionDenied, ConnectionHandler, ConnectionHandlerEvent, - ConnectionId, FromSwarm, NetworkBehaviour, SubstreamProtocol, Swarm, SwarmEvent, THandler, - THandlerInEvent, THandlerOutEvent, ToSwarm, + ConnectionDenied, ConnectionHandler, ConnectionHandlerEvent, ConnectionId, FromSwarm, + NetworkBehaviour, SubstreamProtocol, Swarm, SwarmEvent, THandler, THandlerInEvent, + THandlerOutEvent, ToSwarm, handler::ConnectionEvent, }; use libp2p_swarm_test::SwarmExt; diff --git a/swarm/tests/listener.rs b/swarm/tests/listener.rs index 01d5784cfa5..4f843de732f 100644 --- a/swarm/tests/listener.rs +++ b/swarm/tests/listener.rs @@ -5,15 +5,15 @@ use std::{ }; use libp2p_core::{ + Endpoint, Multiaddr, multiaddr::Protocol, transport::{ListenerId, PortUse}, - Endpoint, Multiaddr, }; use libp2p_identity::PeerId; use libp2p_swarm::{ - derive_prelude::NewListener, dummy, ConnectionDenied, ConnectionId, FromSwarm, ListenOpts, - ListenerClosed, ListenerError, NetworkBehaviour, NewListenAddr, Swarm, SwarmEvent, THandler, - THandlerInEvent, THandlerOutEvent, ToSwarm, + ConnectionDenied, ConnectionId, FromSwarm, ListenOpts, ListenerClosed, ListenerError, + NetworkBehaviour, NewListenAddr, Swarm, SwarmEvent, THandler, THandlerInEvent, + THandlerOutEvent, ToSwarm, derive_prelude::NewListener, dummy, }; use libp2p_swarm_test::SwarmExt; diff --git a/swarm/tests/swarm_derive.rs b/swarm/tests/swarm_derive.rs index e297f2f4afa..50f1ad7cd8e 100644 --- a/swarm/tests/swarm_derive.rs +++ b/swarm/tests/swarm_derive.rs @@ -21,12 +21,12 @@ use std::fmt::Debug; use futures::StreamExt; -use libp2p_core::{transport::PortUse, Endpoint, Multiaddr}; +use libp2p_core::{Endpoint, Multiaddr, transport::PortUse}; use libp2p_identify as identify; use libp2p_ping as ping; use libp2p_swarm::{ - behaviour::FromSwarm, dummy, ConnectionDenied, NetworkBehaviour, SwarmEvent, THandler, - THandlerInEvent, THandlerOutEvent, + ConnectionDenied, NetworkBehaviour, SwarmEvent, THandler, THandlerInEvent, THandlerOutEvent, + behaviour::FromSwarm, dummy, }; /// Small utility to check that a type implements `NetworkBehaviour`. diff --git a/transports/dns/src/lib.rs b/transports/dns/src/lib.rs index 7e3cf5d3c37..35eaeda140f 100644 --- a/transports/dns/src/lib.rs +++ b/transports/dns/src/lib.rs @@ -117,7 +117,7 @@ pub mod async_std { pub mod tokio { use std::sync::Arc; - use hickory_resolver::{system_conf, TokioResolver}; + use hickory_resolver::{TokioResolver, system_conf}; use parking_lot::Mutex; /// A `Transport` wrapper for performing DNS lookups when dialing `Multiaddr`esses @@ -159,8 +159,8 @@ use std::{ use async_trait::async_trait; use futures::{future::BoxFuture, prelude::*}; pub use hickory_resolver::{ - config::{ResolverConfig, ResolverOpts}, ResolveError, ResolveErrorKind, + config::{ResolverConfig, ResolverOpts}, }; use hickory_resolver::{ lookup::{Ipv4Lookup, Ipv6Lookup, TxtLookup}, @@ -469,7 +469,7 @@ fn resolve<'a, E: 'a + Send, R: Resolver>( resolver: &'a R, ) -> BoxFuture<'a, Result, Error>> { match proto { - Protocol::Dns(ref name) => resolver + Protocol::Dns(name) => resolver .lookup_ip(name.clone().into_owned()) .map(move |res| match res { Ok(ips) => { @@ -492,7 +492,7 @@ fn resolve<'a, E: 'a + Send, R: Resolver>( Err(e) => Err(Error::ResolveError(e)), }) .boxed(), - Protocol::Dns4(ref name) => resolver + Protocol::Dns4(name) => resolver .ipv4_lookup(name.clone().into_owned()) .map(move |res| match res { Ok(ips) => { @@ -516,7 +516,7 @@ fn resolve<'a, E: 'a + Send, R: Resolver>( Err(e) => Err(Error::ResolveError(e)), }) .boxed(), - Protocol::Dns6(ref name) => resolver + Protocol::Dns6(name) => resolver .ipv6_lookup(name.clone().into_owned()) .map(move |res| match res { Ok(ips) => { @@ -540,7 +540,7 @@ fn resolve<'a, E: 'a + Send, R: Resolver>( Err(e) => Err(Error::ResolveError(e)), }) .boxed(), - Protocol::Dnsaddr(ref name) => { + Protocol::Dnsaddr(name) => { let name = [DNSADDR_PREFIX, name].concat(); resolver .txt_lookup(name) @@ -619,9 +619,9 @@ mod tests { use futures::future::BoxFuture; use hickory_resolver::proto::{ProtoError, ProtoErrorKind}; use libp2p_core::{ + Endpoint, Transport, multiaddr::{Multiaddr, Protocol}, transport::{PortUse, TransportError, TransportEvent}, - Endpoint, Transport, }; use libp2p_identity::PeerId; diff --git a/transports/noise/src/io/framed.rs b/transports/noise/src/io/framed.rs index 5aaad6f55e7..1c30e6dc3be 100644 --- a/transports/noise/src/io/framed.rs +++ b/transports/noise/src/io/framed.rs @@ -30,7 +30,7 @@ use bytes::{Buf, Bytes, BytesMut}; use quick_protobuf::{BytesReader, MessageRead, MessageWrite, Writer}; use super::handshake::proto; -use crate::{protocol::PublicKey, Error}; +use crate::{Error, protocol::PublicKey}; /// Max. size of a noise message. const MAX_NOISE_MSG_LEN: usize = 65535; diff --git a/transports/noise/src/io/handshake.rs b/transports/noise/src/io/handshake.rs index d4727b91420..fbf085a2569 100644 --- a/transports/noise/src/io/handshake.rs +++ b/transports/noise/src/io/handshake.rs @@ -36,9 +36,9 @@ use quick_protobuf::MessageWrite; use super::framed::Codec; use crate::{ + Error, io::Output, protocol::{KeypairIdentity, PublicKey, STATIC_KEY_DOMAIN}, - Error, }; ////////////////////////////////////////////////////////////////////////////// diff --git a/transports/noise/src/lib.rs b/transports/noise/src/lib.rs index e05556744fe..06c00baf297 100644 --- a/transports/noise/src/lib.rs +++ b/transports/noise/src/lib.rs @@ -39,7 +39,7 @@ //! Example: //! //! ``` -//! use libp2p_core::{transport::MemoryTransport, upgrade, Transport}; +//! use libp2p_core::{Transport, transport::MemoryTransport, upgrade}; //! use libp2p_identity as identity; //! use libp2p_noise as noise; //! @@ -65,8 +65,8 @@ use std::{collections::HashSet, fmt::Write, pin::Pin}; use futures::prelude::*; pub use io::Output; use libp2p_core::{ - upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}, UpgradeInfo, + upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}, }; use libp2p_identity as identity; use libp2p_identity::PeerId; @@ -77,7 +77,7 @@ use snow::params::NoiseParams; use crate::{ handshake::State, io::handshake, - protocol::{noise_params_into_builder, AuthenticKeypair, Keypair, PARAMS_XX}, + protocol::{AuthenticKeypair, Keypair, PARAMS_XX, noise_params_into_builder}, }; /// The configuration for the noise handshake. diff --git a/transports/noise/src/protocol.rs b/transports/noise/src/protocol.rs index 2b72a1f23ca..f604e908418 100644 --- a/transports/noise/src/protocol.rs +++ b/transports/noise/src/protocol.rs @@ -25,7 +25,7 @@ use std::sync::LazyLock; use libp2p_identity as identity; use rand::{Rng as _, SeedableRng}; use snow::params::NoiseParams; -use x25519_dalek::{x25519, X25519_BASEPOINT_BYTES}; +use x25519_dalek::{X25519_BASEPOINT_BYTES, x25519}; use zeroize::Zeroize; use crate::Error; diff --git a/transports/plaintext/src/handshake.rs b/transports/plaintext/src/handshake.rs index 38a56b84862..5876e10811d 100644 --- a/transports/plaintext/src/handshake.rs +++ b/transports/plaintext/src/handshake.rs @@ -26,9 +26,9 @@ use futures::prelude::*; use libp2p_identity::{PeerId, PublicKey}; use crate::{ + Config, error::{DecodeError, Error}, proto::Exchange, - Config, }; pub(crate) async fn handshake(socket: S, config: Config) -> Result<(S, PublicKey, Bytes), Error> diff --git a/transports/plaintext/src/lib.rs b/transports/plaintext/src/lib.rs index f841a859a62..af0c7a63027 100644 --- a/transports/plaintext/src/lib.rs +++ b/transports/plaintext/src/lib.rs @@ -31,8 +31,8 @@ use std::{ use bytes::Bytes; use futures::{future::BoxFuture, prelude::*}; use libp2p_core::{ - upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}, UpgradeInfo, + upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}, }; use libp2p_identity as identity; use libp2p_identity::{PeerId, PublicKey}; diff --git a/transports/pnet/src/crypt_writer.rs b/transports/pnet/src/crypt_writer.rs index 8b302089a1d..1f09c0d5fdc 100644 --- a/transports/pnet/src/crypt_writer.rs +++ b/transports/pnet/src/crypt_writer.rs @@ -26,7 +26,7 @@ use futures::{ task::{Context, Poll}, }; use pin_project::pin_project; -use salsa20::{cipher::StreamCipher, XSalsa20}; +use salsa20::{XSalsa20, cipher::StreamCipher}; /// A writer that encrypts and forwards to an inner writer #[pin_project] diff --git a/transports/pnet/src/lib.rs b/transports/pnet/src/lib.rs index b27f9777c47..f8e810d097b 100644 --- a/transports/pnet/src/lib.rs +++ b/transports/pnet/src/lib.rs @@ -42,10 +42,10 @@ use futures::prelude::*; use pin_project::pin_project; use rand::RngCore; use salsa20::{ - cipher::{KeyIvInit, StreamCipher}, Salsa20, XSalsa20, + cipher::{KeyIvInit, StreamCipher}, }; -use sha3::{digest::ExtendableOutput, Shake128}; +use sha3::{Shake128, digest::ExtendableOutput}; const KEY_SIZE: usize = 32; const NONCE_SIZE: usize = 24; diff --git a/transports/pnet/tests/smoke.rs b/transports/pnet/tests/smoke.rs index d57b191d752..c0e611bc8f1 100644 --- a/transports/pnet/tests/smoke.rs +++ b/transports/pnet/tests/smoke.rs @@ -1,11 +1,11 @@ use std::time::Duration; -use futures::{future, AsyncRead, AsyncWrite, StreamExt}; +use futures::{AsyncRead, AsyncWrite, StreamExt, future}; use libp2p_core::{ - multiaddr::Protocol, transport::MemoryTransport, upgrade::Version, Multiaddr, Transport, + Multiaddr, Transport, multiaddr::Protocol, transport::MemoryTransport, upgrade::Version, }; use libp2p_pnet::{PnetConfig, PreSharedKey}; -use libp2p_swarm::{dummy, Config, NetworkBehaviour, Swarm, SwarmEvent}; +use libp2p_swarm::{Config, NetworkBehaviour, Swarm, SwarmEvent, dummy}; const TIMEOUT: Duration = Duration::from_secs(5); diff --git a/transports/quic/src/config.rs b/transports/quic/src/config.rs index 85b89cf35e3..0d514db5751 100644 --- a/transports/quic/src/config.rs +++ b/transports/quic/src/config.rs @@ -21,8 +21,8 @@ use std::{sync::Arc, time::Duration}; use quinn::{ - crypto::rustls::{QuicClientConfig, QuicServerConfig}, MtuDiscoveryConfig, VarInt, + crypto::rustls::{QuicClientConfig, QuicServerConfig}, }; /// Config for the transport. diff --git a/transports/quic/src/connection.rs b/transports/quic/src/connection.rs index a7375a1ca6d..a822b56d9d4 100644 --- a/transports/quic/src/connection.rs +++ b/transports/quic/src/connection.rs @@ -27,7 +27,7 @@ use std::{ }; pub use connecting::Connecting; -use futures::{future::BoxFuture, FutureExt}; +use futures::{FutureExt, future::BoxFuture}; use libp2p_core::muxing::{StreamMuxer, StreamMuxerEvent}; pub use stream::Stream; diff --git a/transports/quic/src/connection/connecting.rs b/transports/quic/src/connection/connecting.rs index 0ce7f9041db..707fb7c1e70 100644 --- a/transports/quic/src/connection/connecting.rs +++ b/transports/quic/src/connection/connecting.rs @@ -27,7 +27,7 @@ use std::{ }; use futures::{ - future::{select, Either, FutureExt, Select}, + future::{Either, FutureExt, Select, select}, prelude::*, }; use futures_timer::Delay; diff --git a/transports/quic/src/hole_punching.rs b/transports/quic/src/hole_punching.rs index 48d1494c95c..cb2f85b3a2f 100644 --- a/transports/quic/src/hole_punching.rs +++ b/transports/quic/src/hole_punching.rs @@ -5,9 +5,9 @@ use std::{ }; use futures::future::Either; -use rand::{distributions, Rng}; +use rand::{Rng, distributions}; -use crate::{provider::Provider, Error}; +use crate::{Error, provider::Provider}; pub(crate) async fn hole_puncher( socket: UdpSocket, diff --git a/transports/quic/src/lib.rs b/transports/quic/src/lib.rs index 9d97e6c4319..833fe6a9ba5 100644 --- a/transports/quic/src/lib.rs +++ b/transports/quic/src/lib.rs @@ -31,7 +31,7 @@ //! # #[cfg(feature = "async-std")] //! # fn main() -> std::io::Result<()> { //! # -//! use libp2p_core::{transport::ListenerId, Multiaddr, Transport}; +//! use libp2p_core::{Multiaddr, Transport, transport::ListenerId}; //! use libp2p_quic as quic; //! //! let keypair = libp2p_identity::Keypair::generate_ed25519(); @@ -70,11 +70,11 @@ use std::net::SocketAddr; pub use config::Config; pub use connection::{Connecting, Connection, Stream}; +pub use provider::Provider; #[cfg(feature = "async-std")] pub use provider::async_std; #[cfg(feature = "tokio")] pub use provider::tokio; -pub use provider::Provider; pub use transport::GenTransport; /// Errors that may happen on the [`GenTransport`] or a single [`Connection`]. diff --git a/transports/quic/src/provider/async_std.rs b/transports/quic/src/provider/async_std.rs index b5c3ac917dc..d8130860910 100644 --- a/transports/quic/src/provider/async_std.rs +++ b/transports/quic/src/provider/async_std.rs @@ -25,7 +25,7 @@ use std::{ time::Duration, }; -use futures::{future::BoxFuture, FutureExt}; +use futures::{FutureExt, future::BoxFuture}; use crate::GenTransport; diff --git a/transports/quic/src/provider/tokio.rs b/transports/quic/src/provider/tokio.rs index 83753faac01..26436e557f2 100644 --- a/transports/quic/src/provider/tokio.rs +++ b/transports/quic/src/provider/tokio.rs @@ -25,7 +25,7 @@ use std::{ time::Duration, }; -use futures::{future::BoxFuture, FutureExt}; +use futures::{FutureExt, future::BoxFuture}; use crate::GenTransport; diff --git a/transports/quic/src/transport.rs b/transports/quic/src/transport.rs index b42e0b13591..deb33a1b5a5 100644 --- a/transports/quic/src/transport.rs +++ b/transports/quic/src/transport.rs @@ -20,8 +20,8 @@ use std::{ collections::{ - hash_map::{DefaultHasher, Entry}, HashMap, HashSet, + hash_map::{DefaultHasher, Entry}, }, fmt, hash::{Hash, Hasher}, @@ -41,18 +41,18 @@ use futures::{ }; use if_watch::IfEvent; use libp2p_core::{ + Endpoint, Transport, multiaddr::{Multiaddr, Protocol}, transport::{DialOpts, ListenerId, PortUse, TransportError, TransportEvent}, - Endpoint, Transport, }; use libp2p_identity::PeerId; use socket2::{Domain, Socket, Type}; use crate::{ + ConnectError, Connecting, Connection, Error, config::{Config, QuinnConfig}, hole_punching::hole_puncher, provider::Provider, - ConnectError, Connecting, Connection, Error, }; /// Implementation of the [`Transport`] trait for QUIC. @@ -573,7 +573,7 @@ impl Listener

{ return Poll::Ready(TransportEvent::ListenerError { listener_id: self.listener_id, error: err.into(), - }) + }); } } } @@ -605,7 +605,7 @@ impl Stream for Listener

{ return Poll::Ready(Some(TransportEvent::ListenerError { listener_id: self.listener_id, error: Error::Connection(crate::ConnectionError(error)), - })) + })); } }; @@ -755,11 +755,13 @@ mod tests { #[test] fn multiaddr_to_udp_conversion() { - assert!(multiaddr_to_socketaddr( - &"/ip4/127.0.0.1/udp/1234".parse::().unwrap(), - true - ) - .is_none()); + assert!( + multiaddr_to_socketaddr( + &"/ip4/127.0.0.1/udp/1234".parse::().unwrap(), + true + ) + .is_none() + ); assert_eq!( multiaddr_to_socketaddr( @@ -828,11 +830,13 @@ mod tests { )) ); - assert!(multiaddr_to_socketaddr( - &"/ip4/127.0.0.1/udp/1234/quic".parse::().unwrap(), - false - ) - .is_none()); + assert!( + multiaddr_to_socketaddr( + &"/ip4/127.0.0.1/udp/1234/quic".parse::().unwrap(), + false + ) + .is_none() + ); assert_eq!( multiaddr_to_socketaddr( &"/ip4/127.0.0.1/udp/1234/quic".parse::().unwrap(), @@ -852,9 +856,11 @@ mod tests { let keypair = libp2p_identity::Keypair::generate_ed25519(); let config = Config::new(&keypair); let mut transport = crate::tokio::Transport::new(config); - assert!(poll_fn(|cx| Pin::new(&mut transport).as_mut().poll(cx)) - .now_or_never() - .is_none()); + assert!( + poll_fn(|cx| Pin::new(&mut transport).as_mut().poll(cx)) + .now_or_never() + .is_none() + ); // Run test twice to check that there is no unexpected behaviour if `Transport.listener` // is temporarily empty. @@ -892,9 +898,11 @@ mod tests { } // Poll once again so that the listener has the chance to return `Poll::Ready(None)` and // be removed from the list of listeners. - assert!(poll_fn(|cx| Pin::new(&mut transport).as_mut().poll(cx)) - .now_or_never() - .is_none()); + assert!( + poll_fn(|cx| Pin::new(&mut transport).as_mut().poll(cx)) + .now_or_never() + .is_none() + ); assert!(transport.listeners.is_empty()); } } diff --git a/transports/quic/tests/smoke.rs b/transports/quic/tests/smoke.rs index ed2ff981634..ee01f18b58e 100644 --- a/transports/quic/tests/smoke.rs +++ b/transports/quic/tests/smoke.rs @@ -11,20 +11,21 @@ use std::{ }; use futures::{ + AsyncReadExt, AsyncWriteExt, FutureExt, SinkExt, channel::{mpsc, oneshot}, future, - future::{poll_fn, BoxFuture, Either}, + future::{BoxFuture, Either, poll_fn}, stream::StreamExt, - AsyncReadExt, AsyncWriteExt, FutureExt, SinkExt, }; use futures_timer::Delay; use libp2p_core::{ + Endpoint, Multiaddr, Transport, multiaddr::Protocol, muxing::{StreamMuxerBox, StreamMuxerExt, SubstreamBox}, transport::{ Boxed, DialOpts, ListenerId, OrTransport, PortUse, TransportError, TransportEvent, }, - upgrade, Endpoint, Multiaddr, Transport, + upgrade, }; use libp2p_identity::PeerId; use libp2p_noise as noise; @@ -207,7 +208,7 @@ async fn wrapped_with_delay() { #[cfg(feature = "tokio")] #[tokio::test] #[ignore] // Transport currently does not validate PeerId. - // Enable once we make use of PeerId validation in rustls. +// Enable once we make use of PeerId validation in rustls. async fn wrong_peerid() { use libp2p_identity::PeerId; diff --git a/transports/quic/tests/stream_compliance.rs b/transports/quic/tests/stream_compliance.rs index 225ea1e4936..8712ba15e19 100644 --- a/transports/quic/tests/stream_compliance.rs +++ b/transports/quic/tests/stream_compliance.rs @@ -1,9 +1,9 @@ use std::time::Duration; -use futures::{channel::oneshot, StreamExt}; +use futures::{StreamExt, channel::oneshot}; use libp2p_core::{ - transport::{DialOpts, ListenerId, PortUse}, Endpoint, Transport, + transport::{DialOpts, ListenerId, PortUse}, }; use libp2p_quic as quic; diff --git a/transports/tcp/src/provider.rs b/transports/tcp/src/provider.rs index 7a609d9f031..bfcdcc8093a 100644 --- a/transports/tcp/src/provider.rs +++ b/transports/tcp/src/provider.rs @@ -33,9 +33,9 @@ use std::{ }; use futures::{ + Stream, future::BoxFuture, io::{AsyncRead, AsyncWrite}, - Stream, }; use if_watch::{IfEvent, IpNet}; diff --git a/transports/tls/src/certificate.rs b/transports/tls/src/certificate.rs index 9c771fc71b1..bc2ae97bb65 100644 --- a/transports/tls/src/certificate.rs +++ b/transports/tls/src/certificate.rs @@ -511,8 +511,8 @@ mod tests { let cert = parse_unverified(cert).unwrap(); assert!(cert.verify().is_err()); // Because p2p extension - // was not signed with the private key - // of the certificate. + // was not signed with the private key + // of the certificate. assert_eq!(cert.signature_scheme(), Ok($scheme)); } }; diff --git a/transports/tls/src/upgrade.rs b/transports/tls/src/upgrade.rs index a6d81ab36c9..2563f636dac 100644 --- a/transports/tls/src/upgrade.rs +++ b/transports/tls/src/upgrade.rs @@ -23,15 +23,15 @@ use std::{ sync::Arc, }; -use futures::{future::BoxFuture, AsyncRead, AsyncWrite, FutureExt}; +use futures::{AsyncRead, AsyncWrite, FutureExt, future::BoxFuture}; use futures_rustls::TlsStream; use libp2p_core::{ - upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}, UpgradeInfo, + upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade}, }; use libp2p_identity as identity; use libp2p_identity::PeerId; -use rustls::{pki_types::ServerName, CommonState}; +use rustls::{CommonState, pki_types::ServerName}; use crate::{certificate, certificate::P2pCertificate}; diff --git a/transports/tls/src/verifier.rs b/transports/tls/src/verifier.rs index 82b275bc7be..08d6f6ae84f 100644 --- a/transports/tls/src/verifier.rs +++ b/transports/tls/src/verifier.rs @@ -27,14 +27,14 @@ use std::sync::Arc; use libp2p_identity::PeerId; use rustls::{ + CertificateError, DigitallySignedStruct, DistinguishedName, OtherError, SignatureScheme, + SupportedCipherSuite, SupportedProtocolVersion, client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, crypto::ring::cipher_suite::{ TLS13_AES_128_GCM_SHA256, TLS13_AES_256_GCM_SHA384, TLS13_CHACHA20_POLY1305_SHA256, }, pki_types::CertificateDer, server::danger::{ClientCertVerified, ClientCertVerifier}, - CertificateError, DigitallySignedStruct, DistinguishedName, OtherError, SignatureScheme, - SupportedCipherSuite, SupportedProtocolVersion, }; use crate::certificate; diff --git a/transports/tls/tests/smoke.rs b/transports/tls/tests/smoke.rs index e335f68a7e4..0cf7dde15be 100644 --- a/transports/tls/tests/smoke.rs +++ b/transports/tls/tests/smoke.rs @@ -1,6 +1,6 @@ -use futures::{future, StreamExt}; -use libp2p_core::{multiaddr::Protocol, transport::MemoryTransport, upgrade::Version, Transport}; -use libp2p_swarm::{dummy, Config, Swarm, SwarmEvent}; +use futures::{StreamExt, future}; +use libp2p_core::{Transport, multiaddr::Protocol, transport::MemoryTransport, upgrade::Version}; +use libp2p_swarm::{Config, Swarm, SwarmEvent, dummy}; #[tokio::test] async fn can_establish_connection() { diff --git a/transports/uds/src/lib.rs b/transports/uds/src/lib.rs index 74e19476595..34111b3e07e 100644 --- a/transports/uds/src/lib.rs +++ b/transports/uds/src/lib.rs @@ -52,9 +52,9 @@ use futures::{ stream::BoxStream, }; use libp2p_core::{ + Transport, multiaddr::{Multiaddr, Protocol}, transport::{DialOpts, ListenerId, TransportError, TransportEvent}, - Transport, }; pub type Listener = BoxStream< @@ -248,12 +248,12 @@ mod tests { use futures::{channel::oneshot, prelude::*}; use libp2p_core::{ + Endpoint, Transport, multiaddr::{Multiaddr, Protocol}, transport::{DialOpts, ListenerId, PortUse}, - Endpoint, Transport, }; - use super::{multiaddr_to_path, UdsConfig}; + use super::{UdsConfig, multiaddr_to_path}; #[test] fn multiaddr_to_path_conversion() { diff --git a/transports/webrtc-websys/src/connection.rs b/transports/webrtc-websys/src/connection.rs index 01c1a8b3b60..acd84cfe313 100644 --- a/transports/webrtc-websys/src/connection.rs +++ b/transports/webrtc-websys/src/connection.rs @@ -2,10 +2,10 @@ use std::{ pin::Pin, - task::{ready, Context, Poll, Waker}, + task::{Context, Poll, Waker, ready}, }; -use futures::{channel::mpsc, stream::FuturesUnordered, StreamExt}; +use futures::{StreamExt, channel::mpsc, stream::FuturesUnordered}; use js_sys::{Object, Reflect}; use libp2p_core::muxing::{StreamMuxer, StreamMuxerEvent}; use libp2p_webrtc_utils::Fingerprint; @@ -307,6 +307,9 @@ mod sdp_tests { let fingerprint = parse_fingerprint(sdp).unwrap(); assert_eq!(fingerprint.algorithm(), "sha-256"); - assert_eq!(fingerprint.to_sdp_format(), "A8:17:77:1E:02:7E:D1:2B:53:92:70:A6:8E:F9:02:CC:21:72:3A:92:5D:F4:97:5F:27:C4:5E:75:D4:F4:31:89"); + assert_eq!( + fingerprint.to_sdp_format(), + "A8:17:77:1E:02:7E:D1:2B:53:92:70:A6:8E:F9:02:CC:21:72:3A:92:5D:F4:97:5F:27:C4:5E:75:D4:F4:31:89" + ); } } diff --git a/transports/webrtc-websys/src/stream/poll_data_channel.rs b/transports/webrtc-websys/src/stream/poll_data_channel.rs index 2abe499afce..eaeec4d6789 100644 --- a/transports/webrtc-websys/src/stream/poll_data_channel.rs +++ b/transports/webrtc-websys/src/stream/poll_data_channel.rs @@ -4,14 +4,14 @@ use std::{ pin::Pin, rc::Rc, sync::{ - atomic::{AtomicBool, Ordering}, Mutex, + atomic::{AtomicBool, Ordering}, }, task::{Context, Poll}, }; use bytes::BytesMut; -use futures::{task::AtomicWaker, AsyncRead, AsyncWrite}; +use futures::{AsyncRead, AsyncWrite, task::AtomicWaker}; use libp2p_webrtc_utils::MAX_MSG_LEN; use wasm_bindgen::prelude::*; use web_sys::{Event, MessageEvent, RtcDataChannel, RtcDataChannelEvent, RtcDataChannelState}; @@ -150,7 +150,7 @@ impl PollDataChannel { return Poll::Pending; } RtcDataChannelState::Closing | RtcDataChannelState::Closed => { - return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())) + return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); } RtcDataChannelState::Open | RtcDataChannelState::__Invalid => {} _ => {} diff --git a/transports/webrtc-websys/src/transport.rs b/transports/webrtc-websys/src/transport.rs index abf02520244..365216f35c2 100644 --- a/transports/webrtc-websys/src/transport.rs +++ b/transports/webrtc-websys/src/transport.rs @@ -12,7 +12,7 @@ use libp2p_core::{ }; use libp2p_identity::{Keypair, PeerId}; -use super::{upgrade, Connection, Error}; +use super::{Connection, Error, upgrade}; /// Config for the [`Transport`]. #[derive(Clone)] diff --git a/transports/webrtc-websys/src/upgrade.rs b/transports/webrtc-websys/src/upgrade.rs index b1de908ae82..d1e322a0838 100644 --- a/transports/webrtc-websys/src/upgrade.rs +++ b/transports/webrtc-websys/src/upgrade.rs @@ -1,11 +1,11 @@ use std::net::SocketAddr; use libp2p_identity::{Keypair, PeerId}; -use libp2p_webrtc_utils::{noise, Fingerprint}; +use libp2p_webrtc_utils::{Fingerprint, noise}; use send_wrapper::SendWrapper; use super::Error; -use crate::{connection::RtcPeerConnection, error::AuthenticationError, sdp, Connection}; +use crate::{Connection, connection::RtcPeerConnection, error::AuthenticationError, sdp}; /// Upgrades an outbound WebRTC connection by creating the data channel /// and conducting a Noise handshake diff --git a/transports/webrtc/src/tokio/certificate.rs b/transports/webrtc/src/tokio/certificate.rs index 7ff35d46bdd..98603297362 100644 --- a/transports/webrtc/src/tokio/certificate.rs +++ b/transports/webrtc/src/tokio/certificate.rs @@ -18,7 +18,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use rand::{distributions::DistString, CryptoRng, Rng}; +use rand::{CryptoRng, Rng, distributions::DistString}; use webrtc::peer_connection::certificate::RTCCertificate; use crate::tokio::fingerprint::Fingerprint; @@ -38,7 +38,7 @@ impl Certificate { R: CryptoRng + Rng, { let mut params = rcgen::CertificateParams::new(vec![ - rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 16) + rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 16), ]); params.alg = &rcgen::PKCS_ECDSA_P256_SHA256; Ok(Self { diff --git a/transports/webrtc/src/tokio/connection.rs b/transports/webrtc/src/tokio/connection.rs index 19232707e7f..71136f82614 100644 --- a/transports/webrtc/src/tokio/connection.rs +++ b/transports/webrtc/src/tokio/connection.rs @@ -25,6 +25,7 @@ use std::{ }; use futures::{ + StreamExt, channel::{ mpsc, oneshot::{self, Sender}, @@ -33,7 +34,6 @@ use futures::{ lock::Mutex as FutMutex, ready, stream::FuturesUnordered, - StreamExt, }; use libp2p_core::muxing::{StreamMuxer, StreamMuxerEvent}; use webrtc::{ diff --git a/transports/webrtc/src/tokio/req_res_chan.rs b/transports/webrtc/src/tokio/req_res_chan.rs index a733c86d5cc..45caa1919fd 100644 --- a/transports/webrtc/src/tokio/req_res_chan.rs +++ b/transports/webrtc/src/tokio/req_res_chan.rs @@ -24,8 +24,8 @@ use std::{ }; use futures::{ - channel::{mpsc, oneshot}, SinkExt, StreamExt, + channel::{mpsc, oneshot}, }; pub(crate) fn new(capacity: usize) -> (Sender, Receiver) { diff --git a/transports/webrtc/src/tokio/sdp.rs b/transports/webrtc/src/tokio/sdp.rs index d9f869d4433..f28c5c33105 100644 --- a/transports/webrtc/src/tokio/sdp.rs +++ b/transports/webrtc/src/tokio/sdp.rs @@ -21,7 +21,7 @@ use std::net::SocketAddr; pub(crate) use libp2p_webrtc_utils::sdp::random_ufrag; -use libp2p_webrtc_utils::{sdp::render_description, Fingerprint}; +use libp2p_webrtc_utils::{Fingerprint, sdp::render_description}; use webrtc::peer_connection::sdp::session_description::RTCSessionDescription; /// Creates the SDP answer used by the client. diff --git a/transports/webrtc/src/tokio/transport.rs b/transports/webrtc/src/tokio/transport.rs index 29fad180d93..d5857a42c11 100644 --- a/transports/webrtc/src/tokio/transport.rs +++ b/transports/webrtc/src/tokio/transport.rs @@ -26,7 +26,7 @@ use std::{ }; use futures::{future::BoxFuture, prelude::*, stream::SelectAll}; -use if_watch::{tokio::IfWatcher, IfEvent}; +use if_watch::{IfEvent, tokio::IfWatcher}; use libp2p_core::{ multiaddr::{Multiaddr, Protocol}, transport::{DialOpts, ListenerId, TransportError, TransportEvent}, @@ -495,9 +495,11 @@ mod tests { let mut transport = Transport::new(id_keys, Certificate::generate(&mut thread_rng()).unwrap()); - assert!(poll_fn(|cx| Pin::new(&mut transport).as_mut().poll(cx)) - .now_or_never() - .is_none()); + assert!( + poll_fn(|cx| Pin::new(&mut transport).as_mut().poll(cx)) + .now_or_never() + .is_none() + ); // Run test twice to check that there is no unexpected behaviour if `QuicTransport.listener` // is temporarily empty. @@ -543,9 +545,11 @@ mod tests { } // Poll once again so that the listener has the chance to return `Poll::Ready(None)` and // be removed from the list of listeners. - assert!(poll_fn(|cx| Pin::new(&mut transport).as_mut().poll(cx)) - .now_or_never() - .is_none()); + assert!( + poll_fn(|cx| Pin::new(&mut transport).as_mut().poll(cx)) + .now_or_never() + .is_none() + ); assert!(transport.listeners.is_empty()); } } diff --git a/transports/webrtc/src/tokio/udp_mux.rs b/transports/webrtc/src/tokio/udp_mux.rs index 090f99a8ef2..1be3bb822e0 100644 --- a/transports/webrtc/src/tokio/udp_mux.rs +++ b/transports/webrtc/src/tokio/udp_mux.rs @@ -29,14 +29,14 @@ use std::{ use async_trait::async_trait; use futures::{ + StreamExt, channel::oneshot, future::{BoxFuture, FutureExt, OptionFuture}, stream::FuturesUnordered, - StreamExt, }; use stun::{ attributes::ATTR_USERNAME, - message::{is_message as is_stun_message, Message as STUNMessage}, + message::{Message as STUNMessage, is_message as is_stun_message}, }; use thiserror::Error; use tokio::{io::ReadBuf, net::UdpSocket}; diff --git a/transports/webrtc/src/tokio/upgrade.rs b/transports/webrtc/src/tokio/upgrade.rs index 9293a474084..de7f59f93d5 100644 --- a/transports/webrtc/src/tokio/upgrade.rs +++ b/transports/webrtc/src/tokio/upgrade.rs @@ -24,17 +24,17 @@ use futures::{channel::oneshot, future::Either}; use futures_timer::Delay; use libp2p_identity as identity; use libp2p_identity::PeerId; -use libp2p_webrtc_utils::{noise, Fingerprint}; +use libp2p_webrtc_utils::{Fingerprint, noise}; use webrtc::{ - api::{setting_engine::SettingEngine, APIBuilder}, + api::{APIBuilder, setting_engine::SettingEngine}, data::data_channel::DataChannel, data_channel::data_channel_init::RTCDataChannelInit, dtls_transport::dtls_role::DTLSRole, ice::{network_type::NetworkType, udp_mux::UDPMux, udp_network::UDPNetwork}, - peer_connection::{configuration::RTCConfiguration, RTCPeerConnection}, + peer_connection::{RTCPeerConnection, configuration::RTCConfiguration}, }; -use crate::tokio::{error::Error, sdp, sdp::random_ufrag, stream::Stream, Connection}; +use crate::tokio::{Connection, error::Error, sdp, sdp::random_ufrag, stream::Stream}; /// Creates a new outbound WebRTC connection. pub(crate) async fn outbound( @@ -202,12 +202,12 @@ async fn create_substream_for_noise_handshake(conn: &RTCPeerConnection) -> Resul let channel = match futures::future::select(rx, Delay::new(Duration::from_secs(10))).await { Either::Left((Ok(channel), _)) => channel, Either::Left((Err(_), _)) => { - return Err(Error::Internal("failed to open data channel".to_owned())) + return Err(Error::Internal("failed to open data channel".to_owned())); } Either::Right(((), _)) => { return Err(Error::Internal( "data channel opening took longer than 10 seconds (see logs)".into(), - )) + )); } }; diff --git a/transports/webrtc/tests/smoke.rs b/transports/webrtc/tests/smoke.rs index 5f67c09d962..cd647c092e3 100644 --- a/transports/webrtc/tests/smoke.rs +++ b/transports/webrtc/tests/smoke.rs @@ -27,21 +27,21 @@ use std::{ }; use futures::{ + AsyncReadExt, AsyncWriteExt, FutureExt, SinkExt, channel::mpsc, future, future::{BoxFuture, Either}, ready, stream::StreamExt, - AsyncReadExt, AsyncWriteExt, FutureExt, SinkExt, }; use libp2p_core::{ + Endpoint, Multiaddr, Transport, muxing::{StreamMuxerBox, StreamMuxerExt}, transport::{Boxed, DialOpts, ListenerId, PortUse, TransportEvent}, - Endpoint, Multiaddr, Transport, }; use libp2p_identity::PeerId; use libp2p_webrtc as webrtc; -use rand::{thread_rng, RngCore}; +use rand::{RngCore, thread_rng}; use tracing_subscriber::EnvFilter; #[tokio::test] diff --git a/transports/websocket-websys/src/lib.rs b/transports/websocket-websys/src/lib.rs index 72f4068610d..c801bbe4645 100644 --- a/transports/websocket-websys/src/lib.rs +++ b/transports/websocket-websys/src/lib.rs @@ -29,8 +29,8 @@ use std::{ pin::Pin, rc::Rc, sync::{ - atomic::{AtomicBool, Ordering}, Mutex, + atomic::{AtomicBool, Ordering}, }, task::{Context, Poll}, }; diff --git a/transports/websocket/src/framed.rs b/transports/websocket/src/framed.rs index 3e667c8cc1b..2db327fe4de 100644 --- a/transports/websocket/src/framed.rs +++ b/transports/websocket/src/framed.rs @@ -33,9 +33,9 @@ use either::Either; use futures::{future::BoxFuture, prelude::*, ready, stream::BoxStream}; use futures_rustls::{client, rustls::pki_types::ServerName, server}; use libp2p_core::{ + Transport, multiaddr::{Multiaddr, Protocol}, transport::{DialOpts, ListenerId, TransportError, TransportEvent}, - Transport, }; use parking_lot::Mutex; use soketto::{ @@ -261,7 +261,7 @@ where let mut addr = match parse_ws_dial_addr(addr) { Ok(addr) => addr, Err(Error::InvalidMultiaddr(a)) => { - return Err(TransportError::MultiaddrNotSupported(a)) + return Err(TransportError::MultiaddrNotSupported(a)); } Err(e) => return Err(TransportError::Other(e)), }; @@ -521,7 +521,7 @@ fn parse_ws_dial_addr(addr: Multiaddr) -> Result> { (Some(Protocol::Dns(h)), Some(Protocol::Tcp(port))) | (Some(Protocol::Dns4(h)), Some(Protocol::Tcp(port))) | (Some(Protocol::Dns6(h)), Some(Protocol::Tcp(port))) => { - break (format!("{h}:{port}"), tls::dns_name_ref(&h)?) + break (format!("{h}:{port}"), tls::dns_name_ref(&h)?); } (Some(_), Some(p)) => { ip = Some(p); diff --git a/transports/websocket/src/lib.rs b/transports/websocket/src/lib.rs index ba46bbabfd9..8f78008745a 100644 --- a/transports/websocket/src/lib.rs +++ b/transports/websocket/src/lib.rs @@ -37,10 +37,10 @@ use error::Error; use framed::{Connection, Incoming}; use futures::{future::BoxFuture, prelude::*, ready}; use libp2p_core::{ + Transport, connection::ConnectedPoint, multiaddr::Multiaddr, - transport::{map::MapFuture, DialOpts, ListenerId, TransportError, TransportEvent}, - Transport, + transport::{DialOpts, ListenerId, TransportError, TransportEvent, map::MapFuture}, }; use rw_stream_sink::RwStreamSink; @@ -307,9 +307,9 @@ where mod tests { use futures::prelude::*; use libp2p_core::{ + Endpoint, Multiaddr, Transport, multiaddr::Protocol, transport::{DialOpts, ListenerId, PortUse}, - Endpoint, Multiaddr, Transport, }; use libp2p_identity::PeerId; use libp2p_tcp as tcp; diff --git a/transports/websocket/src/quicksink.rs b/transports/websocket/src/quicksink.rs index a0e2fb8b0f6..628994d52d3 100644 --- a/transports/websocket/src/quicksink.rs +++ b/transports/websocket/src/quicksink.rs @@ -296,7 +296,7 @@ mod tests { use async_std::{io, task}; use futures::{channel::mpsc, prelude::*}; - use crate::quicksink::{make_sink, Action}; + use crate::quicksink::{Action, make_sink}; #[test] fn smoke_test() { diff --git a/transports/websocket/src/tls.rs b/transports/websocket/src/tls.rs index 598dcc22765..7a6a1ee22f9 100644 --- a/transports/websocket/src/tls.rs +++ b/transports/websocket/src/tls.rs @@ -20,7 +20,7 @@ use std::{fmt, io, sync::Arc}; -use futures_rustls::{rustls, TlsAcceptor, TlsConnector}; +use futures_rustls::{TlsAcceptor, TlsConnector, rustls}; /// TLS configuration. #[derive(Clone)] diff --git a/transports/webtransport-websys/src/connection.rs b/transports/webtransport-websys/src/connection.rs index 75c8603864a..24d561e8fd8 100644 --- a/transports/webtransport-websys/src/connection.rs +++ b/transports/webtransport-websys/src/connection.rs @@ -2,14 +2,14 @@ use std::{ collections::HashSet, future::poll_fn, pin::Pin, - task::{ready, Context, Poll}, + task::{Context, Poll, ready}, }; use futures::FutureExt; use libp2p_core::{ + UpgradeInfo, muxing::{StreamMuxer, StreamMuxerEvent}, upgrade::OutboundConnectionUpgrade, - UpgradeInfo, }; use libp2p_identity::{Keypair, PeerId}; use multihash::Multihash; @@ -18,11 +18,11 @@ use wasm_bindgen_futures::JsFuture; use web_sys::ReadableStreamDefaultReader; use crate::{ + Error, Stream, bindings::{WebTransport, WebTransportBidirectionalStream}, endpoint::Endpoint, fused_js_promise::FusedJsPromise, utils::{detach_promise, parse_reader_response, to_js_type}, - Error, Stream, }; /// An opened WebTransport connection. @@ -133,10 +133,11 @@ impl ConnectionInner { cx: &mut Context, ) -> Poll> { // Create bidirectional stream - let val = ready!(self - .create_stream_promise - .maybe_init(|| self.session.create_bidirectional_stream()) - .poll_unpin(cx)) + let val = ready!( + self.create_stream_promise + .maybe_init(|| self.session.create_bidirectional_stream()) + .poll_unpin(cx) + ) .map_err(Error::from_js_value)?; let bidi_stream = to_js_type::(val)?; @@ -151,10 +152,11 @@ impl ConnectionInner { cx: &mut Context, ) -> Poll> { // Read the next incoming stream from the JS channel - let val = ready!(self - .incoming_stream_promise - .maybe_init(|| self.incoming_streams_reader.read()) - .poll_unpin(cx)) + let val = ready!( + self.incoming_stream_promise + .maybe_init(|| self.incoming_streams_reader.read()) + .poll_unpin(cx) + ) .map_err(Error::from_js_value)?; let val = parse_reader_response(&val) diff --git a/transports/webtransport-websys/src/endpoint.rs b/transports/webtransport-websys/src/endpoint.rs index fd209c51664..849c0d6b269 100644 --- a/transports/webtransport-websys/src/endpoint.rs +++ b/transports/webtransport-websys/src/endpoint.rs @@ -6,8 +6,8 @@ use multiaddr::{Multiaddr, Protocol}; use multihash::Multihash; use crate::{ - bindings::{WebTransportHash, WebTransportOptions}, Error, + bindings::{WebTransportHash, WebTransportOptions}, }; pub(crate) struct Endpoint { diff --git a/transports/webtransport-websys/src/fused_js_promise.rs b/transports/webtransport-websys/src/fused_js_promise.rs index d3d3858a553..853ac185b5b 100644 --- a/transports/webtransport-websys/src/fused_js_promise.rs +++ b/transports/webtransport-websys/src/fused_js_promise.rs @@ -1,7 +1,7 @@ use std::{ future::Future, pin::Pin, - task::{ready, Context, Poll}, + task::{Context, Poll, ready}, }; use futures::FutureExt; @@ -47,11 +47,12 @@ impl Future for FusedJsPromise { type Output = Result; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { - let val = ready!(self - .promise - .as_mut() - .expect("FusedJsPromise not initialized") - .poll_unpin(cx)); + let val = ready!( + self.promise + .as_mut() + .expect("FusedJsPromise not initialized") + .poll_unpin(cx) + ); // Future finished, drop it self.promise.take(); diff --git a/transports/webtransport-websys/src/stream.rs b/transports/webtransport-websys/src/stream.rs index b9d1669b6dc..704d0af69de 100644 --- a/transports/webtransport-websys/src/stream.rs +++ b/transports/webtransport-websys/src/stream.rs @@ -1,7 +1,7 @@ use std::{ io, pin::Pin, - task::{ready, Context, Poll}, + task::{Context, Poll, ready}, }; use futures::{AsyncRead, AsyncWrite, FutureExt}; @@ -10,10 +10,10 @@ use send_wrapper::SendWrapper; use web_sys::{ReadableStreamDefaultReader, WritableStreamDefaultWriter}; use crate::{ + Error, bindings::WebTransportBidirectionalStream, fused_js_promise::FusedJsPromise, utils::{detach_promise, parse_reader_response, to_io_error, to_js_type}, - Error, }; /// A stream on a connection. @@ -66,10 +66,11 @@ impl Stream { impl StreamInner { fn poll_reader_read(&mut self, cx: &mut Context) -> Poll>> { - let val = ready!(self - .reader_read_promise - .maybe_init(|| self.reader.read()) - .poll_unpin(cx)) + let val = ready!( + self.reader_read_promise + .maybe_init(|| self.reader.read()) + .poll_unpin(cx) + ) .map_err(to_io_error)?; let val = parse_reader_response(&val) @@ -125,10 +126,11 @@ impl StreamInner { // // NOTE: `desired_size` can be negative if we overcommit messages to the queue. if desired_size <= 0 || self.writer_ready_promise.is_active() { - ready!(self - .writer_ready_promise - .maybe_init(|| self.writer.ready()) - .poll_unpin(cx)) + ready!( + self.writer_ready_promise + .maybe_init(|| self.writer.ready()) + .poll_unpin(cx) + ) .map_err(to_io_error)?; } @@ -170,10 +172,11 @@ impl StreamInner { detach_promise(self.writer.close()); // Assume closed on error - let _ = ready!(self - .writer_closed_promise - .maybe_init(|| self.writer.closed()) - .poll_unpin(cx)); + let _ = ready!( + self.writer_closed_promise + .maybe_init(|| self.writer.closed()) + .poll_unpin(cx) + ); self.writer_state = StreamState::Closed; } diff --git a/transports/webtransport-websys/src/transport.rs b/transports/webtransport-websys/src/transport.rs index bad9509864e..49a17264862 100644 --- a/transports/webtransport-websys/src/transport.rs +++ b/transports/webtransport-websys/src/transport.rs @@ -12,7 +12,7 @@ use libp2p_core::{ use libp2p_identity::{Keypair, PeerId}; use multiaddr::Multiaddr; -use crate::{endpoint::Endpoint, Connection, Error}; +use crate::{Connection, Error, endpoint::Endpoint}; /// Config for the [`Transport`]. pub struct Config { diff --git a/wasm-tests/webtransport-tests/src/lib.rs b/wasm-tests/webtransport-tests/src/lib.rs index 0ff838b49e5..f4c78a0d38e 100644 --- a/wasm-tests/webtransport-tests/src/lib.rs +++ b/wasm-tests/webtransport-tests/src/lib.rs @@ -1,11 +1,11 @@ #![allow(unexpected_cfgs)] use std::{future::poll_fn, pin::Pin}; -use futures::{channel::oneshot, AsyncReadExt, AsyncWriteExt}; +use futures::{AsyncReadExt, AsyncWriteExt, channel::oneshot}; use getrandom::getrandom; use libp2p_core::{ - transport::{DialOpts, PortUse}, Endpoint, StreamMuxer, Transport as _, + transport::{DialOpts, PortUse}, }; use libp2p_identity::{Keypair, PeerId}; use libp2p_noise as noise; @@ -13,9 +13,9 @@ use libp2p_webtransport_websys::{Config, Connection, Error, Stream, Transport}; use multiaddr::{Multiaddr, Protocol}; use multihash::Multihash; use wasm_bindgen::JsCast; -use wasm_bindgen_futures::{spawn_local, JsFuture}; +use wasm_bindgen_futures::{JsFuture, spawn_local}; use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure}; -use web_sys::{window, Response}; +use web_sys::{Response, window}; wasm_bindgen_test_configure!(run_in_browser);