cs_mwc_libp2p_swarm/
behaviour.rs

1// Copyright 2019 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use crate::{AddressScore, AddressRecord};
22use crate::protocols_handler::{IntoProtocolsHandler, ProtocolsHandler};
23use mwc_libp2p_core::{ConnectedPoint, Multiaddr, PeerId, connection::{ConnectionId, ListenerId}};
24use std::{error, task::Context, task::Poll};
25
26/// A behaviour for the network. Allows customizing the swarm.
27///
28/// This trait has been designed to be composable. Multiple implementations can be combined into
29/// one that handles all the behaviours at once.
30///
31/// # Deriving `NetworkBehaviour`
32///
33/// Crate users can implement this trait by using the the `#[derive(NetworkBehaviour)]`
34/// proc macro re-exported by the `libp2p` crate. The macro generates a delegating `trait`
35/// implementation for the `struct`, which delegates method calls to all trait members.
36///
37/// By default the derive sets the [`NetworkBehaviour::OutEvent`] as `()` but this can be overridden
38/// with `#[behaviour(out_event = "AnotherType")]`.
39///
40/// Struct members that don't implement [`NetworkBehaviour`] must be annotated with `#[behaviour(ignore)]`.
41///
42/// By default, events generated by the remaining members are delegated to [`NetworkBehaviourEventProcess`]
43/// implementations. Those must be provided by the user on the type that [`NetworkBehaviour`] is
44/// derived on.
45///
46/// Alternatively, users can specify `#[behaviour(event_process = false)]`. In this case, users
47/// should provide a custom `out_event` and implement [`From`] for each of the event types generated
48/// by the struct members.
49/// Not processing events within the derived [`NetworkBehaviour`] will cause them to be emitted as
50/// part of polling the swarm in [`SwarmEvent::Behaviour`](crate::SwarmEvent::Behaviour).
51///
52/// Optionally one can provide a custom `poll` function through the `#[behaviour(poll_method = "poll")]`
53/// attribute.
54/// This function must have the same signature as the [`NetworkBehaviour#poll`] function and will
55/// be called last within the generated [`NetworkBehaviour`] implementation.
56pub trait NetworkBehaviour: Send + 'static {
57    /// Handler for all the protocols the network behaviour supports.
58    type ProtocolsHandler: IntoProtocolsHandler;
59
60    /// Event generated by the `NetworkBehaviour` and that the swarm will report back.
61    type OutEvent: Send + 'static;
62
63    /// Creates a new `ProtocolsHandler` for a connection with a peer.
64    ///
65    /// Every time an incoming connection is opened, and every time we start dialing a node, this
66    /// method is called.
67    ///
68    /// The returned object is a handler for that specific connection, and will be moved to a
69    /// background task dedicated to that connection.
70    ///
71    /// The network behaviour (ie. the implementation of this trait) and the handlers it has
72    /// spawned (ie. the objects returned by `new_handler`) can communicate by passing messages.
73    /// Messages sent from the handler to the behaviour are injected with `inject_event`, and
74    /// the behaviour can send a message to the handler by making `poll` return `SendEvent`.
75    fn new_handler(&mut self) -> Self::ProtocolsHandler;
76
77    /// Addresses that this behaviour is aware of for this specific peer, and that may allow
78    /// reaching the peer.
79    ///
80    /// The addresses will be tried in the order returned by this function, which means that they
81    /// should be ordered by decreasing likelihood of reachability. In other words, the first
82    /// address should be the most likely to be reachable.
83    fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr>;
84
85    /// Indicate to the behaviour that we connected to the node with the given peer id.
86    ///
87    /// This node now has a handler (as spawned by `new_handler`) running in the background.
88    ///
89    /// This method is only called when the first connection to the peer is established, preceded by
90    /// [`inject_connection_established`](NetworkBehaviour::inject_connection_established).
91    fn inject_connected(&mut self, peer_id: &PeerId);
92
93    /// Indicates to the behaviour that we disconnected from the node with the given peer id.
94    ///
95    /// There is no handler running anymore for this node. Any event that has been sent to it may
96    /// or may not have been processed by the handler.
97    ///
98    /// This method is only called when the last established connection to the peer is closed,
99    /// preceded by [`inject_connection_closed`](NetworkBehaviour::inject_connection_closed).
100    fn inject_disconnected(&mut self, peer_id: &PeerId);
101
102    /// Informs the behaviour about a newly established connection to a peer.
103    fn inject_connection_established(&mut self, _: &PeerId, _: &ConnectionId, _: &ConnectedPoint)
104    {}
105
106    /// Informs the behaviour about a closed connection to a peer.
107    ///
108    /// A call to this method is always paired with an earlier call to
109    /// `inject_connection_established` with the same peer ID, connection ID and
110    /// endpoint.
111    fn inject_connection_closed(&mut self, _: &PeerId, _: &ConnectionId, _: &ConnectedPoint)
112    {}
113
114    /// Informs the behaviour that the [`ConnectedPoint`] of an existing connection has changed.
115    fn inject_address_change(
116        &mut self,
117        _: &PeerId,
118        _: &ConnectionId,
119        _old: &ConnectedPoint,
120        _new: &ConnectedPoint
121    ) {}
122
123    /// Informs the behaviour about an event generated by the handler dedicated to the peer identified by `peer_id`.
124    /// for the behaviour.
125    ///
126    /// The `peer_id` is guaranteed to be in a connected state. In other words, `inject_connected`
127    /// has previously been called with this `PeerId`.
128    fn inject_event(
129        &mut self,
130        peer_id: PeerId,
131        connection: ConnectionId,
132        event: <<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent
133    );
134
135    /// Indicates to the behaviour that we tried to reach an address, but failed.
136    ///
137    /// If we were trying to reach a specific node, its ID is passed as parameter. If this is the
138    /// last address to attempt for the given node, then `inject_dial_failure` is called afterwards.
139    fn inject_addr_reach_failure(&mut self, _peer_id: Option<&PeerId>, _addr: &Multiaddr, _error: &dyn error::Error) {
140    }
141
142    /// Indicates to the behaviour that we tried to dial all the addresses known for a node, but
143    /// failed.
144    ///
145    /// The `peer_id` is guaranteed to be in a disconnected state. In other words,
146    /// `inject_connected` has not been called, or `inject_disconnected` has been called since then.
147    fn inject_dial_failure(&mut self, _peer_id: &PeerId) {
148    }
149
150    /// Indicates to the behaviour that we have started listening on a new multiaddr.
151    fn inject_new_listen_addr(&mut self, _addr: &Multiaddr) {
152    }
153
154    /// Indicates to the behaviour that a new multiaddr we were listening on has expired,
155    /// which means that we are no longer listening in it.
156    fn inject_expired_listen_addr(&mut self, _addr: &Multiaddr) {
157    }
158
159    /// Indicates to the behaviour that we have discovered a new external address for us.
160    fn inject_new_external_addr(&mut self, _addr: &Multiaddr) {
161    }
162
163    /// A listener experienced an error.
164    fn inject_listener_error(&mut self, _id: ListenerId, _err: &(dyn std::error::Error + 'static)) {
165    }
166
167    /// A listener closed.
168    fn inject_listener_closed(&mut self, _id: ListenerId, _reason: Result<(), &std::io::Error>) {
169    }
170
171    /// Polls for things that swarm should do.
172    ///
173    /// This API mimics the API of the `Stream` trait. The method may register the current task in
174    /// order to wake it up at a later point in time.
175    fn poll(&mut self, cx: &mut Context<'_>, params: &mut impl PollParameters)
176        -> Poll<NetworkBehaviourAction<<<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::InEvent, Self::OutEvent>>;
177}
178
179/// Parameters passed to `poll()`, that the `NetworkBehaviour` has access to.
180pub trait PollParameters {
181    /// Iterator returned by [`supported_protocols`](PollParameters::supported_protocols).
182    type SupportedProtocolsIter: ExactSizeIterator<Item = Vec<u8>>;
183    /// Iterator returned by [`listened_addresses`](PollParameters::listened_addresses).
184    type ListenedAddressesIter: ExactSizeIterator<Item = Multiaddr>;
185    /// Iterator returned by [`external_addresses`](PollParameters::external_addresses).
186    type ExternalAddressesIter: ExactSizeIterator<Item = AddressRecord>;
187
188    /// Returns the list of protocol the behaviour supports when a remote negotiates a protocol on
189    /// an inbound substream.
190    ///
191    /// The iterator's elements are the ASCII names as reported on the wire.
192    ///
193    /// Note that the list is computed once at initialization and never refreshed.
194    fn supported_protocols(&self) -> Self::SupportedProtocolsIter;
195
196    /// Returns the list of the addresses we're listening on.
197    fn listened_addresses(&self) -> Self::ListenedAddressesIter;
198
199    /// Returns the list of the addresses nodes can use to reach us.
200    fn external_addresses(&self) -> Self::ExternalAddressesIter;
201
202    /// Returns the peer id of the local node.
203    fn local_peer_id(&self) -> &PeerId;
204}
205
206/// When deriving [`NetworkBehaviour`] this trait must by default be implemented for all the
207/// possible event types generated by the inner behaviours.
208///
209/// You can opt out of this behaviour through `#[behaviour(event_process = false)]`. See the
210/// documentation of [`NetworkBehaviour`] for details.
211pub trait NetworkBehaviourEventProcess<TEvent> {
212    /// Called when one of the fields of the type you're deriving `NetworkBehaviour` on generates
213    /// an event.
214    fn inject_event(&mut self, event: TEvent);
215}
216
217/// An action that a [`NetworkBehaviour`] can trigger in the [`Swarm`]
218/// in whose context it is executing.
219///
220/// [`Swarm`]: super::Swarm
221#[derive(Debug)]
222pub enum NetworkBehaviourAction<TInEvent, TOutEvent> {
223    /// Instructs the `Swarm` to return an event when it is being polled.
224    GenerateEvent(TOutEvent),
225
226    /// Instructs the swarm to dial the given multiaddress, with no knowledge of the `PeerId` that
227    /// may be reached.
228    DialAddress {
229        /// The address to dial.
230        address: Multiaddr,
231    },
232
233    /// Instructs the swarm to dial a known `PeerId`.
234    ///
235    /// The `addresses_of_peer` method is called to determine which addresses to attempt to reach.
236    ///
237    /// If we were already trying to dial this node, the addresses that are not yet in the queue of
238    /// addresses to try are added back to this queue.
239    ///
240    /// On success, [`NetworkBehaviour::inject_connected`] is invoked.
241    /// On failure, [`NetworkBehaviour::inject_dial_failure`] is invoked.
242    DialPeer {
243        /// The peer to try reach.
244        peer_id: PeerId,
245        /// The condition for initiating a new dialing attempt.
246        condition: DialPeerCondition,
247    },
248
249    /// Instructs the swarm to close connection the peer with `PeerId`.
250    /// The connection status flag will be update with disconnect timeout
251    DisconnectPeer {
252        /// The peer to try reach.
253        peer_id: PeerId,
254    },
255
256    /// Instructs the `Swarm` to send an event to the handler dedicated to a
257    /// connection with a peer.
258    ///
259    /// If the `Swarm` is connected to the peer, the message is delivered to the
260    /// `ProtocolsHandler` instance identified by the peer ID and connection ID.
261    ///
262    /// If the specified connection no longer exists, the event is silently dropped.
263    ///
264    /// Typically the connection ID given is the same as the one passed to
265    /// [`NetworkBehaviour::inject_event`], i.e. whenever the behaviour wishes to
266    /// respond to a request on the same connection (and possibly the same
267    /// substream, as per the implementation of `ProtocolsHandler`).
268    ///
269    /// Note that even if the peer is currently connected, connections can get closed
270    /// at any time and thus the event may not reach a handler.
271    NotifyHandler {
272        /// The peer for whom a `ProtocolsHandler` should be notified.
273        peer_id: PeerId,
274        /// The options w.r.t. which connection handler to notify of the event.
275        handler: NotifyHandler,
276        /// The event to send.
277        event: TInEvent,
278    },
279
280    /// Informs the `Swarm` about an address observed by a remote for
281    /// the local node by which the local node is supposedly publicly
282    /// reachable.
283    ///
284    /// It is advisable to issue `ReportObservedAddr` actions at a fixed frequency
285    /// per node. This way address information will be more accurate over time
286    /// and individual outliers carry less weight.
287    ReportObservedAddr {
288        /// The observed address of the local node.
289        address: Multiaddr,
290        /// The score to associate with this observation, i.e.
291        /// an indicator for the trusworthiness of this address
292        /// relative to other observed addresses.
293        score: AddressScore,
294    },
295}
296
297impl<TInEvent, TOutEvent> NetworkBehaviourAction<TInEvent, TOutEvent> {
298    /// Map the handler event.
299    pub fn map_in<E>(self, f: impl FnOnce(TInEvent) -> E) -> NetworkBehaviourAction<E, TOutEvent> {
300        match self {
301            NetworkBehaviourAction::GenerateEvent(e) =>
302                NetworkBehaviourAction::GenerateEvent(e),
303            NetworkBehaviourAction::DialAddress { address } =>
304                NetworkBehaviourAction::DialAddress { address },
305            NetworkBehaviourAction::DialPeer { peer_id, condition } =>
306                NetworkBehaviourAction::DialPeer { peer_id, condition },
307            NetworkBehaviourAction::DisconnectPeer { peer_id } =>
308                NetworkBehaviourAction::DisconnectPeer { peer_id },
309            NetworkBehaviourAction::NotifyHandler { peer_id, handler, event } =>
310                NetworkBehaviourAction::NotifyHandler {
311                    peer_id,
312                    handler,
313                    event: f(event)
314                },
315            NetworkBehaviourAction::ReportObservedAddr { address, score } =>
316                NetworkBehaviourAction::ReportObservedAddr { address, score }
317        }
318    }
319
320    /// Map the event the swarm will return.
321    pub fn map_out<E>(self, f: impl FnOnce(TOutEvent) -> E) -> NetworkBehaviourAction<TInEvent, E> {
322        match self {
323            NetworkBehaviourAction::GenerateEvent(e) =>
324                NetworkBehaviourAction::GenerateEvent(f(e)),
325            NetworkBehaviourAction::DialAddress { address } =>
326                NetworkBehaviourAction::DialAddress { address },
327            NetworkBehaviourAction::DialPeer { peer_id, condition } =>
328                NetworkBehaviourAction::DialPeer { peer_id, condition },
329            NetworkBehaviourAction::DisconnectPeer { peer_id } =>
330                NetworkBehaviourAction::DisconnectPeer { peer_id },
331            NetworkBehaviourAction::NotifyHandler { peer_id, handler, event } =>
332                NetworkBehaviourAction::NotifyHandler { peer_id, handler, event },
333            NetworkBehaviourAction::ReportObservedAddr { address, score } =>
334                NetworkBehaviourAction::ReportObservedAddr { address, score }
335        }
336    }
337}
338
339/// The options w.r.t. which connection handler to notify of an event.
340#[derive(Debug, Clone)]
341pub enum NotifyHandler {
342    /// Notify a particular connection handler.
343    One(ConnectionId),
344    /// Notify an arbitrary connection handler.
345    Any,
346}
347
348/// The available conditions under which a new dialing attempt to
349/// a peer is initiated when requested by [`NetworkBehaviourAction::DialPeer`].
350#[derive(Debug, Copy, Clone)]
351#[non_exhaustive]
352pub enum DialPeerCondition {
353    /// A new dialing attempt is initiated _only if_ the peer is currently
354    /// considered disconnected, i.e. there is no established connection
355    /// and no ongoing dialing attempt.
356    ///
357    /// If there is an ongoing dialing attempt, the addresses reported by
358    /// [`NetworkBehaviour::addresses_of_peer`] are added to the ongoing
359    /// dialing attempt, ignoring duplicates.
360    Disconnected,
361    /// A new dialing attempt is initiated _only if_ there is currently
362    /// no ongoing dialing attempt, i.e. the peer is either considered
363    /// disconnected or connected but without an ongoing dialing attempt.
364    ///
365    /// If there is an ongoing dialing attempt, the addresses reported by
366    /// [`NetworkBehaviour::addresses_of_peer`] are added to the ongoing
367    /// dialing attempt, ignoring duplicates.
368    NotDialing,
369    /// A new dialing attempt is always initiated, only subject to the
370    /// configured connection limits.
371    Always,
372}
373
374impl Default for DialPeerCondition {
375    fn default() -> Self {
376        DialPeerCondition::Disconnected
377    }
378}