Thomas Eizinger 19a554965f
feat(swarm)!: allow NetworkBehaviours to manage connections
Previously, a `ConnectionHandler` was immediately requested from the `NetworkBehaviour` as soon as a new dial was initiated or a new incoming connection accepted.

With this patch, we delay the creation of the handler until the connection is actually established and fully upgraded, i.e authenticated and multiplexed.

As a consequence, `NetworkBehaviour::new_handler` is now deprecated in favor of a new set of callbacks:

- `NetworkBehaviour::handle_pending_inbound_connection`
- `NetworkBehaviour::handle_pending_outbound_connection`
- `NetworkBehaviour::handle_established_inbound_connection`
- `NetworkBehaviour::handle_established_outbound_connection`

All callbacks are fallible, allowing the `NetworkBehaviour` to abort the connection either immediately or after it is fully established. All callbacks also receive a `ConnectionId` parameter which uniquely identifies the connection. For example, in case a `NetworkBehaviour` issues a dial via `NetworkBehaviourAction::Dial`, it can unambiguously detect this dial in these lifecycle callbacks via the `ConnectionId`.

Finally, `NetworkBehaviour::handle_pending_outbound_connection` also replaces `NetworkBehaviour::addresses_of_peer` by allowing the behaviour to return more addresses to be used for the dial.

Resolves #2824.

Pull-Request: #3254.
2023-02-23 23:43:33 +00:00

158 lines
5.9 KiB
Rust

// Copyright 2021 COMIT Network.
//
// 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 futures::StreamExt;
use libp2p_core::{identity, multiaddr::Protocol, upgrade::Version, Multiaddr, PeerId, Transport};
use libp2p_ping as ping;
use libp2p_rendezvous as rendezvous;
use libp2p_swarm::{keep_alive, Swarm, SwarmEvent};
use std::time::Duration;
use void::Void;
const NAMESPACE: &str = "rendezvous";
#[tokio::main]
async fn main() {
env_logger::init();
let identity = identity::Keypair::generate_ed25519();
let rendezvous_point_address = "/ip4/127.0.0.1/tcp/62649".parse::<Multiaddr>().unwrap();
let rendezvous_point = "12D3KooWDpJ7As7BWAwRMfu1VU2WCqNjvq387JEYKDBj4kx6nXTN"
.parse()
.unwrap();
let mut swarm = Swarm::with_tokio_executor(
libp2p_tcp::tokio::Transport::default()
.upgrade(Version::V1)
.authenticate(libp2p_noise::NoiseAuthenticated::xx(&identity).unwrap())
.multiplex(libp2p_yamux::YamuxConfig::default())
.boxed(),
MyBehaviour {
rendezvous: rendezvous::client::Behaviour::new(identity.clone()),
ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
keep_alive: keep_alive::Behaviour,
},
PeerId::from(identity.public()),
);
log::info!("Local peer id: {}", swarm.local_peer_id());
swarm.dial(rendezvous_point_address.clone()).unwrap();
let mut discover_tick = tokio::time::interval(Duration::from_secs(30));
let mut cookie = None;
loop {
tokio::select! {
event = swarm.select_next_some() => match event {
SwarmEvent::ConnectionEstablished { peer_id, .. } if peer_id == rendezvous_point => {
log::info!(
"Connected to rendezvous point, discovering nodes in '{}' namespace ...",
NAMESPACE
);
swarm.behaviour_mut().rendezvous.discover(
Some(rendezvous::Namespace::new(NAMESPACE.to_string()).unwrap()),
None,
None,
rendezvous_point,
);
}
SwarmEvent::Behaviour(MyEvent::Rendezvous(rendezvous::client::Event::Discovered {
registrations,
cookie: new_cookie,
..
})) => {
cookie.replace(new_cookie);
for registration in registrations {
for address in registration.record.addresses() {
let peer = registration.record.peer_id();
log::info!("Discovered peer {} at {}", peer, address);
let p2p_suffix = Protocol::P2p(*peer.as_ref());
let address_with_p2p =
if !address.ends_with(&Multiaddr::empty().with(p2p_suffix.clone())) {
address.clone().with(p2p_suffix)
} else {
address.clone()
};
swarm.dial(address_with_p2p).unwrap();
}
}
}
SwarmEvent::Behaviour(MyEvent::Ping(ping::Event {
peer,
result: Ok(ping::Success::Ping { rtt }),
})) if peer != rendezvous_point => {
log::info!("Ping to {} is {}ms", peer, rtt.as_millis())
}
other => {
log::debug!("Unhandled {:?}", other);
}
},
_ = discover_tick.tick(), if cookie.is_some() =>
swarm.behaviour_mut().rendezvous.discover(
Some(rendezvous::Namespace::new(NAMESPACE.to_string()).unwrap()),
cookie.clone(),
None,
rendezvous_point
)
}
}
}
#[derive(Debug)]
enum MyEvent {
Rendezvous(rendezvous::client::Event),
Ping(ping::Event),
}
impl From<rendezvous::client::Event> for MyEvent {
fn from(event: rendezvous::client::Event) -> Self {
MyEvent::Rendezvous(event)
}
}
impl From<ping::Event> for MyEvent {
fn from(event: ping::Event) -> Self {
MyEvent::Ping(event)
}
}
impl From<Void> for MyEvent {
fn from(event: Void) -> Self {
void::unreachable(event)
}
}
#[derive(libp2p_swarm::NetworkBehaviour)]
#[behaviour(
out_event = "MyEvent",
event_process = false,
prelude = "libp2p_swarm::derive_prelude"
)]
struct MyBehaviour {
rendezvous: rendezvous::client::Behaviour,
ping: ping::Behaviour,
keep_alive: keep_alive::Behaviour,
}