2020-06-29 17:08:40 +02:00
|
|
|
// Copyright 2020 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.
|
|
|
|
|
|
|
|
//! Integration tests for the `RequestResponse` network behaviour.
|
|
|
|
|
|
|
|
use async_trait::async_trait;
|
|
|
|
use libp2p_core::{
|
|
|
|
Multiaddr,
|
|
|
|
PeerId,
|
|
|
|
identity,
|
|
|
|
muxing::StreamMuxerBox,
|
2020-10-07 11:10:54 +02:00
|
|
|
transport::{self, Transport},
|
2020-06-29 17:08:40 +02:00
|
|
|
upgrade::{self, read_one, write_one}
|
|
|
|
};
|
|
|
|
use libp2p_noise::{NoiseConfig, X25519Spec, Keypair};
|
|
|
|
use libp2p_request_response::*;
|
2021-01-12 13:35:11 +01:00
|
|
|
use libp2p_swarm::{Swarm, SwarmEvent};
|
2020-06-29 17:08:40 +02:00
|
|
|
use libp2p_tcp::TcpConfig;
|
2020-12-16 16:03:35 +01:00
|
|
|
use futures::{prelude::*, channel::mpsc, executor::LocalPool, task::SpawnExt};
|
2020-06-29 17:08:40 +02:00
|
|
|
use rand::{self, Rng};
|
2020-08-18 14:29:38 +02:00
|
|
|
use std::{io, iter};
|
2020-09-07 17:22:40 +02:00
|
|
|
use std::{collections::HashSet, num::NonZeroU16};
|
2020-06-29 17:08:40 +02:00
|
|
|
|
|
|
|
/// Exercises a simple ping protocol.
|
|
|
|
#[test]
|
|
|
|
fn ping_protocol() {
|
|
|
|
let ping = Ping("ping".to_string().into_bytes());
|
|
|
|
let pong = Pong("pong".to_string().into_bytes());
|
|
|
|
|
|
|
|
let protocols = iter::once((PingProtocol(), ProtocolSupport::Full));
|
|
|
|
let cfg = RequestResponseConfig::default();
|
|
|
|
|
|
|
|
let (peer1_id, trans) = mk_transport();
|
|
|
|
let ping_proto1 = RequestResponse::new(PingCodec(), protocols.clone(), cfg.clone());
|
|
|
|
let mut swarm1 = Swarm::new(trans, ping_proto1, peer1_id.clone());
|
|
|
|
|
|
|
|
let (peer2_id, trans) = mk_transport();
|
|
|
|
let ping_proto2 = RequestResponse::new(PingCodec(), protocols, cfg);
|
|
|
|
let mut swarm2 = Swarm::new(trans, ping_proto2, peer2_id.clone());
|
|
|
|
|
|
|
|
let (mut tx, mut rx) = mpsc::channel::<Multiaddr>(1);
|
|
|
|
|
|
|
|
let addr = "/ip4/127.0.0.1/tcp/0".parse().unwrap();
|
|
|
|
Swarm::listen_on(&mut swarm1, addr).unwrap();
|
|
|
|
|
|
|
|
let expected_ping = ping.clone();
|
|
|
|
let expected_pong = pong.clone();
|
|
|
|
|
|
|
|
let peer1 = async move {
|
|
|
|
loop {
|
2021-01-12 13:35:11 +01:00
|
|
|
match swarm1.next_event().await {
|
|
|
|
SwarmEvent::NewListenAddr(addr) => tx.send(addr).await.unwrap(),
|
|
|
|
SwarmEvent::Behaviour(RequestResponseEvent::Message {
|
2020-06-29 17:08:40 +02:00
|
|
|
peer,
|
2020-09-07 17:22:40 +02:00
|
|
|
message: RequestResponseMessage::Request { request, channel, .. }
|
2021-01-12 13:35:11 +01:00
|
|
|
}) => {
|
2020-06-29 17:08:40 +02:00
|
|
|
assert_eq!(&request, &expected_ping);
|
|
|
|
assert_eq!(&peer, &peer2_id);
|
[request-response] Refine success & error reporting for inbound requests. (#1867)
* Refine error reporting for inbound request handling.
At the moment one can neither get confirmation when a
response has been sent on the underlying transport, nor
is one aware of response omissions. The latter was
originally intended as a feature for support of
one-way protocols, which seems like a bad idea in
hindsight. The lack of notification for sent
responses may prohibit implementation of some
request-response protocols that need to ensure
a happens-before relation between sending a
response and a subsequent request, besides uses
for collecting statistics.
Even with these changes, there is no active notification
for failed inbound requests as a result of connections
unexpectedly closing, as is the case for outbound requests.
Instead, for pending inbound requests this scenario
can be identified if necessary by the absense of both
`InboundFailure` and `ResponseSent` events for a particular
previously received request. Interest in this situation is
not expected to be common and would otherwise require
explicitly tracking all inbound requests in the `RequestResponse`
behaviour, which would be a pity. `RequestResponse::send_response`
now also synchronously returns an error if the inbound upgrade
handling the request has been aborted, due to timeout or
closing of the connection, giving more options for graceful
error handling for inbound requests.
As an aside, the `Throttled` wrapper now no longer emits
inbound or outbound error events occurring in the context
of sending credit requests or responses. This is in addition
to not emitting `ResponseSent` events for ACK responses of
credit grants.
* Update protocols/request-response/src/lib.rs
Co-authored-by: Max Inden <mail@max-inden.de>
* Address some minor clippy warnings. (#1868)
* Track pending credit request IDs.
In order to avoid emitting events relating to credit grants or acks
on the public API. The public API should only emit events relating
to the actual requests and responses sent by client code.
* Small cleanup
* Cleanup
* Update versions and changelogs.
* Unreleased
Co-authored-by: Max Inden <mail@max-inden.de>
2020-12-07 13:07:47 +01:00
|
|
|
swarm1.send_response(channel, pong.clone()).unwrap();
|
2020-06-29 17:08:40 +02:00
|
|
|
},
|
2021-01-12 13:35:11 +01:00
|
|
|
SwarmEvent::Behaviour(RequestResponseEvent::ResponseSent {
|
[request-response] Refine success & error reporting for inbound requests. (#1867)
* Refine error reporting for inbound request handling.
At the moment one can neither get confirmation when a
response has been sent on the underlying transport, nor
is one aware of response omissions. The latter was
originally intended as a feature for support of
one-way protocols, which seems like a bad idea in
hindsight. The lack of notification for sent
responses may prohibit implementation of some
request-response protocols that need to ensure
a happens-before relation between sending a
response and a subsequent request, besides uses
for collecting statistics.
Even with these changes, there is no active notification
for failed inbound requests as a result of connections
unexpectedly closing, as is the case for outbound requests.
Instead, for pending inbound requests this scenario
can be identified if necessary by the absense of both
`InboundFailure` and `ResponseSent` events for a particular
previously received request. Interest in this situation is
not expected to be common and would otherwise require
explicitly tracking all inbound requests in the `RequestResponse`
behaviour, which would be a pity. `RequestResponse::send_response`
now also synchronously returns an error if the inbound upgrade
handling the request has been aborted, due to timeout or
closing of the connection, giving more options for graceful
error handling for inbound requests.
As an aside, the `Throttled` wrapper now no longer emits
inbound or outbound error events occurring in the context
of sending credit requests or responses. This is in addition
to not emitting `ResponseSent` events for ACK responses of
credit grants.
* Update protocols/request-response/src/lib.rs
Co-authored-by: Max Inden <mail@max-inden.de>
* Address some minor clippy warnings. (#1868)
* Track pending credit request IDs.
In order to avoid emitting events relating to credit grants or acks
on the public API. The public API should only emit events relating
to the actual requests and responses sent by client code.
* Small cleanup
* Cleanup
* Update versions and changelogs.
* Unreleased
Co-authored-by: Max Inden <mail@max-inden.de>
2020-12-07 13:07:47 +01:00
|
|
|
peer, ..
|
2021-01-12 13:35:11 +01:00
|
|
|
}) => {
|
[request-response] Refine success & error reporting for inbound requests. (#1867)
* Refine error reporting for inbound request handling.
At the moment one can neither get confirmation when a
response has been sent on the underlying transport, nor
is one aware of response omissions. The latter was
originally intended as a feature for support of
one-way protocols, which seems like a bad idea in
hindsight. The lack of notification for sent
responses may prohibit implementation of some
request-response protocols that need to ensure
a happens-before relation between sending a
response and a subsequent request, besides uses
for collecting statistics.
Even with these changes, there is no active notification
for failed inbound requests as a result of connections
unexpectedly closing, as is the case for outbound requests.
Instead, for pending inbound requests this scenario
can be identified if necessary by the absense of both
`InboundFailure` and `ResponseSent` events for a particular
previously received request. Interest in this situation is
not expected to be common and would otherwise require
explicitly tracking all inbound requests in the `RequestResponse`
behaviour, which would be a pity. `RequestResponse::send_response`
now also synchronously returns an error if the inbound upgrade
handling the request has been aborted, due to timeout or
closing of the connection, giving more options for graceful
error handling for inbound requests.
As an aside, the `Throttled` wrapper now no longer emits
inbound or outbound error events occurring in the context
of sending credit requests or responses. This is in addition
to not emitting `ResponseSent` events for ACK responses of
credit grants.
* Update protocols/request-response/src/lib.rs
Co-authored-by: Max Inden <mail@max-inden.de>
* Address some minor clippy warnings. (#1868)
* Track pending credit request IDs.
In order to avoid emitting events relating to credit grants or acks
on the public API. The public API should only emit events relating
to the actual requests and responses sent by client code.
* Small cleanup
* Cleanup
* Update versions and changelogs.
* Unreleased
Co-authored-by: Max Inden <mail@max-inden.de>
2020-12-07 13:07:47 +01:00
|
|
|
assert_eq!(&peer, &peer2_id);
|
|
|
|
}
|
2021-01-12 13:35:11 +01:00
|
|
|
SwarmEvent::Behaviour(e) => panic!("Peer1: Unexpected event: {:?}", e),
|
|
|
|
_ => {}
|
2020-06-29 17:08:40 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-08-12 16:04:54 +02:00
|
|
|
let num_pings: u8 = rand::thread_rng().gen_range(1, 100);
|
|
|
|
|
2020-06-29 17:08:40 +02:00
|
|
|
let peer2 = async move {
|
|
|
|
let mut count = 0;
|
|
|
|
let addr = rx.next().await.unwrap();
|
|
|
|
swarm2.add_address(&peer1_id, addr.clone());
|
|
|
|
let mut req_id = swarm2.send_request(&peer1_id, ping.clone());
|
|
|
|
|
|
|
|
loop {
|
|
|
|
match swarm2.next().await {
|
|
|
|
RequestResponseEvent::Message {
|
|
|
|
peer,
|
|
|
|
message: RequestResponseMessage::Response { request_id, response }
|
|
|
|
} => {
|
|
|
|
count += 1;
|
|
|
|
assert_eq!(&response, &expected_pong);
|
|
|
|
assert_eq!(&peer, &peer1_id);
|
|
|
|
assert_eq!(req_id, request_id);
|
|
|
|
if count >= num_pings {
|
|
|
|
return
|
|
|
|
} else {
|
|
|
|
req_id = swarm2.send_request(&peer1_id, ping.clone());
|
|
|
|
}
|
|
|
|
},
|
|
|
|
e => panic!("Peer2: Unexpected event: {:?}", e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
async_std::task::spawn(Box::pin(peer1));
|
|
|
|
let () = async_std::task::block_on(peer2);
|
|
|
|
}
|
|
|
|
|
2020-12-16 16:03:35 +01:00
|
|
|
#[test]
|
|
|
|
fn emits_inbound_connection_closed_failure() {
|
|
|
|
let ping = Ping("ping".to_string().into_bytes());
|
|
|
|
|
|
|
|
let protocols = iter::once((PingProtocol(), ProtocolSupport::Full));
|
|
|
|
let cfg = RequestResponseConfig::default();
|
|
|
|
|
|
|
|
let (peer1_id, trans) = mk_transport();
|
|
|
|
let ping_proto1 = RequestResponse::new(PingCodec(), protocols.clone(), cfg.clone());
|
|
|
|
let mut swarm1 = Swarm::new(trans, ping_proto1, peer1_id.clone());
|
|
|
|
|
|
|
|
let (peer2_id, trans) = mk_transport();
|
|
|
|
let ping_proto2 = RequestResponse::new(PingCodec(), protocols, cfg);
|
|
|
|
let mut swarm2 = Swarm::new(trans, ping_proto2, peer2_id.clone());
|
|
|
|
|
|
|
|
let addr = "/ip4/127.0.0.1/tcp/0".parse().unwrap();
|
|
|
|
Swarm::listen_on(&mut swarm1, addr).unwrap();
|
|
|
|
|
|
|
|
futures::executor::block_on(async move {
|
|
|
|
while let Some(_) = swarm1.next().now_or_never() {}
|
|
|
|
let addr1 = Swarm::listeners(&swarm1).next().unwrap();
|
|
|
|
|
|
|
|
swarm2.add_address(&peer1_id, addr1.clone());
|
|
|
|
swarm2.send_request(&peer1_id, ping.clone());
|
|
|
|
|
|
|
|
// Wait for swarm 1 to receive request by swarm 2.
|
|
|
|
let _channel = loop {
|
|
|
|
futures::select!(
|
|
|
|
event = swarm1.next().fuse() => match event {
|
|
|
|
RequestResponseEvent::Message {
|
|
|
|
peer,
|
|
|
|
message: RequestResponseMessage::Request { request, channel, .. }
|
|
|
|
} => {
|
|
|
|
assert_eq!(&request, &ping);
|
|
|
|
assert_eq!(&peer, &peer2_id);
|
|
|
|
break channel;
|
|
|
|
},
|
|
|
|
e => panic!("Peer1: Unexpected event: {:?}", e)
|
|
|
|
},
|
|
|
|
event = swarm2.next().fuse() => panic!("Peer2: Unexpected event: {:?}", event),
|
|
|
|
)
|
|
|
|
};
|
|
|
|
|
|
|
|
// Drop swarm 2 in order for the connection between swarm 1 and 2 to close.
|
|
|
|
drop(swarm2);
|
|
|
|
|
|
|
|
match swarm1.next().await {
|
|
|
|
RequestResponseEvent::InboundFailure { error: InboundFailure::ConnectionClosed, ..} => {},
|
|
|
|
e => panic!("Peer1: Unexpected event: {:?}", e)
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-09-07 17:22:40 +02:00
|
|
|
#[test]
|
|
|
|
fn ping_protocol_throttled() {
|
|
|
|
let ping = Ping("ping".to_string().into_bytes());
|
|
|
|
let pong = Pong("pong".to_string().into_bytes());
|
|
|
|
|
|
|
|
let protocols = iter::once((PingProtocol(), ProtocolSupport::Full));
|
|
|
|
let cfg = RequestResponseConfig::default();
|
|
|
|
|
|
|
|
let (peer1_id, trans) = mk_transport();
|
|
|
|
let ping_proto1 = RequestResponse::throttled(PingCodec(), protocols.clone(), cfg.clone());
|
|
|
|
let mut swarm1 = Swarm::new(trans, ping_proto1, peer1_id.clone());
|
|
|
|
|
|
|
|
let (peer2_id, trans) = mk_transport();
|
|
|
|
let ping_proto2 = RequestResponse::throttled(PingCodec(), protocols, cfg);
|
|
|
|
let mut swarm2 = Swarm::new(trans, ping_proto2, peer2_id.clone());
|
|
|
|
|
|
|
|
let (mut tx, mut rx) = mpsc::channel::<Multiaddr>(1);
|
|
|
|
|
|
|
|
let addr = "/ip4/127.0.0.1/tcp/0".parse().unwrap();
|
|
|
|
Swarm::listen_on(&mut swarm1, addr).unwrap();
|
|
|
|
|
|
|
|
let expected_ping = ping.clone();
|
|
|
|
let expected_pong = pong.clone();
|
|
|
|
|
|
|
|
let limit1: u16 = rand::thread_rng().gen_range(1, 10);
|
|
|
|
let limit2: u16 = rand::thread_rng().gen_range(1, 10);
|
|
|
|
swarm1.set_receive_limit(NonZeroU16::new(limit1).unwrap());
|
|
|
|
swarm2.set_receive_limit(NonZeroU16::new(limit2).unwrap());
|
|
|
|
|
|
|
|
let peer1 = async move {
|
2020-09-09 11:04:20 +02:00
|
|
|
for i in 1 .. {
|
2021-01-12 13:35:11 +01:00
|
|
|
match swarm1.next_event().await {
|
|
|
|
SwarmEvent::NewListenAddr(addr) => tx.send(addr).await.unwrap(),
|
|
|
|
SwarmEvent::Behaviour(throttled::Event::Event(RequestResponseEvent::Message {
|
2020-09-07 17:22:40 +02:00
|
|
|
peer,
|
|
|
|
message: RequestResponseMessage::Request { request, channel, .. },
|
2021-01-12 13:35:11 +01:00
|
|
|
})) => {
|
2020-09-07 17:22:40 +02:00
|
|
|
assert_eq!(&request, &expected_ping);
|
|
|
|
assert_eq!(&peer, &peer2_id);
|
[request-response] Refine success & error reporting for inbound requests. (#1867)
* Refine error reporting for inbound request handling.
At the moment one can neither get confirmation when a
response has been sent on the underlying transport, nor
is one aware of response omissions. The latter was
originally intended as a feature for support of
one-way protocols, which seems like a bad idea in
hindsight. The lack of notification for sent
responses may prohibit implementation of some
request-response protocols that need to ensure
a happens-before relation between sending a
response and a subsequent request, besides uses
for collecting statistics.
Even with these changes, there is no active notification
for failed inbound requests as a result of connections
unexpectedly closing, as is the case for outbound requests.
Instead, for pending inbound requests this scenario
can be identified if necessary by the absense of both
`InboundFailure` and `ResponseSent` events for a particular
previously received request. Interest in this situation is
not expected to be common and would otherwise require
explicitly tracking all inbound requests in the `RequestResponse`
behaviour, which would be a pity. `RequestResponse::send_response`
now also synchronously returns an error if the inbound upgrade
handling the request has been aborted, due to timeout or
closing of the connection, giving more options for graceful
error handling for inbound requests.
As an aside, the `Throttled` wrapper now no longer emits
inbound or outbound error events occurring in the context
of sending credit requests or responses. This is in addition
to not emitting `ResponseSent` events for ACK responses of
credit grants.
* Update protocols/request-response/src/lib.rs
Co-authored-by: Max Inden <mail@max-inden.de>
* Address some minor clippy warnings. (#1868)
* Track pending credit request IDs.
In order to avoid emitting events relating to credit grants or acks
on the public API. The public API should only emit events relating
to the actual requests and responses sent by client code.
* Small cleanup
* Cleanup
* Update versions and changelogs.
* Unreleased
Co-authored-by: Max Inden <mail@max-inden.de>
2020-12-07 13:07:47 +01:00
|
|
|
swarm1.send_response(channel, pong.clone()).unwrap();
|
2020-09-07 17:22:40 +02:00
|
|
|
},
|
2021-01-12 13:35:11 +01:00
|
|
|
SwarmEvent::Behaviour(throttled::Event::Event(RequestResponseEvent::ResponseSent {
|
[request-response] Refine success & error reporting for inbound requests. (#1867)
* Refine error reporting for inbound request handling.
At the moment one can neither get confirmation when a
response has been sent on the underlying transport, nor
is one aware of response omissions. The latter was
originally intended as a feature for support of
one-way protocols, which seems like a bad idea in
hindsight. The lack of notification for sent
responses may prohibit implementation of some
request-response protocols that need to ensure
a happens-before relation between sending a
response and a subsequent request, besides uses
for collecting statistics.
Even with these changes, there is no active notification
for failed inbound requests as a result of connections
unexpectedly closing, as is the case for outbound requests.
Instead, for pending inbound requests this scenario
can be identified if necessary by the absense of both
`InboundFailure` and `ResponseSent` events for a particular
previously received request. Interest in this situation is
not expected to be common and would otherwise require
explicitly tracking all inbound requests in the `RequestResponse`
behaviour, which would be a pity. `RequestResponse::send_response`
now also synchronously returns an error if the inbound upgrade
handling the request has been aborted, due to timeout or
closing of the connection, giving more options for graceful
error handling for inbound requests.
As an aside, the `Throttled` wrapper now no longer emits
inbound or outbound error events occurring in the context
of sending credit requests or responses. This is in addition
to not emitting `ResponseSent` events for ACK responses of
credit grants.
* Update protocols/request-response/src/lib.rs
Co-authored-by: Max Inden <mail@max-inden.de>
* Address some minor clippy warnings. (#1868)
* Track pending credit request IDs.
In order to avoid emitting events relating to credit grants or acks
on the public API. The public API should only emit events relating
to the actual requests and responses sent by client code.
* Small cleanup
* Cleanup
* Update versions and changelogs.
* Unreleased
Co-authored-by: Max Inden <mail@max-inden.de>
2020-12-07 13:07:47 +01:00
|
|
|
peer, ..
|
2021-01-12 13:35:11 +01:00
|
|
|
})) => {
|
[request-response] Refine success & error reporting for inbound requests. (#1867)
* Refine error reporting for inbound request handling.
At the moment one can neither get confirmation when a
response has been sent on the underlying transport, nor
is one aware of response omissions. The latter was
originally intended as a feature for support of
one-way protocols, which seems like a bad idea in
hindsight. The lack of notification for sent
responses may prohibit implementation of some
request-response protocols that need to ensure
a happens-before relation between sending a
response and a subsequent request, besides uses
for collecting statistics.
Even with these changes, there is no active notification
for failed inbound requests as a result of connections
unexpectedly closing, as is the case for outbound requests.
Instead, for pending inbound requests this scenario
can be identified if necessary by the absense of both
`InboundFailure` and `ResponseSent` events for a particular
previously received request. Interest in this situation is
not expected to be common and would otherwise require
explicitly tracking all inbound requests in the `RequestResponse`
behaviour, which would be a pity. `RequestResponse::send_response`
now also synchronously returns an error if the inbound upgrade
handling the request has been aborted, due to timeout or
closing of the connection, giving more options for graceful
error handling for inbound requests.
As an aside, the `Throttled` wrapper now no longer emits
inbound or outbound error events occurring in the context
of sending credit requests or responses. This is in addition
to not emitting `ResponseSent` events for ACK responses of
credit grants.
* Update protocols/request-response/src/lib.rs
Co-authored-by: Max Inden <mail@max-inden.de>
* Address some minor clippy warnings. (#1868)
* Track pending credit request IDs.
In order to avoid emitting events relating to credit grants or acks
on the public API. The public API should only emit events relating
to the actual requests and responses sent by client code.
* Small cleanup
* Cleanup
* Update versions and changelogs.
* Unreleased
Co-authored-by: Max Inden <mail@max-inden.de>
2020-12-07 13:07:47 +01:00
|
|
|
assert_eq!(&peer, &peer2_id);
|
|
|
|
}
|
2021-01-12 13:35:11 +01:00
|
|
|
SwarmEvent::Behaviour(e) => panic!("Peer1: Unexpected event: {:?}", e),
|
|
|
|
_ => {}
|
2020-09-07 17:22:40 +02:00
|
|
|
}
|
|
|
|
if i % 31 == 0 {
|
|
|
|
let lim = rand::thread_rng().gen_range(1, 17);
|
|
|
|
swarm1.override_receive_limit(&peer2_id, NonZeroU16::new(lim).unwrap());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let num_pings: u16 = rand::thread_rng().gen_range(100, 1000);
|
|
|
|
|
|
|
|
let peer2 = async move {
|
|
|
|
let mut count = 0;
|
|
|
|
let addr = rx.next().await.unwrap();
|
|
|
|
swarm2.add_address(&peer1_id, addr.clone());
|
|
|
|
|
|
|
|
let mut blocked = false;
|
|
|
|
let mut req_ids = HashSet::new();
|
|
|
|
|
|
|
|
loop {
|
|
|
|
if !blocked {
|
|
|
|
while let Some(id) = swarm2.send_request(&peer1_id, ping.clone()).ok() {
|
|
|
|
req_ids.insert(id);
|
|
|
|
}
|
|
|
|
blocked = true;
|
|
|
|
}
|
|
|
|
match swarm2.next().await {
|
|
|
|
throttled::Event::ResumeSending(peer) => {
|
|
|
|
assert_eq!(peer, peer1_id);
|
|
|
|
blocked = false
|
|
|
|
}
|
|
|
|
throttled::Event::Event(RequestResponseEvent::Message {
|
|
|
|
peer,
|
|
|
|
message: RequestResponseMessage::Response { request_id, response }
|
|
|
|
}) => {
|
|
|
|
count += 1;
|
|
|
|
assert_eq!(&response, &expected_pong);
|
|
|
|
assert_eq!(&peer, &peer1_id);
|
|
|
|
assert!(req_ids.remove(&request_id));
|
|
|
|
if count >= num_pings {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
e => panic!("Peer2: Unexpected event: {:?}", e)
|
2020-12-16 16:03:35 +01:00
|
|
|
|
2020-09-07 17:22:40 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-12-16 16:03:35 +01:00
|
|
|
let mut pool = LocalPool::new();
|
|
|
|
pool.spawner().spawn(peer1.boxed()).unwrap();
|
|
|
|
pool.run_until(peer2);
|
2020-09-07 17:22:40 +02:00
|
|
|
}
|
2020-08-12 16:04:54 +02:00
|
|
|
|
2020-10-16 16:53:02 +02:00
|
|
|
fn mk_transport() -> (PeerId, transport::Boxed<(PeerId, StreamMuxerBox)>) {
|
2020-06-29 17:08:40 +02:00
|
|
|
let id_keys = identity::Keypair::generate_ed25519();
|
|
|
|
let peer_id = id_keys.public().into_peer_id();
|
|
|
|
let noise_keys = Keypair::<X25519Spec>::new().into_authentic(&id_keys).unwrap();
|
2020-10-07 11:10:54 +02:00
|
|
|
(peer_id, TcpConfig::new()
|
2020-06-29 17:08:40 +02:00
|
|
|
.nodelay(true)
|
|
|
|
.upgrade(upgrade::Version::V1)
|
|
|
|
.authenticate(NoiseConfig::xx(noise_keys).into_authenticated())
|
2020-11-06 09:46:22 +01:00
|
|
|
.multiplex(libp2p_yamux::YamuxConfig::default())
|
2020-10-07 11:10:54 +02:00
|
|
|
.boxed())
|
2020-06-29 17:08:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Simple Ping-Pong Protocol
|
|
|
|
|
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
struct PingProtocol();
|
|
|
|
#[derive(Clone)]
|
|
|
|
struct PingCodec();
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
|
|
struct Ping(Vec<u8>);
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
|
|
struct Pong(Vec<u8>);
|
|
|
|
|
|
|
|
impl ProtocolName for PingProtocol {
|
|
|
|
fn protocol_name(&self) -> &[u8] {
|
|
|
|
"/ping/1".as_bytes()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[async_trait]
|
|
|
|
impl RequestResponseCodec for PingCodec {
|
|
|
|
type Protocol = PingProtocol;
|
|
|
|
type Request = Ping;
|
|
|
|
type Response = Pong;
|
|
|
|
|
|
|
|
async fn read_request<T>(&mut self, _: &PingProtocol, io: &mut T)
|
|
|
|
-> io::Result<Self::Request>
|
|
|
|
where
|
|
|
|
T: AsyncRead + Unpin + Send
|
|
|
|
{
|
|
|
|
read_one(io, 1024)
|
2020-08-13 12:49:16 +02:00
|
|
|
.map(|res| match res {
|
|
|
|
Err(e) => Err(io::Error::new(io::ErrorKind::InvalidData, e)),
|
|
|
|
Ok(vec) if vec.is_empty() => Err(io::ErrorKind::UnexpectedEof.into()),
|
|
|
|
Ok(vec) => Ok(Ping(vec))
|
|
|
|
})
|
2020-06-29 17:08:40 +02:00
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn read_response<T>(&mut self, _: &PingProtocol, io: &mut T)
|
|
|
|
-> io::Result<Self::Response>
|
|
|
|
where
|
|
|
|
T: AsyncRead + Unpin + Send
|
|
|
|
{
|
|
|
|
read_one(io, 1024)
|
2020-08-13 12:49:16 +02:00
|
|
|
.map(|res| match res {
|
|
|
|
Err(e) => Err(io::Error::new(io::ErrorKind::InvalidData, e)),
|
|
|
|
Ok(vec) if vec.is_empty() => Err(io::ErrorKind::UnexpectedEof.into()),
|
|
|
|
Ok(vec) => Ok(Pong(vec))
|
|
|
|
})
|
2020-06-29 17:08:40 +02:00
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn write_request<T>(&mut self, _: &PingProtocol, io: &mut T, Ping(data): Ping)
|
|
|
|
-> io::Result<()>
|
|
|
|
where
|
|
|
|
T: AsyncWrite + Unpin + Send
|
|
|
|
{
|
|
|
|
write_one(io, data).await
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn write_response<T>(&mut self, _: &PingProtocol, io: &mut T, Pong(data): Pong)
|
|
|
|
-> io::Result<()>
|
|
|
|
where
|
|
|
|
T: AsyncWrite + Unpin + Send
|
|
|
|
{
|
|
|
|
write_one(io, data).await
|
|
|
|
}
|
|
|
|
}
|