2018-12-07 10:23:38 +01:00
|
|
|
// 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.
|
|
|
|
|
2022-10-04 01:17:31 +01:00
|
|
|
use crate::handler::{self, Proto, Push};
|
|
|
|
use crate::protocol::{Info, ReplySubstream, UpgradeError};
|
2018-12-07 10:23:38 +01:00
|
|
|
use futures::prelude::*;
|
2019-07-04 14:47:59 +02:00
|
|
|
use libp2p_core::{
|
2022-07-04 04:16:57 +02:00
|
|
|
connection::ConnectionId, multiaddr::Protocol, transport::ListenerId, ConnectedPoint,
|
|
|
|
Multiaddr, PeerId, PublicKey,
|
2019-07-04 14:47:59 +02:00
|
|
|
};
|
|
|
|
use libp2p_swarm::{
|
2022-08-10 12:20:24 +04:30
|
|
|
dial_opts::DialOpts, AddressScore, ConnectionHandler, ConnectionHandlerUpgrErr, DialError,
|
|
|
|
IntoConnectionHandler, NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction,
|
|
|
|
NotifyHandler, PollParameters,
|
2019-07-04 14:47:59 +02:00
|
|
|
};
|
2021-10-14 06:46:34 +11:00
|
|
|
use lru::LruCache;
|
2022-09-27 11:39:10 +10:00
|
|
|
use std::num::NonZeroUsize;
|
2020-03-31 15:41:13 +02:00
|
|
|
use std::{
|
2021-03-18 12:47:01 +01:00
|
|
|
collections::{HashMap, HashSet, VecDeque},
|
2021-10-14 06:46:34 +11:00
|
|
|
iter::FromIterator,
|
2020-03-31 15:41:13 +02:00
|
|
|
pin::Pin,
|
|
|
|
task::Context,
|
2021-03-18 12:47:01 +01:00
|
|
|
task::Poll,
|
|
|
|
time::Duration,
|
2020-03-31 15:41:13 +02:00
|
|
|
};
|
2018-12-07 10:23:38 +01:00
|
|
|
|
|
|
|
/// Network behaviour that automatically identifies nodes periodically, returns information
|
|
|
|
/// about them, and answers identify queries from other nodes.
|
2020-11-18 15:52:33 +01:00
|
|
|
///
|
|
|
|
/// All external addresses of the local node supposedly observed by remotes
|
|
|
|
/// are reported via [`NetworkBehaviourAction::ReportObservedAddr`] with a
|
|
|
|
/// [score](AddressScore) of `1`.
|
2022-10-04 01:17:31 +01:00
|
|
|
pub struct Behaviour {
|
|
|
|
config: Config,
|
2018-12-07 10:23:38 +01:00
|
|
|
/// For each peer we're connected to, the observed address to send back to it.
|
2021-03-18 12:47:01 +01:00
|
|
|
connected: HashMap<PeerId, HashMap<ConnectionId, Multiaddr>>,
|
2019-09-02 11:16:52 +02:00
|
|
|
/// Pending replies to send.
|
2020-02-07 16:29:30 +01:00
|
|
|
pending_replies: VecDeque<Reply>,
|
2019-09-02 11:16:52 +02:00
|
|
|
/// Pending events to be emitted when polled.
|
2022-10-04 01:17:31 +01:00
|
|
|
events: VecDeque<NetworkBehaviourAction<Event, Proto>>,
|
2021-03-18 12:47:01 +01:00
|
|
|
/// Peers to which an active push with current information about
|
|
|
|
/// the local peer should be sent.
|
|
|
|
pending_push: HashSet<PeerId>,
|
2021-10-14 06:46:34 +11:00
|
|
|
/// The addresses of all peers that we have discovered.
|
2022-09-27 11:39:10 +10:00
|
|
|
discovered_peers: PeerCache,
|
2019-09-02 11:16:52 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// A pending reply to an inbound identification request.
|
2020-02-07 16:29:30 +01:00
|
|
|
enum Reply {
|
2019-09-02 11:16:52 +02:00
|
|
|
/// The reply is queued for sending.
|
|
|
|
Queued {
|
|
|
|
peer: PeerId,
|
2020-02-07 16:29:30 +01:00
|
|
|
io: ReplySubstream<NegotiatedSubstream>,
|
2019-09-02 11:16:52 +02:00
|
|
|
observed: Multiaddr,
|
|
|
|
},
|
|
|
|
/// The reply is being sent.
|
|
|
|
Sending {
|
|
|
|
peer: PeerId,
|
2022-05-05 18:28:47 +02:00
|
|
|
io: Pin<Box<dyn Future<Output = Result<(), UpgradeError>> + Send>>,
|
2019-09-02 11:16:52 +02:00
|
|
|
},
|
2018-12-07 10:23:38 +01:00
|
|
|
}
|
|
|
|
|
2022-10-04 01:17:31 +01:00
|
|
|
/// Configuration for the [`identify::Behaviour`](Behaviour).
|
2021-03-18 12:47:01 +01:00
|
|
|
#[non_exhaustive]
|
2022-02-16 17:16:54 +02:00
|
|
|
#[derive(Debug, Clone)]
|
2022-10-04 01:17:31 +01:00
|
|
|
pub struct Config {
|
2021-03-18 12:47:01 +01:00
|
|
|
/// Application-specific version of the protocol family used by the peer,
|
|
|
|
/// e.g. `ipfs/1.0.0` or `polkadot/1.0.0`.
|
|
|
|
pub protocol_version: String,
|
|
|
|
/// The public key of the local node. To report on the wire.
|
|
|
|
pub local_public_key: PublicKey,
|
|
|
|
/// Name and version of the local peer implementation, similar to the
|
|
|
|
/// `User-Agent` header in the HTTP protocol.
|
|
|
|
///
|
|
|
|
/// Defaults to `rust-libp2p/<libp2p-identify-version>`.
|
|
|
|
pub agent_version: String,
|
|
|
|
/// The initial delay before the first identification request
|
|
|
|
/// is sent to a remote on a newly established connection.
|
|
|
|
///
|
|
|
|
/// Defaults to 500ms.
|
|
|
|
pub initial_delay: Duration,
|
|
|
|
/// The interval at which identification requests are sent to
|
|
|
|
/// the remote on established connections after the first request,
|
|
|
|
/// i.e. the delay between identification requests.
|
|
|
|
///
|
|
|
|
/// Defaults to 5 minutes.
|
|
|
|
pub interval: Duration,
|
2021-03-22 10:53:30 +01:00
|
|
|
|
|
|
|
/// Whether new or expired listen addresses of the local node should
|
|
|
|
/// trigger an active push of an identify message to all connected peers.
|
|
|
|
///
|
|
|
|
/// Enabling this option can result in connected peers being informed
|
|
|
|
/// earlier about new or expired listen addresses of the local node,
|
|
|
|
/// i.e. before the next periodic identify request with each peer.
|
|
|
|
///
|
|
|
|
/// Disabled by default.
|
|
|
|
pub push_listen_addr_updates: bool,
|
2021-10-14 06:46:34 +11:00
|
|
|
|
|
|
|
/// How many entries of discovered peers to keep before we discard
|
|
|
|
/// the least-recently used one.
|
2021-10-27 18:25:37 +02:00
|
|
|
///
|
|
|
|
/// Disabled by default.
|
2021-10-14 06:46:34 +11:00
|
|
|
pub cache_size: usize,
|
2021-03-18 12:47:01 +01:00
|
|
|
}
|
|
|
|
|
2022-10-04 01:17:31 +01:00
|
|
|
impl Config {
|
|
|
|
/// Creates a new configuration for the identify [`Behaviour`] that
|
2021-03-18 12:47:01 +01:00
|
|
|
/// advertises the given protocol version and public key.
|
|
|
|
pub fn new(protocol_version: String, local_public_key: PublicKey) -> Self {
|
2022-10-04 01:17:31 +01:00
|
|
|
Self {
|
2021-03-18 12:47:01 +01:00
|
|
|
protocol_version,
|
|
|
|
agent_version: format!("rust-libp2p/{}", env!("CARGO_PKG_VERSION")),
|
|
|
|
local_public_key,
|
|
|
|
initial_delay: Duration::from_millis(500),
|
|
|
|
interval: Duration::from_secs(5 * 60),
|
2021-03-22 10:53:30 +01:00
|
|
|
push_listen_addr_updates: false,
|
2021-10-27 18:25:37 +02:00
|
|
|
cache_size: 0,
|
2021-03-18 12:47:01 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Configures the agent version sent to peers.
|
|
|
|
pub fn with_agent_version(mut self, v: String) -> Self {
|
|
|
|
self.agent_version = v;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Configures the initial delay before the first identification
|
|
|
|
/// request is sent on a newly established connection to a peer.
|
|
|
|
pub fn with_initial_delay(mut self, d: Duration) -> Self {
|
|
|
|
self.initial_delay = d;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Configures the interval at which identification requests are
|
|
|
|
/// sent to peers after the initial request.
|
|
|
|
pub fn with_interval(mut self, d: Duration) -> Self {
|
|
|
|
self.interval = d;
|
|
|
|
self
|
|
|
|
}
|
2021-03-22 10:53:30 +01:00
|
|
|
|
|
|
|
/// Configures whether new or expired listen addresses of the local
|
|
|
|
/// node should trigger an active push of an identify message to all
|
|
|
|
/// connected peers.
|
|
|
|
pub fn with_push_listen_addr_updates(mut self, b: bool) -> Self {
|
|
|
|
self.push_listen_addr_updates = b;
|
|
|
|
self
|
|
|
|
}
|
2021-10-14 06:46:34 +11:00
|
|
|
|
|
|
|
/// Configures the size of the LRU cache, caching addresses of discovered peers.
|
|
|
|
///
|
|
|
|
/// The [`Swarm`](libp2p_swarm::Swarm) may extend the set of addresses of an outgoing connection attempt via
|
2022-10-04 01:17:31 +01:00
|
|
|
/// [`Behaviour::addresses_of_peer`].
|
2021-10-14 06:46:34 +11:00
|
|
|
pub fn with_cache_size(mut self, cache_size: usize) -> Self {
|
|
|
|
self.cache_size = cache_size;
|
|
|
|
self
|
|
|
|
}
|
2021-03-18 12:47:01 +01:00
|
|
|
}
|
|
|
|
|
2022-10-04 01:17:31 +01:00
|
|
|
impl Behaviour {
|
|
|
|
/// Creates a new identify [`Behaviour`].
|
|
|
|
pub fn new(config: Config) -> Self {
|
2022-09-27 11:39:10 +10:00
|
|
|
let discovered_peers = match NonZeroUsize::new(config.cache_size) {
|
|
|
|
None => PeerCache::disabled(),
|
|
|
|
Some(size) => PeerCache::enabled(size),
|
|
|
|
};
|
2021-10-14 06:46:34 +11:00
|
|
|
|
2022-10-04 01:17:31 +01:00
|
|
|
Self {
|
2021-03-18 12:47:01 +01:00
|
|
|
config,
|
|
|
|
connected: HashMap::new(),
|
2019-09-02 11:16:52 +02:00
|
|
|
pending_replies: VecDeque::new(),
|
2018-12-07 10:23:38 +01:00
|
|
|
events: VecDeque::new(),
|
2021-03-18 12:47:01 +01:00
|
|
|
pending_push: HashSet::new(),
|
2021-10-14 06:46:34 +11:00
|
|
|
discovered_peers,
|
2021-03-18 12:47:01 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Initiates an active push of the local peer information to the given peers.
|
|
|
|
pub fn push<I>(&mut self, peers: I)
|
|
|
|
where
|
|
|
|
I: IntoIterator<Item = PeerId>,
|
|
|
|
{
|
|
|
|
for p in peers {
|
2022-05-03 13:11:48 +02:00
|
|
|
if self.pending_push.insert(p) && !self.connected.contains_key(&p) {
|
|
|
|
let handler = self.new_handler();
|
|
|
|
self.events.push_back(NetworkBehaviourAction::Dial {
|
2022-08-10 12:20:24 +04:30
|
|
|
opts: DialOpts::peer_id(p).build(),
|
2022-05-03 13:11:48 +02:00
|
|
|
handler,
|
|
|
|
});
|
2021-03-18 12:47:01 +01:00
|
|
|
}
|
2018-12-07 10:23:38 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-04 01:17:31 +01:00
|
|
|
impl NetworkBehaviour for Behaviour {
|
|
|
|
type ConnectionHandler = Proto;
|
|
|
|
type OutEvent = Event;
|
2018-12-07 10:23:38 +01:00
|
|
|
|
2022-02-21 13:32:24 +01:00
|
|
|
fn new_handler(&mut self) -> Self::ConnectionHandler {
|
2022-10-04 01:17:31 +01:00
|
|
|
Proto::new(self.config.initial_delay, self.config.interval)
|
2018-12-07 10:23:38 +01:00
|
|
|
}
|
|
|
|
|
2020-03-31 15:41:13 +02:00
|
|
|
fn inject_connection_established(
|
|
|
|
&mut self,
|
|
|
|
peer_id: &PeerId,
|
|
|
|
conn: &ConnectionId,
|
|
|
|
endpoint: &ConnectedPoint,
|
2021-10-14 18:05:07 +02:00
|
|
|
failed_addresses: Option<&Vec<Multiaddr>>,
|
2022-02-09 10:08:28 -05:00
|
|
|
_other_established: usize,
|
2020-03-31 15:41:13 +02:00
|
|
|
) {
|
|
|
|
let addr = match endpoint {
|
2022-01-17 16:35:14 +01:00
|
|
|
ConnectedPoint::Dialer { address, .. } => address.clone(),
|
2020-03-31 15:41:13 +02:00
|
|
|
ConnectedPoint::Listener { send_back_addr, .. } => send_back_addr.clone(),
|
2018-12-07 10:23:38 +01:00
|
|
|
};
|
|
|
|
|
2021-03-22 10:53:30 +01:00
|
|
|
self.connected
|
|
|
|
.entry(*peer_id)
|
|
|
|
.or_default()
|
|
|
|
.insert(*conn, addr);
|
2021-10-14 18:05:07 +02:00
|
|
|
|
|
|
|
if let Some(entry) = self.discovered_peers.get_mut(peer_id) {
|
|
|
|
for addr in failed_addresses
|
|
|
|
.into_iter()
|
2022-05-03 13:11:48 +02:00
|
|
|
.flat_map(|addresses| addresses.iter())
|
2021-10-14 18:05:07 +02:00
|
|
|
{
|
|
|
|
entry.remove(addr);
|
|
|
|
}
|
|
|
|
}
|
2020-03-31 15:41:13 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fn inject_connection_closed(
|
|
|
|
&mut self,
|
|
|
|
peer_id: &PeerId,
|
|
|
|
conn: &ConnectionId,
|
|
|
|
_: &ConnectedPoint,
|
2022-02-21 13:32:24 +01:00
|
|
|
_: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
|
2022-02-09 10:08:28 -05:00
|
|
|
remaining_established: usize,
|
2020-03-31 15:41:13 +02:00
|
|
|
) {
|
2022-02-09 10:08:28 -05:00
|
|
|
if remaining_established == 0 {
|
|
|
|
self.connected.remove(peer_id);
|
|
|
|
self.pending_push.remove(peer_id);
|
|
|
|
} else if let Some(addrs) = self.connected.get_mut(peer_id) {
|
2020-03-31 15:41:13 +02:00
|
|
|
addrs.remove(conn);
|
|
|
|
}
|
2018-12-07 10:23:38 +01:00
|
|
|
}
|
|
|
|
|
2021-10-14 18:05:07 +02:00
|
|
|
fn inject_dial_failure(
|
|
|
|
&mut self,
|
|
|
|
peer_id: Option<PeerId>,
|
2022-02-21 13:32:24 +01:00
|
|
|
_: Self::ConnectionHandler,
|
2021-10-14 18:05:07 +02:00
|
|
|
error: &DialError,
|
|
|
|
) {
|
|
|
|
if let Some(peer_id) = peer_id {
|
|
|
|
if !self.connected.contains_key(&peer_id) {
|
|
|
|
self.pending_push.remove(&peer_id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(entry) = peer_id.and_then(|id| self.discovered_peers.get_mut(&id)) {
|
|
|
|
if let DialError::Transport(errors) = error {
|
|
|
|
for (addr, _error) in errors {
|
|
|
|
entry.remove(addr);
|
|
|
|
}
|
|
|
|
}
|
2021-03-18 12:47:01 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-24 17:21:53 +01:00
|
|
|
fn inject_new_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) {
|
2021-03-22 10:53:30 +01:00
|
|
|
if self.config.push_listen_addr_updates {
|
|
|
|
self.pending_push.extend(self.connected.keys());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-24 17:21:53 +01:00
|
|
|
fn inject_expired_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) {
|
2021-03-22 10:53:30 +01:00
|
|
|
if self.config.push_listen_addr_updates {
|
|
|
|
self.pending_push.extend(self.connected.keys());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Multiple connections per peer (#1440)
* Allow multiple connections per peer in libp2p-core.
Instead of trying to enforce a single connection per peer,
which involves quite a bit of additional complexity e.g.
to prioritise simultaneously opened connections and can
have other undesirable consequences [1], we now
make multiple connections per peer a feature.
The gist of these changes is as follows:
The concept of a "node" with an implicit 1-1 correspondence
to a connection has been replaced with the "first-class"
concept of a "connection". The code from `src/nodes` has moved
(with varying degrees of modification) to `src/connection`.
A `HandledNode` has become a `Connection`, a `NodeHandler` a
`ConnectionHandler`, the `CollectionStream` was the basis for
the new `connection::Pool`, and so forth.
Conceptually, a `Network` contains a `connection::Pool` which
in turn internally employs the `connection::Manager` for
handling the background `connection::manager::Task`s, one
per connection, as before. These are all considered implementation
details. On the public API, `Peer`s are managed as before through
the `Network`, except now the API has changed with the shift of focus
to (potentially multiple) connections per peer. The `NetworkEvent`s have
accordingly also undergone changes.
The Swarm APIs remain largely unchanged, except for the fact that
`inject_replaced` is no longer called. It may now practically happen
that multiple `ProtocolsHandler`s are associated with a single
`NetworkBehaviour`, one per connection. If implementations of
`NetworkBehaviour` rely somehow on communicating with exactly
one `ProtocolsHandler`, this may cause issues, but it is unlikely.
[1]: https://github.com/paritytech/substrate/issues/4272
* Fix intra-rustdoc links.
* Update core/src/connection/pool.rs
Co-Authored-By: Max Inden <mail@max-inden.de>
* Address some review feedback and fix doc links.
* Allow responses to be sent on the same connection.
* Remove unnecessary remainders of inject_replaced.
* Update swarm/src/behaviour.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update swarm/src/lib.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/pool.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Incorporate more review feedback.
* Move module declaration below imports.
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Simplify as per review.
* Fix rustoc link.
* Add try_notify_handler and simplify.
* Relocate DialingConnection and DialingAttempt.
For better visibility constraints.
* Small cleanup.
* Small cleanup. More robust EstablishedConnectionIter.
* Clarify semantics of `DialingPeer::connect`.
* Don't call inject_disconnected on InvalidPeerId.
To preserve the previous behavior and ensure calls to
`inject_disconnected` are always paired with calls to
`inject_connected`.
* Provide public ConnectionId constructor.
Mainly needed for testing purposes, e.g. in substrate.
* Move the established connection limit check to the right place.
* Clean up connection error handling.
Separate connection errors into those occuring during
connection setup or upon rejecting a newly established
connection (the `PendingConnectionError`) and those
errors occurring on previously established connections,
i.e. for which a `ConnectionEstablished` event has
been emitted by the connection pool earlier.
* Revert change in log level and clarify an invariant.
* Remove inject_replaced entirely.
* Allow notifying all connection handlers.
Thereby simplify by introducing a new enum `NotifyHandler`,
used with a single constructor `NetworkBehaviourAction::NotifyHandler`.
* Finishing touches.
Small API simplifications and code deduplication.
Some more useful debug logging.
Co-authored-by: Max Inden <mail@max-inden.de>
Co-authored-by: Pierre Krieger <pierre.krieger1708@gmail.com>
Co-authored-by: Toralf Wittner <tw@dtex.org>
2020-03-04 13:49:25 +01:00
|
|
|
fn inject_event(
|
2018-12-07 10:23:38 +01:00
|
|
|
&mut self,
|
|
|
|
peer_id: PeerId,
|
2020-03-31 15:41:13 +02:00
|
|
|
connection: ConnectionId,
|
2022-06-26 10:37:29 +02:00
|
|
|
event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
|
2018-12-07 10:23:38 +01:00
|
|
|
) {
|
|
|
|
match event {
|
2022-10-04 01:17:31 +01:00
|
|
|
handler::Event::Identified(mut info) => {
|
2021-11-16 04:05:47 -08:00
|
|
|
// Remove invalid multiaddrs.
|
|
|
|
info.listen_addrs
|
|
|
|
.retain(|addr| multiaddr_matches_peer_id(addr, &peer_id));
|
|
|
|
|
2021-10-14 06:46:34 +11:00
|
|
|
// Replace existing addresses to prevent other peer from filling up our memory.
|
|
|
|
self.discovered_peers
|
2022-09-27 11:39:10 +10:00
|
|
|
.put(peer_id, info.listen_addrs.iter().cloned());
|
2021-10-14 06:46:34 +11:00
|
|
|
|
2021-03-18 12:47:01 +01:00
|
|
|
let observed = info.observed_addr.clone();
|
2022-10-04 01:17:31 +01:00
|
|
|
self.events
|
|
|
|
.push_back(NetworkBehaviourAction::GenerateEvent(Event::Received {
|
|
|
|
peer_id,
|
|
|
|
info,
|
|
|
|
}));
|
2019-09-02 11:16:52 +02:00
|
|
|
self.events
|
|
|
|
.push_back(NetworkBehaviourAction::ReportObservedAddr {
|
2021-03-18 12:47:01 +01:00
|
|
|
address: observed,
|
2020-11-18 15:52:33 +01:00
|
|
|
score: AddressScore::Finite(1),
|
2018-12-07 10:23:38 +01:00
|
|
|
});
|
|
|
|
}
|
2022-10-04 01:17:31 +01:00
|
|
|
handler::Event::IdentificationPushed => {
|
|
|
|
self.events
|
|
|
|
.push_back(NetworkBehaviourAction::GenerateEvent(Event::Pushed {
|
|
|
|
peer_id,
|
|
|
|
}));
|
2021-04-10 19:46:57 +02:00
|
|
|
}
|
2022-10-04 01:17:31 +01:00
|
|
|
handler::Event::Identify(sender) => {
|
2021-03-18 12:47:01 +01:00
|
|
|
let observed = self
|
|
|
|
.connected
|
|
|
|
.get(&peer_id)
|
2020-03-31 15:41:13 +02:00
|
|
|
.and_then(|addrs| addrs.get(&connection))
|
|
|
|
.expect(
|
|
|
|
"`inject_event` is only called with an established connection \
|
|
|
|
and `inject_connection_established` ensures there is an entry; qed",
|
|
|
|
);
|
2019-09-02 11:16:52 +02:00
|
|
|
self.pending_replies.push_back(Reply::Queued {
|
|
|
|
peer: peer_id,
|
|
|
|
io: sender,
|
|
|
|
observed: observed.clone(),
|
|
|
|
});
|
2018-12-07 10:23:38 +01:00
|
|
|
}
|
2022-10-04 01:17:31 +01:00
|
|
|
handler::Event::IdentificationError(error) => {
|
|
|
|
self.events
|
|
|
|
.push_back(NetworkBehaviourAction::GenerateEvent(Event::Error {
|
|
|
|
peer_id,
|
|
|
|
error,
|
|
|
|
}));
|
2018-12-07 10:23:38 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll(
|
|
|
|
&mut self,
|
2020-07-27 20:27:33 +00:00
|
|
|
cx: &mut Context<'_>,
|
2019-06-18 10:23:26 +02:00
|
|
|
params: &mut impl PollParameters,
|
2022-02-21 13:32:24 +01:00
|
|
|
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
|
2018-12-07 10:23:38 +01:00
|
|
|
if let Some(event) = self.events.pop_front() {
|
2019-09-16 11:08:44 +02:00
|
|
|
return Poll::Ready(event);
|
2018-12-07 10:23:38 +01:00
|
|
|
}
|
|
|
|
|
2021-03-18 12:47:01 +01:00
|
|
|
// Check for a pending active push to perform.
|
|
|
|
let peer_push = self.pending_push.iter().find_map(|peer| {
|
|
|
|
self.connected.get(peer).map(|conns| {
|
|
|
|
let observed_addr = conns
|
|
|
|
.values()
|
|
|
|
.next()
|
|
|
|
.expect("connected peer has a connection")
|
|
|
|
.clone();
|
|
|
|
|
|
|
|
let listen_addrs = listen_addrs(params);
|
|
|
|
let protocols = supported_protocols(params);
|
|
|
|
|
2022-10-04 01:17:31 +01:00
|
|
|
let info = Info {
|
2021-03-18 12:47:01 +01:00
|
|
|
public_key: self.config.local_public_key.clone(),
|
|
|
|
protocol_version: self.config.protocol_version.clone(),
|
|
|
|
agent_version: self.config.agent_version.clone(),
|
|
|
|
listen_addrs,
|
|
|
|
protocols,
|
|
|
|
observed_addr,
|
|
|
|
};
|
2018-12-07 10:23:38 +01:00
|
|
|
|
2022-10-04 01:17:31 +01:00
|
|
|
(*peer, Push(info))
|
2021-03-18 12:47:01 +01:00
|
|
|
})
|
|
|
|
});
|
|
|
|
|
|
|
|
if let Some((peer_id, push)) = peer_push {
|
|
|
|
self.pending_push.remove(&peer_id);
|
|
|
|
return Poll::Ready(NetworkBehaviourAction::NotifyHandler {
|
|
|
|
peer_id,
|
|
|
|
event: push,
|
|
|
|
handler: NotifyHandler::Any,
|
|
|
|
});
|
|
|
|
}
|
2019-02-07 11:04:04 +01:00
|
|
|
|
2021-03-18 12:47:01 +01:00
|
|
|
// Check for pending replies to send.
|
|
|
|
if let Some(r) = self.pending_replies.pop_front() {
|
2019-09-02 11:16:52 +02:00
|
|
|
let mut sending = 0;
|
|
|
|
let to_send = self.pending_replies.len() + 1;
|
|
|
|
let mut reply = Some(r);
|
|
|
|
loop {
|
|
|
|
match reply {
|
|
|
|
Some(Reply::Queued { peer, io, observed }) => {
|
2022-10-04 01:17:31 +01:00
|
|
|
let info = Info {
|
2021-03-18 12:47:01 +01:00
|
|
|
listen_addrs: listen_addrs(params),
|
|
|
|
protocols: supported_protocols(params),
|
|
|
|
public_key: self.config.local_public_key.clone(),
|
|
|
|
protocol_version: self.config.protocol_version.clone(),
|
|
|
|
agent_version: self.config.agent_version.clone(),
|
|
|
|
observed_addr: observed,
|
2019-09-02 11:16:52 +02:00
|
|
|
};
|
2021-03-18 12:47:01 +01:00
|
|
|
let io = Box::pin(io.send(info));
|
2019-09-02 11:16:52 +02:00
|
|
|
reply = Some(Reply::Sending { peer, io });
|
|
|
|
}
|
|
|
|
Some(Reply::Sending { peer, mut io }) => {
|
|
|
|
sending += 1;
|
2019-09-16 11:08:44 +02:00
|
|
|
match Future::poll(Pin::new(&mut io), cx) {
|
|
|
|
Poll::Ready(Ok(())) => {
|
2022-10-04 01:17:31 +01:00
|
|
|
let event = Event::Sent { peer_id: peer };
|
2019-09-16 11:08:44 +02:00
|
|
|
return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event));
|
2019-09-02 11:16:52 +02:00
|
|
|
}
|
2019-09-16 11:08:44 +02:00
|
|
|
Poll::Pending => {
|
2019-09-02 11:16:52 +02:00
|
|
|
self.pending_replies.push_back(Reply::Sending { peer, io });
|
|
|
|
if sending == to_send {
|
|
|
|
// All remaining futures are NotReady
|
|
|
|
break;
|
|
|
|
} else {
|
|
|
|
reply = self.pending_replies.pop_front();
|
|
|
|
}
|
|
|
|
}
|
2019-09-16 11:08:44 +02:00
|
|
|
Poll::Ready(Err(err)) => {
|
2022-10-04 01:17:31 +01:00
|
|
|
let event = Event::Error {
|
2019-09-02 11:16:52 +02:00
|
|
|
peer_id: peer,
|
2022-05-05 18:28:47 +02:00
|
|
|
error: ConnectionHandlerUpgrErr::Upgrade(
|
|
|
|
libp2p_core::upgrade::UpgradeError::Apply(err),
|
|
|
|
),
|
2019-09-02 11:16:52 +02:00
|
|
|
};
|
2019-09-16 11:08:44 +02:00
|
|
|
return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event));
|
2019-09-02 11:16:52 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
None => unreachable!(),
|
|
|
|
}
|
2018-12-07 10:23:38 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-16 11:08:44 +02:00
|
|
|
Poll::Pending
|
2018-12-07 10:23:38 +01:00
|
|
|
}
|
2021-10-14 06:46:34 +11:00
|
|
|
|
|
|
|
fn addresses_of_peer(&mut self, peer: &PeerId) -> Vec<Multiaddr> {
|
2022-09-27 11:39:10 +10:00
|
|
|
self.discovered_peers.get(peer)
|
2021-10-14 06:46:34 +11:00
|
|
|
}
|
2018-12-07 10:23:38 +01:00
|
|
|
}
|
|
|
|
|
2019-09-02 11:16:52 +02:00
|
|
|
/// Event emitted by the `Identify` behaviour.
|
2021-12-07 02:13:42 +11:00
|
|
|
#[allow(clippy::large_enum_variant)]
|
2018-12-07 10:23:38 +01:00
|
|
|
#[derive(Debug)]
|
2022-10-04 01:17:31 +01:00
|
|
|
pub enum Event {
|
2021-04-10 19:46:57 +02:00
|
|
|
/// Identification information has been received from a peer.
|
2019-09-02 11:16:52 +02:00
|
|
|
Received {
|
|
|
|
/// The peer that has been identified.
|
2018-12-07 10:23:38 +01:00
|
|
|
peer_id: PeerId,
|
2019-09-02 11:16:52 +02:00
|
|
|
/// The information provided by the peer.
|
2022-10-04 01:17:31 +01:00
|
|
|
info: Info,
|
2018-12-07 10:23:38 +01:00
|
|
|
},
|
2021-04-10 19:46:57 +02:00
|
|
|
/// Identification information of the local node has been sent to a peer in
|
|
|
|
/// response to an identification request.
|
2019-09-02 11:16:52 +02:00
|
|
|
Sent {
|
|
|
|
/// The peer that the information has been sent to.
|
|
|
|
peer_id: PeerId,
|
|
|
|
},
|
2021-04-10 19:46:57 +02:00
|
|
|
/// Identification information of the local node has been actively pushed to
|
|
|
|
/// a peer.
|
|
|
|
Pushed {
|
|
|
|
/// The peer that the information has been sent to.
|
|
|
|
peer_id: PeerId,
|
|
|
|
},
|
2018-12-07 10:23:38 +01:00
|
|
|
/// Error while attempting to identify the remote.
|
|
|
|
Error {
|
2019-09-02 11:16:52 +02:00
|
|
|
/// The peer with whom the error originated.
|
2018-12-07 10:23:38 +01:00
|
|
|
peer_id: PeerId,
|
2019-09-02 11:16:52 +02:00
|
|
|
/// The error that occurred.
|
2022-05-05 18:28:47 +02:00
|
|
|
error: ConnectionHandlerUpgrErr<UpgradeError>,
|
2018-12-07 10:23:38 +01:00
|
|
|
},
|
|
|
|
}
|
2019-02-18 13:59:12 +01:00
|
|
|
|
2021-03-18 12:47:01 +01:00
|
|
|
fn supported_protocols(params: &impl PollParameters) -> Vec<String> {
|
|
|
|
// The protocol names can be bytes, but the identify protocol except UTF-8 strings.
|
|
|
|
// There's not much we can do to solve this conflict except strip non-UTF-8 characters.
|
|
|
|
params
|
|
|
|
.supported_protocols()
|
|
|
|
.map(|p| String::from_utf8_lossy(&p).to_string())
|
|
|
|
.collect()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn listen_addrs(params: &impl PollParameters) -> Vec<Multiaddr> {
|
|
|
|
let mut listen_addrs: Vec<_> = params.external_addresses().map(|r| r.addr).collect();
|
|
|
|
listen_addrs.extend(params.listened_addresses());
|
|
|
|
listen_addrs
|
|
|
|
}
|
|
|
|
|
2021-11-16 04:05:47 -08:00
|
|
|
/// If there is a given peer_id in the multiaddr, make sure it is the same as
|
|
|
|
/// the given peer_id. If there is no peer_id for the peer in the mutiaddr, this returns true.
|
|
|
|
fn multiaddr_matches_peer_id(addr: &Multiaddr, peer_id: &PeerId) -> bool {
|
|
|
|
let last_component = addr.iter().last();
|
|
|
|
if let Some(Protocol::P2p(multi_addr_peer_id)) = last_component {
|
|
|
|
return multi_addr_peer_id == *peer_id.as_ref();
|
|
|
|
}
|
2022-05-03 13:11:48 +02:00
|
|
|
true
|
2021-11-16 04:05:47 -08:00
|
|
|
}
|
|
|
|
|
2022-09-27 11:39:10 +10:00
|
|
|
struct PeerCache(Option<LruCache<PeerId, HashSet<Multiaddr>>>);
|
|
|
|
|
|
|
|
impl PeerCache {
|
|
|
|
fn disabled() -> Self {
|
|
|
|
Self(None)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn enabled(size: NonZeroUsize) -> Self {
|
|
|
|
Self(Some(LruCache::new(size)))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_mut(&mut self, peer: &PeerId) -> Option<&mut HashSet<Multiaddr>> {
|
|
|
|
self.0.as_mut()?.get_mut(peer)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn put(&mut self, peer: PeerId, addresses: impl Iterator<Item = Multiaddr>) {
|
|
|
|
let cache = match self.0.as_mut() {
|
|
|
|
None => return,
|
|
|
|
Some(cache) => cache,
|
|
|
|
};
|
|
|
|
|
|
|
|
cache.put(peer, HashSet::from_iter(addresses));
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get(&mut self, peer: &PeerId) -> Vec<Multiaddr> {
|
|
|
|
let cache = match self.0.as_mut() {
|
|
|
|
None => return Vec::new(),
|
|
|
|
Some(cache) => cache,
|
|
|
|
};
|
|
|
|
|
|
|
|
cache
|
|
|
|
.get(peer)
|
|
|
|
.cloned()
|
|
|
|
.map(Vec::from_iter)
|
|
|
|
.unwrap_or_default()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-18 13:59:12 +01:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2021-03-18 12:47:01 +01:00
|
|
|
use super::*;
|
|
|
|
use futures::pin_mut;
|
2022-06-29 06:37:57 +02:00
|
|
|
use libp2p::mplex::MplexConfig;
|
|
|
|
use libp2p::noise;
|
2022-07-04 04:16:57 +02:00
|
|
|
use libp2p::tcp::{GenTcpConfig, TcpTransport};
|
2020-10-16 16:53:02 +02:00
|
|
|
use libp2p_core::{identity, muxing::StreamMuxerBox, transport, upgrade, PeerId, Transport};
|
2020-01-07 11:57:00 +01:00
|
|
|
use libp2p_swarm::{Swarm, SwarmEvent};
|
2022-07-04 03:58:16 +02:00
|
|
|
use std::time::Duration;
|
2019-04-20 16:00:21 +02:00
|
|
|
|
2020-10-16 16:53:02 +02:00
|
|
|
fn transport() -> (
|
|
|
|
identity::PublicKey,
|
|
|
|
transport::Boxed<(PeerId, StreamMuxerBox)>,
|
|
|
|
) {
|
2019-04-20 16:00:21 +02:00
|
|
|
let id_keys = identity::Keypair::generate_ed25519();
|
2020-09-07 12:13:10 +02:00
|
|
|
let noise_keys = noise::Keypair::<noise::X25519Spec>::new()
|
|
|
|
.into_authentic(&id_keys)
|
|
|
|
.unwrap();
|
2019-04-20 16:00:21 +02:00
|
|
|
let pubkey = id_keys.public();
|
2022-07-04 04:16:57 +02:00
|
|
|
let transport = TcpTransport::new(GenTcpConfig::default().nodelay(true))
|
2019-10-10 11:31:44 +02:00
|
|
|
.upgrade(upgrade::Version::V1)
|
2020-09-07 12:13:10 +02:00
|
|
|
.authenticate(noise::NoiseConfig::xx(noise_keys).into_authenticated())
|
2020-10-16 16:53:02 +02:00
|
|
|
.multiplex(MplexConfig::new())
|
|
|
|
.boxed();
|
2019-04-20 16:00:21 +02:00
|
|
|
(pubkey, transport)
|
|
|
|
}
|
2019-02-18 13:59:12 +01:00
|
|
|
|
|
|
|
#[test]
|
2021-03-18 12:47:01 +01:00
|
|
|
fn periodic_identify() {
|
2019-04-20 16:00:21 +02:00
|
|
|
let (mut swarm1, pubkey1) = {
|
|
|
|
let (pubkey, transport) = transport();
|
2022-10-04 01:17:31 +01:00
|
|
|
let protocol = Behaviour::new(
|
|
|
|
Config::new("a".to_string(), pubkey.clone()).with_agent_version("b".to_string()),
|
2021-03-18 12:47:01 +01:00
|
|
|
);
|
2021-07-22 22:34:13 +02:00
|
|
|
let swarm = Swarm::new(transport, protocol, pubkey.to_peer_id());
|
2019-04-20 16:00:21 +02:00
|
|
|
(swarm, pubkey)
|
2019-02-18 13:59:12 +01:00
|
|
|
};
|
|
|
|
|
2019-04-20 16:00:21 +02:00
|
|
|
let (mut swarm2, pubkey2) = {
|
|
|
|
let (pubkey, transport) = transport();
|
2022-10-04 01:17:31 +01:00
|
|
|
let protocol = Behaviour::new(
|
|
|
|
Config::new("c".to_string(), pubkey.clone()).with_agent_version("d".to_string()),
|
2021-03-18 12:47:01 +01:00
|
|
|
);
|
2021-07-22 22:34:13 +02:00
|
|
|
let swarm = Swarm::new(transport, protocol, pubkey.to_peer_id());
|
2019-04-20 16:00:21 +02:00
|
|
|
(swarm, pubkey)
|
2019-02-18 13:59:12 +01:00
|
|
|
};
|
|
|
|
|
2021-03-18 14:55:33 +01:00
|
|
|
swarm1
|
|
|
|
.listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap())
|
|
|
|
.unwrap();
|
2019-04-10 10:29:21 +02:00
|
|
|
|
2020-01-07 11:57:00 +01:00
|
|
|
let listen_addr = async_std::task::block_on(async {
|
|
|
|
loop {
|
2021-06-14 20:41:44 +02:00
|
|
|
let swarm1_fut = swarm1.select_next_some();
|
2020-01-07 11:57:00 +01:00
|
|
|
pin_mut!(swarm1_fut);
|
2022-10-04 18:24:38 +11:00
|
|
|
if let SwarmEvent::NewListenAddr { address, .. } = swarm1_fut.await {
|
|
|
|
return address;
|
2020-01-07 11:57:00 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2021-11-15 14:17:23 +01:00
|
|
|
swarm2.dial(listen_addr).unwrap();
|
2019-02-18 13:59:12 +01:00
|
|
|
|
2019-04-20 16:00:21 +02:00
|
|
|
// nb. Either swarm may receive the `Identified` event first, upon which
|
|
|
|
// it will permit the connection to be closed, as defined by
|
2019-09-02 11:16:52 +02:00
|
|
|
// `IdentifyHandler::connection_keep_alive`. Hence the test succeeds if
|
2019-04-20 16:00:21 +02:00
|
|
|
// either `Identified` event arrives correctly.
|
2019-12-18 16:31:31 +01:00
|
|
|
async_std::task::block_on(async move {
|
2019-11-26 14:47:49 +01:00
|
|
|
loop {
|
2021-06-14 20:41:44 +02:00
|
|
|
let swarm1_fut = swarm1.select_next_some();
|
2020-01-07 11:57:00 +01:00
|
|
|
pin_mut!(swarm1_fut);
|
2021-06-14 20:41:44 +02:00
|
|
|
let swarm2_fut = swarm2.select_next_some();
|
2020-01-07 11:57:00 +01:00
|
|
|
pin_mut!(swarm2_fut);
|
|
|
|
|
|
|
|
match future::select(swarm1_fut, swarm2_fut)
|
|
|
|
.await
|
|
|
|
.factor_second()
|
|
|
|
.0
|
|
|
|
{
|
2022-10-04 01:17:31 +01:00
|
|
|
future::Either::Left(SwarmEvent::Behaviour(Event::Received {
|
|
|
|
info, ..
|
2021-06-14 20:41:44 +02:00
|
|
|
})) => {
|
2019-11-26 14:47:49 +01:00
|
|
|
assert_eq!(info.public_key, pubkey2);
|
|
|
|
assert_eq!(info.protocol_version, "c");
|
|
|
|
assert_eq!(info.agent_version, "d");
|
|
|
|
assert!(!info.protocols.is_empty());
|
|
|
|
assert!(info.listen_addrs.is_empty());
|
|
|
|
return;
|
2019-02-18 13:59:12 +01:00
|
|
|
}
|
2022-10-04 01:17:31 +01:00
|
|
|
future::Either::Right(SwarmEvent::Behaviour(Event::Received {
|
|
|
|
info, ..
|
2021-06-14 20:41:44 +02:00
|
|
|
})) => {
|
2019-11-26 14:47:49 +01:00
|
|
|
assert_eq!(info.public_key, pubkey1);
|
|
|
|
assert_eq!(info.protocol_version, "a");
|
|
|
|
assert_eq!(info.agent_version, "b");
|
|
|
|
assert!(!info.protocols.is_empty());
|
|
|
|
assert_eq!(info.listen_addrs.len(), 1);
|
|
|
|
return;
|
2019-02-18 13:59:12 +01:00
|
|
|
}
|
2019-11-26 14:47:49 +01:00
|
|
|
_ => {}
|
2019-02-18 13:59:12 +01:00
|
|
|
}
|
2019-11-26 14:47:49 +01:00
|
|
|
}
|
|
|
|
})
|
2019-02-18 13:59:12 +01:00
|
|
|
}
|
2021-03-18 12:47:01 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn identify_push() {
|
|
|
|
let _ = env_logger::try_init();
|
|
|
|
|
|
|
|
let (mut swarm1, pubkey1) = {
|
|
|
|
let (pubkey, transport) = transport();
|
2022-10-04 01:17:31 +01:00
|
|
|
let protocol = Behaviour::new(Config::new("a".to_string(), pubkey.clone()));
|
2021-07-22 22:34:13 +02:00
|
|
|
let swarm = Swarm::new(transport, protocol, pubkey.to_peer_id());
|
2021-03-18 12:47:01 +01:00
|
|
|
(swarm, pubkey)
|
|
|
|
};
|
|
|
|
|
|
|
|
let (mut swarm2, pubkey2) = {
|
|
|
|
let (pubkey, transport) = transport();
|
2022-10-04 01:17:31 +01:00
|
|
|
let protocol = Behaviour::new(
|
|
|
|
Config::new("a".to_string(), pubkey.clone()).with_agent_version("b".to_string()),
|
2021-03-18 12:47:01 +01:00
|
|
|
);
|
2021-07-22 22:34:13 +02:00
|
|
|
let swarm = Swarm::new(transport, protocol, pubkey.to_peer_id());
|
2021-03-18 12:47:01 +01:00
|
|
|
(swarm, pubkey)
|
|
|
|
};
|
|
|
|
|
|
|
|
Swarm::listen_on(&mut swarm1, "/ip4/127.0.0.1/tcp/0".parse().unwrap()).unwrap();
|
|
|
|
|
|
|
|
let listen_addr = async_std::task::block_on(async {
|
|
|
|
loop {
|
2021-06-14 20:41:44 +02:00
|
|
|
let swarm1_fut = swarm1.select_next_some();
|
2021-03-18 12:47:01 +01:00
|
|
|
pin_mut!(swarm1_fut);
|
2022-10-04 18:24:38 +11:00
|
|
|
if let SwarmEvent::NewListenAddr { address, .. } = swarm1_fut.await {
|
|
|
|
return address;
|
2021-03-18 12:47:01 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2021-11-15 14:17:23 +01:00
|
|
|
swarm2.dial(listen_addr).unwrap();
|
2021-03-18 12:47:01 +01:00
|
|
|
|
|
|
|
async_std::task::block_on(async move {
|
|
|
|
loop {
|
2021-06-14 20:41:44 +02:00
|
|
|
let swarm1_fut = swarm1.select_next_some();
|
|
|
|
let swarm2_fut = swarm2.select_next_some();
|
2021-03-18 12:47:01 +01:00
|
|
|
|
|
|
|
{
|
|
|
|
pin_mut!(swarm1_fut);
|
|
|
|
pin_mut!(swarm2_fut);
|
|
|
|
match future::select(swarm1_fut, swarm2_fut)
|
|
|
|
.await
|
|
|
|
.factor_second()
|
|
|
|
.0
|
|
|
|
{
|
2022-10-04 01:17:31 +01:00
|
|
|
future::Either::Left(SwarmEvent::Behaviour(Event::Received {
|
2021-03-18 12:47:01 +01:00
|
|
|
info,
|
|
|
|
..
|
|
|
|
})) => {
|
|
|
|
assert_eq!(info.public_key, pubkey2);
|
|
|
|
assert_eq!(info.protocol_version, "a");
|
|
|
|
assert_eq!(info.agent_version, "b");
|
|
|
|
assert!(!info.protocols.is_empty());
|
|
|
|
assert!(info.listen_addrs.is_empty());
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
future::Either::Right(SwarmEvent::ConnectionEstablished { .. }) => {
|
|
|
|
// Once a connection is established, we can initiate an
|
|
|
|
// active push below.
|
|
|
|
}
|
|
|
|
_ => continue,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-22 22:34:13 +02:00
|
|
|
swarm2
|
|
|
|
.behaviour_mut()
|
|
|
|
.push(std::iter::once(pubkey1.to_peer_id()));
|
2021-03-18 12:47:01 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2021-10-14 06:46:34 +11:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn discover_peer_after_disconnect() {
|
|
|
|
let _ = env_logger::try_init();
|
|
|
|
|
|
|
|
let mut swarm1 = {
|
|
|
|
let (pubkey, transport) = transport();
|
2022-10-04 01:17:31 +01:00
|
|
|
let protocol = Behaviour::new(
|
|
|
|
Config::new("a".to_string(), pubkey.clone())
|
2022-07-04 03:58:16 +02:00
|
|
|
// `swarm1` will set `KeepAlive::No` once it identified `swarm2` and thus
|
|
|
|
// closes the connection. At this point in time `swarm2` might not yet have
|
|
|
|
// identified `swarm1`. To give `swarm2` enough time, set an initial delay on
|
|
|
|
// `swarm1`.
|
|
|
|
.with_initial_delay(Duration::from_secs(10)),
|
|
|
|
);
|
2021-10-14 06:46:34 +11:00
|
|
|
|
|
|
|
Swarm::new(transport, protocol, pubkey.to_peer_id())
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut swarm2 = {
|
|
|
|
let (pubkey, transport) = transport();
|
2022-10-04 01:17:31 +01:00
|
|
|
let protocol = Behaviour::new(
|
|
|
|
Config::new("a".to_string(), pubkey.clone())
|
2021-10-27 18:25:37 +02:00
|
|
|
.with_cache_size(100)
|
2021-10-14 06:46:34 +11:00
|
|
|
.with_agent_version("b".to_string()),
|
|
|
|
);
|
|
|
|
|
|
|
|
Swarm::new(transport, protocol, pubkey.to_peer_id())
|
|
|
|
};
|
|
|
|
|
|
|
|
let swarm1_peer_id = *swarm1.local_peer_id();
|
|
|
|
|
|
|
|
let listener = swarm1
|
|
|
|
.listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap())
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
let listen_addr = async_std::task::block_on(async {
|
|
|
|
loop {
|
|
|
|
match swarm1.select_next_some().await {
|
|
|
|
SwarmEvent::NewListenAddr {
|
|
|
|
address,
|
|
|
|
listener_id,
|
|
|
|
} if listener_id == listener => return address,
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
async_std::task::spawn(async move {
|
|
|
|
loop {
|
|
|
|
swarm1.next().await;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2021-11-15 14:17:23 +01:00
|
|
|
swarm2.dial(listen_addr).unwrap();
|
2021-10-14 06:46:34 +11:00
|
|
|
|
2021-11-15 14:17:23 +01:00
|
|
|
// Wait until we identified.
|
2021-10-14 06:46:34 +11:00
|
|
|
async_std::task::block_on(async {
|
|
|
|
loop {
|
2022-10-04 01:17:31 +01:00
|
|
|
if let SwarmEvent::Behaviour(Event::Received { .. }) =
|
2021-10-14 06:46:34 +11:00
|
|
|
swarm2.select_next_some().await
|
|
|
|
{
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
swarm2.disconnect_peer_id(swarm1_peer_id).unwrap();
|
|
|
|
|
2021-11-15 14:17:23 +01:00
|
|
|
// Wait for connection to close.
|
|
|
|
async_std::task::block_on(async {
|
|
|
|
loop {
|
|
|
|
if let SwarmEvent::ConnectionClosed { peer_id, .. } =
|
|
|
|
swarm2.select_next_some().await
|
|
|
|
{
|
|
|
|
break peer_id;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// We should still be able to dial now!
|
|
|
|
swarm2.dial(swarm1_peer_id).unwrap();
|
2021-10-14 06:46:34 +11:00
|
|
|
|
|
|
|
let connected_peer = async_std::task::block_on(async {
|
|
|
|
loop {
|
|
|
|
if let SwarmEvent::ConnectionEstablished { peer_id, .. } =
|
|
|
|
swarm2.select_next_some().await
|
|
|
|
{
|
|
|
|
break peer_id;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
assert_eq!(connected_peer, swarm1_peer_id);
|
|
|
|
}
|
2021-11-16 04:05:47 -08:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn check_multiaddr_matches_peer_id() {
|
|
|
|
let peer_id = PeerId::random();
|
|
|
|
let other_peer_id = PeerId::random();
|
|
|
|
let mut addr: Multiaddr = "/ip4/147.75.69.143/tcp/4001"
|
|
|
|
.parse()
|
|
|
|
.expect("failed to parse multiaddr");
|
|
|
|
|
|
|
|
let addr_without_peer_id: Multiaddr = addr.clone();
|
|
|
|
let mut addr_with_other_peer_id = addr.clone();
|
|
|
|
|
2022-10-04 18:24:38 +11:00
|
|
|
addr.push(Protocol::P2p(peer_id.into()));
|
2021-11-16 04:05:47 -08:00
|
|
|
addr_with_other_peer_id.push(Protocol::P2p(other_peer_id.into()));
|
|
|
|
|
|
|
|
assert!(multiaddr_matches_peer_id(&addr, &peer_id));
|
|
|
|
assert!(!multiaddr_matches_peer_id(
|
|
|
|
&addr_with_other_peer_id,
|
|
|
|
&peer_id
|
|
|
|
));
|
|
|
|
assert!(multiaddr_matches_peer_id(&addr_without_peer_id, &peer_id));
|
|
|
|
}
|
2019-02-18 13:59:12 +01:00
|
|
|
}
|