Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(swarm)!: allow NetworkBehaviours to manage connections #3254

Merged
merged 199 commits into from
Feb 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
199 commits
Select commit Hold shift + click to select a range
9b01d61
Use GATs to avoid lifetimes on trait interface
thomaseizinger Dec 14, 2022
4d246dc
Bump MSRV accordingly
thomaseizinger Dec 14, 2022
74a2758
Bump MSRV of libp2p-metrics
thomaseizinger Dec 14, 2022
b25176f
Merge branch 'master' into feat-kademlia/use-gats
thomaseizinger Dec 14, 2022
c1e880c
Refactor dialling to have a more linear flow
thomaseizinger Dec 16, 2022
82ae04d
Introduce new callbacks for connection management
thomaseizinger Dec 16, 2022
c494cd4
Fix up some more code
thomaseizinger Dec 16, 2022
2c23ac2
Complete deprecation notice
thomaseizinger Dec 16, 2022
b65bbbc
Fix some more errors
thomaseizinger Dec 16, 2022
acfc50e
Refine deprecation message
thomaseizinger Dec 16, 2022
ca04985
Delegate to `addresses_of_peer` by default
thomaseizinger Dec 16, 2022
6a73454
Add hack to clear listen addresses
thomaseizinger Dec 19, 2022
644cbeb
Merge branch 'master' into feat-kademlia/use-gats
thomaseizinger Dec 20, 2022
ddea596
Merge branch 'feat-kademlia/use-gats' of github.com:libp2p/rust-libp2…
thomaseizinger Dec 20, 2022
e6e33c5
Add changelog entry
thomaseizinger Dec 20, 2022
e612feb
Merge branch 'master' into 2824-deprecate-into-connection-handler
thomaseizinger Dec 21, 2022
9a5ce29
Use an atomic counter to avoid collisions on connection IDs
thomaseizinger Dec 21, 2022
1662273
Fix minor compile error
thomaseizinger Dec 21, 2022
5c944e6
Fill in a few more bits
thomaseizinger Dec 21, 2022
59bcc9f
Don't be generic over transport
thomaseizinger Dec 21, 2022
a1c55b2
Remove type parameter for transport error
thomaseizinger Dec 21, 2022
7132ff5
Remove unnecessary type hint
thomaseizinger Dec 21, 2022
01efa8f
Remove type parameters from `ConcurrentDial`
thomaseizinger Dec 21, 2022
b0f2678
Fix rustfmt
thomaseizinger Dec 21, 2022
52cbaf6
Merge branch 'feat-kademlia/use-gats' into 2824-deprecate-into-connec…
thomaseizinger Dec 21, 2022
7efc3c5
Merge branch '2824-simplify-dial-opts' into 2824-deprecate-into-conne…
thomaseizinger Dec 21, 2022
db6fcc5
Merge branch '2824-no-generic-transport-pool' into 2824-deprecate-int…
thomaseizinger Dec 21, 2022
d3a259e
Remove `PendingConnectionDenied`
thomaseizinger Dec 21, 2022
e89ec57
Handle new DialError variants
thomaseizinger Dec 21, 2022
b0ee140
Make `libp2p-kad` compile
thomaseizinger Dec 21, 2022
20d93bb
Fix a few more errors
thomaseizinger Dec 21, 2022
138feb2
No more compile errors!
thomaseizinger Dec 21, 2022
6f9298a
Merge branch 'master' into 2824-deprecate-into-connection-handler
thomaseizinger Dec 23, 2022
796432a
Undo explicit `Sized` bound
thomaseizinger Dec 23, 2022
dfd349f
Let user know that we are discarding addresses
thomaseizinger Dec 23, 2022
600791d
Fix unused variable warning
thomaseizinger Dec 23, 2022
72fecc8
Fix unused import warnings
thomaseizinger Dec 23, 2022
62b11aa
Port `dcutr` protocol
thomaseizinger Dec 23, 2022
75d1f5a
Re-implement relay
thomaseizinger Dec 23, 2022
03dd88f
Fix some deprecation warnings
thomaseizinger Dec 23, 2022
760604f
Fix some deprecation warnings kad
thomaseizinger Dec 23, 2022
87ad92b
Port autonat
thomaseizinger Dec 23, 2022
6f5a2c8
Port identify
thomaseizinger Dec 23, 2022
e455317
Fix more deprecation warnings
thomaseizinger Dec 23, 2022
912f35d
Ignore clippy warning
thomaseizinger Dec 23, 2022
c5cbfbd
Fix derive and remove todo
thomaseizinger Dec 23, 2022
0b10f45
Make derive tests compile by using type alias
thomaseizinger Dec 23, 2022
dc59e81
Ignore clippy warnings in generated code
thomaseizinger Dec 23, 2022
ceda44c
Fix more warnings by allowing deprecations
thomaseizinger Dec 23, 2022
ec06475
Merge branch 'master' into 2824-deprecate-into-connection-handler
thomaseizinger Dec 23, 2022
18426d1
Remove unnecessary `extern crate`
thomaseizinger Dec 23, 2022
bae533e
Revert let-else usage
thomaseizinger Dec 23, 2022
80295ac
Less let else
thomaseizinger Dec 23, 2022
05988cc
No let else in mdns
thomaseizinger Dec 23, 2022
f22f5a2
No let-else in dcutr
thomaseizinger Dec 23, 2022
c7871d1
No let else in rendezvous
thomaseizinger Dec 23, 2022
10c3161
Last let-else usage
thomaseizinger Dec 23, 2022
de2d837
Remove fn from bad merge
thomaseizinger Dec 23, 2022
a6616aa
Minimize diff
thomaseizinger Dec 23, 2022
848ac79
Attempt to minimize diff
thomaseizinger Dec 23, 2022
65521e2
Undo re-ordering to reduce diff
thomaseizinger Dec 23, 2022
6f7d7f0
Minimize diff (and fix bad merge)
thomaseizinger Dec 23, 2022
27f04cc
Remove default impl for `ConnectionId` in favor of `next`
thomaseizinger Dec 23, 2022
2b13bd4
Deprecate `IntoMultiHandler`
thomaseizinger Dec 23, 2022
e8c9942
Implement dial failure reporting
thomaseizinger Dec 23, 2022
f51f0aa
Fix formatting
thomaseizinger Dec 23, 2022
3a84c14
Use single quotes to avoid running commands
thomaseizinger Jan 11, 2023
458aa53
Use intermediary variable
thomaseizinger Jan 13, 2023
d0d8b77
Make connection IDs globally unique
thomaseizinger Jan 16, 2023
11e5f74
Deprecate old new function
thomaseizinger Jan 16, 2023
47cf01f
Add changelog entry
thomaseizinger Jan 16, 2023
341d096
Merge branch 'master' into no-run-title-as-command
thomaseizinger Jan 16, 2023
f77e443
Remove `handler` field from `NetworkBehaviourAction::Dial`
thomaseizinger Jan 16, 2023
f6cf751
Port dcutr protocol
thomaseizinger Jan 16, 2023
08c5160
Port relay protocol
thomaseizinger Jan 16, 2023
8e0d7d8
Add changelog entry to swarm
thomaseizinger Jan 16, 2023
b337ec1
Merge branch 'no-run-title-as-command' into 2824-unique-connection-ids
thomaseizinger Jan 16, 2023
3c4ab32
Merge branch '2824-unique-connection-ids' into 2824-no-handler-in-dial
thomaseizinger Jan 16, 2023
1beec8c
Remove ordering functionality from `ConnectionId`
thomaseizinger Jan 17, 2023
eb48acb
Merge branch '2824-unique-connection-ids' of github.com:libp2p/rust-l…
thomaseizinger Jan 17, 2023
de9f152
Remove unnecessary visibility qualifiers
thomaseizinger Jan 17, 2023
7692c77
Convert `DialOpts` to struct variant
thomaseizinger Jan 17, 2023
b492236
Eagerly set defaults in `DialOpts`
thomaseizinger Jan 17, 2023
92b2985
Merge branch '2824-refactor-dial-opts' into 2824-no-handler-in-dial
thomaseizinger Jan 17, 2023
951a0dc
Make `ConnectionId` part of `DialOpts`
thomaseizinger Jan 17, 2023
41e49a5
Inline `_dial`
thomaseizinger Jan 17, 2023
3547b53
Rustfmt
thomaseizinger Jan 17, 2023
75b30ac
Fix wrong default
thomaseizinger Jan 17, 2023
30df5c8
Merge branch '2824-refactor-dial-opts' into 2824-no-handler-in-dial
thomaseizinger Jan 17, 2023
6e58cb9
Merge branch 'master' into 2824-deprecate-into-connection-handler
thomaseizinger Jan 17, 2023
3d91173
Merge branch 'master' into 2824-unique-connection-ids
thomaseizinger Jan 18, 2023
aa19d69
Merge branch '2824-unique-connection-ids' of github.com:libp2p/rust-l…
thomaseizinger Jan 18, 2023
0f53692
Merge branch 'master' into 2824-unique-connection-ids
thomaseizinger Jan 18, 2023
4084846
Merge branch '2824-unique-connection-ids' into 2824-no-handler-in-dial
thomaseizinger Jan 18, 2023
42c9758
Expand changelog entry
thomaseizinger Jan 18, 2023
14b9841
Move most important changelog entry to the top
thomaseizinger Jan 18, 2023
1a3a100
Add more text to changelog entry
thomaseizinger Jan 18, 2023
5535395
Fix formatting
thomaseizinger Jan 18, 2023
244c171
Merge branch 'master' into 2824-unique-connection-ids
thomaseizinger Jan 20, 2023
a82e087
Merge branch '2824-unique-connection-ids' into 2824-no-handler-in-dial
thomaseizinger Jan 20, 2023
5c86d66
Merge branch '2824-no-handler-in-dial' into 2824-deprecate-into-conne…
thomaseizinger Jan 23, 2023
70690da
Fix most errors
thomaseizinger Jan 23, 2023
b536773
Merge branch 'master' into 2824-unique-connection-ids
mergify[bot] Jan 23, 2023
64a333d
Merge branch 'master' into 2824-unique-connection-ids
thomaseizinger Jan 23, 2023
867c880
Merge branch '2824-unique-connection-ids' into 2824-no-handler-in-dial
thomaseizinger Jan 23, 2023
74be0d7
Merge branch '2824-no-handler-in-dial' into 2824-deprecate-into-conne…
thomaseizinger Jan 23, 2023
649745c
Fix implementation of dcutr
thomaseizinger Jan 23, 2023
7216a1a
Reduce diff
thomaseizinger Jan 23, 2023
eb8f8b5
Undo accidential change
thomaseizinger Jan 23, 2023
05337d5
Reduce diff
thomaseizinger Jan 23, 2023
338c35a
Attempt to reduce diff
thomaseizinger Jan 23, 2023
e97d899
Merge branch 'master' into 2824-no-handler-in-dial
thomaseizinger Jan 24, 2023
c0a7d2a
Remove unnecessary `..`
thomaseizinger Jan 24, 2023
5dce749
Merge branch '2824-no-handler-in-dial' into 2824-deprecate-into-conne…
thomaseizinger Jan 24, 2023
04da3b4
WIP
thomaseizinger Jan 24, 2023
2384c72
Remove unused error variant
thomaseizinger Jan 24, 2023
49d2326
Apply suggestions from code review
thomaseizinger Jan 24, 2023
6b335e9
Merge branch '2824-remove-unused-error' into 2824-introduce-listen-error
thomaseizinger Jan 24, 2023
439628f
WIP
thomaseizinger Jan 24, 2023
494d131
Remove unused `DialError::ConnectionIo` variant
thomaseizinger Jan 24, 2023
9eed96e
Merge branch '2824-remove-unused-error' into 2824-remove-unused-conne…
thomaseizinger Jan 24, 2023
e389876
add changelog entry
thomaseizinger Jan 24, 2023
f5c2a0e
Fix missing colon
thomaseizinger Jan 24, 2023
11eeed8
Merge branch '2824-remove-unused-connection-error' into 2824-introduc…
thomaseizinger Jan 24, 2023
a553ab7
Remove unused `ConnectionIo` variant from `ListenError`
thomaseizinger Jan 24, 2023
717e2d7
Update docs
thomaseizinger Jan 24, 2023
be9bb13
Add changelog entry
thomaseizinger Jan 24, 2023
e2476a3
Update changelog
thomaseizinger Jan 24, 2023
8e20996
Merge branch 'master' into 2824-no-handler-in-dial
thomaseizinger Jan 24, 2023
62bd505
Merge branch '2824-introduce-listen-error' into 2824-deprecate-into-c…
thomaseizinger Jan 24, 2023
130ef66
Report cause of denied connection
thomaseizinger Jan 24, 2023
dbebfd0
Introduce dedicated error type
thomaseizinger Jan 24, 2023
f545594
Don't comment docs
thomaseizinger Jan 24, 2023
1c99ff1
Fix docs
thomaseizinger Jan 24, 2023
d9f8567
Migrate `CallTraceBehaviour`
thomaseizinger Jan 24, 2023
478854e
Temporarily allow usage of `new_handler`
thomaseizinger Jan 24, 2023
5da8dce
Refactor gossipsub config handler to avoid calls to trait functions
thomaseizinger Jan 24, 2023
2a12efe
Undo bad doc comment change
thomaseizinger Jan 25, 2023
da9c926
Fix rustdocs
thomaseizinger Jan 25, 2023
7651d4a
Fix deprecation warnings
thomaseizinger Jan 25, 2023
096a303
Fix failing gossipsub test
thomaseizinger Jan 25, 2023
0dcee3e
Fix more docs
thomaseizinger Jan 25, 2023
0c706d5
Fix beta clippy
thomaseizinger Jan 25, 2023
c5f3320
Actually fix beta clippy
thomaseizinger Jan 25, 2023
ab35c11
Resolve remaining todos
thomaseizinger Jan 25, 2023
9a420e4
Don't use else block if we return in the previous one
thomaseizinger Jan 26, 2023
f5f37ab
Remove closure in favor of spawning connection from the outside
thomaseizinger Jan 26, 2023
e867b26
Merge branch 'master' into 2824-no-handler-in-dial
thomaseizinger Jan 26, 2023
dd1eb8c
Add `ConnectionId` to `ListenFailure`
thomaseizinger Jan 26, 2023
32a465b
Clean up pending commands on failure
thomaseizinger Jan 26, 2023
91f942f
Add docs and fix bug
thomaseizinger Jan 26, 2023
6f19246
Merge branch 'master' into 2824-no-handler-in-dial
thomaseizinger Jan 26, 2023
d704e89
Consistently use `THandlerInEvent`
thomaseizinger Jan 26, 2023
55baab1
Use type alias
thomaseizinger Jan 26, 2023
2c84f28
Remove unnecessary indentation and "quote"-ing
thomaseizinger Jan 26, 2023
cf77246
Fix bad changelog entry
thomaseizinger Jan 26, 2023
72640a0
Merge branch '2824-no-handler-in-dial' into 2824-deprecate-into-conne…
thomaseizinger Jan 27, 2023
55f922d
Spawn connection at right point in time
thomaseizinger Jan 27, 2023
a2dfc39
Attempt to reduce diff
thomaseizinger Jan 27, 2023
e38002e
Reduce diff further
thomaseizinger Jan 27, 2023
5798081
Less diff ...
thomaseizinger Jan 27, 2023
67577a7
Don't override deprecated callbacks anywhere
thomaseizinger Jan 27, 2023
91a7a70
Better order of callbacks
thomaseizinger Jan 27, 2023
92a9625
Spawn connection at right point in time
thomaseizinger Jan 27, 2023
6df1c9a
Be consistent in order of parameters
thomaseizinger Jan 27, 2023
87ef2be
Merge branch '2824-no-handler-in-dial' into 2824-deprecate-into-conne…
thomaseizinger Jan 27, 2023
17db8b4
Reduce diff
thomaseizinger Jan 27, 2023
d90ac81
Fix rustdoc
thomaseizinger Jan 27, 2023
cfe9f95
One more missing rustdoc link
thomaseizinger Jan 27, 2023
b7fb23f
Merge branch '2824-no-handler-in-dial' into 2824-deprecate-into-conne…
thomaseizinger Jan 27, 2023
3f8f73c
Remove `banned_peer_connections`
thomaseizinger Jan 27, 2023
063ef5c
Fix test
thomaseizinger Jan 27, 2023
751cad4
Remove duplication around detecting relayed addresses in `libp2p-relay`
thomaseizinger Jan 27, 2023
9462dbe
Extract utility fn for dcutr protocol
thomaseizinger Jan 27, 2023
639b9da
Remove unused import
thomaseizinger Jan 27, 2023
0bcfe81
Remove underscore from used variable
thomaseizinger Jan 27, 2023
26f6cf0
Merge branch 'master' into 2824-no-handler-in-dial
thomaseizinger Jan 27, 2023
95cde92
Add changelog entry
thomaseizinger Jan 31, 2023
2efe073
Add footnote
thomaseizinger Jan 31, 2023
916fe57
Don't use footnotes
thomaseizinger Jan 31, 2023
c3ba2e3
Merge branch 'master' into 2824-no-handler-in-dial
thomaseizinger Feb 1, 2023
3ecd623
Inline `spawn` function
thomaseizinger Feb 10, 2023
02cbf42
Box future inside `spawn`
thomaseizinger Feb 10, 2023
1c906db
Merge impl blocks
thomaseizinger Feb 10, 2023
87cf5fd
Gracefully close connection to banned peer
thomaseizinger Feb 10, 2023
5a2cc76
Merge branch '2824-no-handler-in-dial' into 2824-deprecate-into-conne…
thomaseizinger Feb 10, 2023
e74ea67
Ensure new connections are either spawned or gracefully closed
thomaseizinger Feb 10, 2023
f204859
Ignore error when closing connection
thomaseizinger Feb 10, 2023
ade4421
Merge branch '2824-no-handler-in-dial' into 2824-deprecate-into-conne…
thomaseizinger Feb 10, 2023
31407ac
Merge branch 'master' into 2824-deprecate-into-connection-handler
thomaseizinger Feb 16, 2023
fb93cd6
Fix compile error
thomaseizinger Feb 16, 2023
82e3aca
Restore `IntoEitherHandler`
thomaseizinger Feb 20, 2023
2a44198
Don't underscore used variable
thomaseizinger Feb 20, 2023
88e0e62
Merge branch 'master' into 2824-deprecate-into-connection-handler
thomaseizinger Feb 21, 2023
7bae092
Undo merge conflicts with #3465
thomaseizinger Feb 21, 2023
0ca08c1
Call out limitations in Rust compiler
thomaseizinger Feb 21, 2023
dd4e374
Move manage conn entry to top of changelog
thomaseizinger Feb 21, 2023
392b0d2
Fix fmt
thomaseizinger Feb 21, 2023
4f38189
Merge branch 'master' into 2824-deprecate-into-connection-handler
thomaseizinger Feb 23, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@

# 0.51.0 [unreleased]

- Enable `NetworkBehaviour`s to manage connections.
This deprecates `NetworkBehaviour::new_handler` and `NetworkBehaviour::addresses_of_peer`.
Due to limitations in the Rust compiler, these deprecations may not show up for you, nevertheless they will be removed in a future release.
See [`libp2p-swarm`'s CHANGELOG](swarm/CHANGELOG.md#0420) for details.

- Count bandwidth at the application level. Previously `BandwidthLogging` would implement `Transport` and now implements `StreamMuxer` ([PR 3180](https://github.com/libp2p/rust-libp2p/pull/3180)).
- `BandwidthLogging::new` now requires a 2nd argument: `Arc<BandwidthSinks>`
- Remove `BandwidthFuture`
Expand Down
6 changes: 6 additions & 0 deletions misc/metrics/src/swarm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,9 @@ impl<TBvEv, THandleErr> super::Recorder<libp2p_swarm::SwarmEvent<TBvEv, THandleE
libp2p_swarm::DialError::WrongPeerId { .. } => {
record(OutgoingConnectionError::WrongPeerId)
}
libp2p_swarm::DialError::Denied { .. } => {
record(OutgoingConnectionError::Denied)
}
};
}
libp2p_swarm::SwarmEvent::BannedPeer { endpoint, .. } => {
Expand Down Expand Up @@ -344,6 +347,7 @@ enum OutgoingConnectionError {
WrongPeerId,
TransportMultiaddrNotSupported,
TransportOther,
Denied,
}

#[derive(EncodeLabelSet, Hash, Clone, Eq, PartialEq, Debug)]
Expand All @@ -360,6 +364,7 @@ enum IncomingConnectionError {
TransportErrorOther,
Aborted,
ConnectionLimit,
Denied,
}

impl From<&libp2p_swarm::ListenError> for IncomingConnectionError {
Expand All @@ -377,6 +382,7 @@ impl From<&libp2p_swarm::ListenError> for IncomingConnectionError {
libp2p_core::transport::TransportError::Other(_),
) => IncomingConnectionError::TransportErrorOther,
libp2p_swarm::ListenError::Aborted => IncomingConnectionError::Aborted,
libp2p_swarm::ListenError::Denied { .. } => IncomingConnectionError::Denied,
}
}
}
Expand Down
55 changes: 49 additions & 6 deletions protocols/autonat/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ use libp2p_swarm::{
AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredExternalAddr,
ExpiredListenAddr, FromSwarm,
},
ConnectionId, ExternalAddresses, ListenAddresses, NetworkBehaviour, NetworkBehaviourAction,
PollParameters, THandlerInEvent, THandlerOutEvent,
ConnectionDenied, ConnectionId, ExternalAddresses, ListenAddresses, NetworkBehaviour,
NetworkBehaviourAction, PollParameters, THandler, THandlerInEvent, THandlerOutEvent,
};
use std::{
collections::{HashMap, VecDeque},
Expand Down Expand Up @@ -485,12 +485,55 @@ impl NetworkBehaviour for Behaviour {
}
}

fn new_handler(&mut self) -> Self::ConnectionHandler {
self.inner.new_handler()
fn handle_pending_inbound_connection(
&mut self,
connection_id: ConnectionId,
local_addr: &Multiaddr,
remote_addr: &Multiaddr,
) -> Result<(), ConnectionDenied> {
self.inner
.handle_pending_inbound_connection(connection_id, local_addr, remote_addr)
}

fn handle_established_inbound_connection(
&mut self,
_connection_id: ConnectionId,
peer: PeerId,
local_addr: &Multiaddr,
remote_addr: &Multiaddr,
) -> Result<THandler<Self>, ConnectionDenied> {
self.inner.handle_established_inbound_connection(
_connection_id,
peer,
local_addr,
remote_addr,
)
}

fn addresses_of_peer(&mut self, peer: &PeerId) -> Vec<Multiaddr> {
self.inner.addresses_of_peer(peer)
fn handle_pending_outbound_connection(
&mut self,
_connection_id: ConnectionId,
maybe_peer: Option<PeerId>,
_addresses: &[Multiaddr],
_effective_role: Endpoint,
) -> Result<Vec<Multiaddr>, ConnectionDenied> {
self.inner.handle_pending_outbound_connection(
_connection_id,
maybe_peer,
_addresses,
_effective_role,
)
}

fn handle_established_outbound_connection(
&mut self,
_connection_id: ConnectionId,
peer: PeerId,
addr: &Multiaddr,
role_override: Endpoint,
) -> Result<THandler<Self>, ConnectionDenied> {
self.inner
.handle_established_outbound_connection(_connection_id, peer, addr, role_override)
}

fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
Expand Down
94 changes: 86 additions & 8 deletions protocols/dcutr/src/behaviour_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ use crate::handler;
use either::Either;
use libp2p_core::connection::ConnectedPoint;
use libp2p_core::multiaddr::Protocol;
use libp2p_core::{Multiaddr, PeerId};
use libp2p_core::{Endpoint, Multiaddr, PeerId};
use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm};
use libp2p_swarm::dial_opts::{self, DialOpts};
use libp2p_swarm::{dummy, ConnectionDenied, ConnectionId, THandler, THandlerOutEvent};
use libp2p_swarm::{
ConnectionHandlerUpgrErr, ExternalAddresses, NetworkBehaviour, NetworkBehaviourAction,
NotifyHandler, PollParameters, THandlerInEvent,
};
use libp2p_swarm::{ConnectionId, THandlerOutEvent};
use std::collections::{HashMap, HashSet, VecDeque};
use std::task::{Context, Poll};
use thiserror::Error;
Expand Down Expand Up @@ -64,12 +64,14 @@ pub enum Error {
#[error("Failed to dial peer.")]
Dial,
#[error("Failed to establish substream: {0}.")]
Handler(ConnectionHandlerUpgrErr<void::Void>),
Handler(ConnectionHandlerUpgrErr<Void>),
}

pub struct Behaviour {
/// Queue of actions to return when polled.
queued_events: VecDeque<NetworkBehaviourAction<Event, Either<handler::relayed::Command, Void>>>,
queued_events: VecDeque<
NetworkBehaviourAction<Event, Either<handler::relayed::Command, Either<Void, Void>>>,
>,

/// All direct (non-relayed) connections.
direct_connections: HashMap<PeerId, HashSet<ConnectionId>>,
Expand Down Expand Up @@ -237,11 +239,82 @@ impl Behaviour {
}

impl NetworkBehaviour for Behaviour {
type ConnectionHandler = handler::Prototype;
type ConnectionHandler = Either<
handler::relayed::Handler,
Either<handler::direct::Handler, dummy::ConnectionHandler>,
>;
type OutEvent = Event;

fn new_handler(&mut self) -> Self::ConnectionHandler {
handler::Prototype
fn handle_established_inbound_connection(
&mut self,
connection_id: ConnectionId,
peer: PeerId,
local_addr: &Multiaddr,
remote_addr: &Multiaddr,
) -> Result<THandler<Self>, ConnectionDenied> {
match self
.outgoing_direct_connection_attempts
.remove(&(connection_id, peer))
{
None => {
let handler = if is_relayed(local_addr) {
Either::Left(handler::relayed::Handler::new(ConnectedPoint::Listener {
local_addr: local_addr.clone(),
send_back_addr: remote_addr.clone(),
})) // TODO: We could make two `handler::relayed::Handler` here, one inbound one outbound.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you expand on this comment?

Copy link
Contributor Author

@thomaseizinger thomaseizinger Feb 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"dcutr" cares about who the dialer and listener on a relayed connection is. Now that we have different callbacks for this, it is even more obvious that we could split this logic into two handlers instead of being conditional on the ConnectedPoint within the single handler. That would remove some panic!s in the implementation that are unreachable.

} else {
Either::Right(Either::Right(dummy::ConnectionHandler))
};

Ok(handler)
}
Some(_) => {
assert!(
!is_relayed(local_addr),
"`Prototype::DirectConnection` is never created for relayed connection."
);

Ok(Either::Right(Either::Left(
handler::direct::Handler::default(),
)))
}
}
}

fn handle_established_outbound_connection(
&mut self,
connection_id: ConnectionId,
peer: PeerId,
addr: &Multiaddr,
role_override: Endpoint,
) -> Result<THandler<Self>, ConnectionDenied> {
match self
.outgoing_direct_connection_attempts
.remove(&(connection_id, peer))
{
None => {
let handler = if is_relayed(addr) {
Either::Left(handler::relayed::Handler::new(ConnectedPoint::Dialer {
address: addr.clone(),
role_override,
})) // TODO: We could make two `handler::relayed::Handler` here, one inbound one outbound.
} else {
Either::Right(Either::Right(dummy::ConnectionHandler))
};

Ok(handler)
}
Some(_) => {
assert!(
!is_relayed(addr),
"`Prototype::DirectConnection` is never created for relayed connection."
);

Ok(Either::Right(Either::Left(
handler::direct::Handler::default(),
)))
}
}
}

fn on_connection_handler_event(
Expand Down Expand Up @@ -332,7 +405,7 @@ impl NetworkBehaviour for Behaviour {
self.queued_events
.push_back(NetworkBehaviourAction::Dial { opts });
}
Either::Right(handler::direct::Event::DirectConnectionEstablished) => {
Either::Right(Either::Left(handler::direct::Event::DirectConnectionEstablished)) => {
self.queued_events.extend([
NetworkBehaviourAction::NotifyHandler {
peer_id: event_source,
Expand All @@ -348,6 +421,7 @@ impl NetworkBehaviour for Behaviour {
),
]);
}
Either::Right(Either::Right(never)) => void::unreachable(never),
};
}

Expand Down Expand Up @@ -386,3 +460,7 @@ impl NetworkBehaviour for Behaviour {
}
}
}

fn is_relayed(addr: &Multiaddr) -> bool {
addr.iter().any(|p| p == Protocol::P2pCircuit)
}
thomaseizinger marked this conversation as resolved.
Show resolved Hide resolved
24 changes: 0 additions & 24 deletions protocols/dcutr/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,29 +18,5 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use crate::protocol;
use either::Either;
use libp2p_core::{ConnectedPoint, PeerId};
use libp2p_swarm::handler::SendWrapper;
use libp2p_swarm::{ConnectionHandler, IntoConnectionHandler};

pub mod direct;
pub mod relayed;

pub struct Prototype;

impl IntoConnectionHandler for Prototype {
type Handler = Either<relayed::Handler, direct::Handler>;

fn into_handler(self, _remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler {
if endpoint.is_relayed() {
Either::Left(relayed::Handler::new(endpoint.clone()))
} else {
Either::Right(direct::Handler::default()) // This is a direct connection. What we don't know is whether it is the one we created or another one that happened accidentally.
}
}

fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol {
Either::Left(SendWrapper(Either::Left(protocol::inbound::Upgrade {})))
}
}
26 changes: 21 additions & 5 deletions protocols/floodsub/src/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ use crate::topic::Topic;
use crate::FloodsubConfig;
use cuckoofilter::{CuckooError, CuckooFilter};
use fnv::FnvHashSet;
use libp2p_core::PeerId;
use libp2p_core::{Endpoint, Multiaddr, PeerId};
use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, FromSwarm};
use libp2p_swarm::{
dial_opts::DialOpts, ConnectionId, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler,
OneShotHandler, PollParameters, THandlerInEvent, THandlerOutEvent,
dial_opts::DialOpts, ConnectionDenied, ConnectionId, NetworkBehaviour, NetworkBehaviourAction,
NotifyHandler, OneShotHandler, PollParameters, THandler, THandlerInEvent, THandlerOutEvent,
};
use log::warn;
use smallvec::SmallVec;
Expand Down Expand Up @@ -334,8 +334,24 @@ impl NetworkBehaviour for Floodsub {
type ConnectionHandler = OneShotHandler<FloodsubProtocol, FloodsubRpc, InnerMessage>;
type OutEvent = FloodsubEvent;

fn new_handler(&mut self) -> Self::ConnectionHandler {
Default::default()
fn handle_established_inbound_connection(
&mut self,
_: ConnectionId,
_: PeerId,
_: &Multiaddr,
_: &Multiaddr,
) -> Result<THandler<Self>, ConnectionDenied> {
Ok(Default::default())
}

fn handle_established_outbound_connection(
&mut self,
_: ConnectionId,
_: PeerId,
_: &Multiaddr,
_: Endpoint,
) -> Result<THandler<Self>, ConnectionDenied> {
Ok(Default::default())
}

fn on_connection_handler_event(
Expand Down
32 changes: 26 additions & 6 deletions protocols/gossipsub/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,14 @@ use prost::Message as _;
use rand::{seq::SliceRandom, thread_rng};

use libp2p_core::{
identity::Keypair, multiaddr::Protocol::Ip4, multiaddr::Protocol::Ip6, Multiaddr, PeerId,
identity::Keypair, multiaddr::Protocol::Ip4, multiaddr::Protocol::Ip6, Endpoint, Multiaddr,
PeerId,
};
use libp2p_swarm::{
behaviour::{AddressChange, ConnectionClosed, ConnectionEstablished, FromSwarm},
dial_opts::DialOpts,
ConnectionId, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters,
THandlerInEvent, THandlerOutEvent,
ConnectionDenied, ConnectionId, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler,
PollParameters, THandler, THandlerInEvent, THandlerOutEvent,
};
use wasm_timer::Instant;

Expand Down Expand Up @@ -3289,11 +3290,30 @@ where
type ConnectionHandler = Handler;
type OutEvent = Event;

fn new_handler(&mut self) -> Self::ConnectionHandler {
Handler::new(
fn handle_established_inbound_connection(
&mut self,
_: ConnectionId,
_: PeerId,
_: &Multiaddr,
_: &Multiaddr,
) -> Result<THandler<Self>, ConnectionDenied> {
Ok(Handler::new(
ProtocolConfig::new(&self.config),
self.config.idle_timeout(),
)
))
}

fn handle_established_outbound_connection(
&mut self,
_: ConnectionId,
_: PeerId,
_: &Multiaddr,
_: Endpoint,
) -> Result<THandler<Self>, ConnectionDenied> {
Ok(Handler::new(
ProtocolConfig::new(&self.config),
self.config.idle_timeout(),
))
}

fn on_connection_handler_event(
Expand Down
Loading