Rename RawSwarm* to Network*. (#1194)

* Rename RawSwarm* to Network*.

To complete the cut performed in [1].

The only remaining mention of a "swarm" in libp2p-core is in some tests
which actually depend on libp2p-swarm.

[1]: https://github.com/libp2p/rust-libp2p/pull/1188

* Post-merge corrections.
This commit is contained in:
Roman Borschel 2019-07-10 10:27:21 +02:00 committed by GitHub
parent ede114a13c
commit dfbf5b65c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 229 additions and 229 deletions

View File

@ -32,7 +32,7 @@ mod tests;
pub trait NodeHandler {
/// Custom event that can be received from the outside.
type InEvent;
/// Custom event that can be produced by the handler and that will be returned by the swarm.
/// Custom event that can be produced by the handler and that will be returned by the `Network`.
type OutEvent;
/// Error that can happen during the processing of the node.
type Error;

View File

@ -23,7 +23,7 @@
//! Contains structs that are aiming at providing very precise control over what happens over the
//! network.
//!
//! The more complete and highest-level struct is the `RawSwarm`. The `RawSwarm` directly or
//! The more complete and highest-level struct is the `Network`. The `Network` directly or
//! indirectly uses all the other structs of this module.
pub mod collection;
@ -31,9 +31,9 @@ pub mod handled_node;
pub mod tasks;
pub mod listeners;
pub mod node;
pub mod raw_swarm;
pub mod network;
pub use collection::ConnectionInfo;
pub use node::Substream;
pub use handled_node::{NodeHandlerEvent, NodeHandlerEndpoint};
pub use raw_swarm::{Peer, RawSwarm, RawSwarmEvent};
pub use network::{Peer, Network, NetworkEvent};

View File

@ -56,7 +56,7 @@ pub use crate::nodes::collection::StartTakeOver;
mod tests;
/// Implementation of `Stream` that handles the nodes.
pub struct RawSwarm<TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo = PeerId, TPeerId = PeerId>
pub struct Network<TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo = PeerId, TPeerId = PeerId>
where
TTrans: Transport,
{
@ -66,7 +66,7 @@ where
/// The nodes currently active.
active_nodes: CollectionStream<TInEvent, TOutEvent, THandler, InternalReachErr<TTrans::Error, TConnInfo>, THandlerErr, (), (TConnInfo, ConnectedPoint), TPeerId>,
/// The reach attempts of the swarm.
/// The reach attempts of the network.
/// This needs to be a separate struct in order to handle multiple mutable borrows issues.
reach_attempts: ReachAttempts<TPeerId>,
@ -85,7 +85,7 @@ where
}
impl<TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId> fmt::Debug for
RawSwarm<TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>
Network<TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>
where
TTrans: fmt::Debug + Transport,
TConnInfo: fmt::Debug,
@ -155,8 +155,8 @@ struct OutReachAttempt {
next_attempts: Vec<Multiaddr>,
}
/// Event that can happen on the `RawSwarm`.
pub enum RawSwarmEvent<'a, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo = PeerId, TPeerId = PeerId>
/// Event that can happen on the `Network`.
pub enum NetworkEvent<'a, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo = PeerId, TPeerId = PeerId>
where
TTrans: Transport,
{
@ -242,7 +242,7 @@ where
multiaddr: Multiaddr,
/// The error that happened.
error: RawSwarmReachError<TTrans::Error, TConnInfo>,
error: NetworkReachError<TTrans::Error, TConnInfo>,
},
/// Failed to reach a peer that we were trying to dial.
@ -267,7 +267,7 @@ where
}
impl<'a, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId> fmt::Debug for
RawSwarmEvent<'a, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>
NetworkEvent<'a, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>
where
TOutEvent: fmt::Debug,
TTrans: Transport,
@ -278,28 +278,28 @@ where
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match *self {
RawSwarmEvent::NewListenerAddress { ref listen_addr } => {
NetworkEvent::NewListenerAddress { ref listen_addr } => {
f.debug_struct("NewListenerAddress")
.field("listen_addr", listen_addr)
.finish()
}
RawSwarmEvent::ExpiredListenerAddress { ref listen_addr } => {
NetworkEvent::ExpiredListenerAddress { ref listen_addr } => {
f.debug_struct("ExpiredListenerAddress")
.field("listen_addr", listen_addr)
.finish()
}
RawSwarmEvent::ListenerClosed { ref result, .. } => {
NetworkEvent::ListenerClosed { ref result, .. } => {
f.debug_struct("ListenerClosed")
.field("result", result)
.finish()
}
RawSwarmEvent::IncomingConnection(ref event) => {
NetworkEvent::IncomingConnection(ref event) => {
f.debug_struct("IncomingConnection")
.field("listen_addr", &event.listen_addr)
.field("send_back_addr", &event.send_back_addr)
.finish()
}
RawSwarmEvent::IncomingConnectionError {
NetworkEvent::IncomingConnectionError {
ref listen_addr,
ref send_back_addr,
ref error
@ -310,13 +310,13 @@ where
.field("error", error)
.finish()
}
RawSwarmEvent::Connected { ref conn_info, ref endpoint } => {
NetworkEvent::Connected { ref conn_info, ref endpoint } => {
f.debug_struct("Connected")
.field("conn_info", conn_info)
.field("endpoint", endpoint)
.finish()
}
RawSwarmEvent::Replaced { ref new_info, ref old_info, ref closed_endpoint, ref endpoint } => {
NetworkEvent::Replaced { ref new_info, ref old_info, ref closed_endpoint, ref endpoint } => {
f.debug_struct("Replaced")
.field("new_info", new_info)
.field("old_info", old_info)
@ -324,14 +324,14 @@ where
.field("endpoint", endpoint)
.finish()
}
RawSwarmEvent::NodeClosed { ref conn_info, ref endpoint, ref error } => {
NetworkEvent::NodeClosed { ref conn_info, ref endpoint, ref error } => {
f.debug_struct("NodeClosed")
.field("conn_info", conn_info)
.field("endpoint", endpoint)
.field("error", error)
.finish()
}
RawSwarmEvent::DialError { ref new_state, ref peer_id, ref multiaddr, ref error } => {
NetworkEvent::DialError { ref new_state, ref peer_id, ref multiaddr, ref error } => {
f.debug_struct("DialError")
.field("new_state", new_state)
.field("peer_id", peer_id)
@ -339,13 +339,13 @@ where
.field("error", error)
.finish()
}
RawSwarmEvent::UnknownPeerDialError { ref multiaddr, ref error, .. } => {
NetworkEvent::UnknownPeerDialError { ref multiaddr, ref error, .. } => {
f.debug_struct("UnknownPeerDialError")
.field("multiaddr", multiaddr)
.field("error", error)
.finish()
}
RawSwarmEvent::NodeEvent { ref conn_info, ref event } => {
NetworkEvent::NodeEvent { ref conn_info, ref event } => {
f.debug_struct("NodeEvent")
.field("conn_info", conn_info)
.field("event", event)
@ -418,7 +418,7 @@ pub enum PeerState {
/// Error that can happen when trying to reach a node.
#[derive(Debug)]
pub enum RawSwarmReachError<TTransErr, TConnInfo> {
pub enum NetworkReachError<TTransErr, TConnInfo> {
/// Error in the transport layer.
Transport(TransportError<TTransErr>),
@ -430,30 +430,30 @@ pub enum RawSwarmReachError<TTransErr, TConnInfo> {
}
}
impl<TTransErr, TConnInfo> fmt::Display for RawSwarmReachError<TTransErr, TConnInfo>
impl<TTransErr, TConnInfo> fmt::Display for NetworkReachError<TTransErr, TConnInfo>
where
TTransErr: fmt::Display,
TConnInfo: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RawSwarmReachError::Transport(err) => write!(f, "{}", err),
RawSwarmReachError::PeerIdMismatch { obtained } => {
NetworkReachError::Transport(err) => write!(f, "{}", err),
NetworkReachError::PeerIdMismatch { obtained } => {
write!(f, "Peer ID mismatch, obtained: {:?}", obtained)
},
}
}
}
impl<TTransErr, TConnInfo> error::Error for RawSwarmReachError<TTransErr, TConnInfo>
impl<TTransErr, TConnInfo> error::Error for NetworkReachError<TTransErr, TConnInfo>
where
TTransErr: error::Error + 'static,
TConnInfo: fmt::Debug,
{
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
RawSwarmReachError::Transport(err) => Some(err),
RawSwarmReachError::PeerIdMismatch { .. } => None,
NetworkReachError::Transport(err) => Some(err),
NetworkReachError::PeerIdMismatch { .. } => None,
}
}
}
@ -544,9 +544,9 @@ where TTrans: Transport
listen_addr: Multiaddr,
/// Address used to send back data to the remote.
send_back_addr: Multiaddr,
/// Reference to the `active_nodes` field of the swarm.
/// Reference to the `active_nodes` field of the `Network`.
active_nodes: &'a mut CollectionStream<TInEvent, TOutEvent, THandler, InternalReachErr<TTrans::Error, TConnInfo>, THandlerErr, (), (TConnInfo, ConnectedPoint), TPeerId>,
/// Reference to the `other_reach_attempts` field of the swarm.
/// Reference to the `other_reach_attempts` field of the `Network`.
other_reach_attempts: &'a mut Vec<(ReachAttemptId, ConnectedPoint)>,
}
@ -648,7 +648,7 @@ impl<'a> IncomingInfo<'a> {
}
impl<TTrans, TInEvent, TOutEvent, TMuxer, THandler, THandlerErr, TConnInfo, TPeerId>
RawSwarm<TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>
Network<TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>
where
TTrans: Transport + Clone,
TMuxer: StreamMuxer,
@ -662,7 +662,7 @@ where
/// Creates a new node events stream.
pub fn new(transport: TTrans, local_peer_id: TPeerId) -> Self {
// TODO: with_capacity?
RawSwarm {
Network {
listeners: ListenersStream::new(transport),
active_nodes: CollectionStream::new(),
reach_attempts: ReachAttempts {
@ -680,7 +680,7 @@ where
pub fn new_with_incoming_limit(transport: TTrans,
local_peer_id: TPeerId, incoming_limit: Option<u32>) -> Self
{
RawSwarm {
Network {
incoming_limit,
listeners: ListenersStream::new(transport),
active_nodes: CollectionStream::new(),
@ -942,7 +942,7 @@ where
}
/// Provides an API similar to `Stream`, except that it cannot error.
pub fn poll(&mut self) -> Async<RawSwarmEvent<'_, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>>
pub fn poll(&mut self) -> Async<NetworkEvent<'_, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>>
where
TTrans: Transport<Output = (TConnInfo, TMuxer)>,
TTrans::Error: Send + 'static,
@ -977,16 +977,16 @@ where
active_nodes: &mut self.active_nodes,
other_reach_attempts: &mut self.reach_attempts.other_reach_attempts,
};
return Async::Ready(RawSwarmEvent::IncomingConnection(event));
return Async::Ready(NetworkEvent::IncomingConnection(event));
}
Async::Ready(ListenersEvent::NewAddress { listen_addr }) => {
return Async::Ready(RawSwarmEvent::NewListenerAddress { listen_addr })
return Async::Ready(NetworkEvent::NewListenerAddress { listen_addr })
}
Async::Ready(ListenersEvent::AddressExpired { listen_addr }) => {
return Async::Ready(RawSwarmEvent::ExpiredListenerAddress { listen_addr })
return Async::Ready(NetworkEvent::ExpiredListenerAddress { listen_addr })
}
Async::Ready(ListenersEvent::Closed { listener, result }) => {
return Async::Ready(RawSwarmEvent::ListenerClosed { listener, result })
return Async::Ready(NetworkEvent::ListenerClosed { listener, result })
}
}
}
@ -1036,7 +1036,7 @@ where
closed message after it has been opened, and no two closed \
messages; QED");
action = Default::default();
out_event = RawSwarmEvent::NodeClosed {
out_event = NetworkEvent::NodeClosed {
conn_info: conn_info.0,
endpoint,
error,
@ -1044,7 +1044,7 @@ where
}
Async::Ready(CollectionEvent::NodeEvent { peer, event }) => {
action = Default::default();
out_event = RawSwarmEvent::NodeEvent { conn_info: peer.info().0.clone(), event };
out_event = NetworkEvent::NodeEvent { conn_info: peer.info().0.clone(), event };
}
}
@ -1077,7 +1077,7 @@ where
}
}
/// Internal struct indicating an action to perform of the swarm.
/// Internal struct indicating an action to perform on the network.
#[derive(Debug)]
#[must_use]
struct ActionItem<THandler, TPeerId> {
@ -1105,7 +1105,7 @@ impl<THandler, TPeerId> Default for ActionItem<THandler, TPeerId> {
fn handle_node_reached<'a, TTrans, TMuxer, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>(
reach_attempts: &mut ReachAttempts<TPeerId>,
event: CollectionReachEvent<'_, TInEvent, TOutEvent, THandler, InternalReachErr<TTrans::Error, TConnInfo>, THandlerErr, (), (TConnInfo, ConnectedPoint), TPeerId>,
) -> (ActionItem<THandler, TPeerId>, RawSwarmEvent<'a, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>)
) -> (ActionItem<THandler, TPeerId>, NetworkEvent<'a, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>)
where
TTrans: Transport<Output = (TConnInfo, TMuxer)> + Clone,
TMuxer: StreamMuxer + Send + Sync + 'static,
@ -1131,7 +1131,7 @@ where
if event.would_replace() && has_dial_prio {
if let Some(ConnectedPoint::Dialer { .. }) = reach_attempts.connected_points.get(event.peer_id()) {
if let ConnectedPoint::Listener { listen_addr, send_back_addr } = opened_endpoint {
return (Default::default(), RawSwarmEvent::IncomingConnectionError {
return (Default::default(), NetworkEvent::IncomingConnectionError {
listen_addr,
send_back_addr,
error: IncomingError::DeniedLowerPriority,
@ -1172,14 +1172,14 @@ where
remove only when a connection is closed; the underlying API is \
guaranteed to always deliver a connection closed message after it has \
been opened, and no two closed messages; QED");
return (action, RawSwarmEvent::Replaced {
return (action, NetworkEvent::Replaced {
new_info: conn_info.0,
old_info: old_info.0,
endpoint: opened_endpoint,
closed_endpoint,
});
} else {
return (action, RawSwarmEvent::Connected {
return (action, NetworkEvent::Connected {
conn_info: conn_info.0,
endpoint: opened_endpoint
});
@ -1214,7 +1214,7 @@ where
remove only when a connection is closed; the underlying API is guaranteed \
to always deliver a connection closed message after it has been opened, \
and no two closed messages; QED");
return (Default::default(), RawSwarmEvent::Replaced {
return (Default::default(), NetworkEvent::Replaced {
new_info: conn_info.0,
old_info: old_info.0,
endpoint: opened_endpoint,
@ -1222,7 +1222,7 @@ where
});
} else {
return (Default::default(), RawSwarmEvent::Connected {
return (Default::default(), NetworkEvent::Connected {
conn_info: conn_info.0,
endpoint: opened_endpoint
});
@ -1260,7 +1260,7 @@ fn handle_reach_error<'a, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TC
reach_id: ReachAttemptId,
error: InternalReachErr<TTrans::Error, TConnInfo>,
handler: THandler,
) -> (ActionItem<THandler, TPeerId>, RawSwarmEvent<'a, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>)
) -> (ActionItem<THandler, TPeerId>, NetworkEvent<'a, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>)
where
TTrans: Transport,
TConnInfo: ConnectionInfo<PeerId = TPeerId> + Send + 'static,
@ -1303,9 +1303,9 @@ where
};
let error = match error {
InternalReachErr::Transport(err) => RawSwarmReachError::Transport(err),
InternalReachErr::Transport(err) => NetworkReachError::Transport(err),
InternalReachErr::PeerIdMismatch { obtained } => {
RawSwarmReachError::PeerIdMismatch { obtained }
NetworkReachError::PeerIdMismatch { obtained }
},
InternalReachErr::FoundLocalPeerId => {
unreachable!("We only generate FoundLocalPeerId within dial() or accept(); neither \
@ -1313,7 +1313,7 @@ where
},
};
return (action, RawSwarmEvent::DialError {
return (action, NetworkEvent::DialError {
new_state,
peer_id,
multiaddr: failed_addr,
@ -1338,7 +1338,7 @@ where
which doesn't add any entry in other_reach_attempts; QED")
},
};
return (Default::default(), RawSwarmEvent::UnknownPeerDialError {
return (Default::default(), NetworkEvent::UnknownPeerDialError {
multiaddr: address,
error,
handler,
@ -1353,7 +1353,7 @@ where
which doesn't add any entry in other_reach_attempts; QED")
},
};
return (Default::default(), RawSwarmEvent::IncomingConnectionError {
return (Default::default(), NetworkEvent::IncomingConnectionError {
listen_addr,
send_back_addr,
error
@ -1693,7 +1693,7 @@ where
TTrans: Transport,
{
peer_id: TPeerId,
nodes: &'a mut RawSwarm<TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>,
nodes: &'a mut Network<TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId>,
}
impl<'a, TTrans, TInEvent, TOutEvent, THandler, THandlerErr, TConnInfo, TPeerId> fmt::Debug for

View File

@ -36,45 +36,45 @@ use tokio::runtime::{Builder, Runtime};
fn query_transport() {
let transport = DummyTransport::new();
let transport2 = transport.clone();
let raw_swarm = RawSwarm::<_, _, _, Handler, _>::new(transport, PeerId::random());
assert_eq!(raw_swarm.transport(), &transport2);
let network = Network::<_, _, _, Handler, _>::new(transport, PeerId::random());
assert_eq!(network.transport(), &transport2);
}
#[test]
fn local_node_peer() {
let peer_id = PeerId::random();
let mut raw_swarm = RawSwarm::<_, _, _, Handler, _>::new(DummyTransport::new(), peer_id.clone());
assert_matches!(raw_swarm.peer(peer_id), Peer::LocalNode);
let mut network = Network::<_, _, _, Handler, _>::new(DummyTransport::new(), peer_id.clone());
assert_matches!(network.peer(peer_id), Peer::LocalNode);
}
#[test]
fn successful_dial_reaches_a_node() {
let mut swarm = RawSwarm::<_, _, _, Handler, _>::new(DummyTransport::new(), PeerId::random());
let mut network = Network::<_, _, _, Handler, _>::new(DummyTransport::new(), PeerId::random());
let addr = "/ip4/127.0.0.1/tcp/1234".parse::<Multiaddr>().expect("bad multiaddr");
let dial_res = swarm.dial(addr, Handler::default());
let dial_res = network.dial(addr, Handler::default());
assert!(dial_res.is_ok());
// Poll the swarm until we get a `NodeReached` then assert on the peer:
// Poll the network until we get a `NodeReached` then assert on the peer:
// it's there and it's connected.
let swarm = Arc::new(Mutex::new(swarm));
let network = Arc::new(Mutex::new(network));
let mut rt = Runtime::new().unwrap();
let mut peer_id : Option<PeerId> = None;
// Drive forward until we're Connected
while peer_id.is_none() {
let swarm_fut = swarm.clone();
let network_fut = network.clone();
peer_id = rt.block_on(future::poll_fn(move || -> Poll<Option<PeerId>, ()> {
let mut swarm = swarm_fut.lock();
let poll_res = swarm.poll();
let mut network = network_fut.lock();
let poll_res = network.poll();
match poll_res {
Async::Ready(RawSwarmEvent::Connected { conn_info, .. }) => Ok(Async::Ready(Some(conn_info))),
Async::Ready(NetworkEvent::Connected { conn_info, .. }) => Ok(Async::Ready(Some(conn_info))),
_ => Ok(Async::Ready(None))
}
})).expect("tokio works");
}
let mut swarm = swarm.lock();
let peer = swarm.peer(peer_id.unwrap());
let mut network = network.lock();
let peer = network.peer(peer_id.unwrap());
assert_matches!(peer, Peer::Connected(PeerConnected{..}));
}
@ -94,46 +94,46 @@ fn num_incoming_negotiated() {
];
transport.set_initial_listener_state(ListenerState::Events(events));
let mut swarm = RawSwarm::<_, _, _, Handler, _>::new(transport, PeerId::random());
swarm.listen_on("/memory/0".parse().unwrap()).unwrap();
let mut network = Network::<_, _, _, Handler, _>::new(transport, PeerId::random());
network.listen_on("/memory/0".parse().unwrap()).unwrap();
// no incoming yet
assert_eq!(swarm.incoming_negotiated().count(), 0);
assert_eq!(network.incoming_negotiated().count(), 0);
let mut rt = Runtime::new().unwrap();
let swarm = Arc::new(Mutex::new(swarm));
let swarm_fut = swarm.clone();
let network = Arc::new(Mutex::new(network));
let network_fut = network.clone();
let fut = future::poll_fn(move || -> Poll<_, ()> {
let mut swarm_fut = swarm_fut.lock();
assert_matches!(swarm_fut.poll(), Async::Ready(RawSwarmEvent::NewListenerAddress {..}));
assert_matches!(swarm_fut.poll(), Async::Ready(RawSwarmEvent::IncomingConnection(incoming)) => {
let mut network_fut = network_fut.lock();
assert_matches!(network_fut.poll(), Async::Ready(NetworkEvent::NewListenerAddress {..}));
assert_matches!(network_fut.poll(), Async::Ready(NetworkEvent::IncomingConnection(incoming)) => {
incoming.accept(Handler::default());
});
Ok(Async::Ready(()))
});
rt.block_on(fut).expect("tokio works");
let swarm = swarm.lock();
let network = network.lock();
// Now there's an incoming connection
assert_eq!(swarm.incoming_negotiated().count(), 1);
assert_eq!(network.incoming_negotiated().count(), 1);
}
#[test]
fn broadcasted_events_reach_active_nodes() {
let mut swarm = RawSwarm::<_, _, _, Handler, _>::new(DummyTransport::new(), PeerId::random());
let mut network = Network::<_, _, _, Handler, _>::new(DummyTransport::new(), PeerId::random());
let mut muxer = DummyMuxer::new();
muxer.set_inbound_connection_state(DummyConnectionState::Pending);
muxer.set_outbound_connection_state(DummyConnectionState::Opened);
let addr = "/ip4/127.0.0.1/tcp/1234".parse::<Multiaddr>().expect("bad multiaddr");
let mut handler = Handler::default();
handler.next_states = vec![HandlerState::Ready(NodeHandlerEvent::Custom(OutEvent::Custom("from handler 1") )),];
let dial_result = swarm.dial(addr, handler);
let dial_result = network.dial(addr, handler);
assert!(dial_result.is_ok());
let swarm = Arc::new(Mutex::new(swarm));
let network = Arc::new(Mutex::new(network));
let mut rt = Runtime::new().unwrap();
let swarm2 = swarm.clone();
let network2 = network.clone();
rt.block_on(future::poll_fn(move || {
if swarm2.lock().start_broadcast(&InEvent::NextState).is_not_ready() {
if network2.lock().start_broadcast(&InEvent::NextState).is_not_ready() {
Ok::<_, ()>(Async::NotReady)
} else {
Ok(Async::Ready(()))
@ -141,15 +141,15 @@ fn broadcasted_events_reach_active_nodes() {
})).unwrap();
let mut peer_id : Option<PeerId> = None;
while peer_id.is_none() {
let swarm_fut = swarm.clone();
let network_fut = network.clone();
peer_id = rt.block_on(future::poll_fn(move || -> Poll<Option<PeerId>, ()> {
let mut swarm = swarm_fut.lock();
if swarm.complete_broadcast().is_not_ready() {
let mut network = network_fut.lock();
if network.complete_broadcast().is_not_ready() {
return Ok(Async::NotReady)
}
let poll_res = swarm.poll();
let poll_res = network.poll();
match poll_res {
Async::Ready(RawSwarmEvent::Connected { conn_info, .. }) => Ok(Async::Ready(Some(conn_info))),
Async::Ready(NetworkEvent::Connected { conn_info, .. }) => Ok(Async::Ready(Some(conn_info))),
_ => Ok(Async::Ready(None))
}
})).expect("tokio works");
@ -157,12 +157,12 @@ fn broadcasted_events_reach_active_nodes() {
let mut keep_polling = true;
while keep_polling {
let swarm_fut = swarm.clone();
let network_fut = network.clone();
keep_polling = rt.block_on(future::poll_fn(move || -> Poll<_, ()> {
let mut swarm = swarm_fut.lock();
match swarm.poll() {
let mut network = network_fut.lock();
match network.poll() {
Async::Ready(event) => {
assert_matches!(event, RawSwarmEvent::NodeEvent { conn_info: _, event: inner_event } => {
assert_matches!(event, NetworkEvent::NodeEvent { conn_info: _, event: inner_event } => {
// The event we sent reached the node and triggered sending the out event we told it to return
assert_matches!(inner_event, OutEvent::Custom("from handler 1"));
});
@ -176,9 +176,9 @@ fn broadcasted_events_reach_active_nodes() {
#[test]
fn querying_for_pending_peer() {
let mut swarm = RawSwarm::<_, _, _, Handler, _>::new(DummyTransport::new(), PeerId::random());
let mut network = Network::<_, _, _, Handler, _>::new(DummyTransport::new(), PeerId::random());
let peer_id = PeerId::random();
let peer = swarm.peer(peer_id.clone());
let peer = network.peer(peer_id.clone());
assert_matches!(peer, Peer::NotConnected(PeerNotConnected{ .. }));
let addr = "/memory/0".parse().expect("bad multiaddr");
let pending_peer = peer.into_not_connected().unwrap().connect(addr, Handler::default());
@ -187,9 +187,9 @@ fn querying_for_pending_peer() {
#[test]
fn querying_for_unknown_peer() {
let mut swarm = RawSwarm::<_, _, _, Handler, _>::new(DummyTransport::new(), PeerId::random());
let mut network = Network::<_, _, _, Handler, _>::new(DummyTransport::new(), PeerId::random());
let peer_id = PeerId::random();
let peer = swarm.peer(peer_id.clone());
let peer = network.peer(peer_id.clone());
assert_matches!(peer, Peer::NotConnected( PeerNotConnected { nodes: _, peer_id: node_peer_id }) => {
assert_eq!(node_peer_id, peer_id);
});
@ -197,31 +197,31 @@ fn querying_for_unknown_peer() {
#[test]
fn querying_for_connected_peer() {
let mut swarm = RawSwarm::<_, _, _, Handler, _>::new(DummyTransport::new(), PeerId::random());
let mut network = Network::<_, _, _, Handler, _>::new(DummyTransport::new(), PeerId::random());
// Dial a node
let addr = "/ip4/127.0.0.1/tcp/1234".parse().expect("bad multiaddr");
swarm.dial(addr, Handler::default()).expect("dialing works");
network.dial(addr, Handler::default()).expect("dialing works");
let swarm = Arc::new(Mutex::new(swarm));
let network = Arc::new(Mutex::new(network));
let mut rt = Runtime::new().unwrap();
// Drive it forward until we connect; extract the new PeerId.
let mut peer_id : Option<PeerId> = None;
while peer_id.is_none() {
let swarm_fut = swarm.clone();
let network_fut = network.clone();
peer_id = rt.block_on(future::poll_fn(move || -> Poll<Option<PeerId>, ()> {
let mut swarm = swarm_fut.lock();
let poll_res = swarm.poll();
let mut network = network_fut.lock();
let poll_res = network.poll();
match poll_res {
Async::Ready(RawSwarmEvent::Connected { conn_info, .. }) => Ok(Async::Ready(Some(conn_info))),
Async::Ready(NetworkEvent::Connected { conn_info, .. }) => Ok(Async::Ready(Some(conn_info))),
_ => Ok(Async::Ready(None))
}
})).expect("tokio works");
}
// We're connected.
let mut swarm = swarm.lock();
let peer = swarm.peer(peer_id.unwrap());
let mut network = network.lock();
let peer = network.peer(peer_id.unwrap());
assert_matches!(peer, Peer::Connected( PeerConnected { .. } ));
}
@ -231,16 +231,16 @@ fn poll_with_closed_listener() {
// Set up listener to be closed
transport.set_initial_listener_state(ListenerState::Ok(Async::Ready(None)));
let mut swarm = RawSwarm::<_, _, _, Handler, _>::new(transport, PeerId::random());
swarm.listen_on("/memory/0".parse().unwrap()).unwrap();
let mut network = Network::<_, _, _, Handler, _>::new(transport, PeerId::random());
network.listen_on("/memory/0".parse().unwrap()).unwrap();
let mut rt = Runtime::new().unwrap();
let swarm = Arc::new(Mutex::new(swarm));
let network = Arc::new(Mutex::new(network));
let swarm_fut = swarm.clone();
let network_fut = network.clone();
let fut = future::poll_fn(move || -> Poll<_, ()> {
let mut swarm = swarm_fut.lock();
assert_matches!(swarm.poll(), Async::Ready(RawSwarmEvent::ListenerClosed { .. } ));
let mut network = network_fut.lock();
assert_matches!(network.poll(), Async::Ready(NetworkEvent::ListenerClosed { .. } ));
Ok(Async::Ready(()))
});
rt.block_on(fut).expect("tokio works");
@ -250,24 +250,24 @@ fn poll_with_closed_listener() {
fn unknown_peer_that_is_unreachable_yields_unknown_peer_dial_error() {
let mut transport = DummyTransport::new();
transport.make_dial_fail();
let mut swarm = RawSwarm::<_, _, _, Handler, _>::new(transport, PeerId::random());
let mut network = Network::<_, _, _, Handler, _>::new(transport, PeerId::random());
let addr = "/memory/0".parse::<Multiaddr>().expect("bad multiaddr");
let handler = Handler::default();
let dial_result = swarm.dial(addr, handler);
let dial_result = network.dial(addr, handler);
assert!(dial_result.is_ok());
let swarm = Arc::new(Mutex::new(swarm));
let network = Arc::new(Mutex::new(network));
let mut rt = Runtime::new().unwrap();
// Drive it forward until we hear back from the node.
let mut keep_polling = true;
while keep_polling {
let swarm_fut = swarm.clone();
let network_fut = network.clone();
keep_polling = rt.block_on(future::poll_fn(move || -> Poll<_, ()> {
let mut swarm = swarm_fut.lock();
match swarm.poll() {
let mut network = network_fut.lock();
match network.poll() {
Async::NotReady => Ok(Async::Ready(true)),
Async::Ready(event) => {
assert_matches!(event, RawSwarmEvent::UnknownPeerDialError { .. } );
assert_matches!(event, NetworkEvent::UnknownPeerDialError { .. } );
Ok(Async::Ready(false))
},
}
@ -281,12 +281,12 @@ fn known_peer_that_is_unreachable_yields_dial_error() {
let peer_id = PeerId::random();
transport.set_next_peer_id(&peer_id);
transport.make_dial_fail();
let swarm = Arc::new(Mutex::new(RawSwarm::<_, _, _, Handler, _>::new(transport, PeerId::random())));
let network = Arc::new(Mutex::new(Network::<_, _, _, Handler, _>::new(transport, PeerId::random())));
{
let swarm1 = swarm.clone();
let mut swarm1 = swarm1.lock();
let peer = swarm1.peer(peer_id.clone());
let network1 = network.clone();
let mut network1 = network1.lock();
let peer = network1.peer(peer_id.clone());
assert_matches!(peer, Peer::NotConnected(PeerNotConnected{ .. }));
let addr = "/memory/0".parse::<Multiaddr>().expect("bad multiaddr");
let pending_peer = peer.into_not_connected().unwrap().connect(addr, Handler::default());
@ -296,16 +296,16 @@ fn known_peer_that_is_unreachable_yields_dial_error() {
// Drive it forward until we hear back from the node.
let mut keep_polling = true;
while keep_polling {
let swarm_fut = swarm.clone();
let network_fut = network.clone();
let peer_id = peer_id.clone();
keep_polling = rt.block_on(future::poll_fn(move || -> Poll<_, ()> {
let mut swarm = swarm_fut.lock();
match swarm.poll() {
let mut network = network_fut.lock();
match network.poll() {
Async::NotReady => Ok(Async::Ready(true)),
Async::Ready(event) => {
let failed_peer_id = assert_matches!(
event,
RawSwarmEvent::DialError { new_state: _, peer_id: failed_peer_id, .. } => failed_peer_id
NetworkEvent::DialError { new_state: _, peer_id: failed_peer_id, .. } => failed_peer_id
);
assert_eq!(peer_id, failed_peer_id);
Ok(Async::Ready(false))
@ -320,13 +320,13 @@ fn yields_node_error_when_there_is_an_error_after_successful_connect() {
let mut transport = DummyTransport::new();
let peer_id = PeerId::random();
transport.set_next_peer_id(&peer_id);
let swarm = Arc::new(Mutex::new(RawSwarm::<_, _, _, Handler, _>::new(transport, PeerId::random())));
let network = Arc::new(Mutex::new(Network::<_, _, _, Handler, _>::new(transport, PeerId::random())));
{
// Set up an outgoing connection with a PeerId we know
let swarm1 = swarm.clone();
let mut swarm1 = swarm1.lock();
let peer = swarm1.peer(peer_id.clone());
let network1 = network.clone();
let mut network1 = network1.lock();
let peer = network1.peer(peer_id.clone());
let addr = "/unix/reachable".parse().expect("bad multiaddr");
let mut handler = Handler::default();
// Force an error
@ -340,25 +340,25 @@ fn yields_node_error_when_there_is_an_error_after_successful_connect() {
// Drive it forward until we connect to the node.
let mut keep_polling = true;
while keep_polling {
let swarm_fut = swarm.clone();
let swarm2 = swarm.clone();
let network_fut = network.clone();
let network2 = network.clone();
rt.block_on(future::poll_fn(move || {
if swarm2.lock().start_broadcast(&InEvent::NextState).is_not_ready() {
if network2.lock().start_broadcast(&InEvent::NextState).is_not_ready() {
Ok::<_, ()>(Async::NotReady)
} else {
Ok(Async::Ready(()))
}
})).unwrap();
keep_polling = rt.block_on(future::poll_fn(move || -> Poll<_, ()> {
let mut swarm = swarm_fut.lock();
let mut network = network_fut.lock();
// Push the Handler into an error state on the next poll
if swarm.complete_broadcast().is_not_ready() {
if network.complete_broadcast().is_not_ready() {
return Ok(Async::NotReady)
}
match swarm.poll() {
match network.poll() {
Async::NotReady => Ok(Async::Ready(true)),
Async::Ready(event) => {
assert_matches!(event, RawSwarmEvent::Connected { .. });
assert_matches!(event, NetworkEvent::Connected { .. });
// We're connected, we can move on
Ok(Async::Ready(false))
},
@ -368,11 +368,11 @@ fn yields_node_error_when_there_is_an_error_after_successful_connect() {
// Poll again. It is going to be a NodeClosed because of how the
// handler's next state was set up.
let swarm_fut = swarm.clone();
let network_fut = network.clone();
let expected_peer_id = peer_id.clone();
rt.block_on(future::poll_fn(move || -> Poll<_, ()> {
let mut swarm = swarm_fut.lock();
assert_matches!(swarm.poll(), Async::Ready(RawSwarmEvent::NodeClosed { conn_info, .. }) => {
let mut network = network_fut.lock();
assert_matches!(network.poll(), Async::Ready(NetworkEvent::NodeClosed { conn_info, .. }) => {
assert_eq!(conn_info, expected_peer_id);
});
Ok(Async::Ready(()))
@ -405,32 +405,32 @@ fn limit_incoming_connections() {
).take(10));
transport.set_initial_listener_state(ListenerState::Events(events));
let mut swarm = RawSwarm::<_, _, _, Handler, _>::new_with_incoming_limit(transport, PeerId::random(), Some(limit));
assert_eq!(swarm.incoming_limit(), Some(limit));
swarm.listen_on("/memory/0".parse().unwrap()).unwrap();
assert_eq!(swarm.incoming_negotiated().count(), 0);
let mut network = Network::<_, _, _, Handler, _>::new_with_incoming_limit(transport, PeerId::random(), Some(limit));
assert_eq!(network.incoming_limit(), Some(limit));
network.listen_on("/memory/0".parse().unwrap()).unwrap();
assert_eq!(network.incoming_negotiated().count(), 0);
let swarm = Arc::new(Mutex::new(swarm));
let network = Arc::new(Mutex::new(network));
let mut rt = Runtime::new().unwrap();
for i in 1..10 {
let swarm_fut = swarm.clone();
let network_fut = network.clone();
let fut = future::poll_fn(move || -> Poll<_, ()> {
let mut swarm_fut = swarm_fut.lock();
let mut network_fut = network_fut.lock();
if i <= limit {
assert_matches!(swarm_fut.poll(), Async::Ready(RawSwarmEvent::NewListenerAddress {..}));
assert_matches!(swarm_fut.poll(),
Async::Ready(RawSwarmEvent::IncomingConnection(incoming)) => {
assert_matches!(network_fut.poll(), Async::Ready(NetworkEvent::NewListenerAddress {..}));
assert_matches!(network_fut.poll(),
Async::Ready(NetworkEvent::IncomingConnection(incoming)) => {
incoming.accept(Handler::default());
});
} else {
match swarm_fut.poll() {
match network_fut.poll() {
Async::NotReady => (),
Async::Ready(x) => {
match x {
RawSwarmEvent::NewListenerAddress {..} => {}
RawSwarmEvent::ExpiredListenerAddress {..} => {}
RawSwarmEvent::IncomingConnection(_) => {}
RawSwarmEvent::Connected {..} => {}
NetworkEvent::NewListenerAddress {..} => {}
NetworkEvent::ExpiredListenerAddress {..} => {}
NetworkEvent::IncomingConnection(_) => {}
NetworkEvent::Connected {..} => {}
e => panic!("Not expected event: {:?}", e)
}
},
@ -439,7 +439,7 @@ fn limit_incoming_connections() {
Ok(Async::Ready(()))
});
rt.block_on(fut).expect("tokio works");
let swarm = swarm.lock();
assert!(swarm.incoming_negotiated().count() <= (limit as usize));
let network = network.lock();
assert!(network.incoming_negotiated().count() <= (limit as usize));
}
}

View File

@ -21,7 +21,7 @@
use futures::{future, prelude::*};
use libp2p_core::identity;
use libp2p_core::multiaddr::multiaddr;
use libp2p_core::nodes::raw_swarm::{RawSwarm, RawSwarmEvent, RawSwarmReachError, PeerState, UnknownPeerDialErr, IncomingError};
use libp2p_core::nodes::network::{Network, NetworkEvent, NetworkReachError, PeerState, UnknownPeerDialErr, IncomingError};
use libp2p_core::{PeerId, Transport, upgrade, upgrade::InboundUpgradeExt, upgrade::OutboundUpgradeExt};
use libp2p_swarm::{
ProtocolsHandler,
@ -91,7 +91,7 @@ fn deny_incoming_connec() {
// TODO: make creating the transport more elegant ; literaly half of the code of the test
// is about creating the transport
let mut swarm1: RawSwarm<_, _, _, NodeHandlerWrapperBuilder<TestHandler<_>>, _> = {
let mut swarm1: Network<_, _, _, NodeHandlerWrapperBuilder<TestHandler<_>>, _> = {
let local_key = identity::Keypair::generate_ed25519();
let local_public_key = local_key.public();
let transport = libp2p_tcp::TcpConfig::new()
@ -104,7 +104,7 @@ fn deny_incoming_connec() {
.map_inbound(move |muxer| (peer_id2, muxer));
upgrade::apply(out.stream, upgrade, endpoint)
});
RawSwarm::new(transport, local_public_key.into())
Network::new(transport, local_public_key.into())
};
let mut swarm2 = {
@ -120,13 +120,13 @@ fn deny_incoming_connec() {
.map_inbound(move |muxer| (peer_id2, muxer));
upgrade::apply(out.stream, upgrade, endpoint)
});
RawSwarm::new(transport, local_public_key.into())
Network::new(transport, local_public_key.into())
};
swarm1.listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap()).unwrap();
let address =
if let Async::Ready(RawSwarmEvent::NewListenerAddress { listen_addr, .. }) = swarm1.poll() {
if let Async::Ready(NetworkEvent::NewListenerAddress { listen_addr, .. }) = swarm1.poll() {
listen_addr
} else {
panic!("Was expecting the listen address to be reported")
@ -139,17 +139,17 @@ fn deny_incoming_connec() {
let future = future::poll_fn(|| -> Poll<(), io::Error> {
match swarm1.poll() {
Async::Ready(RawSwarmEvent::IncomingConnection(inc)) => drop(inc),
Async::Ready(NetworkEvent::IncomingConnection(inc)) => drop(inc),
Async::Ready(_) => unreachable!(),
Async::NotReady => (),
}
match swarm2.poll() {
Async::Ready(RawSwarmEvent::DialError {
Async::Ready(NetworkEvent::DialError {
new_state: PeerState::NotConnected,
peer_id,
multiaddr,
error: RawSwarmReachError::Transport(_)
error: NetworkReachError::Transport(_)
}) => {
assert_eq!(peer_id, *swarm1.local_peer_id());
assert_eq!(multiaddr, address);
@ -192,14 +192,14 @@ fn dial_self() {
.map_inbound(move |muxer| (peer_id2, muxer));
upgrade::apply(out.stream, upgrade, endpoint)
});
RawSwarm::new(transport, local_public_key.into())
Network::new(transport, local_public_key.into())
};
swarm.listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap()).unwrap();
let (address, mut swarm) =
future::lazy(move || {
if let Async::Ready(RawSwarmEvent::NewListenerAddress { listen_addr, .. }) = swarm.poll() {
if let Async::Ready(NetworkEvent::NewListenerAddress { listen_addr, .. }) = swarm.poll() {
Ok::<_, void::Void>((listen_addr, swarm))
} else {
panic!("Was expecting the listen address to be reported")
@ -215,7 +215,7 @@ fn dial_self() {
let future = future::poll_fn(|| -> Poll<(), io::Error> {
loop {
match swarm.poll() {
Async::Ready(RawSwarmEvent::UnknownPeerDialError {
Async::Ready(NetworkEvent::UnknownPeerDialError {
multiaddr,
error: UnknownPeerDialErr::FoundLocalPeerId,
handler: _
@ -227,7 +227,7 @@ fn dial_self() {
return Ok(Async::Ready(()));
}
},
Async::Ready(RawSwarmEvent::IncomingConnectionError {
Async::Ready(NetworkEvent::IncomingConnectionError {
listen_addr,
send_back_addr: _,
error: IncomingError::FoundLocalPeerId
@ -239,7 +239,7 @@ fn dial_self() {
return Ok(Async::Ready(()));
}
},
Async::Ready(RawSwarmEvent::IncomingConnection(inc)) => {
Async::Ready(NetworkEvent::IncomingConnection(inc)) => {
assert_eq!(*inc.listen_addr(), address);
inc.accept(TestHandler::default().into_node_handler_builder());
},
@ -259,7 +259,7 @@ fn dial_self_by_id() {
// TODO: make creating the transport more elegant ; literaly half of the code of the test
// is about creating the transport
let mut swarm: RawSwarm<_, _, _, NodeHandlerWrapperBuilder<TestHandler<_>>, _> = {
let mut swarm: Network<_, _, _, NodeHandlerWrapperBuilder<TestHandler<_>>, _> = {
let local_key = identity::Keypair::generate_ed25519();
let local_public_key = local_key.public();
let transport = libp2p_tcp::TcpConfig::new()
@ -272,7 +272,7 @@ fn dial_self_by_id() {
.map_inbound(move |muxer| (peer_id2, muxer));
upgrade::apply(out.stream, upgrade, endpoint)
});
RawSwarm::new(transport, local_public_key.into())
Network::new(transport, local_public_key.into())
};
let peer_id = swarm.local_peer_id().clone();
@ -298,7 +298,7 @@ fn multiple_addresses_err() {
.map_inbound(move |muxer| (peer_id2, muxer));
upgrade::apply(out.stream, upgrade, endpoint)
});
RawSwarm::new(transport, local_public_key.into())
Network::new(transport, local_public_key.into())
};
let mut addresses = Vec::new();
@ -319,11 +319,11 @@ fn multiple_addresses_err() {
let future = future::poll_fn(|| -> Poll<(), io::Error> {
loop {
match swarm.poll() {
Async::Ready(RawSwarmEvent::DialError {
Async::Ready(NetworkEvent::DialError {
new_state,
peer_id,
multiaddr,
error: RawSwarmReachError::Transport(_)
error: NetworkReachError::Transport(_)
}) => {
assert_eq!(peer_id, target);
let expected = addresses.remove(0);

View File

@ -20,7 +20,7 @@
use futures::{future, prelude::*};
use libp2p_core::identity;
use libp2p_core::nodes::raw_swarm::{RawSwarm, RawSwarmEvent, IncomingError};
use libp2p_core::nodes::network::{Network, NetworkEvent, IncomingError};
use libp2p_core::{Transport, upgrade, upgrade::OutboundUpgradeExt, upgrade::InboundUpgradeExt};
use libp2p_swarm::{
ProtocolsHandler,
@ -119,7 +119,7 @@ fn raw_swarm_simultaneous_connect() {
.map_inbound(move |muxer| (peer_id2, muxer));
upgrade::apply(out.stream, upgrade, endpoint)
});
RawSwarm::new(transport, local_public_key.into_peer_id())
Network::new(transport, local_public_key.into_peer_id())
};
let mut swarm2 = {
@ -135,7 +135,7 @@ fn raw_swarm_simultaneous_connect() {
.map_inbound(move |muxer| (peer_id2, muxer));
upgrade::apply(out.stream, upgrade, endpoint)
});
RawSwarm::new(transport, local_public_key.into_peer_id())
Network::new(transport, local_public_key.into_peer_id())
};
swarm1.listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap()).unwrap();
@ -144,14 +144,14 @@ fn raw_swarm_simultaneous_connect() {
let (swarm1_listen_addr, swarm2_listen_addr, mut swarm1, mut swarm2) =
future::lazy(move || {
let swarm1_listen_addr =
if let Async::Ready(RawSwarmEvent::NewListenerAddress { listen_addr, .. }) = swarm1.poll() {
if let Async::Ready(NetworkEvent::NewListenerAddress { listen_addr, .. }) = swarm1.poll() {
listen_addr
} else {
panic!("Was expecting the listen address to be reported")
};
let swarm2_listen_addr =
if let Async::Ready(RawSwarmEvent::NewListenerAddress { listen_addr, .. }) = swarm2.poll() {
if let Async::Ready(NetworkEvent::NewListenerAddress { listen_addr, .. }) = swarm2.poll() {
listen_addr
} else {
panic!("Was expecting the listen address to be reported")
@ -207,21 +207,21 @@ fn raw_swarm_simultaneous_connect() {
if rand::random::<f32>() < 0.1 {
match swarm1.poll() {
Async::Ready(RawSwarmEvent::IncomingConnectionError { error: IncomingError::DeniedLowerPriority, .. }) => {
Async::Ready(NetworkEvent::IncomingConnectionError { error: IncomingError::DeniedLowerPriority, .. }) => {
assert_eq!(swarm1_step, 2);
swarm1_step = 3;
},
Async::Ready(RawSwarmEvent::Connected { conn_info, .. }) => {
Async::Ready(NetworkEvent::Connected { conn_info, .. }) => {
assert_eq!(conn_info, *swarm2.local_peer_id());
assert_eq!(swarm1_step, 1);
swarm1_step = 2;
},
Async::Ready(RawSwarmEvent::Replaced { new_info, .. }) => {
Async::Ready(NetworkEvent::Replaced { new_info, .. }) => {
assert_eq!(new_info, *swarm2.local_peer_id());
assert_eq!(swarm1_step, 2);
swarm1_step = 3;
},
Async::Ready(RawSwarmEvent::IncomingConnection(inc)) => {
Async::Ready(NetworkEvent::IncomingConnection(inc)) => {
inc.accept(TestHandler::default().into_node_handler_builder());
},
Async::Ready(_) => unreachable!(),
@ -231,21 +231,21 @@ fn raw_swarm_simultaneous_connect() {
if rand::random::<f32>() < 0.1 {
match swarm2.poll() {
Async::Ready(RawSwarmEvent::IncomingConnectionError { error: IncomingError::DeniedLowerPriority, .. }) => {
Async::Ready(NetworkEvent::IncomingConnectionError { error: IncomingError::DeniedLowerPriority, .. }) => {
assert_eq!(swarm2_step, 2);
swarm2_step = 3;
},
Async::Ready(RawSwarmEvent::Connected { conn_info, .. }) => {
Async::Ready(NetworkEvent::Connected { conn_info, .. }) => {
assert_eq!(conn_info, *swarm1.local_peer_id());
assert_eq!(swarm2_step, 1);
swarm2_step = 2;
},
Async::Ready(RawSwarmEvent::Replaced { new_info, .. }) => {
Async::Ready(NetworkEvent::Replaced { new_info, .. }) => {
assert_eq!(new_info, *swarm1.local_peer_id());
assert_eq!(swarm2_step, 2);
swarm2_step = 3;
},
Async::Ready(RawSwarmEvent::IncomingConnection(inc)) => {
Async::Ready(NetworkEvent::IncomingConnection(inc)) => {
inc.accept(TestHandler::default().into_node_handler_builder());
},
Async::Ready(_) => unreachable!(),

View File

@ -86,7 +86,7 @@ use libp2p_core::{
collection::ConnectionInfo,
handled_node::NodeHandler,
node::Substream,
raw_swarm::{self, RawSwarm, RawSwarmEvent}
network::{self, Network, NetworkEvent}
},
transport::TransportError
};
@ -111,7 +111,7 @@ pub struct ExpandedSwarm<TTransport, TBehaviour, TInEvent, TOutEvent, THandler,
where
TTransport: Transport,
{
raw_swarm: RawSwarm<
network: Network<
TTransport,
TInEvent,
TOutEvent,
@ -212,14 +212,14 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
/// Returns the transport passed when building this object.
pub fn transport(me: &Self) -> &TTransport {
me.raw_swarm.transport()
me.network.transport()
}
/// Starts listening on the given address.
///
/// Returns an error if the address is not supported.
pub fn listen_on(me: &mut Self, addr: Multiaddr) -> Result<(), TransportError<TTransport::Error>> {
me.raw_swarm.listen_on(addr)
me.network.listen_on(addr)
}
/// Tries to dial the given address.
@ -227,7 +227,7 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
/// Returns an error if the address is not supported.
pub fn dial_addr(me: &mut Self, addr: Multiaddr) -> Result<(), TransportError<TTransport::Error>> {
let handler = me.behaviour.new_handler();
me.raw_swarm.dial(addr, handler.into_node_handler_builder())
me.network.dial(addr, handler.into_node_handler_builder())
}
/// Tries to reach the given peer using the elements in the topology.
@ -236,23 +236,23 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
/// peer.
pub fn dial(me: &mut Self, peer_id: PeerId) {
let addrs = me.behaviour.addresses_of_peer(&peer_id);
match me.raw_swarm.peer(peer_id.clone()) {
raw_swarm::Peer::NotConnected(peer) => {
match me.network.peer(peer_id.clone()) {
network::Peer::NotConnected(peer) => {
let handler = me.behaviour.new_handler().into_node_handler_builder();
if peer.connect_iter(addrs, handler).is_err() {
me.behaviour.inject_dial_failure(&peer_id);
}
},
raw_swarm::Peer::PendingConnect(mut peer) => {
network::Peer::PendingConnect(mut peer) => {
peer.append_multiaddr_attempts(addrs)
},
raw_swarm::Peer::Connected(_) | raw_swarm::Peer::LocalNode => {}
network::Peer::Connected(_) | network::Peer::LocalNode => {}
}
}
/// Returns an iterator that produces the list of addresses we're listening on.
pub fn listeners(me: &Self) -> impl Iterator<Item = &Multiaddr> {
me.raw_swarm.listen_addrs()
me.network.listen_addrs()
}
/// Returns an iterator that produces the list of addresses that other nodes can use to reach
@ -263,7 +263,7 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
/// Returns the peer ID of the swarm passed as parameter.
pub fn local_peer_id(me: &Self) -> &PeerId {
&me.raw_swarm.local_peer_id()
&me.network.local_peer_id()
}
/// Adds an external address.
@ -275,9 +275,9 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
}
/// Returns the connection info of a node, or `None` if we're not connected to it.
// TODO: should take &self instead of &mut self, but the API in raw_swarm requires &mut
// TODO: should take &self instead of &mut self, but the API in network requires &mut
pub fn connection_info(me: &mut Self, peer_id: &PeerId) -> Option<TConnInfo> {
if let Some(mut n) = me.raw_swarm.peer(peer_id.clone()).into_connected() {
if let Some(mut n) = me.network.peer(peer_id.clone()).into_connected() {
Some(n.connection_info().clone())
} else {
None
@ -290,7 +290,7 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
/// This function has no effect is the peer is already banned.
pub fn ban_peer_id(me: &mut Self, peer_id: PeerId) {
me.banned_peers.insert(peer_id.clone());
if let Some(c) = me.raw_swarm.peer(peer_id).into_connected() {
if let Some(c) = me.network.peer(peer_id).into_connected() {
c.close();
}
}
@ -339,59 +339,59 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
fn poll(&mut self) -> Poll<Option<Self::Item>, io::Error> {
loop {
let mut raw_swarm_not_ready = false;
let mut network_not_ready = false;
match self.raw_swarm.poll() {
Async::NotReady => raw_swarm_not_ready = true,
Async::Ready(RawSwarmEvent::NodeEvent { conn_info, event }) => {
match self.network.poll() {
Async::NotReady => network_not_ready = true,
Async::Ready(NetworkEvent::NodeEvent { conn_info, event }) => {
self.behaviour.inject_node_event(conn_info.peer_id().clone(), event);
},
Async::Ready(RawSwarmEvent::Connected { conn_info, endpoint }) => {
Async::Ready(NetworkEvent::Connected { conn_info, endpoint }) => {
if self.banned_peers.contains(conn_info.peer_id()) {
self.raw_swarm.peer(conn_info.peer_id().clone())
self.network.peer(conn_info.peer_id().clone())
.into_connected()
.expect("the RawSwarm just notified us that we were connected; QED")
.expect("the Network just notified us that we were connected; QED")
.close();
} else {
self.behaviour.inject_connected(conn_info.peer_id().clone(), endpoint);
}
},
Async::Ready(RawSwarmEvent::NodeClosed { conn_info, endpoint, .. }) => {
Async::Ready(NetworkEvent::NodeClosed { conn_info, endpoint, .. }) => {
self.behaviour.inject_disconnected(conn_info.peer_id(), endpoint);
},
Async::Ready(RawSwarmEvent::Replaced { new_info, closed_endpoint, endpoint, .. }) => {
Async::Ready(NetworkEvent::Replaced { new_info, closed_endpoint, endpoint, .. }) => {
self.behaviour.inject_replaced(new_info.peer_id().clone(), closed_endpoint, endpoint);
},
Async::Ready(RawSwarmEvent::IncomingConnection(incoming)) => {
Async::Ready(NetworkEvent::IncomingConnection(incoming)) => {
let handler = self.behaviour.new_handler();
incoming.accept(handler.into_node_handler_builder());
},
Async::Ready(RawSwarmEvent::NewListenerAddress { listen_addr }) => {
Async::Ready(NetworkEvent::NewListenerAddress { listen_addr }) => {
if !self.listened_addrs.contains(&listen_addr) {
self.listened_addrs.push(listen_addr.clone())
}
self.behaviour.inject_new_listen_addr(&listen_addr);
}
Async::Ready(RawSwarmEvent::ExpiredListenerAddress { listen_addr }) => {
Async::Ready(NetworkEvent::ExpiredListenerAddress { listen_addr }) => {
self.listened_addrs.retain(|a| a != &listen_addr);
self.behaviour.inject_expired_listen_addr(&listen_addr);
}
Async::Ready(RawSwarmEvent::ListenerClosed { .. }) => {},
Async::Ready(RawSwarmEvent::IncomingConnectionError { .. }) => {},
Async::Ready(RawSwarmEvent::DialError { peer_id, multiaddr, error, new_state }) => {
Async::Ready(NetworkEvent::ListenerClosed { .. }) => {},
Async::Ready(NetworkEvent::IncomingConnectionError { .. }) => {},
Async::Ready(NetworkEvent::DialError { peer_id, multiaddr, error, new_state }) => {
self.behaviour.inject_addr_reach_failure(Some(&peer_id), &multiaddr, &error);
if let raw_swarm::PeerState::NotConnected = new_state {
if let network::PeerState::NotConnected = new_state {
self.behaviour.inject_dial_failure(&peer_id);
}
},
Async::Ready(RawSwarmEvent::UnknownPeerDialError { multiaddr, error, .. }) => {
Async::Ready(NetworkEvent::UnknownPeerDialError { multiaddr, error, .. }) => {
self.behaviour.inject_addr_reach_failure(None, &multiaddr, &error);
},
}
// Try to deliver pending event.
if let Some((id, pending)) = self.send_event_to_complete.take() {
if let Some(mut peer) = self.raw_swarm.peer(id.clone()).into_connected() {
if let Some(mut peer) = self.network.peer(id.clone()).into_connected() {
if let AsyncSink::NotReady(e) = pending {
if let Ok(a@AsyncSink::NotReady(_)) = peer.start_send_event(e) {
self.send_event_to_complete = Some((id, a))
@ -409,7 +409,7 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
let behaviour_poll = {
let mut parameters = SwarmPollParameters {
local_peer_id: &mut self.raw_swarm.local_peer_id(),
local_peer_id: &mut self.network.local_peer_id(),
supported_protocols: &self.supported_protocols,
listened_addrs: &self.listened_addrs,
external_addrs: &self.external_addrs
@ -418,7 +418,7 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
};
match behaviour_poll {
Async::NotReady if raw_swarm_not_ready => return Ok(Async::NotReady),
Async::NotReady if network_not_ready => return Ok(Async::NotReady),
Async::NotReady => (),
Async::Ready(NetworkBehaviourAction::GenerateEvent(event)) => {
return Ok(Async::Ready(Some(event)))
@ -434,7 +434,7 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
}
},
Async::Ready(NetworkBehaviourAction::SendEvent { peer_id, event }) => {
if let Some(mut peer) = self.raw_swarm.peer(peer_id.clone()).into_connected() {
if let Some(mut peer) = self.network.peer(peer_id.clone()).into_connected() {
if let Ok(a@AsyncSink::NotReady(_)) = peer.start_send_event(event) {
self.send_event_to_complete = Some((peer_id, a))
} else if let Ok(Async::NotReady) = peer.complete_send_event() {
@ -443,7 +443,7 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
}
},
Async::Ready(NetworkBehaviourAction::ReportObservedAddr { address }) => {
for addr in self.raw_swarm.nat_traversal(&address) {
for addr in self.network.nat_traversal(&address) {
if self.external_addrs.iter().all(|a| *a != addr) {
self.behaviour.inject_new_external_addr(&addr);
}
@ -547,10 +547,10 @@ where TBehaviour: NetworkBehaviour,
.map(|info| info.protocol_name().to_vec())
.collect();
let raw_swarm = RawSwarm::new_with_incoming_limit(self.transport, self.local_peer_id, self.incoming_limit);
let network = Network::new_with_incoming_limit(self.transport, self.local_peer_id, self.incoming_limit);
ExpandedSwarm {
raw_swarm,
network,
behaviour: self.behaviour,
supported_protocols,
listened_addrs: SmallVec::new(),
@ -628,7 +628,7 @@ mod tests {
let behaviour = DummyBehaviour{marker: PhantomData};
let swarm = SwarmBuilder::new(transport, behaviour, id.into())
.incoming_limit(Some(4)).build();
assert_eq!(swarm.raw_swarm.incoming_limit(), Some(4));
assert_eq!(swarm.network.incoming_limit(), Some(4));
}
#[test]
@ -637,6 +637,6 @@ mod tests {
let transport = DummyTransport::<(PeerId, Multiplex<DummyStream>)>::new();
let behaviour = DummyBehaviour{marker: PhantomData};
let swarm = SwarmBuilder::new(transport, behaviour, id.into()).build();
assert!(swarm.raw_swarm.incoming_limit().is_none())
assert!(swarm.network.incoming_limit().is_none())
}
}