Integrate litep2p into Polkadot SDK (#2944)

[litep2p](https://github.com/altonen/litep2p) is a libp2p-compatible P2P
networking library. It supports all of the features of `rust-libp2p`
that are currently being utilized by Polkadot SDK.

Compared to `rust-libp2p`, `litep2p` has a quite different architecture
which is why the new `litep2p` network backend is only able to use a
little of the existing code in `sc-network`. The design has been mainly
influenced by how we'd wish to structure our networking-related code in
Polkadot SDK: independent higher-levels protocols directly communicating
with the network over links that support bidirectional backpressure. A
good example would be `NotificationHandle`/`RequestResponseHandle`
abstractions which allow, e.g., `SyncingEngine` to directly communicate
with peers to announce/request blocks.

I've tried running `polkadot --network-backend litep2p` with a few
different peer configurations and there is a noticeable reduction in
networking CPU usage. For high load (`--out-peers 200`), networking CPU
usage goes down from ~110% to ~30% (80 pp) and for normal load
(`--out-peers 40`), the usage goes down from ~55% to ~18% (37 pp).

These should not be taken as final numbers because:

a) there are still some low-hanging optimization fruits, such as
enabling [receive window
auto-tuning](https://github.com/libp2p/rust-yamux/pull/176), integrating
`Peerset` more closely with `litep2p` or improving memory usage of the
WebSocket transport
b) fixing bugs/instabilities that incorrectly cause `litep2p` to do less
work will increase the networking CPU usage
c) verification in a more diverse set of tests/conditions is needed

Nevertheless, these numbers should give an early estimate for CPU usage
of the new networking backend.

This PR consists of three separate changes:
* introduce a generic `PeerId` (wrapper around `Multihash`) so that we
don't have use `NetworkService::PeerId` in every part of the code that
uses a `PeerId`
* introduce `NetworkBackend` trait, implement it for the libp2p network
stack and make Polkadot SDK generic over `NetworkBackend`
  * implement `NetworkBackend` for litep2p

The new library should be considered experimental which is why
`rust-libp2p` will remain as the default option for the time being. This
PR currently depends on the master branch of `litep2p` but I'll cut a
new release for the library once all review comments have been
addresses.

---------

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
Co-authored-by: Dmitry Markin <dmitry@markin.tech>
Co-authored-by: Alexandru Vasile <60601340+lexnv@users.noreply.github.com>
Co-authored-by: Alexandru Vasile <alexandru.vasile@parity.io>
This commit is contained in:
authored and GitHub committed 2024-04-08 16:44:13 +00:00
1 parent 9543d31474
commit 80616f6d03
181 files changed
+11055 -1862

No files matched your search

@@ -0,0 +1,104 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Shim for litep2p's Bitswap implementation to make it work with `sc-network`.
use futures::StreamExt;
use litep2p::protocol::libp2p::bitswap::{
BitswapEvent, BitswapHandle, BlockPresenceType, Config, ResponseType, WantType,
};
use sc_client_api::BlockBackend;
use sp_runtime::traits::Block as BlockT;
use std::{future::Future, pin::Pin, sync::Arc};
/// Logging target for the file.
const LOG_TARGET: &str = "sub-libp2p::bitswap";
pub struct BitswapServer<Block: BlockT> {
/// Bitswap handle.
handle: BitswapHandle,
/// Blockchain client.
client: Arc<dyn BlockBackend<Block> + Send + Sync>,
}
impl<Block: BlockT> BitswapServer<Block> {
/// Create new [`BitswapServer`].
pub fn new(
client: Arc<dyn BlockBackend<Block> + Send + Sync>,
) -> (Pin<Box<dyn Future<Output = ()> + Send>>, Config) {
let (config, handle) = Config::new();
let bitswap = Self { client, handle };
(Box::pin(async move { bitswap.run().await }), config)
}
async fn run(mut self) {
log::debug!(target: LOG_TARGET, "starting bitswap server");
while let Some(event) = self.handle.next().await {
match event {
BitswapEvent::Request { peer, cids } => {
log::debug!(target: LOG_TARGET, "handle bitswap request from {peer:?} for {cids:?}");
let response: Vec<ResponseType> = cids
.into_iter()
.map(|(cid, want_type)| {
let mut hash = Block::Hash::default();
hash.as_mut().copy_from_slice(&cid.hash().digest()[0..32]);
let transaction = match self.client.indexed_transaction(hash) {
Ok(ex) => ex,
Err(error) => {
log::error!(target: LOG_TARGET, "error retrieving transaction {hash}: {error}");
None
},
};
match transaction {
Some(transaction) => {
log::trace!(target: LOG_TARGET, "found cid {cid:?}, hash {hash:?}");
match want_type {
WantType::Block =>
ResponseType::Block { cid, block: transaction },
_ => ResponseType::Presence {
cid,
presence: BlockPresenceType::Have,
},
}
},
None => {
log::trace!(target: LOG_TARGET, "missing cid {cid:?}, hash {hash:?}");
ResponseType::Presence {
cid,
presence: BlockPresenceType::DontHave,
}
},
}
})
.collect();
self.handle.send_response(peer, response).await;
},
}
}
}
}
@@ -0,0 +1,23 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Shims for fitting `litep2p` APIs to `sc-network` APIs.
pub(crate) mod bitswap;
pub(crate) mod notification;
pub(crate) mod request_response;
@@ -0,0 +1,168 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! `litep2p` notification protocol configuration.
use crate::{
config::{MultiaddrWithPeerId, NonReservedPeerMode, NotificationHandshake, SetConfig},
litep2p::shim::notification::{
peerset::{Peerset, PeersetCommand},
NotificationProtocol,
},
peer_store::PeerStoreProvider,
service::{metrics::NotificationMetrics, traits::NotificationConfig},
NotificationService, ProtocolName,
};
use litep2p::protocol::notification::{Config, ConfigBuilder};
use sc_utils::mpsc::TracingUnboundedSender;
use std::sync::{atomic::AtomicUsize, Arc};
/// Handle for controlling the notification protocol.
#[derive(Debug, Clone)]
pub struct ProtocolControlHandle {
/// TX channel for sending commands to `Peerset` of the notification protocol.
pub tx: TracingUnboundedSender<PeersetCommand>,
/// Peers currently connected to this protocol.
pub connected_peers: Arc<AtomicUsize>,
}
impl ProtocolControlHandle {
/// Create new [`ProtocolControlHandle`].
pub fn new(
tx: TracingUnboundedSender<PeersetCommand>,
connected_peers: Arc<AtomicUsize>,
) -> Self {
Self { tx, connected_peers }
}
}
/// Configuration for the notification protocol.
#[derive(Debug)]
pub struct NotificationProtocolConfig {
/// Name of the notifications protocols of this set. A substream on this set will be
/// considered established once this protocol is open.
pub protocol_name: ProtocolName,
/// Maximum allowed size of single notifications.
max_notification_size: usize,
/// Base configuration.
set_config: SetConfig,
/// `litep2p` notification config.
pub config: Config,
/// Handle for controlling the notification protocol.
pub handle: ProtocolControlHandle,
}
impl NotificationProtocolConfig {
// Create new [`NotificationProtocolConfig`].
pub fn new(
protocol_name: ProtocolName,
fallback_names: Vec<ProtocolName>,
max_notification_size: usize,
handshake: Option<NotificationHandshake>,
set_config: SetConfig,
metrics: NotificationMetrics,
peerstore_handle: Arc<dyn PeerStoreProvider>,
) -> (Self, Box<dyn NotificationService>) {
// create `Peerset`/`Peerstore` handle for the protocol
let connected_peers = Arc::new(Default::default());
let (peerset, peerset_tx) = Peerset::new(
protocol_name.clone(),
set_config.out_peers as usize,
set_config.in_peers as usize,
set_config.non_reserved_mode == NonReservedPeerMode::Deny,
set_config.reserved_nodes.iter().map(|address| address.peer_id).collect(),
Arc::clone(&connected_peers),
peerstore_handle,
);
// create `litep2p` notification protocol configuration for the protocol
//
// NOTE: currently only dummy value is given as the handshake as protocols (apart from
// syncing) are not configuring their own handshake and instead default to role being the
// handshake. As the time of writing this, most protocols are not aware of the role and
// that should be refactored in the future.
let (config, handle) = ConfigBuilder::new(protocol_name.clone().into())
.with_handshake(handshake.map_or(vec![1], |handshake| (*handshake).to_vec()))
.with_max_size(max_notification_size as usize)
.with_auto_accept_inbound(true)
.with_fallback_names(fallback_names.into_iter().map(From::from).collect())
.build();
// initialize the actual object implementing `NotificationService` and combine the
// `litep2p::NotificationHandle` with `Peerset` to implement a full and independent
// notification protocol runner
let protocol = NotificationProtocol::new(protocol_name.clone(), handle, peerset, metrics);
(
Self {
protocol_name,
max_notification_size,
set_config,
config,
handle: ProtocolControlHandle::new(peerset_tx, connected_peers),
},
Box::new(protocol),
)
}
/// Get reference to protocol name.
pub fn protocol_name(&self) -> &ProtocolName {
&self.protocol_name
}
/// Get reference to `SetConfig`.
pub fn set_config(&self) -> &SetConfig {
&self.set_config
}
/// Modifies the configuration to allow non-reserved nodes.
pub fn allow_non_reserved(&mut self, in_peers: u32, out_peers: u32) {
self.set_config.in_peers = in_peers;
self.set_config.out_peers = out_peers;
self.set_config.non_reserved_mode = NonReservedPeerMode::Accept;
}
/// Add a node to the list of reserved nodes.
pub fn add_reserved(&mut self, peer: MultiaddrWithPeerId) {
self.set_config.reserved_nodes.push(peer);
}
/// Get maximum notification size.
pub fn max_notification_size(&self) -> usize {
self.max_notification_size
}
}
impl NotificationConfig for NotificationProtocolConfig {
fn set_config(&self) -> &SetConfig {
&self.set_config
}
/// Get reference to protocol name.
fn protocol_name(&self) -> &ProtocolName {
&self.protocol_name
}
}
@@ -0,0 +1,374 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Shim for `litep2p::NotificationHandle` to combine `Peerset`-like behavior
//! with `NotificationService`.
use crate::{
error::Error,
litep2p::shim::notification::peerset::{OpenResult, Peerset, PeersetNotificationCommand},
service::{
metrics::NotificationMetrics,
traits::{NotificationEvent as SubstrateNotificationEvent, ValidationResult},
},
MessageSink, NotificationService, ProtocolName,
};
use futures::{future::BoxFuture, stream::FuturesUnordered, StreamExt};
use litep2p::protocol::notification::{
NotificationEvent, NotificationHandle, NotificationSink,
ValidationResult as Litep2pValidationResult,
};
use tokio::sync::oneshot;
use sc_network_types::PeerId;
use std::{collections::HashSet, fmt};
pub mod config;
pub mod peerset;
#[cfg(test)]
mod tests;
/// Logging target for the file.
const LOG_TARGET: &str = "sub-libp2p::notification";
/// Wrapper over `litep2p`'s notification sink.
pub struct Litep2pMessageSink {
/// Protocol.
protocol: ProtocolName,
/// Remote peer ID.
peer: PeerId,
/// Notification sink.
sink: NotificationSink,
/// Notification metrics.
metrics: NotificationMetrics,
}
impl Litep2pMessageSink {
/// Create new [`Litep2pMessageSink`].
fn new(
peer: PeerId,
protocol: ProtocolName,
sink: NotificationSink,
metrics: NotificationMetrics,
) -> Self {
Self { protocol, peer, sink, metrics }
}
}
#[async_trait::async_trait]
impl MessageSink for Litep2pMessageSink {
/// Send synchronous `notification` to the peer associated with this [`MessageSink`].
fn send_sync_notification(&self, notification: Vec<u8>) {
let size = notification.len();
match self.sink.send_sync_notification(notification) {
Ok(_) => self.metrics.register_notification_sent(&self.protocol, size),
Err(error) => log::trace!(
target: LOG_TARGET,
"{}: failed to send sync notification to {:?}: {error:?}",
self.protocol,
self.peer,
),
}
}
/// Send an asynchronous `notification` to to the peer associated with this [`MessageSink`],
/// allowing sender to exercise backpressure.
///
/// Returns an error if the peer does not exist.
async fn send_async_notification(&self, notification: Vec<u8>) -> Result<(), Error> {
let size = notification.len();
match self.sink.send_async_notification(notification).await {
Ok(_) => {
self.metrics.register_notification_sent(&self.protocol, size);
Ok(())
},
Err(error) => {
log::trace!(
target: LOG_TARGET,
"{}: failed to send async notification to {:?}: {error:?}",
self.protocol,
self.peer,
);
Err(Error::Litep2p(error))
},
}
}
}
/// Notification protocol implementation.
pub struct NotificationProtocol {
/// Protocol name.
protocol: ProtocolName,
/// `litep2p` notification handle.
handle: NotificationHandle,
/// Peerset for the notification protocol.
///
/// Listens to peering-related events and either opens or closes substreams to remote peers.
peerset: Peerset,
/// Pending validations for inbound substreams.
pending_validations: FuturesUnordered<
BoxFuture<'static, (PeerId, Result<ValidationResult, oneshot::error::RecvError>)>,
>,
/// Pending cancels.
pending_cancels: HashSet<litep2p::PeerId>,
/// Notification metrics.
metrics: NotificationMetrics,
}
impl fmt::Debug for NotificationProtocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NotificationProtocol")
.field("protocol", &self.protocol)
.field("handle", &self.handle)
.finish()
}
}
impl NotificationProtocol {
/// Create new [`NotificationProtocol`].
pub fn new(
protocol: ProtocolName,
handle: NotificationHandle,
peerset: Peerset,
metrics: NotificationMetrics,
) -> Self {
Self {
protocol,
handle,
peerset,
metrics,
pending_cancels: HashSet::new(),
pending_validations: FuturesUnordered::new(),
}
}
/// Handle `Peerset` command.
async fn on_peerset_command(&mut self, command: PeersetNotificationCommand) {
match command {
PeersetNotificationCommand::OpenSubstream { peers } => {
log::debug!(target: LOG_TARGET, "{}: open substreams to {peers:?}", self.protocol);
let _ = self.handle.open_substream_batch(peers.into_iter().map(From::from)).await;
},
PeersetNotificationCommand::CloseSubstream { peers } => {
log::debug!(target: LOG_TARGET, "{}: close substreams to {peers:?}", self.protocol);
self.handle.close_substream_batch(peers.into_iter().map(From::from)).await;
},
}
}
}
#[async_trait::async_trait]
impl NotificationService for NotificationProtocol {
async fn open_substream(&mut self, _peer: PeerId) -> Result<(), ()> {
unimplemented!();
}
async fn close_substream(&mut self, _peer: PeerId) -> Result<(), ()> {
unimplemented!();
}
fn send_sync_notification(&mut self, peer: &PeerId, notification: Vec<u8>) {
let size = notification.len();
if let Ok(_) = self.handle.send_sync_notification(peer.into(), notification) {
self.metrics.register_notification_sent(&self.protocol, size);
}
}
async fn send_async_notification(
&mut self,
peer: &PeerId,
notification: Vec<u8>,
) -> Result<(), Error> {
let size = notification.len();
match self.handle.send_async_notification(peer.into(), notification).await {
Ok(_) => {
self.metrics.register_notification_sent(&self.protocol, size);
Ok(())
},
Err(_) => Err(Error::ChannelClosed),
}
}
/// Set handshake for the notification protocol replacing the old handshake.
async fn set_handshake(&mut self, handshake: Vec<u8>) -> Result<(), ()> {
self.handle.set_handshake(handshake);
Ok(())
}
/// Set handshake for the notification protocol replacing the old handshake.
///
/// For `litep2p` this is identical to `NotificationService::set_handshake()` since `litep2p`
/// allows updating the handshake synchronously.
fn try_set_handshake(&mut self, handshake: Vec<u8>) -> Result<(), ()> {
self.handle.set_handshake(handshake);
Ok(())
}
/// Make a copy of the object so it can be shared between protocol components
/// who wish to have access to the same underlying notification protocol.
fn clone(&mut self) -> Result<Box<dyn NotificationService>, ()> {
unimplemented!("clonable `NotificationService` not supported by `litep2p`");
}
/// Get protocol name of the `NotificationService`.
fn protocol(&self) -> &ProtocolName {
&self.protocol
}
/// Get message sink of the peer.
fn message_sink(&self, peer: &PeerId) -> Option<Box<dyn MessageSink>> {
self.handle.notification_sink(peer.into()).map(|sink| {
let sink: Box<dyn MessageSink> = Box::new(Litep2pMessageSink::new(
*peer,
self.protocol.clone(),
sink,
self.metrics.clone(),
));
sink
})
}
/// Get next event from the `Notifications` event stream.
async fn next_event(&mut self) -> Option<SubstrateNotificationEvent> {
loop {
tokio::select! {
biased;
event = self.handle.next() => match event? {
NotificationEvent::ValidateSubstream { peer, handshake, .. } => {
if let ValidationResult::Reject = self.peerset.report_inbound_substream(peer.into()) {
self.handle.send_validation_result(peer, Litep2pValidationResult::Reject);
continue;
}
let (tx, rx) = oneshot::channel();
self.pending_validations.push(Box::pin(async move { (peer.into(), rx.await) }));
log::trace!(target: LOG_TARGET, "{}: validate substream for {peer:?}", self.protocol);
return Some(SubstrateNotificationEvent::ValidateInboundSubstream {
peer: peer.into(),
handshake,
result_tx: tx,
});
}
NotificationEvent::NotificationStreamOpened {
peer,
fallback,
handshake,
direction,
..
} => {
self.metrics.register_substream_opened(&self.protocol);
match self.peerset.report_substream_opened(peer.into(), direction.into()) {
OpenResult::Reject => {
let _ = self.handle.close_substream_batch(vec![peer].into_iter().map(From::from)).await;
self.pending_cancels.insert(peer);
continue
}
OpenResult::Accept { direction } => {
log::trace!(target: LOG_TARGET, "{}: substream opened for {peer:?}", self.protocol);
return Some(SubstrateNotificationEvent::NotificationStreamOpened {
peer: peer.into(),
handshake,
direction,
negotiated_fallback: fallback.map(From::from),
});
}
}
}
NotificationEvent::NotificationStreamClosed {
peer,
} => {
log::trace!(target: LOG_TARGET, "{}: substream closed for {peer:?}", self.protocol);
self.metrics.register_substream_closed(&self.protocol);
self.peerset.report_substream_closed(peer.into());
if self.pending_cancels.remove(&peer) {
log::debug!(
target: LOG_TARGET,
"{}: substream closed to canceled peer ({peer:?})",
self.protocol
);
continue
}
return Some(SubstrateNotificationEvent::NotificationStreamClosed { peer: peer.into() })
}
NotificationEvent::NotificationStreamOpenFailure {
peer,
error,
} => {
log::trace!(target: LOG_TARGET, "{}: open failure for {peer:?}", self.protocol);
self.peerset.report_substream_open_failure(peer.into(), error);
}
NotificationEvent::NotificationReceived {
peer,
notification,
} => {
self.metrics.register_notification_received(&self.protocol, notification.len());
if !self.pending_cancels.contains(&peer) {
return Some(SubstrateNotificationEvent::NotificationReceived {
peer: peer.into(),
notification: notification.to_vec(),
});
}
}
},
result = self.pending_validations.next(), if !self.pending_validations.is_empty() => {
let (peer, result) = result?;
let validation_result = match result {
Ok(ValidationResult::Accept) => Litep2pValidationResult::Accept,
_ => {
self.peerset.report_substream_rejected(peer);
Litep2pValidationResult::Reject
}
};
self.handle.send_validation_result(peer.into(), validation_result);
}
command = self.peerset.next() => self.on_peerset_command(command?).await,
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,384 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Fuzz test emulates network events and peer connection handling by `Peerset`
//! and `PeerStore` to discover possible inconsistencies in peer management.
use crate::{
litep2p::{
peerstore::Peerstore,
shim::notification::peerset::{
OpenResult, Peerset, PeersetCommand, PeersetNotificationCommand,
},
},
service::traits::{Direction, PeerStore, ValidationResult},
ProtocolName,
};
use futures::{FutureExt, StreamExt};
use litep2p::protocol::notification::NotificationError;
use rand::{
distributions::{Distribution, Uniform, WeightedIndex},
seq::IteratorRandom,
};
use sc_network_common::types::ReputationChange;
use sc_network_types::PeerId;
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
#[tokio::test]
#[cfg(debug_assertions)]
async fn run() {
sp_tracing::try_init_simple();
for _ in 0..50 {
test_once().await;
}
}
#[cfg(debug_assertions)]
async fn test_once() {
// PRNG to use.
let mut rng = rand::thread_rng();
// peers that the peerset knows about.
let mut known_peers = HashSet::<PeerId>::new();
// peers that we have reserved. Always a subset of `known_peers`.
let mut reserved_peers = HashSet::<PeerId>::new();
// reserved only mode
let mut reserved_only = Uniform::new_inclusive(0, 10).sample(&mut rng) == 0;
// Bootnodes for `PeerStore` initialization.
let bootnodes = (0..Uniform::new_inclusive(0, 4).sample(&mut rng))
.map(|_| {
let id = PeerId::random();
known_peers.insert(id);
id
})
.collect();
let peerstore = Peerstore::new(bootnodes);
let peer_store_handle = peerstore.handle();
let (mut peerset, to_peerset) = Peerset::new(
ProtocolName::from("/notif/1"),
Uniform::new_inclusive(0, 25).sample(&mut rng),
Uniform::new_inclusive(0, 25).sample(&mut rng),
reserved_only,
(0..Uniform::new_inclusive(0, 2).sample(&mut rng))
.map(|_| {
let id = PeerId::random();
known_peers.insert(id);
reserved_peers.insert(id);
id
})
.collect(),
Default::default(),
Arc::clone(&peer_store_handle),
);
tokio::spawn(peerstore.run());
// opening substreams
let mut opening = HashMap::<PeerId, Direction>::new();
// open substreams
let mut open = HashMap::<PeerId, Direction>::new();
// closing substreams
let mut closing = HashSet::<PeerId>::new();
// closed substreams
let mut closed = HashSet::<PeerId>::new();
// perform a certain number of actions while checking that the state is consistent.
//
// if we reach the end of the loop, the run has succeeded
let _ = tokio::task::spawn_blocking(move || {
// PRNG to use in `spawn_blocking` context.
let mut rng = rand::thread_rng();
for _ in 0..2500 {
// each of these weights corresponds to an action that we may perform
let action_weights =
[300, 110, 110, 110, 110, 90, 70, 30, 110, 110, 110, 110, 20, 110, 50, 110];
match WeightedIndex::new(&action_weights).unwrap().sample(&mut rng) {
0 => match peerset.next().now_or_never() {
// open substreams to `peers`
Some(Some(PeersetNotificationCommand::OpenSubstream { peers })) =>
for peer in peers {
opening.insert(peer, Direction::Outbound);
closed.remove(&peer);
assert!(!closing.contains(&peer));
assert!(!open.contains_key(&peer));
},
// close substreams to `peers`
Some(Some(PeersetNotificationCommand::CloseSubstream { peers })) =>
for peer in peers {
assert!(closing.insert(peer));
assert!(open.remove(&peer).is_some());
assert!(!opening.contains_key(&peer));
},
Some(None) => panic!("peerset exited"),
None => {},
},
// get inbound connection from an unknown peer
1 => {
let new_peer = PeerId::random();
peer_store_handle.add_known_peer(new_peer);
match peerset.report_inbound_substream(new_peer) {
ValidationResult::Accept => {
opening.insert(new_peer, Direction::Inbound);
},
ValidationResult::Reject => {},
}
},
// substream opened successfully
//
// remove peer from `opening` (which contains its direction), report the open
// substream to `Peerset` and move peer state to `open`.
//
// if the substream was canceled while it was opening, move peer to `closing`
2 =>
if let Some(peer) = opening.keys().choose(&mut rng).copied() {
let direction = opening.remove(&peer).unwrap();
match peerset.report_substream_opened(peer, direction) {
OpenResult::Accept { .. } => {
assert!(open.insert(peer, direction).is_none());
},
OpenResult::Reject => {
assert!(closing.insert(peer));
},
}
},
// substream failed to open
3 =>
if let Some(peer) = opening.keys().choose(&mut rng).copied() {
let _ = opening.remove(&peer).unwrap();
peerset.report_substream_open_failure(peer, NotificationError::Rejected);
},
// substream was closed by remote peer
4 =>
if let Some(peer) = open.keys().choose(&mut rng).copied() {
let _ = open.remove(&peer).unwrap();
peerset.report_substream_closed(peer);
assert!(closed.insert(peer));
},
// substream was closed by local node
5 =>
if let Some(peer) = closing.iter().choose(&mut rng).copied() {
assert!(closing.remove(&peer));
assert!(closed.insert(peer));
peerset.report_substream_closed(peer);
},
// random connected peer was disconnected by the protocol
6 =>
if let Some(peer) = open.keys().choose(&mut rng).copied() {
to_peerset.unbounded_send(PeersetCommand::DisconnectPeer { peer }).unwrap();
},
// ban random peer
7 =>
if let Some(peer) = known_peers.iter().choose(&mut rng).copied() {
peer_store_handle.report_peer(peer, ReputationChange::new_fatal(""));
},
// inbound substream is received for a peer that was considered
// outbound
8 => {
let outbound_peers = opening
.iter()
.filter_map(|(peer, direction)| {
std::matches!(direction, Direction::Outbound).then_some(*peer)
})
.collect::<HashSet<_>>();
if let Some(peer) = outbound_peers.iter().choose(&mut rng).copied() {
match peerset.report_inbound_substream(peer) {
ValidationResult::Accept => {
opening.insert(peer, Direction::Inbound);
},
ValidationResult::Reject => {},
}
}
},
// set reserved peers
//
// choose peers from all available sets (open, opening, closing, closed) + some new
// peers
9 => {
let num_open = Uniform::new_inclusive(0, open.len()).sample(&mut rng);
let num_opening = Uniform::new_inclusive(0, opening.len()).sample(&mut rng);
let num_closing = Uniform::new_inclusive(0, closing.len()).sample(&mut rng);
let num_closed = Uniform::new_inclusive(0, closed.len()).sample(&mut rng);
let peers = open
.keys()
.copied()
.choose_multiple(&mut rng, num_open)
.into_iter()
.chain(
opening
.keys()
.copied()
.choose_multiple(&mut rng, num_opening)
.into_iter(),
)
.chain(
closing
.iter()
.copied()
.choose_multiple(&mut rng, num_closing)
.into_iter(),
)
.chain(
closed
.iter()
.copied()
.choose_multiple(&mut rng, num_closed)
.into_iter(),
)
.chain((0..5).map(|_| {
let peer = PeerId::random();
known_peers.insert(peer);
peer_store_handle.add_known_peer(peer);
peer
}))
.filter(|peer| !reserved_peers.contains(peer))
.collect::<HashSet<_>>();
reserved_peers.extend(peers.clone().into_iter());
to_peerset.unbounded_send(PeersetCommand::SetReservedPeers { peers }).unwrap();
},
// add reserved peers
10 => {
let num_open = Uniform::new_inclusive(0, open.len()).sample(&mut rng);
let num_opening = Uniform::new_inclusive(0, opening.len()).sample(&mut rng);
let num_closing = Uniform::new_inclusive(0, closing.len()).sample(&mut rng);
let num_closed = Uniform::new_inclusive(0, closed.len()).sample(&mut rng);
let peers = open
.keys()
.copied()
.choose_multiple(&mut rng, num_open)
.into_iter()
.chain(
opening
.keys()
.copied()
.choose_multiple(&mut rng, num_opening)
.into_iter(),
)
.chain(
closing
.iter()
.copied()
.choose_multiple(&mut rng, num_closing)
.into_iter(),
)
.chain(
closed
.iter()
.copied()
.choose_multiple(&mut rng, num_closed)
.into_iter(),
)
.chain((0..5).map(|_| {
let peer = PeerId::random();
known_peers.insert(peer);
peer_store_handle.add_known_peer(peer);
peer
}))
.filter(|peer| !reserved_peers.contains(peer))
.collect::<HashSet<_>>();
reserved_peers.extend(peers.clone().into_iter());
to_peerset.unbounded_send(PeersetCommand::AddReservedPeers { peers }).unwrap();
},
// remove reserved peers
11 => {
let num_to_remove =
Uniform::new_inclusive(0, reserved_peers.len()).sample(&mut rng);
let peers = reserved_peers
.iter()
.copied()
.choose_multiple(&mut rng, num_to_remove)
.into_iter()
.collect::<HashSet<_>>();
peers.iter().for_each(|peer| {
assert!(reserved_peers.remove(peer));
});
to_peerset
.unbounded_send(PeersetCommand::RemoveReservedPeers { peers })
.unwrap();
},
// set reserved only
12 => {
reserved_only = !reserved_only;
let _ = to_peerset
.unbounded_send(PeersetCommand::SetReservedOnly { reserved_only });
},
//
// discover a new node.
13 => {
let new_peer = PeerId::random();
known_peers.insert(new_peer);
peer_store_handle.add_known_peer(new_peer);
},
// protocol rejected a substream that was accepted by `Peerset`
14 => {
let inbound_peers = opening
.iter()
.filter_map(|(peer, direction)| {
std::matches!(direction, Direction::Inbound).then_some(*peer)
})
.collect::<HashSet<_>>();
if let Some(peer) = inbound_peers.iter().choose(&mut rng).copied() {
peerset.report_substream_rejected(peer);
opening.remove(&peer);
}
},
// inbound substream received for a peer in `closed`
15 =>
if let Some(peer) = closed.iter().choose(&mut rng).copied() {
match peerset.report_inbound_substream(peer) {
ValidationResult::Accept => {
assert!(closed.remove(&peer));
opening.insert(peer, Direction::Inbound);
},
ValidationResult::Reject => {},
}
},
_ => unreachable!(),
}
}
})
.await
.unwrap();
}
@@ -0,0 +1,22 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#[cfg(test)]
mod fuzz;
#[cfg(test)]
mod peerset;
@@ -0,0 +1,891 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{
litep2p::{
peerstore::peerstore_handle_test,
shim::notification::peerset::{
Direction, OpenResult, PeerState, Peerset, PeersetCommand, PeersetNotificationCommand,
Reserved,
},
},
service::traits::{self, ValidationResult},
ProtocolName,
};
use futures::prelude::*;
use litep2p::protocol::notification::NotificationError;
use sc_network_types::PeerId;
use std::{
collections::HashSet,
sync::{atomic::Ordering, Arc},
task::Poll,
};
// outbound substream was initiated for a peer but an inbound substream from that same peer
// was receied while the `Peerset` was waiting for the outbound substream to be opened
//
// verify that the peer state is updated correctly
#[tokio::test]
async fn inbound_substream_for_outbound_peer() {
let peerstore_handle = Arc::new(peerstore_handle_test());
let peers = (0..3)
.map(|_| {
let peer = PeerId::random();
peerstore_handle.add_known_peer(peer);
peer
})
.collect::<Vec<_>>();
let inbound_peer = *peers.iter().next().unwrap();
let (mut peerset, _to_peerset) = Peerset::new(
ProtocolName::from("/notif/1"),
25,
25,
false,
Default::default(),
Default::default(),
peerstore_handle,
);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert_eq!(out_peers.len(), 3usize);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 3usize);
assert_eq!(
peerset.peers().get(&inbound_peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::No) })
);
},
event => panic!("invalid event: {event:?}"),
}
// inbound substream was received from peer who was marked outbound
//
// verify that the peer state and inbound/outbound counts are updated correctly
assert_eq!(peerset.report_inbound_substream(inbound_peer), ValidationResult::Accept);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 3usize);
assert_eq!(
peerset.peers().get(&inbound_peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::No) })
);
}
// substream was opening to peer but then it was canceled and before the substream
// was fully closed, the peer got banned
#[tokio::test]
async fn canceled_peer_gets_banned() {
sp_tracing::try_init_simple();
let peerstore_handle = Arc::new(peerstore_handle_test());
let peers = HashSet::from_iter([PeerId::random(), PeerId::random(), PeerId::random()]);
let (mut peerset, to_peerset) = Peerset::new(
ProtocolName::from("/notif/1"),
0,
0,
true,
peers.clone(),
Default::default(),
peerstore_handle,
);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
for outbound_peer in &out_peers {
assert!(peers.contains(outbound_peer));
assert_eq!(
peerset.peers().get(&outbound_peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) })
);
}
},
event => panic!("invalid event: {event:?}"),
}
// remove all reserved peers
to_peerset
.unbounded_send(PeersetCommand::RemoveReservedPeers { peers: peers.clone() })
.unwrap();
match peerset.next().await {
Some(PeersetNotificationCommand::CloseSubstream { peers: out_peers }) => {
assert!(out_peers.is_empty());
},
event => panic!("invalid event: {event:?}"),
}
// verify all reserved peers are canceled
for (_, state) in peerset.peers() {
assert_eq!(state, &PeerState::Canceled { direction: Direction::Outbound(Reserved::Yes) });
}
}
#[tokio::test]
async fn peer_added_and_removed_from_peerset() {
sp_tracing::try_init_simple();
let peerstore_handle = Arc::new(peerstore_handle_test());
let (mut peerset, to_peerset) = Peerset::new(
ProtocolName::from("/notif/1"),
0,
0,
true,
Default::default(),
Default::default(),
peerstore_handle,
);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
// add peers to reserved set
let peers = HashSet::from_iter([PeerId::random(), PeerId::random(), PeerId::random()]);
to_peerset
.unbounded_send(PeersetCommand::AddReservedPeers { peers: peers.clone() })
.unwrap();
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
for outbound_peer in &out_peers {
assert!(peers.contains(outbound_peer));
assert!(peerset.reserved_peers().contains(outbound_peer));
assert_eq!(
peerset.peers().get(&outbound_peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) })
);
}
},
event => panic!("invalid event: {event:?}"),
}
// report that all substreams were opened
for peer in &peers {
assert!(std::matches!(
peerset.report_substream_opened(*peer, traits::Direction::Outbound),
OpenResult::Accept { .. }
));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Connected { direction: Direction::Outbound(Reserved::Yes) })
);
}
// remove all reserved peers
to_peerset
.unbounded_send(PeersetCommand::RemoveReservedPeers { peers: peers.clone() })
.unwrap();
match peerset.next().await {
Some(PeersetNotificationCommand::CloseSubstream { peers: out_peers }) => {
assert!(!out_peers.is_empty());
for peer in &out_peers {
assert!(peers.contains(peer));
assert!(!peerset.reserved_peers().contains(peer));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Closing { direction: Direction::Outbound(Reserved::Yes) }),
);
}
},
event => panic!("invalid event: {event:?}"),
}
// add the peers again and verify that the command is ignored because the substreams are closing
to_peerset
.unbounded_send(PeersetCommand::AddReservedPeers { peers: peers.clone() })
.unwrap();
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert!(out_peers.is_empty());
for peer in &peers {
assert!(peerset.reserved_peers().contains(peer));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Closing { direction: Direction::Outbound(Reserved::Yes) }),
);
}
},
event => panic!("invalid event: {event:?}"),
}
// remove the peers again and verify the state remains as `Closing`
to_peerset
.unbounded_send(PeersetCommand::RemoveReservedPeers { peers: peers.clone() })
.unwrap();
match peerset.next().await {
Some(PeersetNotificationCommand::CloseSubstream { peers: out_peers }) => {
assert!(out_peers.is_empty());
for peer in &peers {
assert!(!peerset.reserved_peers().contains(peer));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Closing { direction: Direction::Outbound(Reserved::Yes) }),
);
}
},
event => panic!("invalid event: {event:?}"),
}
}
#[tokio::test]
async fn set_reserved_peers() {
sp_tracing::try_init_simple();
let reserved = HashSet::from_iter([PeerId::random(), PeerId::random(), PeerId::random()]);
let (mut peerset, to_peerset) = Peerset::new(
ProtocolName::from("/notif/1"),
25,
25,
true,
reserved.clone(),
Default::default(),
Arc::new(peerstore_handle_test()),
);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
for outbound_peer in &out_peers {
assert!(reserved.contains(outbound_peer));
assert!(peerset.reserved_peers().contains(outbound_peer));
assert_eq!(
peerset.peers().get(&outbound_peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) })
);
}
},
event => panic!("invalid event: {event:?}"),
}
// report that all substreams were opened
for peer in &reserved {
assert!(std::matches!(
peerset.report_substream_opened(*peer, traits::Direction::Outbound),
OpenResult::Accept { .. }
));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Connected { direction: Direction::Outbound(Reserved::Yes) })
);
}
// add a totally new set of reserved peers
let new_reserved_peers =
HashSet::from_iter([PeerId::random(), PeerId::random(), PeerId::random()]);
to_peerset
.unbounded_send(PeersetCommand::SetReservedPeers { peers: new_reserved_peers.clone() })
.unwrap();
match peerset.next().await {
Some(PeersetNotificationCommand::CloseSubstream { peers: out_peers }) => {
assert!(!out_peers.is_empty());
assert_eq!(out_peers.len(), 3);
for peer in &out_peers {
assert!(reserved.contains(peer));
assert!(!peerset.reserved_peers().contains(peer));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Closing { direction: Direction::Outbound(Reserved::Yes) }),
);
}
for peer in &new_reserved_peers {
assert!(peerset.reserved_peers().contains(peer));
}
},
event => panic!("invalid event: {event:?}"),
}
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert!(!out_peers.is_empty());
assert_eq!(out_peers.len(), 3);
for peer in &new_reserved_peers {
assert!(peerset.reserved_peers().contains(peer));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) }),
);
}
},
event => panic!("invalid event: {event:?}"),
}
}
#[tokio::test]
async fn set_reserved_peers_one_peer_already_in_the_set() {
sp_tracing::try_init_simple();
let reserved = HashSet::from_iter([PeerId::random(), PeerId::random(), PeerId::random()]);
let common_peer = *reserved.iter().next().unwrap();
let (mut peerset, to_peerset) = Peerset::new(
ProtocolName::from("/notif/1"),
25,
25,
true,
reserved.clone(),
Default::default(),
Arc::new(peerstore_handle_test()),
);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
for outbound_peer in &out_peers {
assert!(reserved.contains(outbound_peer));
assert!(peerset.reserved_peers().contains(outbound_peer));
assert_eq!(
peerset.peers().get(&outbound_peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) })
);
}
},
event => panic!("invalid event: {event:?}"),
}
// report that all substreams were opened
for peer in &reserved {
assert!(std::matches!(
peerset.report_substream_opened(*peer, traits::Direction::Outbound),
OpenResult::Accept { .. }
));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Connected { direction: Direction::Outbound(Reserved::Yes) })
);
}
// add a new set of reserved peers with one peer from the original set
let new_reserved_peers = HashSet::from_iter([PeerId::random(), PeerId::random(), common_peer]);
to_peerset
.unbounded_send(PeersetCommand::SetReservedPeers { peers: new_reserved_peers.clone() })
.unwrap();
match peerset.next().await {
Some(PeersetNotificationCommand::CloseSubstream { peers: out_peers }) => {
assert_eq!(out_peers.len(), 2);
for peer in &out_peers {
assert!(reserved.contains(peer));
if peer != &common_peer {
assert!(!peerset.reserved_peers().contains(peer));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Closing { direction: Direction::Outbound(Reserved::Yes) }),
);
} else {
panic!("common peer disconnected");
}
}
for peer in &new_reserved_peers {
assert!(peerset.reserved_peers().contains(peer));
}
},
event => panic!("invalid event: {event:?}"),
}
// verify the `common_peer` peer between the reserved sets is still in the state `Open`
assert_eq!(
peerset.peers().get(&common_peer),
Some(&PeerState::Connected { direction: Direction::Outbound(Reserved::Yes) })
);
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert!(!out_peers.is_empty());
assert_eq!(out_peers.len(), 2);
for peer in &new_reserved_peers {
assert!(peerset.reserved_peers().contains(peer));
if peer != &common_peer {
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) }),
);
}
}
},
event => panic!("invalid event: {event:?}"),
}
}
#[tokio::test]
async fn add_reserved_peers_one_peer_already_in_the_set() {
sp_tracing::try_init_simple();
let peerstore_handle = Arc::new(peerstore_handle_test());
let reserved = (0..3)
.map(|_| {
let peer = PeerId::random();
peerstore_handle.add_known_peer(peer);
peer
})
.collect::<Vec<_>>();
let common_peer = *reserved.iter().next().unwrap();
let (mut peerset, to_peerset) = Peerset::new(
ProtocolName::from("/notif/1"),
25,
25,
true,
reserved.iter().cloned().collect(),
Default::default(),
peerstore_handle,
);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
assert_eq!(out_peers.len(), 3);
for outbound_peer in &out_peers {
assert!(reserved.contains(outbound_peer));
assert!(peerset.reserved_peers().contains(outbound_peer));
assert_eq!(
peerset.peers().get(&outbound_peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) })
);
}
},
event => panic!("invalid event: {event:?}"),
}
// report that all substreams were opened
for peer in &reserved {
assert!(std::matches!(
peerset.report_substream_opened(*peer, traits::Direction::Outbound),
OpenResult::Accept { .. }
));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Connected { direction: Direction::Outbound(Reserved::Yes) })
);
}
// add a new set of reserved peers with one peer from the original set
let new_reserved_peers = HashSet::from_iter([PeerId::random(), PeerId::random(), common_peer]);
to_peerset
.unbounded_send(PeersetCommand::AddReservedPeers { peers: new_reserved_peers.clone() })
.unwrap();
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert_eq!(out_peers.len(), 2);
assert!(!out_peers.iter().any(|peer| peer == &common_peer));
for peer in &out_peers {
assert!(!reserved.contains(peer));
if peer != &common_peer {
assert!(peerset.reserved_peers().contains(peer));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) }),
);
}
}
},
event => panic!("invalid event: {event:?}"),
}
// verify the `common_peer` peer between the reserved sets is still in the state `Open`
assert_eq!(
peerset.peers().get(&common_peer),
Some(&PeerState::Connected { direction: Direction::Outbound(Reserved::Yes) })
);
}
#[tokio::test]
async fn opening_peer_gets_canceled_and_disconnected() {
sp_tracing::try_init_simple();
let peerstore_handle = Arc::new(peerstore_handle_test());
let _known_peers = (0..1)
.map(|_| {
let peer = PeerId::random();
peerstore_handle.add_known_peer(peer);
peer
})
.collect::<Vec<_>>();
let num_connected = Arc::new(Default::default());
let (mut peerset, to_peerset) = Peerset::new(
ProtocolName::from("/notif/1"),
25,
25,
false,
Default::default(),
Arc::clone(&num_connected),
peerstore_handle,
);
assert_eq!(peerset.num_in(), 0);
assert_eq!(peerset.num_out(), 0);
let peer = match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert_eq!(peerset.num_in(), 0);
assert_eq!(peerset.num_out(), 1);
assert_eq!(out_peers.len(), 1);
for peer in &out_peers {
assert_eq!(
peerset.peers().get(&peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::No) })
);
}
out_peers[0]
},
event => panic!("invalid event: {event:?}"),
};
// disconnect the now-opening peer
to_peerset.unbounded_send(PeersetCommand::DisconnectPeer { peer }).unwrap();
// poll `Peerset` to register the command and verify the peer is now in state `Canceled`
futures::future::poll_fn(|cx| match peerset.poll_next_unpin(cx) {
Poll::Pending => Poll::Ready(()),
_ => panic!("unexpected event"),
})
.await;
assert_eq!(
peerset.peers().get(&peer),
Some(&PeerState::Canceled { direction: Direction::Outbound(Reserved::No) })
);
assert_eq!(peerset.num_out(), 1);
// report to `Peerset` that the substream was opened, verify that it gets closed
assert!(std::matches!(
peerset.report_substream_opened(peer, traits::Direction::Outbound),
OpenResult::Reject { .. }
));
assert_eq!(
peerset.peers().get(&peer),
Some(&PeerState::Closing { direction: Direction::Outbound(Reserved::No) })
);
assert_eq!(num_connected.load(Ordering::SeqCst), 1);
assert_eq!(peerset.num_out(), 1);
// report close event to `Peerset` and verify state
peerset.report_substream_closed(peer);
assert_eq!(peerset.num_out(), 0);
assert_eq!(num_connected.load(Ordering::SeqCst), 0);
assert_eq!(peerset.peers().get(&peer), Some(&PeerState::Backoff));
}
#[tokio::test]
async fn open_failure_for_canceled_peer() {
sp_tracing::try_init_simple();
let peerstore_handle = Arc::new(peerstore_handle_test());
let _known_peers = (0..1)
.map(|_| {
let peer = PeerId::random();
peerstore_handle.add_known_peer(peer);
peer
})
.collect::<Vec<_>>();
let (mut peerset, to_peerset) = Peerset::new(
ProtocolName::from("/notif/1"),
25,
25,
false,
Default::default(),
Default::default(),
peerstore_handle,
);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
let peer = match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 1usize);
assert_eq!(out_peers.len(), 1);
for peer in &out_peers {
assert_eq!(
peerset.peers().get(&peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::No) })
);
}
out_peers[0]
},
event => panic!("invalid event: {event:?}"),
};
// disconnect the now-opening peer
to_peerset.unbounded_send(PeersetCommand::DisconnectPeer { peer }).unwrap();
// poll `Peerset` to register the command and verify the peer is now in state `Canceled`
futures::future::poll_fn(|cx| match peerset.poll_next_unpin(cx) {
Poll::Pending => Poll::Ready(()),
_ => panic!("unexpected event"),
})
.await;
assert_eq!(
peerset.peers().get(&peer),
Some(&PeerState::Canceled { direction: Direction::Outbound(Reserved::No) })
);
// the substream failed to open, verify that peer state is now `Backoff`
// and that `Peerset` doesn't emit any events
peerset.report_substream_open_failure(peer, NotificationError::NoConnection);
assert_eq!(peerset.peers().get(&peer), Some(&PeerState::Backoff));
futures::future::poll_fn(|cx| match peerset.poll_next_unpin(cx) {
Poll::Pending => Poll::Ready(()),
_ => panic!("unexpected event"),
})
.await;
}
#[tokio::test]
async fn peer_disconnected_when_being_validated_then_rejected() {
sp_tracing::try_init_simple();
let peerstore_handle = Arc::new(peerstore_handle_test());
let (mut peerset, _to_peerset) = Peerset::new(
ProtocolName::from("/notif/1"),
25,
25,
false,
Default::default(),
Default::default(),
peerstore_handle,
);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
// inbound substream received
let peer = PeerId::random();
assert_eq!(peerset.report_inbound_substream(peer), ValidationResult::Accept);
// substream failed to open while it was being validated by the protocol
peerset.report_substream_open_failure(peer, NotificationError::NoConnection);
assert_eq!(peerset.peers().get(&peer), Some(&PeerState::Backoff));
// protocol rejected substream, verify
peerset.report_substream_rejected(peer);
assert_eq!(peerset.peers().get(&peer), Some(&PeerState::Backoff));
}
#[tokio::test]
async fn removed_reserved_peer_kept_due_to_free_slots() {
sp_tracing::try_init_simple();
let peerstore_handle = Arc::new(peerstore_handle_test());
let peers = HashSet::from_iter([PeerId::random(), PeerId::random(), PeerId::random()]);
let (mut peerset, to_peerset) = Peerset::new(
ProtocolName::from("/notif/1"),
25,
25,
true,
peers.clone(),
Default::default(),
peerstore_handle,
);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
for outbound_peer in &out_peers {
assert!(peers.contains(outbound_peer));
assert_eq!(
peerset.peers().get(&outbound_peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) })
);
}
},
event => panic!("invalid event: {event:?}"),
}
// remove all reserved peers
to_peerset
.unbounded_send(PeersetCommand::RemoveReservedPeers { peers: peers.clone() })
.unwrap();
match peerset.next().await {
Some(PeersetNotificationCommand::CloseSubstream { peers: out_peers }) => {
assert!(out_peers.is_empty());
},
event => panic!("invalid event: {event:?}"),
}
// verify all reserved peers are canceled
for (_, state) in peerset.peers() {
assert_eq!(state, &PeerState::Opening { direction: Direction::Outbound(Reserved::No) });
}
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 3usize);
}
#[tokio::test]
async fn set_reserved_peers_but_available_slots() {
sp_tracing::try_init_simple();
let peerstore_handle = Arc::new(peerstore_handle_test());
let known_peers = (0..3)
.map(|_| {
let peer = PeerId::random();
peerstore_handle.add_known_peer(peer);
peer
})
.collect::<Vec<_>>();
// one peer is common across operations meaning an outbound substream will be opened to them
// when `Peerset` is polled (along with two random peers) and later on `SetReservedPeers`
// is called with the common peer and with two new random peers
let common_peer = *known_peers.iter().next().unwrap();
let disconnected_peers = known_peers.iter().skip(1).copied().collect::<HashSet<_>>();
assert_eq!(disconnected_peers.len(), 2);
let (mut peerset, to_peerset) = Peerset::new(
ProtocolName::from("/notif/1"),
25,
25,
false,
Default::default(),
Default::default(),
peerstore_handle,
);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 0usize);
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => {
assert_eq!(out_peers.len(), 3);
for peer in &out_peers {
assert_eq!(
peerset.peers().get(&peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::No) })
);
}
},
event => panic!("invalid event: {event:?}"),
}
// verify all three peers are counted as outbound peers
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 3usize);
// report that all substreams were opened
for peer in &known_peers {
assert!(std::matches!(
peerset.report_substream_opened(*peer, traits::Direction::Outbound),
OpenResult::Accept { .. }
));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Connected { direction: Direction::Outbound(Reserved::No) })
);
}
// set reserved peers with `common_peer` being one of them
let reserved_peers = HashSet::from_iter([common_peer, PeerId::random(), PeerId::random()]);
to_peerset
.unbounded_send(PeersetCommand::SetReservedPeers { peers: reserved_peers.clone() })
.unwrap();
match peerset.next().await {
Some(PeersetNotificationCommand::CloseSubstream { peers: out_peers }) => {
assert_eq!(out_peers.len(), 2);
for peer in &out_peers {
assert!(disconnected_peers.contains(peer));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Closing { direction: Direction::Outbound(Reserved::No) }),
);
}
},
event => panic!("invalid event: {event:?}"),
}
// verify that `Peerset` is aware of five peers, with two of them as outbound
// (the two disconnected peers)
assert_eq!(peerset.peers().len(), 5);
assert_eq!(peerset.num_in(), 0usize);
assert_eq!(peerset.num_out(), 2usize);
match peerset.next().await {
Some(PeersetNotificationCommand::OpenSubstream { peers }) => {
assert_eq!(peers.len(), 2);
assert!(!peers.contains(&common_peer));
for peer in &peers {
assert!(reserved_peers.contains(peer));
assert!(peerset.reserved_peers().contains(peer));
assert_eq!(
peerset.peers().get(peer),
Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) }),
);
}
},
event => panic!("invalid event: {event:?}"),
}
assert_eq!(peerset.peers().len(), 5);
assert_eq!(peerset.num_in(), 0usize);
// two substreams are closing still closing
assert_eq!(peerset.num_out(), 2usize);
}
@@ -0,0 +1,78 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Metrics for [`RequestResponseProtocol`](super::RequestResponseProtocol).
use crate::{service::metrics::Metrics, types::ProtocolName};
use std::time::Duration;
/// Request-response metrics.
pub struct RequestResponseMetrics {
/// Metrics.
metrics: Option<Metrics>,
/// Protocol name.
protocol: ProtocolName,
}
impl RequestResponseMetrics {
pub fn new(metrics: Option<Metrics>, protocol: ProtocolName) -> Self {
Self { metrics, protocol }
}
/// Register inbound request failure to Prometheus
pub fn register_inbound_request_failure(&self, reason: &str) {
if let Some(metrics) = &self.metrics {
metrics
.requests_in_failure_total
.with_label_values(&[&self.protocol, reason])
.inc();
}
}
/// Register inbound request success to Prometheus
pub fn register_inbound_request_success(&self, serve_time: Duration) {
if let Some(metrics) = &self.metrics {
metrics
.requests_in_success_total
.with_label_values(&[&self.protocol])
.observe(serve_time.as_secs_f64());
}
}
/// Register inbound request failure to Prometheus
pub fn register_outbound_request_failure(&self, reason: &str) {
if let Some(metrics) = &self.metrics {
metrics
.requests_out_failure_total
.with_label_values(&[&self.protocol, reason])
.inc();
}
}
/// Register inbound request success to Prometheus
pub fn register_outbound_request_success(&self, duration: Duration) {
if let Some(metrics) = &self.metrics {
metrics
.requests_out_success_total
.with_label_values(&[&self.protocol])
.observe(duration.as_secs_f64());
}
}
}
@@ -0,0 +1,529 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Shim for litep2p's request-response implementation to make it work with `sc_network`'s
//! request-response API.
use crate::{
litep2p::shim::request_response::metrics::RequestResponseMetrics,
peer_store::PeerStoreProvider,
request_responses::{IncomingRequest, OutgoingResponse},
service::{metrics::Metrics, traits::RequestResponseConfig as RequestResponseConfigT},
IfDisconnected, ProtocolName, RequestFailure,
};
use futures::{channel::oneshot, future::BoxFuture, stream::FuturesUnordered, StreamExt};
use litep2p::{
protocol::request_response::{
DialOptions, RequestResponseError, RequestResponseEvent, RequestResponseHandle,
},
types::RequestId,
};
use sc_network_types::PeerId;
use sc_utils::mpsc::{TracingUnboundedReceiver, TracingUnboundedSender};
use std::{
collections::HashMap,
sync::Arc,
time::{Duration, Instant},
};
mod metrics;
#[cfg(test)]
mod tests;
/// Logging target for the file.
const LOG_TARGET: &str = "sub-libp2p::request-response";
/// Type containing information related to an outbound request.
#[derive(Debug)]
pub struct OutboundRequest {
/// Peer ID.
peer: PeerId,
/// Request.
request: Vec<u8>,
/// Fallback request, if provided.
fallback_request: Option<(Vec<u8>, ProtocolName)>,
/// `oneshot::Sender` for sending the received response, or failure.
sender: oneshot::Sender<Result<(Vec<u8>, ProtocolName), RequestFailure>>,
/// What should the node do if `peer` is disconnected.
dial_behavior: IfDisconnected,
}
impl OutboundRequest {
/// Create new [`OutboundRequest`].
pub fn new(
peer: PeerId,
request: Vec<u8>,
sender: oneshot::Sender<Result<(Vec<u8>, ProtocolName), RequestFailure>>,
fallback_request: Option<(Vec<u8>, ProtocolName)>,
dial_behavior: IfDisconnected,
) -> Self {
OutboundRequest { peer, request, sender, fallback_request, dial_behavior }
}
}
/// Pending request.
struct PendingRequest {
tx: oneshot::Sender<Result<(Vec<u8>, ProtocolName), RequestFailure>>,
started: Instant,
fallback_request: Option<(Vec<u8>, ProtocolName)>,
}
impl PendingRequest {
/// Create new [`PendingRequest`].
fn new(
tx: oneshot::Sender<Result<(Vec<u8>, ProtocolName), RequestFailure>>,
started: Instant,
fallback_request: Option<(Vec<u8>, ProtocolName)>,
) -> Self {
Self { tx, started, fallback_request }
}
}
/// Request-response protocol configuration.
///
/// See [`RequestResponseConfiguration`](crate::request_response::ProtocolConfig) for more details.
#[derive(Debug)]
pub struct RequestResponseConfig {
/// Name of the protocol on the wire. Should be something like `/foo/bar`.
pub protocol_name: ProtocolName,
/// Fallback on the wire protocol names to support.
pub fallback_names: Vec<ProtocolName>,
/// Maximum allowed size, in bytes, of a request.
pub max_request_size: u64,
/// Maximum allowed size, in bytes, of a response.
pub max_response_size: u64,
/// Duration after which emitted requests are considered timed out.
pub request_timeout: Duration,
/// Channel on which the networking service will send incoming requests.
pub inbound_queue: Option<async_channel::Sender<IncomingRequest>>,
}
impl RequestResponseConfig {
/// Create new [`RequestResponseConfig`].
pub(crate) fn new(
protocol_name: ProtocolName,
fallback_names: Vec<ProtocolName>,
max_request_size: u64,
max_response_size: u64,
request_timeout: Duration,
inbound_queue: Option<async_channel::Sender<IncomingRequest>>,
) -> Self {
Self {
protocol_name,
fallback_names,
max_request_size,
max_response_size,
request_timeout,
inbound_queue,
}
}
}
impl RequestResponseConfigT for RequestResponseConfig {
fn protocol_name(&self) -> &ProtocolName {
&self.protocol_name
}
}
/// Request-response protocol.
///
/// This is slightly different from the `RequestResponsesBehaviour` in that it is protocol-specific,
/// meaning there is an instance of `RequestResponseProtocol` for each installed request-response
/// protocol and that instance deals only with the requests and responses of that protocol, nothing
/// else. It also differs from the other implementation by combining both inbound and outbound
/// requests under one instance so all request-response-related behavior of any given protocol is
/// handled through one instance of `RequestResponseProtocol`.
pub struct RequestResponseProtocol {
/// Protocol name.
protocol: ProtocolName,
/// Handle to request-response protocol.
handle: RequestResponseHandle,
/// Inbound queue for sending received requests to protocol implementation in Polkadot SDK.
inbound_queue: Option<async_channel::Sender<IncomingRequest>>,
/// Handle to `Peerstore`.
peerstore_handle: Arc<dyn PeerStoreProvider>,
/// Pending responses.
pending_inbound_responses: HashMap<RequestId, PendingRequest>,
/// Pending outbound responses.
pending_outbound_responses: FuturesUnordered<
BoxFuture<'static, (litep2p::PeerId, RequestId, Result<OutgoingResponse, ()>, Instant)>,
>,
/// RX channel for receiving info for outbound requests.
request_rx: TracingUnboundedReceiver<OutboundRequest>,
/// Map of supported request-response protocols which are used to support fallback requests.
///
/// If negotiation for the main protocol fails and the request was sent with a fallback,
/// [`RequestResponseProtocol`] queries this map and sends the request that protocol for
/// processing.
request_tx: HashMap<ProtocolName, TracingUnboundedSender<OutboundRequest>>,
/// Metrics, if enabled.
metrics: RequestResponseMetrics,
}
impl RequestResponseProtocol {
/// Create new [`RequestResponseProtocol`].
pub fn new(
protocol: ProtocolName,
handle: RequestResponseHandle,
peerstore_handle: Arc<dyn PeerStoreProvider>,
inbound_queue: Option<async_channel::Sender<IncomingRequest>>,
request_rx: TracingUnboundedReceiver<OutboundRequest>,
request_tx: HashMap<ProtocolName, TracingUnboundedSender<OutboundRequest>>,
metrics: Option<Metrics>,
) -> Self {
Self {
handle,
request_rx,
request_tx,
inbound_queue,
peerstore_handle,
protocol: protocol.clone(),
pending_inbound_responses: HashMap::new(),
pending_outbound_responses: FuturesUnordered::new(),
metrics: RequestResponseMetrics::new(metrics, protocol),
}
}
/// Send `request` to `peer`.
async fn on_send_request(
&mut self,
peer: PeerId,
request: Vec<u8>,
fallback_request: Option<(Vec<u8>, ProtocolName)>,
tx: oneshot::Sender<Result<(Vec<u8>, ProtocolName), RequestFailure>>,
connect: IfDisconnected,
) {
let dial_options = match connect {
IfDisconnected::TryConnect => DialOptions::Dial,
IfDisconnected::ImmediateError => DialOptions::Reject,
};
log::trace!(
target: LOG_TARGET,
"{}: send request to {:?} (fallback {:?}) (dial options: {:?})",
self.protocol,
peer,
fallback_request,
dial_options,
);
match self.handle.try_send_request(peer.into(), request, dial_options) {
Ok(request_id) => {
self.pending_inbound_responses
.insert(request_id, PendingRequest::new(tx, Instant::now(), fallback_request));
},
Err(error) => {
log::warn!(
target: LOG_TARGET,
"{}: failed to send request to {peer:?}: {error:?}",
self.protocol,
);
let _ = tx.send(Err(RequestFailure::Refused));
self.metrics.register_inbound_request_failure(error.to_string().as_ref());
},
}
}
/// Handle inbound request from `peer`
///
/// If the protocol is configured outbound only, reject the request immediately.
fn on_inbound_request(
&mut self,
peer: litep2p::PeerId,
fallback: Option<litep2p::ProtocolName>,
request_id: RequestId,
request: Vec<u8>,
) {
let Some(inbound_queue) = &self.inbound_queue else {
log::trace!(
target: LOG_TARGET,
"{}: rejecting inbound request from {peer:?}, protocol configured as outbound only",
self.protocol,
);
self.handle.reject_request(request_id);
return;
};
log::trace!(
target: LOG_TARGET,
"{}: request received from {peer:?} ({fallback:?} {request_id:?}), request size {:?}",
self.protocol,
request.len(),
);
let (tx, rx) = oneshot::channel();
match inbound_queue.try_send(IncomingRequest {
peer: peer.into(),
payload: request,
pending_response: tx,
}) {
Ok(_) => {
self.pending_outbound_responses.push(Box::pin(async move {
(peer, request_id, rx.await.map_err(|_| ()), Instant::now())
}));
},
Err(error) => {
log::trace!(
target: LOG_TARGET,
"{:?}: dropping request from {peer:?} ({request_id:?}), inbound queue full",
self.protocol,
);
self.handle.reject_request(request_id);
self.metrics.register_inbound_request_failure(error.to_string().as_ref());
},
}
}
/// Handle received inbound response.
fn on_inbound_response(
&mut self,
peer: litep2p::PeerId,
request_id: RequestId,
fallback: Option<litep2p::ProtocolName>,
response: Vec<u8>,
) {
match self.pending_inbound_responses.remove(&request_id) {
None => log::warn!(
target: LOG_TARGET,
"{:?}: response received for {peer:?} but {request_id:?} doesn't exist",
self.protocol,
),
Some(PendingRequest { tx, started, .. }) => {
log::trace!(
target: LOG_TARGET,
"{:?}: response received for {peer:?} ({request_id:?}), response size {:?}",
self.protocol,
response.len(),
);
let _ = tx.send(Ok((
response,
fallback.map_or_else(|| self.protocol.clone(), Into::into),
)));
self.metrics.register_outbound_request_success(started.elapsed());
},
}
}
/// Handle failed outbound request.
fn on_request_failed(
&mut self,
peer: litep2p::PeerId,
request_id: RequestId,
error: RequestResponseError,
) {
log::debug!(
target: LOG_TARGET,
"{:?}: request failed for {peer:?} ({request_id:?}): {error:?}",
self.protocol
);
let Some(PendingRequest { tx, fallback_request, .. }) =
self.pending_inbound_responses.remove(&request_id)
else {
log::warn!(
target: LOG_TARGET,
"{:?}: request failed for peer {peer:?} but {request_id:?} doesn't exist",
self.protocol,
);
return
};
let error = match error {
RequestResponseError::NotConnected => Some(RequestFailure::NotConnected),
RequestResponseError::Rejected | RequestResponseError::Timeout =>
Some(RequestFailure::Refused),
RequestResponseError::Canceled => {
log::debug!(
target: LOG_TARGET,
"{}: request canceled by local node to {peer:?} ({request_id:?})",
self.protocol,
);
None
},
RequestResponseError::TooLargePayload => {
log::warn!(
target: LOG_TARGET,
"{}: tried to send too large request to {peer:?} ({request_id:?})",
self.protocol,
);
Some(RequestFailure::Refused)
},
RequestResponseError::UnsupportedProtocol => match fallback_request {
Some((request, protocol)) => match self.request_tx.get(&protocol) {
Some(sender) => {
log::debug!(
target: LOG_TARGET,
"{}: failed to negotiate protocol with {:?}, try fallback request: ({})",
self.protocol,
peer,
protocol,
);
let outbound_request = OutboundRequest::new(
peer.into(),
request,
tx,
None,
IfDisconnected::ImmediateError,
);
// since remote peer doesn't support the main protocol (`self.protocol`),
// try to send the request over a fallback protocol by creating a new
// `OutboundRequest` from the original data, now with the fallback request
// payload, and send it over to the (fallback) request handler like it was
// a normal request.
let _ = sender.unbounded_send(outbound_request);
return;
},
None => {
log::warn!(
target: LOG_TARGET,
"{}: fallback request provided but protocol ({}) doesn't exist (peer {:?})",
self.protocol,
protocol,
peer,
);
Some(RequestFailure::Refused)
},
},
None => Some(RequestFailure::Refused),
},
};
if let Some(error) = error {
self.metrics.register_outbound_request_failure(error.to_string().as_ref());
let _ = tx.send(Err(error));
}
}
/// Handle outbound response.
fn on_outbound_response(
&mut self,
peer: litep2p::PeerId,
request_id: RequestId,
response: OutgoingResponse,
started: Instant,
) {
let OutgoingResponse { result, reputation_changes, sent_feedback } = response;
for change in reputation_changes {
log::trace!(target: LOG_TARGET, "{}: report {peer:?}: {change:?}", self.protocol);
self.peerstore_handle.report_peer(peer.into(), change);
}
match result {
Err(()) => {
log::debug!(
target: LOG_TARGET,
"{}: response rejected ({request_id:?}) for {peer:?}",
self.protocol,
);
self.handle.reject_request(request_id);
self.metrics.register_inbound_request_failure("rejected");
},
Ok(response) => {
log::trace!(
target: LOG_TARGET,
"{}: send response ({request_id:?}) to {peer:?}, response size {}",
self.protocol,
response.len(),
);
match sent_feedback {
None => self.handle.send_response(request_id, response),
Some(feedback) =>
self.handle.send_response_with_feedback(request_id, response, feedback),
}
self.metrics.register_inbound_request_success(started.elapsed());
},
}
}
/// Start running event loop of the request-response protocol.
pub async fn run(mut self) {
loop {
tokio::select! {
event = self.handle.next() => match event {
None => return,
Some(RequestResponseEvent::RequestReceived {
peer,
fallback,
request_id,
request,
}) => self.on_inbound_request(peer, fallback, request_id, request),
Some(RequestResponseEvent::ResponseReceived { peer, request_id, fallback, response }) => {
self.on_inbound_response(peer, request_id, fallback, response);
},
Some(RequestResponseEvent::RequestFailed { peer, request_id, error }) => {
self.on_request_failed(peer, request_id, error);
},
},
event = self.pending_outbound_responses.next(), if !self.pending_outbound_responses.is_empty() => match event {
None => return,
Some((peer, request_id, Err(()), _)) => {
log::debug!(target: LOG_TARGET, "{}: reject request ({request_id:?}) from {peer:?}", self.protocol);
self.handle.reject_request(request_id);
self.metrics.register_inbound_request_failure("rejected");
}
Some((peer, request_id, Ok(response), started)) => {
self.on_outbound_response(peer, request_id, response, started);
}
},
event = self.request_rx.next() => match event {
None => return,
Some(outbound_request) => {
let OutboundRequest { peer, request, sender, dial_behavior, fallback_request } = outbound_request;
self.on_send_request(peer, request, fallback_request, sender, dial_behavior).await;
}
}
}
}
}
}
@@ -0,0 +1,901 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{
litep2p::{
peerstore::peerstore_handle_test,
shim::request_response::{OutboundRequest, RequestResponseProtocol},
},
request_responses::{IfDisconnected, IncomingRequest, OutgoingResponse},
ProtocolName, RequestFailure,
};
use futures::{channel::oneshot, StreamExt};
use litep2p::{
config::ConfigBuilder as Litep2pConfigBuilder,
protocol::request_response::{
ConfigBuilder, DialOptions, RequestResponseError, RequestResponseEvent,
RequestResponseHandle,
},
transport::tcp::config::Config as TcpConfig,
Litep2p, Litep2pEvent,
};
use sc_network_types::PeerId;
use sc_utils::mpsc::tracing_unbounded;
use std::{collections::HashMap, sync::Arc, task::Poll};
/// Create `litep2p` for testing.
async fn make_litep2p() -> (Litep2p, RequestResponseHandle) {
let (config, handle) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/1"))
.with_max_size(1024)
.build();
(
Litep2p::new(
Litep2pConfigBuilder::new()
.with_request_response_protocol(config)
.with_tcp(TcpConfig {
listen_addresses: vec![
"/ip4/0.0.0.0/tcp/0".parse().unwrap(),
"/ip6/::/tcp/0".parse().unwrap(),
],
..Default::default()
})
.build(),
)
.unwrap(),
handle,
)
}
// connect two `litep2p` instances together
async fn connect_peers(litep2p1: &mut Litep2p, litep2p2: &mut Litep2p) {
let address = litep2p2.listen_addresses().next().unwrap().clone();
litep2p1.dial_address(address).await.unwrap();
let mut litep2p1_connected = false;
let mut litep2p2_connected = false;
loop {
tokio::select! {
event = litep2p1.next_event() => match event.unwrap() {
Litep2pEvent::ConnectionEstablished { .. } => {
litep2p1_connected = true;
}
_ => {},
},
event = litep2p2.next_event() => match event.unwrap() {
Litep2pEvent::ConnectionEstablished { .. } => {
litep2p2_connected = true;
}
_ => {},
}
}
if litep2p1_connected && litep2p2_connected {
break
}
}
}
#[tokio::test]
async fn dial_failure() {
let (mut litep2p, handle) = make_litep2p().await;
let (tx, _rx) = async_channel::bounded(64);
let (outbound_tx, outbound_rx) = tracing_unbounded("outbound-request", 1000);
let senders = HashMap::from_iter([(ProtocolName::from("/protocol/1"), outbound_tx.clone())]);
let protocol = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle,
Arc::new(peerstore_handle_test()),
Some(tx),
outbound_rx,
senders,
None,
);
tokio::spawn(protocol.run());
tokio::spawn(async move { while let Some(_) = litep2p.next_event().await {} });
let peer = PeerId::random();
let (result_tx, result_rx) = oneshot::channel();
outbound_tx
.unbounded_send(OutboundRequest {
peer,
request: vec![1, 2, 3, 4],
sender: result_tx,
fallback_request: None,
dial_behavior: IfDisconnected::TryConnect,
})
.unwrap();
assert!(std::matches!(result_rx.await, Ok(Err(RequestFailure::Refused))));
}
#[tokio::test]
async fn send_request_to_disconnected_peer() {
let (mut litep2p, handle) = make_litep2p().await;
let (tx, _rx) = async_channel::bounded(64);
let (outbound_tx, outbound_rx) = tracing_unbounded("outbound-request", 1000);
let senders = HashMap::from_iter([(ProtocolName::from("/protocol/1"), outbound_tx.clone())]);
let protocol = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle,
Arc::new(peerstore_handle_test()),
Some(tx),
outbound_rx,
senders,
None,
);
tokio::spawn(protocol.run());
tokio::spawn(async move { while let Some(_) = litep2p.next_event().await {} });
let peer = PeerId::random();
let (result_tx, result_rx) = oneshot::channel();
outbound_tx
.unbounded_send(OutboundRequest {
peer,
request: vec![1, 2, 3, 4],
sender: result_tx,
fallback_request: None,
dial_behavior: IfDisconnected::ImmediateError,
})
.unwrap();
assert!(std::matches!(result_rx.await, Ok(Err(RequestFailure::NotConnected))));
}
#[tokio::test]
async fn send_request_to_disconnected_peer_and_dial() {
let (mut litep2p1, handle1) = make_litep2p().await;
let (mut litep2p2, handle2) = make_litep2p().await;
let peer1 = *litep2p1.local_peer_id();
let peer2 = *litep2p2.local_peer_id();
litep2p1.add_known_address(
peer2,
std::iter::once(litep2p2.listen_addresses().next().expect("listen address").clone()),
);
let (outbound_tx1, outbound_rx1) = tracing_unbounded("outbound-request", 1000);
let senders = HashMap::from_iter([(ProtocolName::from("/protocol/1"), outbound_tx1.clone())]);
let (tx1, _rx1) = async_channel::bounded(64);
let protocol1 = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle1,
Arc::new(peerstore_handle_test()),
Some(tx1),
outbound_rx1,
senders,
None,
);
let (outbound_tx2, outbound_rx2) = tracing_unbounded("outbound-request", 1000);
let senders = HashMap::from_iter([(ProtocolName::from("/protocol/1"), outbound_tx2)]);
let (tx2, rx2) = async_channel::bounded(64);
let protocol2 = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle2,
Arc::new(peerstore_handle_test()),
Some(tx2),
outbound_rx2,
senders,
None,
);
tokio::spawn(protocol1.run());
tokio::spawn(protocol2.run());
tokio::spawn(async move { while let Some(_) = litep2p1.next_event().await {} });
tokio::spawn(async move { while let Some(_) = litep2p2.next_event().await {} });
let (result_tx, _result_rx) = oneshot::channel();
outbound_tx1
.unbounded_send(OutboundRequest {
peer: peer2.into(),
request: vec![1, 2, 3, 4],
sender: result_tx,
fallback_request: None,
dial_behavior: IfDisconnected::TryConnect,
})
.unwrap();
match rx2.recv().await {
Ok(IncomingRequest { peer, payload, .. }) => {
assert_eq!(peer, Into::<PeerId>::into(peer1));
assert_eq!(payload, vec![1, 2, 3, 4]);
},
Err(error) => panic!("unexpected error: {error:?}"),
}
}
#[tokio::test]
async fn too_many_inbound_requests() {
let (mut litep2p1, handle1) = make_litep2p().await;
let (mut litep2p2, mut handle2) = make_litep2p().await;
let peer1 = *litep2p1.local_peer_id();
connect_peers(&mut litep2p1, &mut litep2p2).await;
let (outbound_tx, outbound_rx) = tracing_unbounded("outbound-request", 1000);
let senders = HashMap::from_iter([(ProtocolName::from("/protocol/1"), outbound_tx)]);
let (tx, _rx) = async_channel::bounded(4);
let protocol = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle1,
Arc::new(peerstore_handle_test()),
Some(tx),
outbound_rx,
senders,
None,
);
tokio::spawn(protocol.run());
tokio::spawn(async move { while let Some(_) = litep2p1.next_event().await {} });
tokio::spawn(async move { while let Some(_) = litep2p2.next_event().await {} });
// send 5 request and verify that one of the requests will fail
for _ in 0..5 {
handle2
.send_request(peer1, vec![1, 2, 3, 4], DialOptions::Reject)
.await
.unwrap();
}
// verify that one of the requests is rejected
match handle2.next().await {
Some(RequestResponseEvent::RequestFailed { peer, error, .. }) => {
assert_eq!(peer, peer1);
assert_eq!(error, RequestResponseError::Rejected);
},
event => panic!("inavlid event: {event:?}"),
}
// verify that no other events are read from the handle
futures::future::poll_fn(|cx| match handle2.poll_next_unpin(cx) {
Poll::Pending => Poll::Ready(()),
event => panic!("invalid event: {event:?}"),
})
.await;
}
#[tokio::test]
async fn feedback_works() {
let (mut litep2p1, handle1) = make_litep2p().await;
let (mut litep2p2, mut handle2) = make_litep2p().await;
let peer1 = *litep2p1.local_peer_id();
let peer2 = *litep2p2.local_peer_id();
connect_peers(&mut litep2p1, &mut litep2p2).await;
let (outbound_tx, outbound_rx) = tracing_unbounded("outbound-request", 1000);
let senders = HashMap::from_iter([(ProtocolName::from("/protocol/1"), outbound_tx)]);
let (tx, rx) = async_channel::bounded(4);
let protocol = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle1,
Arc::new(peerstore_handle_test()),
Some(tx),
outbound_rx,
senders,
None,
);
tokio::spawn(protocol.run());
tokio::spawn(async move { while let Some(_) = litep2p1.next_event().await {} });
tokio::spawn(async move { while let Some(_) = litep2p2.next_event().await {} });
let request_id = handle2
.send_request(peer1, vec![1, 2, 3, 4], DialOptions::Reject)
.await
.unwrap();
let rx = match rx.recv().await {
Ok(IncomingRequest { peer, payload, pending_response }) => {
assert_eq!(peer, peer2.into());
assert_eq!(payload, vec![1, 2, 3, 4]);
let (tx, rx) = oneshot::channel();
pending_response
.send(OutgoingResponse {
result: Ok(vec![5, 6, 7, 8]),
reputation_changes: Vec::new(),
sent_feedback: Some(tx),
})
.unwrap();
rx
},
event => panic!("invalid event: {event:?}"),
};
match handle2.next().await {
Some(RequestResponseEvent::ResponseReceived {
peer,
request_id: received_id,
response,
..
}) => {
assert_eq!(peer, peer1);
assert_eq!(request_id, received_id);
assert_eq!(response, vec![5, 6, 7, 8]);
assert!(rx.await.is_ok());
},
event => panic!("invalid event: {event:?}"),
}
}
#[tokio::test]
async fn fallback_request_compatible_peers() {
// `litep2p1` supports both the new and the old protocol
let (mut litep2p1, handle1_1, handle1_2) = {
let (config1, handle1) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/2"))
.with_max_size(1024)
.build();
let (config2, handle2) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/1"))
.with_max_size(1024)
.build();
(
Litep2p::new(
Litep2pConfigBuilder::new()
.with_request_response_protocol(config1)
.with_request_response_protocol(config2)
.with_tcp(TcpConfig {
listen_addresses: vec![
"/ip4/0.0.0.0/tcp/0".parse().unwrap(),
"/ip6/::/tcp/0".parse().unwrap(),
],
..Default::default()
})
.build(),
)
.unwrap(),
handle1,
handle2,
)
};
// `litep2p2` supports only the new protocol
let (config2, handle2) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/2"))
.with_max_size(1024)
.build();
let mut litep2p2 = Litep2p::new(
Litep2pConfigBuilder::new()
.with_request_response_protocol(config2)
.with_tcp(TcpConfig {
listen_addresses: vec![
"/ip4/0.0.0.0/tcp/0".parse().unwrap(),
"/ip6/::/tcp/0".parse().unwrap(),
],
..Default::default()
})
.build(),
)
.unwrap();
let peer1 = *litep2p1.local_peer_id();
let peer2 = *litep2p2.local_peer_id();
connect_peers(&mut litep2p1, &mut litep2p2).await;
let (outbound_tx1, outbound_rx1) = tracing_unbounded("outbound-request", 1000);
let (outbound_tx_fallback, outbound_rx_fallback) = tracing_unbounded("outbound-request", 1000);
let senders1 = HashMap::from_iter([
(ProtocolName::from("/protocol/2"), outbound_tx1.clone()),
(ProtocolName::from("/protocol/1"), outbound_tx_fallback),
]);
let (tx1, _rx1) = async_channel::bounded(4);
let protocol1 = RequestResponseProtocol::new(
ProtocolName::from("/protocol/2"),
handle1_1,
Arc::new(peerstore_handle_test()),
Some(tx1),
outbound_rx1,
senders1.clone(),
None,
);
let (tx_fallback, _rx_fallback) = async_channel::bounded(4);
let protocol_fallback = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle1_2,
Arc::new(peerstore_handle_test()),
Some(tx_fallback),
outbound_rx_fallback,
senders1,
None,
);
let (outbound_tx2, outbound_rx2) = tracing_unbounded("outbound-request", 1000);
let senders2 = HashMap::from_iter([(ProtocolName::from("/protocol/2"), outbound_tx2)]);
let (tx2, rx2) = async_channel::bounded(4);
let protocol2 = RequestResponseProtocol::new(
ProtocolName::from("/protocol/2"),
handle2,
Arc::new(peerstore_handle_test()),
Some(tx2),
outbound_rx2,
senders2,
None,
);
tokio::spawn(protocol1.run());
tokio::spawn(protocol2.run());
tokio::spawn(protocol_fallback.run());
tokio::spawn(async move { while let Some(_) = litep2p1.next_event().await {} });
tokio::spawn(async move { while let Some(_) = litep2p2.next_event().await {} });
let (result_tx, result_rx) = oneshot::channel();
outbound_tx1
.unbounded_send(OutboundRequest {
peer: peer2.into(),
request: vec![1, 2, 3, 4],
sender: result_tx,
fallback_request: Some((vec![1, 3, 3, 7], ProtocolName::from("/protocol/1"))),
dial_behavior: IfDisconnected::ImmediateError,
})
.unwrap();
match rx2.recv().await {
Ok(IncomingRequest { peer, payload, pending_response }) => {
assert_eq!(peer, peer1.into());
assert_eq!(payload, vec![1, 2, 3, 4]);
pending_response
.send(OutgoingResponse {
result: Ok(vec![5, 6, 7, 8]),
reputation_changes: Vec::new(),
sent_feedback: None,
})
.unwrap();
},
event => panic!("invalid event: {event:?}"),
}
match result_rx.await {
Ok(Ok((response, protocol))) => {
assert_eq!(response, vec![5, 6, 7, 8]);
assert_eq!(protocol, ProtocolName::from("/protocol/2"));
},
event => panic!("invalid event: {event:?}"),
}
}
#[tokio::test]
async fn fallback_request_old_peer_receives() {
sp_tracing::try_init_simple();
// `litep2p1` supports both the new and the old protocol
let (mut litep2p1, handle1_1, handle1_2) = {
let (config1, handle1) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/2"))
.with_max_size(1024)
.build();
let (config2, handle2) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/1"))
.with_max_size(1024)
.build();
(
Litep2p::new(
Litep2pConfigBuilder::new()
.with_request_response_protocol(config1)
.with_request_response_protocol(config2)
.with_tcp(TcpConfig {
listen_addresses: vec![
"/ip4/0.0.0.0/tcp/0".parse().unwrap(),
"/ip6/::/tcp/0".parse().unwrap(),
],
..Default::default()
})
.build(),
)
.unwrap(),
handle1,
handle2,
)
};
// `litep2p2` supports only the new protocol
let (config2, handle2) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/1"))
.with_max_size(1024)
.build();
let mut litep2p2 = Litep2p::new(
Litep2pConfigBuilder::new()
.with_request_response_protocol(config2)
.with_tcp(TcpConfig {
listen_addresses: vec![
"/ip4/0.0.0.0/tcp/0".parse().unwrap(),
"/ip6/::/tcp/0".parse().unwrap(),
],
..Default::default()
})
.build(),
)
.unwrap();
let peer1 = *litep2p1.local_peer_id();
let peer2 = *litep2p2.local_peer_id();
connect_peers(&mut litep2p1, &mut litep2p2).await;
let (outbound_tx1, outbound_rx1) = tracing_unbounded("outbound-request", 1000);
let (outbound_tx_fallback, outbound_rx_fallback) = tracing_unbounded("outbound-request", 1000);
let senders1 = HashMap::from_iter([
(ProtocolName::from("/protocol/2"), outbound_tx1.clone()),
(ProtocolName::from("/protocol/1"), outbound_tx_fallback),
]);
let (tx1, _rx1) = async_channel::bounded(4);
let protocol1 = RequestResponseProtocol::new(
ProtocolName::from("/protocol/2"),
handle1_1,
Arc::new(peerstore_handle_test()),
Some(tx1),
outbound_rx1,
senders1.clone(),
None,
);
let (tx_fallback, _rx_fallback) = async_channel::bounded(4);
let protocol_fallback = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle1_2,
Arc::new(peerstore_handle_test()),
Some(tx_fallback),
outbound_rx_fallback,
senders1,
None,
);
let (outbound_tx2, outbound_rx2) = tracing_unbounded("outbound-request", 1000);
let senders2 = HashMap::from_iter([(ProtocolName::from("/protocol/1"), outbound_tx2)]);
let (tx2, rx2) = async_channel::bounded(4);
let protocol2 = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle2,
Arc::new(peerstore_handle_test()),
Some(tx2),
outbound_rx2,
senders2,
None,
);
tokio::spawn(protocol1.run());
tokio::spawn(protocol2.run());
tokio::spawn(protocol_fallback.run());
tokio::spawn(async move { while let Some(_) = litep2p1.next_event().await {} });
tokio::spawn(async move { while let Some(_) = litep2p2.next_event().await {} });
let (result_tx, result_rx) = oneshot::channel();
outbound_tx1
.unbounded_send(OutboundRequest {
peer: peer2.into(),
request: vec![1, 2, 3, 4],
sender: result_tx,
fallback_request: Some((vec![1, 3, 3, 7], ProtocolName::from("/protocol/1"))),
dial_behavior: IfDisconnected::ImmediateError,
})
.unwrap();
match rx2.recv().await {
Ok(IncomingRequest { peer, payload, pending_response }) => {
assert_eq!(peer, peer1.into());
assert_eq!(payload, vec![1, 3, 3, 7]);
pending_response
.send(OutgoingResponse {
result: Ok(vec![1, 3, 3, 8]),
reputation_changes: Vec::new(),
sent_feedback: None,
})
.unwrap();
},
event => panic!("invalid event: {event:?}"),
}
match result_rx.await {
Ok(Ok((response, protocol))) => {
assert_eq!(response, vec![1, 3, 3, 8]);
assert_eq!(protocol, ProtocolName::from("/protocol/1"));
},
event => panic!("invalid event: {event:?}"),
}
}
#[tokio::test]
async fn fallback_request_old_peer_sends() {
sp_tracing::try_init_simple();
// `litep2p1` supports both the new and the old protocol
let (mut litep2p1, handle1_1, handle1_2) = {
let (config1, handle1) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/2"))
.with_max_size(1024)
.build();
let (config2, handle2) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/1"))
.with_max_size(1024)
.build();
(
Litep2p::new(
Litep2pConfigBuilder::new()
.with_request_response_protocol(config1)
.with_request_response_protocol(config2)
.with_tcp(TcpConfig {
listen_addresses: vec![
"/ip4/0.0.0.0/tcp/0".parse().unwrap(),
"/ip6/::/tcp/0".parse().unwrap(),
],
..Default::default()
})
.build(),
)
.unwrap(),
handle1,
handle2,
)
};
// `litep2p2` supports only the new protocol
let (config2, handle2) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/1"))
.with_max_size(1024)
.build();
let mut litep2p2 = Litep2p::new(
Litep2pConfigBuilder::new()
.with_request_response_protocol(config2)
.with_tcp(TcpConfig {
listen_addresses: vec![
"/ip4/0.0.0.0/tcp/0".parse().unwrap(),
"/ip6/::/tcp/0".parse().unwrap(),
],
..Default::default()
})
.build(),
)
.unwrap();
let peer1 = *litep2p1.local_peer_id();
let peer2 = *litep2p2.local_peer_id();
connect_peers(&mut litep2p1, &mut litep2p2).await;
let (outbound_tx1, outbound_rx1) = tracing_unbounded("outbound-request", 1000);
let (outbound_tx_fallback, outbound_rx_fallback) = tracing_unbounded("outbound-request", 1000);
let senders1 = HashMap::from_iter([
(ProtocolName::from("/protocol/2"), outbound_tx1.clone()),
(ProtocolName::from("/protocol/1"), outbound_tx_fallback),
]);
let (tx1, _rx1) = async_channel::bounded(4);
let protocol1 = RequestResponseProtocol::new(
ProtocolName::from("/protocol/2"),
handle1_1,
Arc::new(peerstore_handle_test()),
Some(tx1),
outbound_rx1,
senders1.clone(),
None,
);
let (tx_fallback, rx_fallback) = async_channel::bounded(4);
let protocol_fallback = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle1_2,
Arc::new(peerstore_handle_test()),
Some(tx_fallback),
outbound_rx_fallback,
senders1,
None,
);
let (outbound_tx2, outbound_rx2) = tracing_unbounded("outbound-request", 1000);
let senders2 = HashMap::from_iter([(ProtocolName::from("/protocol/1"), outbound_tx2.clone())]);
let (tx2, _rx2) = async_channel::bounded(4);
let protocol2 = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle2,
Arc::new(peerstore_handle_test()),
Some(tx2),
outbound_rx2,
senders2,
None,
);
tokio::spawn(protocol1.run());
tokio::spawn(protocol2.run());
tokio::spawn(protocol_fallback.run());
tokio::spawn(async move { while let Some(_) = litep2p1.next_event().await {} });
tokio::spawn(async move { while let Some(_) = litep2p2.next_event().await {} });
let (result_tx, result_rx) = oneshot::channel();
outbound_tx2
.unbounded_send(OutboundRequest {
peer: peer1.into(),
request: vec![1, 2, 3, 4],
sender: result_tx,
fallback_request: None,
dial_behavior: IfDisconnected::ImmediateError,
})
.unwrap();
match rx_fallback.recv().await {
Ok(IncomingRequest { peer, payload, pending_response }) => {
assert_eq!(peer, peer2.into());
assert_eq!(payload, vec![1, 2, 3, 4]);
pending_response
.send(OutgoingResponse {
result: Ok(vec![1, 3, 3, 8]),
reputation_changes: Vec::new(),
sent_feedback: None,
})
.unwrap();
},
event => panic!("invalid event: {event:?}"),
}
match result_rx.await {
Ok(Ok((response, protocol))) => {
assert_eq!(response, vec![1, 3, 3, 8]);
assert_eq!(protocol, ProtocolName::from("/protocol/1"));
},
event => panic!("invalid event: {event:?}"),
}
}
#[tokio::test]
async fn old_protocol_supported_but_no_fallback_provided() {
sp_tracing::try_init_simple();
// `litep2p1` supports both the new and the old protocol
let (mut litep2p1, handle1_1, handle1_2) = {
let (config1, handle1) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/2"))
.with_max_size(1024)
.build();
let (config2, handle2) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/1"))
.with_max_size(1024)
.build();
(
Litep2p::new(
Litep2pConfigBuilder::new()
.with_request_response_protocol(config1)
.with_request_response_protocol(config2)
.with_tcp(TcpConfig {
listen_addresses: vec![
"/ip4/0.0.0.0/tcp/0".parse().unwrap(),
"/ip6/::/tcp/0".parse().unwrap(),
],
..Default::default()
})
.build(),
)
.unwrap(),
handle1,
handle2,
)
};
// `litep2p2` supports only the old protocol
let (config2, handle2) = ConfigBuilder::new(litep2p::ProtocolName::from("/protocol/1"))
.with_max_size(1024)
.build();
let mut litep2p2 = Litep2p::new(
Litep2pConfigBuilder::new()
.with_request_response_protocol(config2)
.with_tcp(TcpConfig {
listen_addresses: vec![
"/ip4/0.0.0.0/tcp/0".parse().unwrap(),
"/ip6/::/tcp/0".parse().unwrap(),
],
..Default::default()
})
.build(),
)
.unwrap();
let peer2 = *litep2p2.local_peer_id();
connect_peers(&mut litep2p1, &mut litep2p2).await;
let (outbound_tx1, outbound_rx1) = tracing_unbounded("outbound-request", 1000);
let (outbound_tx_fallback, outbound_rx_fallback) = tracing_unbounded("outbound-request", 1000);
let senders1 = HashMap::from_iter([
(ProtocolName::from("/protocol/2"), outbound_tx1.clone()),
(ProtocolName::from("/protocol/1"), outbound_tx_fallback),
]);
let (tx1, _rx1) = async_channel::bounded(4);
let protocol1 = RequestResponseProtocol::new(
ProtocolName::from("/protocol/2"),
handle1_1,
Arc::new(peerstore_handle_test()),
Some(tx1),
outbound_rx1,
senders1.clone(),
None,
);
let (tx_fallback, _rx_fallback) = async_channel::bounded(4);
let protocol_fallback = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle1_2,
Arc::new(peerstore_handle_test()),
Some(tx_fallback),
outbound_rx_fallback,
senders1,
None,
);
let (outbound_tx2, outbound_rx2) = tracing_unbounded("outbound-request", 1000);
let senders2 = HashMap::from_iter([(ProtocolName::from("/protocol/1"), outbound_tx2)]);
let (tx2, _rx2) = async_channel::bounded(4);
let protocol2 = RequestResponseProtocol::new(
ProtocolName::from("/protocol/1"),
handle2,
Arc::new(peerstore_handle_test()),
Some(tx2),
outbound_rx2,
senders2,
None,
);
tokio::spawn(protocol1.run());
tokio::spawn(protocol2.run());
tokio::spawn(protocol_fallback.run());
tokio::spawn(async move { while let Some(_) = litep2p1.next_event().await {} });
tokio::spawn(async move { while let Some(_) = litep2p2.next_event().await {} });
let (result_tx, result_rx) = oneshot::channel();
outbound_tx1
.unbounded_send(OutboundRequest {
peer: peer2.into(),
request: vec![1, 2, 3, 4],
sender: result_tx,
fallback_request: None,
dial_behavior: IfDisconnected::ImmediateError,
})
.unwrap();
match result_rx.await {
Ok(Err(error)) => {
assert!(std::matches!(error, RequestFailure::Refused));
},
event => panic!("invalid event: {event:?}"),
}
}