2018-11-13 14:46:57 +01:00
|
|
|
// Copyright 2018 Parity Technologies (UK) Ltd.
|
|
|
|
//
|
|
|
|
// Permission is hereby granted, free of charge, to any person obtaining a
|
|
|
|
// copy of this software and associated documentation files (the "Software"),
|
|
|
|
// to deal in the Software without restriction, including without limitation
|
|
|
|
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
|
|
// and/or sell copies of the Software, and to permit persons to whom the
|
|
|
|
// Software is furnished to do so, subject to the following conditions:
|
|
|
|
//
|
|
|
|
// The above copyright notice and this permission notice shall be included in
|
|
|
|
// all copies or substantial portions of the Software.
|
|
|
|
//
|
|
|
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
|
|
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
|
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
|
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
|
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
|
|
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
|
|
// DEALINGS IN THE SOFTWARE.
|
|
|
|
|
2018-11-15 17:41:11 +01:00
|
|
|
use crate::rpc_proto;
|
2019-01-21 10:33:51 +00:00
|
|
|
use crate::topic::TopicHash;
|
2019-01-29 16:20:14 +01:00
|
|
|
use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, PeerId, upgrade};
|
|
|
|
use protobuf::{ProtobufError, Message as ProtobufMessage};
|
|
|
|
use std::{error, fmt, io, iter};
|
2018-11-13 14:46:57 +01:00
|
|
|
use tokio_io::{AsyncRead, AsyncWrite};
|
|
|
|
|
2018-11-14 14:07:54 +01:00
|
|
|
/// Implementation of `ConnectionUpgrade` for the floodsub protocol.
|
2019-01-22 14:45:03 +01:00
|
|
|
#[derive(Debug, Clone, Default)]
|
2018-11-13 14:46:57 +01:00
|
|
|
pub struct FloodsubConfig {}
|
|
|
|
|
|
|
|
impl FloodsubConfig {
|
|
|
|
/// Builds a new `FloodsubConfig`.
|
|
|
|
#[inline]
|
|
|
|
pub fn new() -> FloodsubConfig {
|
|
|
|
FloodsubConfig {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-15 17:41:11 +01:00
|
|
|
impl UpgradeInfo for FloodsubConfig {
|
2018-12-11 15:13:10 +01:00
|
|
|
type Info = &'static [u8];
|
|
|
|
type InfoIter = iter::Once<Self::Info>;
|
2018-11-15 17:41:11 +01:00
|
|
|
|
|
|
|
#[inline]
|
2018-12-11 15:13:10 +01:00
|
|
|
fn protocol_info(&self) -> Self::InfoIter {
|
|
|
|
iter::once(b"/floodsub/1.0.0")
|
2018-11-15 17:41:11 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<TSocket> InboundUpgrade<TSocket> for FloodsubConfig
|
2018-11-13 14:46:57 +01:00
|
|
|
where
|
[multistream-select] Reduce roundtrips in protocol negotiation. (#1212)
* Remove tokio-codec dependency from multistream-select.
In preparation for the eventual switch from tokio to std futures.
Includes some initial refactoring in preparation for further work
in the context of https://github.com/libp2p/rust-libp2p/issues/659.
* Reduce default buffer sizes.
* Allow more than one frame to be buffered for sending.
* Doc tweaks.
* Remove superfluous (duplicated) Message types.
* Reduce roundtrips in multistream-select negotiation.
1. Enable 0-RTT: If the dialer only supports a single protocol, it can send
protocol data (e.g. the actual application request) together with
the multistream-select header and protocol proposal. Similarly,
if the listener supports a proposed protocol, it can send protocol
data (e.g. the actual application response) together with the
multistream-select header and protocol confirmation.
2. In general, the dialer "settles on" an expected protocol as soon
as it runs out of alternatives. Furthermore, both dialer and listener
do not immediately flush the final protocol confirmation, allowing it
to be sent together with application protocol data. Attempts to read
from the negotiated I/O stream implicitly flushes any pending data.
3. A clean / graceful shutdown of an I/O stream always completes protocol
negotiation.
The publich API of multistream-select changed slightly, requiring both
AsyncRead and AsyncWrite bounds for async reading and writing due to
the implicit buffering and "lazy" negotiation. The error types have
also been changed, but they were not previously fully exported.
Includes some general refactoring with simplifications and some more tests,
e.g. there was an edge case relating to a possible ambiguity when parsing
multistream-select protocol messages.
* Further missing commentary.
* Remove unused test dependency.
* Adjust commentary.
* Cleanup NegotiatedComplete::poll()
* Fix deflate protocol tests.
* Stabilise network_simult test.
The test implicitly relied on "slow" connection establishment
in order to have a sufficient probability of passing.
With the removal of roundtrips in multistream-select, it is now
more likely that within the up to 50ms duration between swarm1
and swarm2 dialing, the connection is already established, causing
the expectation of step == 1 to fail when receiving a Connected event,
since the step may then still be 0.
This commit aims to avoid these spurious errors by detecting runs
during which a connection is established "too quickly", repeating
the test run.
It still seems theoretically possible that, if connections are always
established "too quickly", the test runs forever. However, given that
the delta between swarm1 and swarm2 dialing is 0-50ms and that the
TCP transport is used, that seems probabilistically unlikely.
Nevertheless, the purpose of the artificial dialing delay between
swarm1 and swarm2 should be re-evaluated and possibly at least
the maximum delay further reduced.
* Complete negotiation between upgrades in libp2p-core.
While multistream-select, as a standalone library and providing
an API at the granularity of a single negotiation, supports
lazy negotiation (and in particular 0-RTT negotiation), in the
context of libp2p-core where any number of negotiations are
composed generically within the concept of composable "upgrades",
it is necessary to wait for protocol negotiation between upgrades
to complete.
* Clarify docs. Simplify listener upgrades.
Since reading from a Negotiated I/O stream implicitly flushes any pending
negotiation data, there is no pitfall involved in not waiting for completion.
2019-08-12 12:09:53 +02:00
|
|
|
TSocket: AsyncRead + AsyncWrite,
|
2018-11-13 14:46:57 +01:00
|
|
|
{
|
2019-01-22 14:45:03 +01:00
|
|
|
type Output = FloodsubRpc;
|
2019-01-29 16:20:14 +01:00
|
|
|
type Error = FloodsubDecodeError;
|
2019-03-19 17:27:30 +01:00
|
|
|
type Future = upgrade::ReadOneThen<upgrade::Negotiated<TSocket>, (), fn(Vec<u8>, ()) -> Result<FloodsubRpc, FloodsubDecodeError>>;
|
2018-11-13 14:46:57 +01:00
|
|
|
|
|
|
|
#[inline]
|
2019-03-19 17:27:30 +01:00
|
|
|
fn upgrade_inbound(self, socket: upgrade::Negotiated<TSocket>, _: Self::Info) -> Self::Future {
|
2019-02-14 11:00:46 +01:00
|
|
|
upgrade::read_one_then(socket, 2048, (), |packet, ()| {
|
2019-01-29 16:20:14 +01:00
|
|
|
let mut rpc: rpc_proto::RPC = protobuf::parse_from_bytes(&packet)?;
|
|
|
|
|
|
|
|
let mut messages = Vec::with_capacity(rpc.get_publish().len());
|
|
|
|
for mut publish in rpc.take_publish().into_iter() {
|
|
|
|
messages.push(FloodsubMessage {
|
|
|
|
source: PeerId::from_bytes(publish.take_from()).map_err(|_| {
|
|
|
|
FloodsubDecodeError::InvalidPeerId
|
|
|
|
})?,
|
|
|
|
data: publish.take_data(),
|
|
|
|
sequence_number: publish.take_seqno(),
|
|
|
|
topics: publish
|
|
|
|
.take_topicIDs()
|
|
|
|
.into_iter()
|
|
|
|
.map(TopicHash::from_raw)
|
|
|
|
.collect(),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(FloodsubRpc {
|
|
|
|
messages,
|
|
|
|
subscriptions: rpc
|
|
|
|
.take_subscriptions()
|
|
|
|
.into_iter()
|
|
|
|
.map(|mut sub| FloodsubSubscription {
|
|
|
|
action: if sub.get_subscribe() {
|
|
|
|
FloodsubSubscriptionAction::Subscribe
|
|
|
|
} else {
|
|
|
|
FloodsubSubscriptionAction::Unsubscribe
|
|
|
|
},
|
|
|
|
topic: TopicHash::from_raw(sub.take_topicid()),
|
|
|
|
})
|
|
|
|
.collect(),
|
2019-01-22 14:45:03 +01:00
|
|
|
})
|
2019-01-29 16:20:14 +01:00
|
|
|
})
|
2018-11-13 14:46:57 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-29 16:20:14 +01:00
|
|
|
/// Reach attempt interrupt errors.
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum FloodsubDecodeError {
|
|
|
|
/// Error when reading the packet from the socket.
|
|
|
|
ReadError(upgrade::ReadOneError),
|
|
|
|
/// Error when decoding the raw buffer into a protobuf.
|
|
|
|
ProtobufError(ProtobufError),
|
|
|
|
/// Error when parsing the `PeerId` in the message.
|
|
|
|
InvalidPeerId,
|
2018-11-13 14:46:57 +01:00
|
|
|
}
|
|
|
|
|
2019-01-29 16:20:14 +01:00
|
|
|
impl From<upgrade::ReadOneError> for FloodsubDecodeError {
|
|
|
|
#[inline]
|
|
|
|
fn from(err: upgrade::ReadOneError) -> Self {
|
|
|
|
FloodsubDecodeError::ReadError(err)
|
|
|
|
}
|
|
|
|
}
|
2018-11-13 14:46:57 +01:00
|
|
|
|
2019-01-29 16:20:14 +01:00
|
|
|
impl From<ProtobufError> for FloodsubDecodeError {
|
|
|
|
#[inline]
|
|
|
|
fn from(err: ProtobufError) -> Self {
|
|
|
|
FloodsubDecodeError::ProtobufError(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for FloodsubDecodeError {
|
2019-02-11 14:58:15 +01:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2019-01-29 16:20:14 +01:00
|
|
|
match *self {
|
|
|
|
FloodsubDecodeError::ReadError(ref err) =>
|
|
|
|
write!(f, "Error while reading from socket: {}", err),
|
|
|
|
FloodsubDecodeError::ProtobufError(ref err) =>
|
|
|
|
write!(f, "Error while decoding protobuf: {}", err),
|
|
|
|
FloodsubDecodeError::InvalidPeerId =>
|
|
|
|
write!(f, "Error while decoding PeerId from message"),
|
2018-11-13 14:46:57 +01:00
|
|
|
}
|
2019-01-29 16:20:14 +01:00
|
|
|
}
|
|
|
|
}
|
2018-11-13 14:46:57 +01:00
|
|
|
|
2019-01-29 16:20:14 +01:00
|
|
|
impl error::Error for FloodsubDecodeError {
|
|
|
|
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
|
|
|
|
match *self {
|
|
|
|
FloodsubDecodeError::ReadError(ref err) => Some(err),
|
|
|
|
FloodsubDecodeError::ProtobufError(ref err) => Some(err),
|
|
|
|
FloodsubDecodeError::InvalidPeerId => None,
|
|
|
|
}
|
2018-11-13 14:46:57 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// An RPC received by the floodsub system.
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
|
|
pub struct FloodsubRpc {
|
|
|
|
/// List of messages that were part of this RPC query.
|
|
|
|
pub messages: Vec<FloodsubMessage>,
|
|
|
|
/// List of subscriptions.
|
|
|
|
pub subscriptions: Vec<FloodsubSubscription>,
|
|
|
|
}
|
|
|
|
|
2019-01-22 14:45:03 +01:00
|
|
|
impl UpgradeInfo for FloodsubRpc {
|
|
|
|
type Info = &'static [u8];
|
|
|
|
type InfoIter = iter::Once<Self::Info>;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn protocol_info(&self) -> Self::InfoIter {
|
|
|
|
iter::once(b"/floodsub/1.0.0")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<TSocket> OutboundUpgrade<TSocket> for FloodsubRpc
|
|
|
|
where
|
[multistream-select] Reduce roundtrips in protocol negotiation. (#1212)
* Remove tokio-codec dependency from multistream-select.
In preparation for the eventual switch from tokio to std futures.
Includes some initial refactoring in preparation for further work
in the context of https://github.com/libp2p/rust-libp2p/issues/659.
* Reduce default buffer sizes.
* Allow more than one frame to be buffered for sending.
* Doc tweaks.
* Remove superfluous (duplicated) Message types.
* Reduce roundtrips in multistream-select negotiation.
1. Enable 0-RTT: If the dialer only supports a single protocol, it can send
protocol data (e.g. the actual application request) together with
the multistream-select header and protocol proposal. Similarly,
if the listener supports a proposed protocol, it can send protocol
data (e.g. the actual application response) together with the
multistream-select header and protocol confirmation.
2. In general, the dialer "settles on" an expected protocol as soon
as it runs out of alternatives. Furthermore, both dialer and listener
do not immediately flush the final protocol confirmation, allowing it
to be sent together with application protocol data. Attempts to read
from the negotiated I/O stream implicitly flushes any pending data.
3. A clean / graceful shutdown of an I/O stream always completes protocol
negotiation.
The publich API of multistream-select changed slightly, requiring both
AsyncRead and AsyncWrite bounds for async reading and writing due to
the implicit buffering and "lazy" negotiation. The error types have
also been changed, but they were not previously fully exported.
Includes some general refactoring with simplifications and some more tests,
e.g. there was an edge case relating to a possible ambiguity when parsing
multistream-select protocol messages.
* Further missing commentary.
* Remove unused test dependency.
* Adjust commentary.
* Cleanup NegotiatedComplete::poll()
* Fix deflate protocol tests.
* Stabilise network_simult test.
The test implicitly relied on "slow" connection establishment
in order to have a sufficient probability of passing.
With the removal of roundtrips in multistream-select, it is now
more likely that within the up to 50ms duration between swarm1
and swarm2 dialing, the connection is already established, causing
the expectation of step == 1 to fail when receiving a Connected event,
since the step may then still be 0.
This commit aims to avoid these spurious errors by detecting runs
during which a connection is established "too quickly", repeating
the test run.
It still seems theoretically possible that, if connections are always
established "too quickly", the test runs forever. However, given that
the delta between swarm1 and swarm2 dialing is 0-50ms and that the
TCP transport is used, that seems probabilistically unlikely.
Nevertheless, the purpose of the artificial dialing delay between
swarm1 and swarm2 should be re-evaluated and possibly at least
the maximum delay further reduced.
* Complete negotiation between upgrades in libp2p-core.
While multistream-select, as a standalone library and providing
an API at the granularity of a single negotiation, supports
lazy negotiation (and in particular 0-RTT negotiation), in the
context of libp2p-core where any number of negotiations are
composed generically within the concept of composable "upgrades",
it is necessary to wait for protocol negotiation between upgrades
to complete.
* Clarify docs. Simplify listener upgrades.
Since reading from a Negotiated I/O stream implicitly flushes any pending
negotiation data, there is no pitfall involved in not waiting for completion.
2019-08-12 12:09:53 +02:00
|
|
|
TSocket: AsyncWrite + AsyncRead,
|
2019-01-22 14:45:03 +01:00
|
|
|
{
|
|
|
|
type Output = ();
|
|
|
|
type Error = io::Error;
|
2019-03-19 17:27:30 +01:00
|
|
|
type Future = upgrade::WriteOne<upgrade::Negotiated<TSocket>>;
|
2019-01-22 14:45:03 +01:00
|
|
|
|
|
|
|
#[inline]
|
2019-03-19 17:27:30 +01:00
|
|
|
fn upgrade_outbound(self, socket: upgrade::Negotiated<TSocket>, _: Self::Info) -> Self::Future {
|
2019-01-29 16:20:14 +01:00
|
|
|
let bytes = self.into_bytes();
|
|
|
|
upgrade::write_one(socket, bytes)
|
2019-01-22 14:45:03 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FloodsubRpc {
|
|
|
|
/// Turns this `FloodsubRpc` into a message that can be sent to a substream.
|
2019-01-29 16:20:14 +01:00
|
|
|
fn into_bytes(self) -> Vec<u8> {
|
2019-01-22 14:45:03 +01:00
|
|
|
let mut proto = rpc_proto::RPC::new();
|
|
|
|
|
|
|
|
for message in self.messages {
|
|
|
|
let mut msg = rpc_proto::Message::new();
|
|
|
|
msg.set_from(message.source.into_bytes());
|
|
|
|
msg.set_data(message.data);
|
|
|
|
msg.set_seqno(message.sequence_number);
|
|
|
|
msg.set_topicIDs(
|
|
|
|
message
|
|
|
|
.topics
|
|
|
|
.into_iter()
|
|
|
|
.map(TopicHash::into_string)
|
|
|
|
.collect(),
|
|
|
|
);
|
|
|
|
proto.mut_publish().push(msg);
|
|
|
|
}
|
|
|
|
|
|
|
|
for topic in self.subscriptions {
|
|
|
|
let mut subscription = rpc_proto::RPC_SubOpts::new();
|
|
|
|
subscription.set_subscribe(topic.action == FloodsubSubscriptionAction::Subscribe);
|
|
|
|
subscription.set_topicid(topic.topic.into_string());
|
|
|
|
proto.mut_subscriptions().push(subscription);
|
|
|
|
}
|
|
|
|
|
|
|
|
proto
|
2019-01-29 16:20:14 +01:00
|
|
|
.write_to_bytes()
|
2019-01-22 14:45:03 +01:00
|
|
|
.expect("there is no situation in which the protobuf message can be invalid")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-13 14:46:57 +01:00
|
|
|
/// A message received by the floodsub system.
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
|
|
pub struct FloodsubMessage {
|
|
|
|
/// Id of the peer that published this message.
|
|
|
|
pub source: PeerId,
|
|
|
|
|
|
|
|
/// Content of the message. Its meaning is out of scope of this library.
|
|
|
|
pub data: Vec<u8>,
|
|
|
|
|
|
|
|
/// An incrementing sequence number.
|
|
|
|
pub sequence_number: Vec<u8>,
|
|
|
|
|
|
|
|
/// List of topics this message belongs to.
|
|
|
|
///
|
|
|
|
/// Each message can belong to multiple topics at once.
|
|
|
|
pub topics: Vec<TopicHash>,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A subscription received by the floodsub system.
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
|
|
pub struct FloodsubSubscription {
|
|
|
|
/// Action to perform.
|
|
|
|
pub action: FloodsubSubscriptionAction,
|
|
|
|
/// The topic from which to subscribe or unsubscribe.
|
|
|
|
pub topic: TopicHash,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Action that a subscription wants to perform.
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
|
|
pub enum FloodsubSubscriptionAction {
|
|
|
|
/// The remote wants to subscribe to the given topic.
|
|
|
|
Subscribe,
|
|
|
|
/// The remote wants to unsubscribe from the given topic.
|
|
|
|
Unsubscribe,
|
|
|
|
}
|