swarm: Split off "keep alive" functionality from DummyConnectionHandler (#2859)

Previously, the `DummyConnectionHandler` offered a "keep alive" functionality,
i.e. it allowed users to set the value of what is returned from
`ConnectionHandler::keep_alive`. This handler is primarily used in tests or
`NetworkBehaviour`s that don't open any connections (like mDNS). In all of these
cases, it is statically known whether we want to keep connections alive. As
such, this functionality is better represented by a static
`KeepAliveConnectionHandler` that always returns `KeepAlive::Yes` and a
`DummyConnectionHandler` that always returns `KeepAlive::No`.

To follow the naming conventions described in
https://github.com/libp2p/rust-libp2p/issues/2217, we introduce a top-level
`keep_alive` and `dummy` behaviour in `libp2p-swarm` that contains both the
`NetworkBehaviour` and `ConnectionHandler` implementation for either case.
This commit is contained in:
Thomas Eizinger 2022-10-06 03:50:11 +11:00 committed by GitHub
parent da0403dc45
commit bdf9209824
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 412 additions and 319 deletions

View File

@ -42,7 +42,8 @@
use futures::prelude::*;
use libp2p::swarm::{Swarm, SwarmEvent};
use libp2p::{identity, ping, Multiaddr, PeerId};
use libp2p::{identity, ping, Multiaddr, NetworkBehaviour, PeerId};
use libp2p_swarm::keep_alive;
use std::error::Error;
#[async_std::main]
@ -53,14 +54,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let transport = libp2p::development_transport(local_key).await?;
// Create a ping network behaviour.
//
// For illustrative purposes, the ping protocol is configured to
// keep the connection alive, so a continuous sequence of pings
// can be observed.
let behaviour = ping::Behaviour::new(ping::Config::new().with_keep_alive(true));
let mut swarm = Swarm::new(transport, behaviour, local_peer_id);
let mut swarm = Swarm::new(transport, Behaviour::default(), local_peer_id);
// Tell the swarm to listen on all interfaces and a random, OS-assigned
// port.
@ -82,3 +76,13 @@ async fn main() -> Result<(), Box<dyn Error>> {
}
}
}
/// Our network behaviour.
///
/// For illustrative purposes, this includes the [`KeepAlive`](behaviour::KeepAlive) behaviour so a continuous sequence of
/// pings can be observed.
#[derive(NetworkBehaviour, Default)]
struct Behaviour {
keep_alive: keep_alive::Behaviour,
ping: ping::Behaviour,
}

View File

@ -1,7 +1,5 @@
# 0.10.0 [unreleased]
- Update to `libp2p-kad` `v0.41.0`.
- Update to `libp2p-swarm` `v0.40.0`.
- Update to `libp2p-dcutr` `v0.7.0`.
@ -12,6 +10,8 @@
- Update to `libp2p-relay` `v0.13.0`.
- Update to `libp2p-kad` `v0.41.0`.
- Update to `libp2p-core` `v0.37.0`.
- Update to `libp2p-gossipsub` `v0.42.0`.

View File

@ -48,19 +48,19 @@
//! You should see a long list of metrics printed to the terminal. Check the
//! `libp2p_ping` metrics, they should be `>0`.
use env_logger::Env;
use futures::executor::block_on;
use futures::stream::StreamExt;
use libp2p::core::Multiaddr;
use libp2p::metrics::{Metrics, Recorder};
use libp2p::ping;
use libp2p::swarm::SwarmEvent;
use libp2p::{identity, PeerId, Swarm};
use libp2p::{identity, ping, NetworkBehaviour, PeerId, Swarm};
use libp2p_swarm::keep_alive;
use log::info;
use prometheus_client::registry::Registry;
use std::error::Error;
use std::thread;
use env_logger::Env;
use log::info;
mod http_service;
fn main() -> Result<(), Box<dyn Error>> {
@ -72,7 +72,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let mut swarm = Swarm::new(
block_on(libp2p::development_transport(local_key))?,
ping::Behaviour::new(ping::Config::new().with_keep_alive(true)),
Behaviour::default(),
local_peer_id,
);
@ -91,7 +91,7 @@ fn main() -> Result<(), Box<dyn Error>> {
block_on(async {
loop {
match swarm.select_next_some().await {
SwarmEvent::Behaviour(ping_event) => {
SwarmEvent::Behaviour(BehaviourEvent::Ping(ping_event)) => {
info!("{:?}", ping_event);
metrics.record(&ping_event);
}
@ -104,3 +104,13 @@ fn main() -> Result<(), Box<dyn Error>> {
});
Ok(())
}
/// Our network behaviour.
///
/// For illustrative purposes, this includes the [`keep_alive::Behaviour`]) behaviour so the ping actually happen
/// and can be observed via the metrics.
#[derive(NetworkBehaviour, Default)]
struct Behaviour {
keep_alive: keep_alive::Behaviour,
ping: ping::Behaviour,
}

View File

@ -28,7 +28,7 @@ use libp2p::core::{
};
use libp2p::mplex::MplexConfig;
use libp2p::plaintext::PlainText2Config;
use libp2p::swarm::{DummyBehaviour, Swarm, SwarmEvent};
use libp2p::swarm::{dummy, Swarm, SwarmEvent};
use rand::random;
use std::task::Poll;
@ -61,8 +61,8 @@ fn transport_upgrade() {
let listen_addr = Multiaddr::from(Protocol::Memory(random::<u64>()));
let mut dialer = Swarm::new(dialer_transport, DummyBehaviour::default(), dialer_id);
let mut listener = Swarm::new(listener_transport, DummyBehaviour::default(), listener_id);
let mut dialer = Swarm::new(dialer_transport, dummy::Behaviour, dialer_id);
let mut listener = Swarm::new(listener_transport, dummy::Behaviour, listener_id);
listener.listen_on(listen_addr).unwrap();
let (addr_sender, addr_receiver) = oneshot::channel();

View File

@ -23,7 +23,7 @@ use either::Either;
use libp2p_core::connection::ConnectionId;
use libp2p_core::upgrade::{self, DeniedUpgrade};
use libp2p_core::{ConnectedPoint, PeerId};
use libp2p_swarm::handler::DummyConnectionHandler;
use libp2p_swarm::dummy;
use libp2p_swarm::handler::SendWrapper;
use libp2p_swarm::{ConnectionHandler, IntoConnectionHandler};
@ -44,7 +44,7 @@ pub enum Role {
}
impl IntoConnectionHandler for Prototype {
type Handler = Either<relayed::Handler, Either<direct::Handler, DummyConnectionHandler>>;
type Handler = Either<relayed::Handler, Either<direct::Handler, dummy::ConnectionHandler>>;
fn into_handler(self, _remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler {
match self {
@ -52,7 +52,7 @@ impl IntoConnectionHandler for Prototype {
if endpoint.is_relayed() {
Either::Left(relayed::Handler::new(endpoint.clone()))
} else {
Either::Right(Either::Right(DummyConnectionHandler::default()))
Either::Right(Either::Right(dummy::ConnectionHandler))
}
}
Self::DirectConnection {

View File

@ -31,8 +31,7 @@ use if_watch::{IfEvent, IfWatcher};
use libp2p_core::transport::ListenerId;
use libp2p_core::{Multiaddr, PeerId};
use libp2p_swarm::{
handler::DummyConnectionHandler, ConnectionHandler, NetworkBehaviour, NetworkBehaviourAction,
PollParameters,
dummy, ConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters,
};
use smallvec::SmallVec;
use std::collections::hash_map::{Entry, HashMap};
@ -120,11 +119,11 @@ where
T: Builder + Stream,
S: AsyncSocket,
{
type ConnectionHandler = DummyConnectionHandler;
type ConnectionHandler = dummy::ConnectionHandler;
type OutEvent = MdnsEvent;
fn new_handler(&mut self) -> Self::ConnectionHandler {
DummyConnectionHandler::default()
dummy::ConnectionHandler
}
fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr> {
@ -168,7 +167,7 @@ where
&mut self,
cx: &mut Context<'_>,
params: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, DummyConnectionHandler>> {
) -> Poll<NetworkBehaviourAction<Self::OutEvent, dummy::ConnectionHandler>> {
// Poll ifwatch.
while let Poll::Ready(event) = Pin::new(&mut self.if_watch).poll(cx) {
match event {

View File

@ -8,8 +8,11 @@
- Update to `libp2p-swarm` `v0.40.0`.
- Deprecate `Config::with_keep_alive`. See [PR 2859].
[PR 2857]: https://github.com/libp2p/rust-libp2p/pull/2857
[PR 2937]: https://github.com/libp2p/rust-libp2p/pull/2937
[PR 2859]: https://github.com/libp2p/rust-libp2p/pull/2859/
# 0.39.0

View File

@ -111,6 +111,10 @@ impl Config {
/// If the maximum number of allowed ping failures is reached, the
/// connection is always terminated as a result of [`ConnectionHandler::poll`]
/// returning an error, regardless of the keep-alive setting.
#[deprecated(
since = "0.40.0",
note = "Use `libp2p::swarm::behaviour::KeepAlive` if you need to keep connections alive unconditionally."
)]
pub fn with_keep_alive(mut self, b: bool) -> Self {
self.keep_alive = b;
self

View File

@ -30,24 +30,24 @@ use libp2p::core::{
use libp2p::mplex;
use libp2p::noise;
use libp2p::ping;
use libp2p::swarm::{DummyBehaviour, KeepAlive, Swarm, SwarmEvent};
use libp2p::swarm::{Swarm, SwarmEvent};
use libp2p::tcp::{GenTcpConfig, TcpTransport};
use libp2p::yamux;
use libp2p::NetworkBehaviour;
use libp2p_swarm::keep_alive;
use quickcheck::*;
use std::{num::NonZeroU8, time::Duration};
#[test]
fn ping_pong() {
fn prop(count: NonZeroU8, muxer: MuxerChoice) {
let cfg = ping::Config::new()
.with_keep_alive(true)
.with_interval(Duration::from_millis(10));
let cfg = ping::Config::new().with_interval(Duration::from_millis(10));
let (peer1_id, trans) = mk_transport(muxer);
let mut swarm1 = Swarm::new(trans, ping::Behaviour::new(cfg.clone()), peer1_id);
let mut swarm1 = Swarm::new(trans, Behaviour::new(cfg.clone()), peer1_id);
let (peer2_id, trans) = mk_transport(muxer);
let mut swarm2 = Swarm::new(trans, ping::Behaviour::new(cfg), peer2_id);
let mut swarm2 = Swarm::new(trans, Behaviour::new(cfg), peer2_id);
let (mut tx, mut rx) = mpsc::channel::<Multiaddr>(1);
@ -62,16 +62,19 @@ fn ping_pong() {
loop {
match swarm1.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => tx.send(address).await.unwrap(),
SwarmEvent::Behaviour(ping::Event {
SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event {
peer,
result: Ok(ping::Success::Ping { rtt }),
}) => {
})) => {
count1 -= 1;
if count1 == 0 {
return (pid1, peer, rtt);
}
}
SwarmEvent::Behaviour(ping::Event { result: Err(e), .. }) => {
SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event {
result: Err(e),
..
})) => {
panic!("Ping failure: {:?}", e)
}
_ => {}
@ -85,16 +88,19 @@ fn ping_pong() {
loop {
match swarm2.select_next_some().await {
SwarmEvent::Behaviour(ping::Event {
SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event {
peer,
result: Ok(ping::Success::Ping { rtt }),
}) => {
})) => {
count2 -= 1;
if count2 == 0 {
return (pid2, peer, rtt);
}
}
SwarmEvent::Behaviour(ping::Event { result: Err(e), .. }) => {
SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event {
result: Err(e),
..
})) => {
panic!("Ping failure: {:?}", e)
}
_ => {}
@ -117,16 +123,15 @@ fn ping_pong() {
fn max_failures() {
fn prop(max_failures: NonZeroU8, muxer: MuxerChoice) {
let cfg = ping::Config::new()
.with_keep_alive(true)
.with_interval(Duration::from_millis(10))
.with_timeout(Duration::from_millis(0))
.with_max_failures(max_failures.into());
let (peer1_id, trans) = mk_transport(muxer);
let mut swarm1 = Swarm::new(trans, ping::Behaviour::new(cfg.clone()), peer1_id);
let mut swarm1 = Swarm::new(trans, Behaviour::new(cfg.clone()), peer1_id);
let (peer2_id, trans) = mk_transport(muxer);
let mut swarm2 = Swarm::new(trans, ping::Behaviour::new(cfg), peer2_id);
let mut swarm2 = Swarm::new(trans, Behaviour::new(cfg), peer2_id);
let (mut tx, mut rx) = mpsc::channel::<Multiaddr>(1);
@ -139,13 +144,16 @@ fn max_failures() {
loop {
match swarm1.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => tx.send(address).await.unwrap(),
SwarmEvent::Behaviour(ping::Event {
SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event {
result: Ok(ping::Success::Ping { .. }),
..
}) => {
})) => {
count1 = 0; // there may be an occasional success
}
SwarmEvent::Behaviour(ping::Event { result: Err(_), .. }) => {
SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event {
result: Err(_),
..
})) => {
count1 += 1;
}
SwarmEvent::ConnectionClosed { .. } => return count1,
@ -161,13 +169,16 @@ fn max_failures() {
loop {
match swarm2.select_next_some().await {
SwarmEvent::Behaviour(ping::Event {
SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event {
result: Ok(ping::Success::Ping { .. }),
..
}) => {
})) => {
count2 = 0; // there may be an occasional success
}
SwarmEvent::Behaviour(ping::Event { result: Err(_), .. }) => {
SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event {
result: Err(_),
..
})) => {
count2 += 1;
}
SwarmEvent::ConnectionClosed { .. } => return count2,
@ -187,18 +198,10 @@ fn max_failures() {
#[test]
fn unsupported_doesnt_fail() {
let (peer1_id, trans) = mk_transport(MuxerChoice::Mplex);
let mut swarm1 = Swarm::new(
trans,
DummyBehaviour::with_keep_alive(KeepAlive::Yes),
peer1_id,
);
let mut swarm1 = Swarm::new(trans, keep_alive::Behaviour, peer1_id);
let (peer2_id, trans) = mk_transport(MuxerChoice::Mplex);
let mut swarm2 = Swarm::new(
trans,
ping::Behaviour::new(ping::Config::new().with_keep_alive(true)),
peer2_id,
);
let mut swarm2 = Swarm::new(trans, Behaviour::default(), peer2_id);
let (mut tx, mut rx) = mpsc::channel::<Multiaddr>(1);
@ -218,10 +221,10 @@ fn unsupported_doesnt_fail() {
loop {
match swarm2.select_next_some().await {
SwarmEvent::Behaviour(ping::Event {
SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event {
result: Err(ping::Failure::Unsupported),
..
}) => {
})) => {
swarm2.disconnect_peer_id(peer1_id).unwrap();
}
SwarmEvent::ConnectionClosed { cause: Some(e), .. } => {
@ -265,3 +268,18 @@ impl Arbitrary for MuxerChoice {
*g.choose(&[MuxerChoice::Mplex, MuxerChoice::Yamux]).unwrap()
}
}
#[derive(NetworkBehaviour, Default)]
struct Behaviour {
keep_alive: keep_alive::Behaviour,
ping: ping::Behaviour,
}
impl Behaviour {
fn new(config: ping::Config) -> Self {
Self {
keep_alive: keep_alive::Behaviour,
ping: ping::Behaviour::new(config),
}
}
}

View File

@ -35,7 +35,7 @@ use futures::stream::StreamExt;
use libp2p_core::connection::{ConnectedPoint, ConnectionId};
use libp2p_core::{Multiaddr, PeerId};
use libp2p_swarm::dial_opts::DialOpts;
use libp2p_swarm::handler::DummyConnectionHandler;
use libp2p_swarm::dummy;
use libp2p_swarm::{
ConnectionHandlerUpgrErr, NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction,
NotifyHandler, PollParameters,
@ -144,7 +144,7 @@ impl NetworkBehaviour for Client {
peer_id: &PeerId,
connection_id: &ConnectionId,
endpoint: &ConnectedPoint,
_handler: Either<handler::Handler, DummyConnectionHandler>,
_handler: Either<handler::Handler, dummy::ConnectionHandler>,
_remaining_established: usize,
) {
if !endpoint.is_relayed() {

View File

@ -31,12 +31,10 @@ use instant::Instant;
use libp2p_core::either::EitherError;
use libp2p_core::multiaddr::Protocol;
use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId};
use libp2p_swarm::handler::{
DummyConnectionHandler, InboundUpgradeSend, OutboundUpgradeSend, SendWrapper,
};
use libp2p_swarm::handler::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper};
use libp2p_swarm::{
ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler,
KeepAlive, NegotiatedSubstream, SubstreamProtocol,
dummy, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr,
IntoConnectionHandler, KeepAlive, NegotiatedSubstream, SubstreamProtocol,
};
use log::debug;
use std::collections::{HashMap, VecDeque};
@ -125,7 +123,7 @@ impl Prototype {
}
impl IntoConnectionHandler for Prototype {
type Handler = Either<Handler, DummyConnectionHandler>;
type Handler = Either<Handler, dummy::ConnectionHandler>;
fn into_handler(self, remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler {
if endpoint.is_relayed() {
@ -138,7 +136,7 @@ impl IntoConnectionHandler for Prototype {
}
// Deny all substreams on relayed connection.
Either::Right(DummyConnectionHandler::default())
Either::Right(dummy::ConnectionHandler)
} else {
let mut handler = Handler {
remote_peer_id: *remote_peer_id,

View File

@ -30,9 +30,8 @@ use instant::Instant;
use libp2p_core::connection::{ConnectedPoint, ConnectionId};
use libp2p_core::multiaddr::Protocol;
use libp2p_core::PeerId;
use libp2p_swarm::handler::DummyConnectionHandler;
use libp2p_swarm::{
ConnectionHandlerUpgrErr, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler,
dummy, ConnectionHandlerUpgrErr, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler,
PollParameters,
};
use std::collections::{hash_map, HashMap, HashSet, VecDeque};
@ -234,7 +233,7 @@ impl NetworkBehaviour for Relay {
peer: &PeerId,
connection: &ConnectionId,
_: &ConnectedPoint,
_handler: Either<handler::Handler, DummyConnectionHandler>,
_handler: Either<handler::Handler, dummy::ConnectionHandler>,
_remaining_established: usize,
) {
if let hash_map::Entry::Occupied(mut peer) = self.reservations.entry(*peer) {
@ -283,7 +282,7 @@ impl NetworkBehaviour for Relay {
assert!(
!endpoint.is_relayed(),
"`DummyConnectionHandler` handles relayed connections. It \
"`dummy::ConnectionHandler` handles relayed connections. It \
denies all inbound substreams."
);
@ -410,7 +409,7 @@ impl NetworkBehaviour for Relay {
assert!(
!endpoint.is_relayed(),
"`DummyConnectionHandler` handles relayed connections. It \
"`dummy::ConnectionHandler` handles relayed connections. It \
denies all inbound substreams."
);

View File

@ -33,11 +33,11 @@ use instant::Instant;
use libp2p_core::connection::ConnectionId;
use libp2p_core::either::EitherError;
use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId};
use libp2p_swarm::handler::{DummyConnectionHandler, SendWrapper};
use libp2p_swarm::handler::SendWrapper;
use libp2p_swarm::handler::{InboundUpgradeSend, OutboundUpgradeSend};
use libp2p_swarm::{
ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler,
KeepAlive, NegotiatedSubstream, SubstreamProtocol,
dummy, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr,
IntoConnectionHandler, KeepAlive, NegotiatedSubstream, SubstreamProtocol,
};
use std::collections::VecDeque;
use std::fmt;
@ -342,12 +342,12 @@ pub struct Prototype {
}
impl IntoConnectionHandler for Prototype {
type Handler = Either<Handler, DummyConnectionHandler>;
type Handler = Either<Handler, dummy::ConnectionHandler>;
fn into_handler(self, _remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler {
if endpoint.is_relayed() {
// Deny all substreams on relayed connection.
Either::Right(DummyConnectionHandler::default())
Either::Right(dummy::ConnectionHandler)
} else {
Either::Left(Handler {
endpoint: endpoint.clone(),

View File

@ -23,10 +23,11 @@ use libp2p::core::identity;
use libp2p::core::PeerId;
use libp2p::multiaddr::Protocol;
use libp2p::ping;
use libp2p::swarm::SwarmEvent;
use libp2p::swarm::{keep_alive, SwarmEvent};
use libp2p::Swarm;
use libp2p::{development_transport, rendezvous, Multiaddr};
use std::time::Duration;
use void::Void;
const NAMESPACE: &str = "rendezvous";
@ -44,11 +45,8 @@ async fn main() {
development_transport(identity.clone()).await.unwrap(),
MyBehaviour {
rendezvous: rendezvous::client::Behaviour::new(identity.clone()),
ping: ping::Behaviour::new(
ping::Config::new()
.with_interval(Duration::from_secs(1))
.with_keep_alive(true),
),
ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
keep_alive: keep_alive::Behaviour,
},
PeerId::from(identity.public()),
);
@ -139,10 +137,17 @@ impl From<ping::Event> for MyEvent {
}
}
impl From<Void> for MyEvent {
fn from(event: Void) -> Self {
void::unreachable(event)
}
}
#[derive(libp2p::NetworkBehaviour)]
#[behaviour(event_process = false)]
#[behaviour(out_event = "MyEvent")]
struct MyBehaviour {
rendezvous: rendezvous::client::Behaviour,
ping: ping::Behaviour,
keep_alive: keep_alive::Behaviour,
}

View File

@ -23,10 +23,11 @@ use libp2p::core::identity;
use libp2p::core::PeerId;
use libp2p::identify;
use libp2p::ping;
use libp2p::swarm::{Swarm, SwarmEvent};
use libp2p::swarm::{keep_alive, Swarm, SwarmEvent};
use libp2p::{development_transport, rendezvous};
use libp2p::{Multiaddr, NetworkBehaviour};
use std::time::Duration;
use void::Void;
#[tokio::main]
async fn main() {
@ -47,11 +48,8 @@ async fn main() {
identity.public(),
)),
rendezvous: rendezvous::client::Behaviour::new(identity.clone()),
ping: ping::Behaviour::new(
ping::Config::new()
.with_interval(Duration::from_secs(1))
.with_keep_alive(true),
),
ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
keep_alive: keep_alive::Behaviour,
},
PeerId::from(identity.public()),
);
@ -139,6 +137,12 @@ impl From<ping::Event> for MyEvent {
}
}
impl From<Void> for MyEvent {
fn from(event: Void) -> Self {
void::unreachable(event)
}
}
#[derive(NetworkBehaviour)]
#[behaviour(event_process = false)]
#[behaviour(out_event = "MyEvent")]
@ -146,4 +150,5 @@ struct MyBehaviour {
identify: identify::Behaviour,
rendezvous: rendezvous::client::Behaviour,
ping: ping::Behaviour,
keep_alive: keep_alive::Behaviour,
}

View File

@ -23,9 +23,10 @@ use libp2p::core::identity;
use libp2p::core::PeerId;
use libp2p::identify;
use libp2p::ping;
use libp2p::swarm::{Swarm, SwarmEvent};
use libp2p::swarm::{keep_alive, Swarm, SwarmEvent};
use libp2p::NetworkBehaviour;
use libp2p::{development_transport, rendezvous};
use void::Void;
/// Examples for the rendezvous protocol:
///
@ -51,7 +52,8 @@ async fn main() {
identity.public(),
)),
rendezvous: rendezvous::server::Behaviour::new(rendezvous::server::Config::default()),
ping: ping::Behaviour::new(ping::Config::new().with_keep_alive(true)),
ping: ping::Behaviour::new(ping::Config::new()),
keep_alive: keep_alive::Behaviour,
},
PeerId::from(identity.public()),
);
@ -123,6 +125,12 @@ impl From<identify::Event> for MyEvent {
}
}
impl From<Void> for MyEvent {
fn from(event: Void) -> Self {
void::unreachable(event)
}
}
#[derive(NetworkBehaviour)]
#[behaviour(event_process = false)]
#[behaviour(out_event = "MyEvent")]
@ -130,4 +138,5 @@ struct MyBehaviour {
identify: identify::Behaviour,
rendezvous: rendezvous::server::Behaviour,
ping: ping::Behaviour,
keep_alive: keep_alive::Behaviour,
}

View File

@ -19,7 +19,7 @@
// DEALINGS IN THE SOFTWARE.
use futures::prelude::*;
use libp2p::swarm::{NetworkBehaviour, SwarmEvent};
use libp2p::swarm::{dummy, NetworkBehaviour, SwarmEvent};
use libp2p::{identify, ping};
use libp2p_swarm_derive::*;
use std::fmt::Debug;
@ -354,7 +354,6 @@ fn generated_out_event_derive_debug() {
#[test]
fn custom_out_event_no_type_parameters() {
use libp2p::core::connection::ConnectionId;
use libp2p::swarm::handler::DummyConnectionHandler;
use libp2p::swarm::{
ConnectionHandler, IntoConnectionHandler, NetworkBehaviourAction, PollParameters,
};
@ -367,11 +366,11 @@ fn custom_out_event_no_type_parameters() {
}
impl<T> NetworkBehaviour for TemplatedBehaviour<T> {
type ConnectionHandler = DummyConnectionHandler;
type ConnectionHandler = dummy::ConnectionHandler;
type OutEvent = void::Void;
fn new_handler(&mut self) -> Self::ConnectionHandler {
DummyConnectionHandler::default()
dummy::ConnectionHandler
}
fn inject_event(

View File

@ -4,7 +4,12 @@
- Update to `libp2p-core` `v0.37.0`.
- Introduce `libp2p_swarm::keep_alive::ConnectionHandler` in favor of removing `keep_alive` from
`libp2p_swarm::dummy::ConnectionHandler`. `dummy::ConnectionHandler` now literally does not do anything. In the same
spirit, introduce `libp2p_swarm::keep_alive::Behaviour` and `libp2p_swarm::dummy::Behaviour`. See [PR 2859].
[PR 2857]: https://github.com/libp2p/rust-libp2p/pull/2857
[PR 2859]: https://github.com/libp2p/rust-libp2p/pull/2859/
- Pass actual `PeerId` of dial to `NetworkBehaviour::inject_dial_failure` on `DialError::ConnectionLimit`. See [PR 2928].

View File

@ -62,9 +62,9 @@ pub(crate) type THandlerOutEvent<THandler> =
/// [`Toggle`](crate::behaviour::toggle::Toggle) [`NetworkBehaviour`].
///
/// ``` rust
/// # use libp2p_swarm::DummyBehaviour;
/// # use libp2p_swarm::dummy;
/// # use libp2p_swarm::behaviour::toggle::Toggle;
/// let my_behaviour = DummyBehaviour::default();
/// let my_behaviour = dummy::Behaviour;
/// let my_toggled_behaviour = Toggle::from(Some(my_behaviour));
/// ```
///

View File

@ -411,7 +411,7 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::handler::DummyConnectionHandler;
use crate::dummy;
/// A disabled [`ToggleConnectionHandler`] can receive listen upgrade errors in
/// the following two cases:
@ -429,7 +429,7 @@ mod tests {
/// [`ToggleConnectionHandler`] should ignore the error in both of these cases.
#[test]
fn ignore_listen_upgrade_error_when_disabled() {
let mut handler = ToggleConnectionHandler::<DummyConnectionHandler> { inner: None };
let mut handler = ToggleConnectionHandler::<dummy::ConnectionHandler> { inner: None };
handler.inject_listen_upgrade_error(Either::Right(()), ConnectionHandlerUpgrErr::Timeout);
}

View File

@ -552,7 +552,7 @@ enum Shutdown {
#[cfg(test)]
mod tests {
use super::*;
use crate::handler::DummyConnectionHandler;
use crate::keep_alive;
use futures::AsyncRead;
use futures::AsyncWrite;
use libp2p_core::upgrade::DeniedUpgrade;
@ -572,9 +572,7 @@ mod tests {
StreamMuxerBox::new(DummyStreamMuxer {
counter: alive_substream_counter.clone(),
}),
DummyConnectionHandler {
keep_alive: KeepAlive::Yes,
},
keep_alive::ConnectionHandler,
None,
max_negotiating_inbound_streams,
);

104
swarm/src/dummy.rs Normal file
View File

@ -0,0 +1,104 @@
use crate::behaviour::{NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use crate::handler::{InboundUpgradeSend, OutboundUpgradeSend};
use crate::{ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, SubstreamProtocol};
use libp2p_core::connection::ConnectionId;
use libp2p_core::upgrade::DeniedUpgrade;
use libp2p_core::PeerId;
use libp2p_core::UpgradeError;
use std::task::{Context, Poll};
use void::Void;
/// Implementation of [`NetworkBehaviour`] that doesn't do anything.
pub struct Behaviour;
impl NetworkBehaviour for Behaviour {
type ConnectionHandler = ConnectionHandler;
type OutEvent = Void;
fn new_handler(&mut self) -> Self::ConnectionHandler {
ConnectionHandler
}
fn inject_event(&mut self, _: PeerId, _: ConnectionId, event: Void) {
void::unreachable(event)
}
fn poll(
&mut self,
_: &mut Context<'_>,
_: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
Poll::Pending
}
}
/// An implementation of [`ConnectionHandler`] that neither handles any protocols nor does it keep the connection alive.
#[derive(Clone)]
pub struct ConnectionHandler;
impl crate::handler::ConnectionHandler for ConnectionHandler {
type InEvent = Void;
type OutEvent = Void;
type Error = Void;
type InboundProtocol = DeniedUpgrade;
type OutboundProtocol = DeniedUpgrade;
type InboundOpenInfo = ();
type OutboundOpenInfo = Void;
fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo> {
SubstreamProtocol::new(DeniedUpgrade, ())
}
fn inject_fully_negotiated_inbound(
&mut self,
protocol: <Self::InboundProtocol as InboundUpgradeSend>::Output,
_: Self::InboundOpenInfo,
) {
void::unreachable(protocol)
}
fn inject_fully_negotiated_outbound(
&mut self,
protocol: <Self::OutboundProtocol as OutboundUpgradeSend>::Output,
_: Self::OutboundOpenInfo,
) {
void::unreachable(protocol)
}
fn inject_event(&mut self, event: Self::InEvent) {
void::unreachable(event)
}
fn inject_dial_upgrade_error(
&mut self,
_: Self::OutboundOpenInfo,
error: ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>,
) {
match error {
ConnectionHandlerUpgrErr::Timeout => unreachable!(),
ConnectionHandlerUpgrErr::Timer => unreachable!(),
ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)) => void::unreachable(e),
ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(_)) => {
unreachable!("Denied upgrade does not support any protocols")
}
}
}
fn connection_keep_alive(&self) -> KeepAlive {
KeepAlive::No
}
fn poll(
&mut self,
_: &mut Context<'_>,
) -> Poll<
ConnectionHandlerEvent<
Self::OutboundProtocol,
Self::OutboundOpenInfo,
Self::OutEvent,
Self::Error,
>,
> {
Poll::Pending
}
}

View File

@ -38,7 +38,6 @@
//! > the network as a whole, see the
//! > [`NetworkBehaviour`](crate::behaviour::NetworkBehaviour) trait.
mod dummy;
pub mod either;
mod map_in;
mod map_out;
@ -53,7 +52,6 @@ use instant::Instant;
use libp2p_core::{upgrade::UpgradeError, ConnectedPoint, Multiaddr, PeerId};
use std::{cmp::Ordering, error, fmt, task::Context, task::Poll, time::Duration};
pub use dummy::DummyConnectionHandler;
pub use map_in::MapInEvent;
pub use map_out::MapOutEvent;
pub use one_shot::{OneShotHandler, OneShotHandlerConfig};

View File

@ -1,117 +0,0 @@
// Copyright 2018 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use crate::handler::{
ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive,
SubstreamProtocol,
};
use crate::NegotiatedSubstream;
use libp2p_core::{
upgrade::{DeniedUpgrade, InboundUpgrade, OutboundUpgrade},
Multiaddr,
};
use std::task::{Context, Poll};
use void::Void;
/// Implementation of [`ConnectionHandler`] that doesn't handle anything.
#[derive(Clone, Debug)]
pub struct DummyConnectionHandler {
pub keep_alive: KeepAlive,
}
impl Default for DummyConnectionHandler {
fn default() -> Self {
DummyConnectionHandler {
keep_alive: KeepAlive::No,
}
}
}
impl ConnectionHandler for DummyConnectionHandler {
type InEvent = Void;
type OutEvent = Void;
type Error = Void;
type InboundProtocol = DeniedUpgrade;
type OutboundProtocol = DeniedUpgrade;
type OutboundOpenInfo = Void;
type InboundOpenInfo = ();
fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo> {
SubstreamProtocol::new(DeniedUpgrade, ())
}
fn inject_fully_negotiated_inbound(
&mut self,
_: <Self::InboundProtocol as InboundUpgrade<NegotiatedSubstream>>::Output,
_: Self::InboundOpenInfo,
) {
unreachable!("`DeniedUpgrade` is never successful.");
}
fn inject_fully_negotiated_outbound(
&mut self,
_: <Self::OutboundProtocol as OutboundUpgrade<NegotiatedSubstream>>::Output,
v: Self::OutboundOpenInfo,
) {
void::unreachable(v)
}
fn inject_event(&mut self, v: Self::InEvent) {
void::unreachable(v)
}
fn inject_address_change(&mut self, _: &Multiaddr) {}
fn inject_dial_upgrade_error(
&mut self,
_: Self::OutboundOpenInfo,
_: ConnectionHandlerUpgrErr<
<Self::OutboundProtocol as OutboundUpgrade<NegotiatedSubstream>>::Error,
>,
) {
}
fn inject_listen_upgrade_error(
&mut self,
_: Self::InboundOpenInfo,
_: ConnectionHandlerUpgrErr<
<Self::InboundProtocol as InboundUpgrade<NegotiatedSubstream>>::Error,
>,
) {
}
fn connection_keep_alive(&self) -> KeepAlive {
self.keep_alive
}
fn poll(
&mut self,
_: &mut Context<'_>,
) -> Poll<
ConnectionHandlerEvent<
Self::OutboundProtocol,
Self::OutboundOpenInfo,
Self::OutEvent,
Self::Error,
>,
> {
Poll::Pending
}
}

119
swarm/src/keep_alive.rs Normal file
View File

@ -0,0 +1,119 @@
use crate::behaviour::{NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use crate::handler::{
ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, SubstreamProtocol,
};
use crate::NegotiatedSubstream;
use libp2p_core::connection::ConnectionId;
use libp2p_core::PeerId;
use libp2p_core::{
upgrade::{DeniedUpgrade, InboundUpgrade, OutboundUpgrade},
Multiaddr,
};
use std::task::{Context, Poll};
use void::Void;
/// Implementation of [`NetworkBehaviour`] that doesn't do anything other than keep all connections alive.
///
/// This is primarily useful for test code. In can however occasionally be useful for production code too.
/// The caveat is that open connections consume system resources and should thus be shutdown when
/// they are not in use. Connections can also fail at any time so really, your application should be
/// designed to establish them when necessary, making the use of this behaviour likely redundant.
#[derive(Default)]
pub struct Behaviour;
impl NetworkBehaviour for Behaviour {
type ConnectionHandler = ConnectionHandler;
type OutEvent = Void;
fn new_handler(&mut self) -> Self::ConnectionHandler {
ConnectionHandler
}
fn inject_event(&mut self, _: PeerId, _: ConnectionId, event: Void) {
void::unreachable(event)
}
fn poll(
&mut self,
_: &mut Context<'_>,
_: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
Poll::Pending
}
}
/// Implementation of [`ConnectionHandler`] that doesn't handle anything but keeps the connection alive.
#[derive(Clone, Debug)]
pub struct ConnectionHandler;
impl crate::handler::ConnectionHandler for ConnectionHandler {
type InEvent = Void;
type OutEvent = Void;
type Error = Void;
type InboundProtocol = DeniedUpgrade;
type OutboundProtocol = DeniedUpgrade;
type InboundOpenInfo = ();
type OutboundOpenInfo = Void;
fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo> {
SubstreamProtocol::new(DeniedUpgrade, ())
}
fn inject_fully_negotiated_inbound(
&mut self,
protocol: <Self::InboundProtocol as InboundUpgrade<NegotiatedSubstream>>::Output,
_: Self::InboundOpenInfo,
) {
void::unreachable(protocol);
}
fn inject_fully_negotiated_outbound(
&mut self,
protocol: <Self::OutboundProtocol as OutboundUpgrade<NegotiatedSubstream>>::Output,
_: Self::OutboundOpenInfo,
) {
void::unreachable(protocol)
}
fn inject_event(&mut self, v: Self::InEvent) {
void::unreachable(v)
}
fn inject_address_change(&mut self, _: &Multiaddr) {}
fn inject_dial_upgrade_error(
&mut self,
_: Self::OutboundOpenInfo,
_: ConnectionHandlerUpgrErr<
<Self::OutboundProtocol as OutboundUpgrade<NegotiatedSubstream>>::Error,
>,
) {
}
fn inject_listen_upgrade_error(
&mut self,
_: Self::InboundOpenInfo,
_: ConnectionHandlerUpgrErr<
<Self::InboundProtocol as InboundUpgrade<NegotiatedSubstream>>::Error,
>,
) {
}
fn connection_keep_alive(&self) -> KeepAlive {
KeepAlive::Yes
}
fn poll(
&mut self,
_: &mut Context<'_>,
) -> Poll<
ConnectionHandlerEvent<
Self::OutboundProtocol,
Self::OutboundOpenInfo,
Self::OutEvent,
Self::Error,
>,
> {
Poll::Pending
}
}

View File

@ -61,7 +61,9 @@ mod upgrade;
pub mod behaviour;
pub mod dial_opts;
pub mod dummy;
pub mod handler;
pub mod keep_alive;
pub use behaviour::{
CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters,
@ -348,11 +350,11 @@ where
/// # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition};
/// # use libp2p_core::{Multiaddr, PeerId, Transport};
/// # use libp2p_core::transport::dummy::DummyTransport;
/// # use libp2p_swarm::DummyBehaviour;
/// # use libp2p_swarm::dummy;
/// #
/// let mut swarm = Swarm::new(
/// DummyTransport::new().boxed(),
/// DummyBehaviour::default(),
/// dummy::Behaviour,
/// PeerId::random(),
/// );
///
@ -1514,58 +1516,6 @@ impl error::Error for DialError {
}
}
/// Dummy implementation of [`NetworkBehaviour`] that doesn't do anything.
#[derive(Clone)]
pub struct DummyBehaviour {
keep_alive: KeepAlive,
}
impl DummyBehaviour {
pub fn with_keep_alive(keep_alive: KeepAlive) -> Self {
Self { keep_alive }
}
pub fn keep_alive_mut(&mut self) -> &mut KeepAlive {
&mut self.keep_alive
}
}
impl Default for DummyBehaviour {
fn default() -> Self {
Self {
keep_alive: KeepAlive::No,
}
}
}
impl NetworkBehaviour for DummyBehaviour {
type ConnectionHandler = handler::DummyConnectionHandler;
type OutEvent = void::Void;
fn new_handler(&mut self) -> Self::ConnectionHandler {
handler::DummyConnectionHandler {
keep_alive: self.keep_alive,
}
}
fn inject_event(
&mut self,
_: PeerId,
_: ConnectionId,
event: <Self::ConnectionHandler as ConnectionHandler>::OutEvent,
) {
void::unreachable(event)
}
fn poll(
&mut self,
_: &mut Context<'_>,
_: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
Poll::Pending
}
}
/// Information about the connections obtained by [`Swarm::network_info()`].
#[derive(Clone, Debug)]
pub struct NetworkInfo {
@ -1617,7 +1567,6 @@ fn p2p_addr(peer: Option<PeerId>, addr: Multiaddr) -> Result<Multiaddr, Multiadd
#[cfg(test)]
mod tests {
use super::*;
use crate::handler::DummyConnectionHandler;
use crate::test::{CallTraceBehaviour, MockBehaviour};
use futures::executor::block_on;
use futures::future::poll_fn;
@ -1714,9 +1663,7 @@ mod tests {
fn test_connect_disconnect_ban() {
// Since the test does not try to open any substreams, we can
// use the dummy protocols handler.
let handler_proto = DummyConnectionHandler {
keep_alive: KeepAlive::Yes,
};
let handler_proto = keep_alive::ConnectionHandler;
let mut swarm1 = new_test_swarm::<_, ()>(handler_proto.clone()).build();
let mut swarm2 = new_test_swarm::<_, ()>(handler_proto).build();
@ -1834,9 +1781,7 @@ mod tests {
fn test_swarm_disconnect() {
// Since the test does not try to open any substreams, we can
// use the dummy protocols handler.
let handler_proto = DummyConnectionHandler {
keep_alive: KeepAlive::Yes,
};
let handler_proto = keep_alive::ConnectionHandler;
let mut swarm1 = new_test_swarm::<_, ()>(handler_proto.clone()).build();
let mut swarm2 = new_test_swarm::<_, ()>(handler_proto).build();
@ -1902,9 +1847,7 @@ mod tests {
fn test_behaviour_disconnect_all() {
// Since the test does not try to open any substreams, we can
// use the dummy protocols handler.
let handler_proto = DummyConnectionHandler {
keep_alive: KeepAlive::Yes,
};
let handler_proto = keep_alive::ConnectionHandler;
let mut swarm1 = new_test_swarm::<_, ()>(handler_proto.clone()).build();
let mut swarm2 = new_test_swarm::<_, ()>(handler_proto).build();
@ -1972,9 +1915,7 @@ mod tests {
fn test_behaviour_disconnect_one() {
// Since the test does not try to open any substreams, we can
// use the dummy protocols handler.
let handler_proto = DummyConnectionHandler {
keep_alive: KeepAlive::Yes,
};
let handler_proto = keep_alive::ConnectionHandler;
let mut swarm1 = new_test_swarm::<_, ()>(handler_proto.clone()).build();
let mut swarm2 = new_test_swarm::<_, ()>(handler_proto).build();
@ -2059,11 +2000,9 @@ mod tests {
fn prop(concurrency_factor: DialConcurrencyFactor) {
block_on(async {
let mut swarm = new_test_swarm::<_, ()>(DummyConnectionHandler {
keep_alive: KeepAlive::Yes,
})
.dial_concurrency_factor(concurrency_factor.0)
.build();
let mut swarm = new_test_swarm::<_, ()>(keep_alive::ConnectionHandler)
.dial_concurrency_factor(concurrency_factor.0)
.build();
// Listen on `concurrency_factor + 1` addresses.
//
@ -2129,11 +2068,9 @@ mod tests {
let outgoing_limit = rand::thread_rng().gen_range(1..10);
let limits = ConnectionLimits::default().with_max_pending_outgoing(Some(outgoing_limit));
let mut network = new_test_swarm::<_, ()>(DummyConnectionHandler {
keep_alive: KeepAlive::Yes,
})
.connection_limits(limits)
.build();
let mut network = new_test_swarm::<_, ()>(keep_alive::ConnectionHandler)
.connection_limits(limits)
.build();
let addr: Multiaddr = "/memory/1234".parse().unwrap();
@ -2185,16 +2122,12 @@ mod tests {
fn prop(limit: Limit) {
let limit = limit.0;
let mut network1 = new_test_swarm::<_, ()>(DummyConnectionHandler {
keep_alive: KeepAlive::Yes,
})
.connection_limits(limits(limit))
.build();
let mut network2 = new_test_swarm::<_, ()>(DummyConnectionHandler {
keep_alive: KeepAlive::Yes,
})
.connection_limits(limits(limit))
.build();
let mut network1 = new_test_swarm::<_, ()>(keep_alive::ConnectionHandler)
.connection_limits(limits(limit))
.build();
let mut network2 = new_test_swarm::<_, ()>(keep_alive::ConnectionHandler)
.connection_limits(limits(limit))
.build();
let _ = network1.listen_on(multiaddr![Memory(0u64)]).unwrap();
let listen_addr = async_std::task::block_on(poll_fn(|cx| {
@ -2299,8 +2232,8 @@ mod tests {
// Checks whether dialing an address containing the wrong peer id raises an error
// for the expected peer id instead of the obtained peer id.
let mut swarm1 = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build();
let mut swarm2 = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build();
let mut swarm1 = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build();
let mut swarm2 = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build();
swarm1.listen_on("/memory/0".parse().unwrap()).unwrap();
@ -2359,7 +2292,7 @@ mod tests {
//
// The last two can happen in any order.
let mut swarm = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build();
let mut swarm = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build();
swarm.listen_on("/memory/0".parse().unwrap()).unwrap();
let local_address =
@ -2417,7 +2350,7 @@ mod tests {
fn dial_self_by_id() {
// Trying to dial self by passing the same `PeerId` shouldn't even be possible in the first
// place.
let swarm = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build();
let swarm = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build();
let peer_id = *swarm.local_peer_id();
assert!(!swarm.is_connected(&peer_id));
}
@ -2428,7 +2361,7 @@ mod tests {
let target = PeerId::random();
let mut swarm = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build();
let mut swarm = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build();
let addresses = HashSet::from([
multiaddr![Ip4([0, 0, 0, 0]), Tcp(rand::random::<u16>())],
@ -2473,8 +2406,8 @@ mod tests {
fn aborting_pending_connection_surfaces_error() {
let _ = env_logger::try_init();
let mut dialer = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build();
let mut listener = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build();
let mut dialer = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build();
let mut listener = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build();
let listener_peer_id = *listener.local_peer_id();
listener.listen_on(multiaddr![Memory(0u64)]).unwrap();