Trait libp2p_swarm::behaviour::NetworkBehaviour
source · pub trait NetworkBehaviour: 'static {
type ConnectionHandler: IntoConnectionHandler;
type OutEvent: Send + 'static;
Show 16 methods
fn new_handler(&mut self) -> Self::ConnectionHandler;
fn inject_event(
&mut self,
peer_id: PeerId,
connection: ConnectionId,
event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent
);
fn poll(
&mut self,
cx: &mut Context<'_>,
params: &mut impl PollParameters
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>>;
fn addresses_of_peer(&mut self, _: &PeerId) -> Vec<Multiaddr> { ... }
fn inject_connection_established(
&mut self,
_peer_id: &PeerId,
_connection_id: &ConnectionId,
_endpoint: &ConnectedPoint,
_failed_addresses: Option<&Vec<Multiaddr>>,
_other_established: usize
) { ... }
fn inject_connection_closed(
&mut self,
_: &PeerId,
_: &ConnectionId,
_: &ConnectedPoint,
_: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
_remaining_established: usize
) { ... }
fn inject_address_change(
&mut self,
_: &PeerId,
_: &ConnectionId,
_old: &ConnectedPoint,
_new: &ConnectedPoint
) { ... }
fn inject_dial_failure(
&mut self,
_peer_id: Option<PeerId>,
_handler: Self::ConnectionHandler,
_error: &DialError
) { ... }
fn inject_listen_failure(
&mut self,
_local_addr: &Multiaddr,
_send_back_addr: &Multiaddr,
_handler: Self::ConnectionHandler
) { ... }
fn inject_new_listener(&mut self, _id: ListenerId) { ... }
fn inject_new_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) { ... }
fn inject_expired_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) { ... }
fn inject_listener_error(
&mut self,
_id: ListenerId,
_err: &(dyn Error + 'static)
) { ... }
fn inject_listener_closed(
&mut self,
_id: ListenerId,
_reason: Result<(), &Error>
) { ... }
fn inject_new_external_addr(&mut self, _addr: &Multiaddr) { ... }
fn inject_expired_external_addr(&mut self, _addr: &Multiaddr) { ... }
}
Expand description
A NetworkBehaviour
defines the behaviour of the local node on the network.
In contrast to Transport
which defines how to send bytes on the
network, NetworkBehaviour
defines what bytes to send and to whom.
Each protocol (e.g. libp2p-ping
, libp2p-identify
or libp2p-kad
) implements
NetworkBehaviour
. Multiple implementations of NetworkBehaviour
can be composed into a
hierarchy of NetworkBehaviour
s where parent implementations delegate to child
implementations. Finally the root of the NetworkBehaviour
hierarchy is passed to
Swarm
where it can then control the behaviour of the local node on a libp2p
network.
Hierarchy of NetworkBehaviour
To compose multiple NetworkBehaviour
implementations into a single NetworkBehaviour
implementation, potentially building a multi-level hierarchy of NetworkBehaviour
s, one can
use one of the NetworkBehaviour
combinators, and/or use the NetworkBehaviour
derive
macro.
Combinators
NetworkBehaviour
combinators wrap one or more NetworkBehaviour
implementations and
implement NetworkBehaviour
themselves. Example is the
Toggle
NetworkBehaviour
.
let my_behaviour = DummyBehaviour::default();
let my_toggled_behaviour = Toggle::from(Some(my_behaviour));
Custom NetworkBehaviour
with the Derive Macro
One can derive NetworkBehaviour
for a custom struct
via the #[derive(NetworkBehaviour)]
proc macro re-exported by the libp2p
crate. The macro generates a delegating trait
implementation for the custom struct
. Each NetworkBehaviour
trait method is simply
delegated to each struct
member in the order the struct
is defined. For example for
NetworkBehaviour::poll
it will first poll the first struct
member until it returns
Poll::Pending
before moving on to later members. For NetworkBehaviour::addresses_of_peer
it will delegate to each struct
member and return a concatenated array of all addresses
returned by the struct members.
When creating a custom NetworkBehaviour
, you must choose one of two methods to respond to
incoming events:
- One option is setting a custom
out_event
with#[behaviour(out_event = "AnotherType")]
. In this case, events generated by the customNetworkBehaviour
struct members will be converted to your customout_event
for you to handle after polling the swarm. - Alternatively, users that need access to the root
NetworkBehaviour
implementation while processing emitted events, can specify#[behaviour(event_process = true)]
(default is false). Events generated by the behaviour’s struct members are delegated toNetworkBehaviourEventProcess
trait implementations. Those must be provided by the user on the type thatNetworkBehaviour
is derived on.
When setting a custom out_event
, the aforementioned conversion of each of the event types
generated by the struct members to the custom out_event
is handled by From
implementations the user needs to provide.
#[derive(NetworkBehaviour)]
#[behaviour(out_event = "Event")]
struct MyBehaviour {
identify: Identify,
ping: Ping,
}
enum Event {
Identify(IdentifyEvent),
Ping(PingEvent),
}
impl From<IdentifyEvent> for Event {
fn from(event: IdentifyEvent) -> Self {
Self::Identify(event)
}
}
impl From<PingEvent> for Event {
fn from(event: PingEvent) -> Self {
Self::Ping(event)
}
}
When using event_process = true
the NetworkBehaviourEventProcess
trait implementations
are granted exclusive access to the NetworkBehaviour
, therefore
blocking code in these implementations will
block the entire Swarm
from processing new events, since the swarm cannot progress
without also having exclusive access to the NetworkBehaviour
. A better alternative is to execute
blocking or asynchronous logic on a separate task, perhaps with the help of a bounded channel to
maintain backpressure. The sender for the channel could be included in the NetworkBehaviours constructor.
Optionally one can provide a custom poll
function through the #[behaviour(poll_method = "poll")]
attribute. This function must have the same signature as the NetworkBehaviour
function and will be called last within the generated NetworkBehaviour
implementation.
Struct members that don’t implement NetworkBehaviour
must be annotated with
#[behaviour(ignore)]
.
#[derive(NetworkBehaviour)]
#[behaviour(out_event = "Event")]
struct MyBehaviour {
identify: Identify,
ping: Ping,
#[behaviour(ignore)]
some_string: String,
}
Required Associated Types§
sourcetype ConnectionHandler: IntoConnectionHandler
type ConnectionHandler: IntoConnectionHandler
Handler for all the protocols the network behaviour supports.
Required Methods§
sourcefn new_handler(&mut self) -> Self::ConnectionHandler
fn new_handler(&mut self) -> Self::ConnectionHandler
Creates a new ConnectionHandler
for a connection with a peer.
Every time an incoming connection is opened, and every time another NetworkBehaviour
emitted a dial request, this method is called.
The returned object is a handler for that specific connection, and will be moved to a background task dedicated to that connection.
The network behaviour (ie. the implementation of this trait) and the handlers it has spawned
(ie. the objects returned by new_handler
) can communicate by passing messages. Messages
sent from the handler to the behaviour are injected with NetworkBehaviour::inject_event
,
and the behaviour can send a message to the handler by making NetworkBehaviour::poll
return NetworkBehaviourAction::NotifyHandler
.
Note that the handler is returned to the NetworkBehaviour
on connection failure and
connection closing.
sourcefn inject_event(
&mut self,
peer_id: PeerId,
connection: ConnectionId,
event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent
)
fn inject_event(
&mut self,
peer_id: PeerId,
connection: ConnectionId,
event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent
)
Informs the behaviour about an event generated by the handler dedicated to the peer identified by peer_id
.
for the behaviour.
The peer_id
is guaranteed to be in a connected state. In other words, inject_connected
has previously been called with this PeerId
.
sourcefn poll(
&mut self,
cx: &mut Context<'_>,
params: &mut impl PollParameters
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>>
fn poll(
&mut self,
cx: &mut Context<'_>,
params: &mut impl PollParameters
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>>
Polls for things that swarm should do.
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.
Provided Methods§
sourcefn addresses_of_peer(&mut self, _: &PeerId) -> Vec<Multiaddr>
fn addresses_of_peer(&mut self, _: &PeerId) -> Vec<Multiaddr>
Addresses that this behaviour is aware of for this specific peer, and that may allow reaching the peer.
The addresses will be tried in the order returned by this function, which means that they should be ordered by decreasing likelihood of reachability. In other words, the first address should be the most likely to be reachable.
sourcefn inject_connection_established(
&mut self,
_peer_id: &PeerId,
_connection_id: &ConnectionId,
_endpoint: &ConnectedPoint,
_failed_addresses: Option<&Vec<Multiaddr>>,
_other_established: usize
)
fn inject_connection_established(
&mut self,
_peer_id: &PeerId,
_connection_id: &ConnectionId,
_endpoint: &ConnectedPoint,
_failed_addresses: Option<&Vec<Multiaddr>>,
_other_established: usize
)
Informs the behaviour about a newly established connection to a peer.
sourcefn inject_connection_closed(
&mut self,
_: &PeerId,
_: &ConnectionId,
_: &ConnectedPoint,
_: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
_remaining_established: usize
)
fn inject_connection_closed(
&mut self,
_: &PeerId,
_: &ConnectionId,
_: &ConnectedPoint,
_: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
_remaining_established: usize
)
Informs the behaviour about a closed connection to a peer.
A call to this method is always paired with an earlier call to
inject_connection_established
with the same peer ID, connection ID and
endpoint.
sourcefn inject_address_change(
&mut self,
_: &PeerId,
_: &ConnectionId,
_old: &ConnectedPoint,
_new: &ConnectedPoint
)
fn inject_address_change(
&mut self,
_: &PeerId,
_: &ConnectionId,
_old: &ConnectedPoint,
_new: &ConnectedPoint
)
Informs the behaviour that the ConnectedPoint
of an existing connection has changed.
sourcefn inject_dial_failure(
&mut self,
_peer_id: Option<PeerId>,
_handler: Self::ConnectionHandler,
_error: &DialError
)
fn inject_dial_failure(
&mut self,
_peer_id: Option<PeerId>,
_handler: Self::ConnectionHandler,
_error: &DialError
)
Indicates to the behaviour that the dial to a known or unknown node failed.
sourcefn inject_listen_failure(
&mut self,
_local_addr: &Multiaddr,
_send_back_addr: &Multiaddr,
_handler: Self::ConnectionHandler
)
fn inject_listen_failure(
&mut self,
_local_addr: &Multiaddr,
_send_back_addr: &Multiaddr,
_handler: Self::ConnectionHandler
)
Indicates to the behaviour that an error happened on an incoming connection during its initial handshake.
This can include, for example, an error during the handshake of the encryption layer, or the connection unexpectedly closed.
sourcefn inject_new_listener(&mut self, _id: ListenerId)
fn inject_new_listener(&mut self, _id: ListenerId)
Indicates to the behaviour that a new listener was created.
sourcefn inject_new_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr)
fn inject_new_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr)
Indicates to the behaviour that we have started listening on a new multiaddr.
sourcefn inject_expired_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr)
fn inject_expired_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr)
Indicates to the behaviour that a multiaddr we were listening on has expired, which means that we are no longer listening in it.
sourcefn inject_listener_error(&mut self, _id: ListenerId, _err: &(dyn Error + 'static))
fn inject_listener_error(&mut self, _id: ListenerId, _err: &(dyn Error + 'static))
A listener experienced an error.
sourcefn inject_listener_closed(&mut self, _id: ListenerId, _reason: Result<(), &Error>)
fn inject_listener_closed(&mut self, _id: ListenerId, _reason: Result<(), &Error>)
A listener closed.
sourcefn inject_new_external_addr(&mut self, _addr: &Multiaddr)
fn inject_new_external_addr(&mut self, _addr: &Multiaddr)
Indicates to the behaviour that we have discovered a new external address for us.
sourcefn inject_expired_external_addr(&mut self, _addr: &Multiaddr)
fn inject_expired_external_addr(&mut self, _addr: &Multiaddr)
Indicates to the behaviour that an external address was removed.
Implementations on Foreign Types§
source§impl<L, R> NetworkBehaviour for Either<L, R>where
L: NetworkBehaviour,
R: NetworkBehaviour,
impl<L, R> NetworkBehaviour for Either<L, R>where
L: NetworkBehaviour,
R: NetworkBehaviour,
Implementation of NetworkBehaviour
that can be either of two implementations.