Clean up directory structure (#426)

* Remove unused circular-buffer crate
* Move transports into subdirectory
* Move misc into subdirectory
* Move stores into subdirectory
* Move multiplexers
* Move protocols
* Move libp2p top layer
* Fix Test: skip doctest if secio isn't enabled
This commit is contained in:
Benjamin Kampmann
2018-08-29 11:24:44 +02:00
committed by GitHub
parent f5ce93c730
commit 2ea49718f3
131 changed files with 146 additions and 1023 deletions

View File

@ -0,0 +1,323 @@
// 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.
use fnv::FnvHashMap;
use futures::{future, Future, Stream};
use libp2p_core::{Multiaddr, MuxedTransport, Transport};
use parking_lot::Mutex;
use protocol::{IdentifyInfo, IdentifyOutput, IdentifyProtocolConfig};
use std::collections::hash_map::Entry;
use std::error::Error;
use std::io::Error as IoError;
use std::sync::Arc;
use tokio_io::{AsyncRead, AsyncWrite};
/// Implementation of `Transport`. See [the crate root description](index.html).
pub struct IdentifyTransport<Trans> {
transport: Trans,
// Each entry is protected by an asynchronous mutex, so that if we dial the same node twice
// simultaneously, the second time will block until the first time has identified it.
cache: Arc<Mutex<FnvHashMap<Multiaddr, CacheEntry>>>,
}
impl<Trans> Clone for IdentifyTransport<Trans>
where Trans: Clone,
{
fn clone(&self) -> Self {
IdentifyTransport {
transport: self.transport.clone(),
cache: self.cache.clone(),
}
}
}
type CacheEntry = future::Shared<Box<Future<Item = IdentifyTransportOutcome, Error = IoError>>>;
impl<Trans> IdentifyTransport<Trans> {
/// Creates an `IdentifyTransport` that wraps around the given transport and peerstore.
#[inline]
pub fn new(transport: Trans) -> Self {
IdentifyTransport {
transport,
cache: Arc::new(Mutex::new(Default::default())),
}
}
}
impl<Trans> Transport for IdentifyTransport<Trans>
where
Trans: Transport + Clone + 'static, // TODO: 'static :(
Trans::Output: AsyncRead + AsyncWrite,
{
type Output = IdentifyTransportOutput<Trans::Output>;
type MultiaddrFuture = future::FutureResult<Multiaddr, IoError>;
type Listener = Box<Stream<Item = Self::ListenerUpgrade, Error = IoError>>;
type ListenerUpgrade = Box<Future<Item = (Self::Output, Self::MultiaddrFuture), Error = IoError>>;
type Dial = Box<Future<Item = (Self::Output, Self::MultiaddrFuture), Error = IoError>>;
#[inline]
fn listen_on(self, addr: Multiaddr) -> Result<(Self::Listener, Multiaddr), (Self, Multiaddr)> {
let (listener, new_addr) = match self.transport.clone().listen_on(addr.clone()) {
Ok((l, a)) => (l, a),
Err((inner, addr)) => {
let id = IdentifyTransport {
transport: inner,
cache: self.cache,
};
return Err((id, addr));
}
};
let identify_upgrade = self.transport.with_upgrade(IdentifyProtocolConfig);
let cache = self.cache.clone();
let listener = listener.map(move |connec| {
let identify_upgrade = identify_upgrade.clone();
let cache = cache.clone();
let fut = connec
.and_then(move |(connec, client_addr)| {
trace!("Incoming connection, waiting for client address");
client_addr.map(move |addr| (connec, addr))
})
.and_then(move |(connec, client_addr)| {
debug!("Incoming connection from {}", client_addr);
// Dial the address that connected to us and try upgrade with the
// identify protocol.
let info_future = cache_entry(&cache, client_addr.clone(), { let client_addr = client_addr.clone(); move || {
debug!("No cache entry for {}, dialing back in order to identify", client_addr);
future::lazy(|| { trace!("Starting identify back"); identify_upgrade
.dial(client_addr)
.unwrap_or_else(|(_, addr)| {
panic!("the multiaddr {} was determined to be valid earlier", addr)
}) })
.map(move |(identify, _)| {
let (info, observed_addr) = match identify {
IdentifyOutput::RemoteInfo { info, observed_addr } => {
(info, observed_addr)
},
_ => unreachable!(
"the identify protocol guarantees that we receive \
remote information when we dial a node"
),
};
debug!("Identified dialed back connection as pubkey {:?}", info.public_key);
IdentifyTransportOutcome {
info,
observed_addr,
}
})
.map_err(move |err| {
debug!("Failed to identify dialed back connection");
err
})
}});
let out = IdentifyTransportOutput {
socket: connec,
info: Box::new(info_future),
};
Ok((out, future::ok(client_addr)))
});
Box::new(fut) as Box<Future<Item = _, Error = _>>
});
Ok((Box::new(listener) as Box<_>, new_addr))
}
#[inline]
fn dial(self, addr: Multiaddr) -> Result<Self::Dial, (Self, Multiaddr)> {
// We dial a first time the node.
let dial = match self.transport.clone().dial(addr) {
Ok(d) => d,
Err((transport, addr)) => {
let id = IdentifyTransport {
transport,
cache: self.cache,
};
return Err((id, addr));
}
};
// Once successfully dialed, we dial again to identify.
let identify_upgrade = self.transport.with_upgrade(IdentifyProtocolConfig);
let cache = self.cache.clone();
let future = dial
.and_then(move |(connec, client_addr)| {
trace!("Dialing successful, waiting for client address");
client_addr.map(move |addr| (connec, addr))
})
.and_then(move |(socket, addr)| {
trace!("Dialing successful ; client address is {}", addr);
let info_future = cache_entry(&cache, addr.clone(), { let addr = addr.clone(); move || {
trace!("No cache entry for {} ; dialing again for identification", addr);
future::lazy(|| { trace!("Starting identify back"); identify_upgrade
.dial(addr)
.unwrap_or_else(|(_, addr)| {
panic!("the multiaddr {} was determined to be valid earlier", addr)
}) })
.map(move |(identify, _)| {
let (info, observed_addr) = match identify {
IdentifyOutput::RemoteInfo { info, observed_addr } => {
(info, observed_addr)
}
_ => unreachable!(
"the identify protocol guarantees that we receive \
remote information when we dial a node"
),
};
IdentifyTransportOutcome {
info,
observed_addr,
}
})
}});
let out = IdentifyTransportOutput {
socket: socket,
info: Box::new(info_future),
};
Ok((out, future::ok(addr)))
});
Ok(Box::new(future) as Box<_>)
}
#[inline]
fn nat_traversal(&self, a: &Multiaddr, b: &Multiaddr) -> Option<Multiaddr> {
self.transport.nat_traversal(a, b)
}
}
impl<Trans> MuxedTransport for IdentifyTransport<Trans>
where
Trans: MuxedTransport + Clone + 'static,
Trans::Output: AsyncRead + AsyncWrite,
{
type Incoming = Box<Future<Item = Self::IncomingUpgrade, Error = IoError>>;
type IncomingUpgrade = Box<Future<Item = (Self::Output, Self::MultiaddrFuture), Error = IoError>>;
#[inline]
fn next_incoming(self) -> Self::Incoming {
let identify_upgrade = self.transport.clone().with_upgrade(IdentifyProtocolConfig);
let cache = self.cache.clone();
let future = self.transport.next_incoming().map(move |incoming| {
let cache = cache.clone();
let future = incoming
.and_then(move |(connec, client_addr)| {
debug!("Incoming substream ; waiting for client address");
client_addr.map(move |addr| (connec, addr))
})
.and_then(move |(connec, client_addr)| {
debug!("Incoming substream from {}", client_addr);
// Dial the address that connected to us and try upgrade with the
// identify protocol.
let info_future = cache_entry(&cache, client_addr.clone(), { let client_addr = client_addr.clone(); move || {
debug!("No cache entry from {} ; dialing back to identify", client_addr);
future::lazy(|| { trace!("Starting identify back"); identify_upgrade
.dial(client_addr)
.unwrap_or_else(|(_, client_addr)| {
panic!("the multiaddr {} was determined to be valid earlier", client_addr)
}) })
.map(move |(identify, _)| {
let (info, observed_addr) = match identify {
IdentifyOutput::RemoteInfo { info, observed_addr } => {
(info, observed_addr)
},
_ => unreachable!(
"the identify protocol guarantees that we receive \
remote information when we dial a node"
),
};
debug!("Identified incoming substream as pubkey {:?}", info.public_key);
IdentifyTransportOutcome {
info,
observed_addr,
}
})
.map_err(move |err| {
debug!("Failed to identify incoming substream");
err
})
}});
let out = IdentifyTransportOutput {
socket: connec,
info: Box::new(info_future),
};
Ok((out, future::ok(client_addr)))
});
Box::new(future) as Box<Future<Item = _, Error = _>>
});
Box::new(future) as Box<_>
}
}
/// Output of the identify transport.
pub struct IdentifyTransportOutput<S> {
/// The socket to communicate with the remote.
pub socket: S,
/// Outcome of the identification of the remote.
pub info: Box<Future<Item = IdentifyTransportOutcome, Error = IoError>>,
}
/// Outcome of the identification of the remote.
#[derive(Debug, Clone)]
pub struct IdentifyTransportOutcome {
/// Identification of the remote.
pub info: IdentifyInfo,
/// Address the remote sees for us.
pub observed_addr: Multiaddr,
}
fn cache_entry<F, Fut>(cache: &Mutex<FnvHashMap<Multiaddr, CacheEntry>>, addr: Multiaddr, if_no_entry: F)
-> impl Future<Item = IdentifyTransportOutcome, Error = IoError>
where F: FnOnce() -> Fut,
Fut: Future<Item = IdentifyTransportOutcome, Error = IoError> + 'static,
{
trace!("Looking up cache entry for {}", addr);
let mut cache = cache.lock();
match cache.entry(addr) {
Entry::Occupied(entry) => {
trace!("Cache entry found, cloning");
future::Either::A(entry.get().clone())
},
Entry::Vacant(entry) => {
trace!("No cache entry available");
let future = (Box::new(if_no_entry()) as Box<Future<Item = _, Error = _>>).shared();
entry.insert(future.clone());
future::Either::B(future)
},
}.map(|out| (*out).clone()).map_err(|err| IoError::new(err.kind(), err.description()))
}
// TODO: test that we receive back what the remote sent us

View File

@ -0,0 +1,90 @@
// 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.
//! Implementation of the `/ipfs/id/1.0.0` protocol. Allows a node A to query another node B which
//! information B knows about A. Also includes the addresses B is listening on.
//!
//! When two nodes connect to each other, the listening half sends a message to the dialing half,
//! indicating the information, and then the protocol stops.
//!
//! # Usage
//!
//! Both low-level and high-level usages are available.
//!
//! ## High-level usage through the `IdentifyTransport` struct
//!
//! This crate provides the `IdentifyTransport` struct, which wraps around a `Transport` and an
//! implementation of `Peerstore`. `IdentifyTransport` is itself a transport that accepts
//! multiaddresses of the form `/p2p/...` or `/ipfs/...`.
//!
//! > **Note**: All the documentation refers to `/p2p/...`, however `/ipfs/...` is also supported.
//!
//! If you dial a multiaddr of the form `/p2p/...`, then the `IdentifyTransport` will look into
//! the `Peerstore` for any known multiaddress for this peer and try to dial them using the
//! underlying transport. If you dial any other multiaddr, then it will dial this multiaddr using
//! the underlying transport, then negotiate the *identify* protocol with the remote in order to
//! obtain its ID, then add it to the peerstore, and finally dial the same multiaddr again and
//! return the connection.
//!
//! Listening doesn't support multiaddresses of the form `/p2p/...` (because that wouldn't make
//! sense). Any address passed to `listen_on` will be passed directly to the underlying transport.
//!
//! Whenever a remote connects to us, either through listening or through `next_incoming`, the
//! `IdentifyTransport` dials back the remote, upgrades the connection to the *identify* protocol
//! in order to obtain the ID of the remote, stores the information in the peerstore, and finally
//! only returns the connection. From the exterior, the multiaddress of the remote is of the form
//! `/p2p/...`. If the remote doesn't support the *identify* protocol, then the socket is closed.
//!
//! Because of the behaviour of `IdentifyProtocol`, it is recommended to build it on top of a
//! `ConnectionReuse`.
//!
//! ## Low-level usage through the `IdentifyProtocolConfig` struct
//!
//! The `IdentifyProtocolConfig` struct implements the `ConnectionUpgrade` trait. Using it will
//! negotiate the *identify* protocol.
//!
//! The output of the upgrade is a `IdentifyOutput`. If we are the dialer, then `IdentifyOutput`
//! will contain the information sent by the remote. If we are the listener, then it will contain
//! a `IdentifySender` struct that can be used to transmit back to the remote the information about
//! it.
extern crate bytes;
extern crate fnv;
extern crate futures;
extern crate libp2p_peerstore;
extern crate libp2p_core;
#[macro_use]
extern crate log;
extern crate multiaddr;
extern crate parking_lot;
extern crate protobuf;
extern crate tokio_codec;
extern crate tokio_io;
extern crate unsigned_varint;
pub use self::identify_transport::IdentifyTransportOutcome;
pub use self::peer_id_transport::{PeerIdTransport, PeerIdTransportOutput};
pub use self::protocol::{IdentifyInfo, IdentifyOutput};
pub use self::protocol::{IdentifyProtocolConfig, IdentifySender};
mod identify_transport;
mod peer_id_transport;
mod protocol;
mod structs_proto;

View File

@ -0,0 +1,360 @@
// 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.
use futures::{future, stream, Future, Stream};
use identify_transport::{IdentifyTransport, IdentifyTransportOutcome};
use libp2p_core::{PeerId, MuxedTransport, Transport};
use multiaddr::{AddrComponent, Multiaddr};
use std::io::{Error as IoError, ErrorKind as IoErrorKind};
use tokio_io::{AsyncRead, AsyncWrite};
/// Implementation of `Transport`. See [the crate root description](index.html).
#[derive(Clone)]
pub struct PeerIdTransport<Trans, AddrRes> {
transport: IdentifyTransport<Trans>,
addr_resolver: AddrRes,
}
impl<Trans, AddrRes> PeerIdTransport<Trans, AddrRes> {
/// Creates an `PeerIdTransport` that wraps around the given transport and address resolver.
#[inline]
pub fn new(transport: Trans, addr_resolver: AddrRes) -> Self {
PeerIdTransport {
transport: IdentifyTransport::new(transport),
addr_resolver,
}
}
}
impl<Trans, AddrRes, AddrResOut> Transport for PeerIdTransport<Trans, AddrRes>
where
Trans: Transport + Clone + 'static, // TODO: 'static :(
Trans::Output: AsyncRead + AsyncWrite,
AddrRes: Fn(PeerId) -> AddrResOut + 'static, // TODO: 'static :(
AddrResOut: IntoIterator<Item = Multiaddr> + 'static, // TODO: 'static :(
{
type Output = PeerIdTransportOutput<Trans::Output>;
type MultiaddrFuture = Box<Future<Item = Multiaddr, Error = IoError>>;
type Listener = Box<Stream<Item = Self::ListenerUpgrade, Error = IoError>>;
type ListenerUpgrade = Box<Future<Item = (Self::Output, Self::MultiaddrFuture), Error = IoError>>;
type Dial = Box<Future<Item = (Self::Output, Self::MultiaddrFuture), Error = IoError>>;
#[inline]
fn listen_on(self, addr: Multiaddr) -> Result<(Self::Listener, Multiaddr), (Self, Multiaddr)> {
// Note that `listen_on` expects a "regular" multiaddr (eg. `/ip/.../tcp/...`),
// and not `/p2p/<foo>`.
let (listener, listened_addr) = match self.transport.listen_on(addr) {
Ok((listener, addr)) => (listener, addr),
Err((inner, addr)) => {
let id = PeerIdTransport {
transport: inner,
addr_resolver: self.addr_resolver,
};
return Err((id, addr));
}
};
let listener = listener.map(move |connec| {
let fut = connec
.and_then(move |(connec, client_addr)| {
client_addr.map(move |addr| (connec, addr))
})
.map(move |(connec, original_addr)| {
debug!("Successfully incoming connection from {}", original_addr);
let info = connec.info.shared();
let out = PeerIdTransportOutput {
socket: connec.socket,
info: Box::new(info.clone()
.map(move |info| (*info).clone())
.map_err(move |err| { let k = err.kind(); IoError::new(k, err) })),
original_addr: original_addr.clone(),
};
let real_addr = Box::new(info
.map_err(move |err| { let k = err.kind(); IoError::new(k, err) })
.map(move |info| {
let peer_id = info.info.public_key.clone().into_peer_id();
debug!("Identified {} as {:?}", original_addr, peer_id);
AddrComponent::P2P(peer_id.into()).into()
})) as Box<Future<Item = _, Error = _>>;
(out, real_addr)
});
Box::new(fut) as Box<Future<Item = _, Error = _>>
});
Ok((Box::new(listener) as Box<_>, listened_addr))
}
#[inline]
fn dial(self, addr: Multiaddr) -> Result<Self::Dial, (Self, Multiaddr)> {
match multiaddr_to_peerid(addr.clone()) {
Ok(peer_id) => {
// If the multiaddress is a peer ID, try each known multiaddress (taken from the
// address resolved) one by one.
let addrs = {
let resolver = &self.addr_resolver;
resolver(peer_id.clone()).into_iter()
};
trace!("Try dialing peer ID {:?} ; loading multiaddrs from addr resolver", peer_id);
let transport = self.transport;
let future = stream::iter_ok(addrs)
// Try to dial each address through the transport.
.filter_map(move |addr| {
match transport.clone().dial(addr) {
Ok(dial) => Some(dial),
Err((_, addr)) => {
debug!("Address {} not supported by underlying transport", addr);
None
},
}
})
.and_then(move |dial| dial)
// Pick the first non-failing dial result by filtering out the ones which fail.
.then(|res| Ok(res))
.filter_map(|res| res.ok())
.into_future()
.map_err(|(err, _)| err)
.and_then(move |(connec, _)| {
match connec {
Some(connec) => Ok((connec, peer_id)),
None => {
debug!("All multiaddresses failed when dialing peer {:?}", peer_id);
Err(IoError::new(IoErrorKind::Other, "couldn't find any multiaddress for peer"))
},
}
})
.and_then(move |((connec, original_addr), peer_id)| {
original_addr.map(move |addr| (connec, addr, peer_id))
})
.and_then(move |(connec, original_addr, peer_id)| {
debug!("Successfully dialed peer {:?} through {}", peer_id, original_addr);
let out = PeerIdTransportOutput {
socket: connec.socket,
info: connec.info,
original_addr: original_addr,
};
// Replace the multiaddress with the one of the form `/p2p/...` or `/ipfs/...`.
Ok((out, Box::new(future::ok(addr)) as Box<Future<Item = _, Error = _>>))
});
Ok(Box::new(future) as Box<_>)
}
Err(addr) => {
// If the multiaddress is something else, propagate it to the underlying transport.
trace!("Propagating {} to the underlying transport", addr);
let dial = match self.transport.dial(addr) {
Ok(d) => d,
Err((inner, addr)) => {
let id = PeerIdTransport {
transport: inner,
addr_resolver: self.addr_resolver,
};
return Err((id, addr));
}
};
let future = dial
.and_then(move |(connec, original_addr)| {
original_addr.map(move |addr| (connec, addr))
})
.map(move |(connec, original_addr)| {
debug!("Successfully dialed {}", original_addr);
let info = connec.info.shared();
let out = PeerIdTransportOutput {
socket: connec.socket,
info: Box::new(info.clone()
.map(move |info| (*info).clone())
.map_err(move |err| { let k = err.kind(); IoError::new(k, err) })),
original_addr: original_addr.clone(),
};
let real_addr = Box::new(info
.map_err(move |err| { let k = err.kind(); IoError::new(k, err) })
.map(move |info| {
let peer_id = info.info.public_key.clone().into_peer_id();
debug!("Identified {} as {:?}", original_addr, peer_id);
AddrComponent::P2P(peer_id.into()).into()
})) as Box<Future<Item = _, Error = _>>;
(out, real_addr)
});
Ok(Box::new(future) as Box<_>)
}
}
}
#[inline]
fn nat_traversal(&self, a: &Multiaddr, b: &Multiaddr) -> Option<Multiaddr> {
self.transport.nat_traversal(a, b)
}
}
impl<Trans, AddrRes, AddrResOut> MuxedTransport for PeerIdTransport<Trans, AddrRes>
where
Trans: MuxedTransport + Clone + 'static,
Trans::Output: AsyncRead + AsyncWrite,
AddrRes: Fn(PeerId) -> AddrResOut + 'static, // TODO: 'static :(
AddrResOut: IntoIterator<Item = Multiaddr> + 'static, // TODO: 'static :(
{
type Incoming = Box<Future<Item = Self::IncomingUpgrade, Error = IoError>>;
type IncomingUpgrade = Box<Future<Item = (Self::Output, Self::MultiaddrFuture), Error = IoError>>;
#[inline]
fn next_incoming(self) -> Self::Incoming {
let future = self.transport.next_incoming().map(move |incoming| {
let future = incoming
.and_then(move |(connec, original_addr)| {
original_addr.map(move |addr| (connec, addr))
})
.map(move |(connec, original_addr)| {
debug!("Successful incoming substream from {}", original_addr);
let info = connec.info.shared();
let out = PeerIdTransportOutput {
socket: connec.socket,
info: Box::new(info.clone()
.map(move |info| (*info).clone())
.map_err(move |err| { let k = err.kind(); IoError::new(k, err) })),
original_addr: original_addr.clone(),
};
let real_addr = Box::new(info
.map_err(move |err| { let k = err.kind(); IoError::new(k, err) })
.map(move |info| {
let peer_id = info.info.public_key.clone().into_peer_id();
debug!("Identified {} as {:?}", original_addr, peer_id);
AddrComponent::P2P(peer_id.into()).into()
})) as Box<Future<Item = _, Error = _>>;
(out, real_addr)
});
Box::new(future) as Box<Future<Item = _, Error = _>>
});
Box::new(future) as Box<_>
}
}
/// Output of the identify transport.
pub struct PeerIdTransportOutput<S> {
/// The socket to communicate with the remote.
pub socket: S,
/// Identification of the remote.
/// This may not be known immediately, hence why we use a future.
pub info: Box<Future<Item = IdentifyTransportOutcome, Error = IoError>>,
/// Original address of the remote.
/// This layer turns the address of the remote into the `/p2p/...` form, but stores the
/// original address in this field.
pub original_addr: Multiaddr,
}
// If the multiaddress is in the form `/p2p/...`, turn it into a `PeerId`.
// Otherwise, return it as-is.
fn multiaddr_to_peerid(addr: Multiaddr) -> Result<PeerId, Multiaddr> {
let components = addr.iter().collect::<Vec<_>>();
if components.len() < 1 {
return Err(addr);
}
match components.last() {
Some(&AddrComponent::P2P(ref peer_id)) => {
match PeerId::from_multihash(peer_id.clone()) {
Ok(peer_id) => Ok(peer_id),
Err(_) => Err(addr),
}
}
_ => Err(addr),
}
}
#[cfg(test)]
mod tests {
extern crate libp2p_tcp_transport;
extern crate tokio_current_thread;
use self::libp2p_tcp_transport::TcpConfig;
use PeerIdTransport;
use futures::{Future, Stream};
use libp2p_core::{Transport, PeerId, PublicKey};
use multiaddr::{AddrComponent, Multiaddr};
use std::io::Error as IoError;
use std::iter;
#[test]
fn dial_peer_id() {
// When we dial an `/p2p/...` address, the `PeerIdTransport` should look into the
// peerstore and dial one of the known multiaddresses of the node instead.
#[derive(Debug, Clone)]
struct UnderlyingTrans {
inner: TcpConfig,
}
impl Transport for UnderlyingTrans {
type Output = <TcpConfig as Transport>::Output;
type MultiaddrFuture = <TcpConfig as Transport>::MultiaddrFuture;
type Listener = Box<Stream<Item = Self::ListenerUpgrade, Error = IoError>>;
type ListenerUpgrade = Box<Future<Item = (Self::Output, Self::MultiaddrFuture), Error = IoError>>;
type Dial = <TcpConfig as Transport>::Dial;
#[inline]
fn listen_on(
self,
_: Multiaddr,
) -> Result<(Self::Listener, Multiaddr), (Self, Multiaddr)> {
unreachable!()
}
#[inline]
fn dial(self, addr: Multiaddr) -> Result<Self::Dial, (Self, Multiaddr)> {
assert_eq!(
addr,
"/ip4/127.0.0.1/tcp/12345".parse::<Multiaddr>().unwrap()
);
Ok(self.inner.dial(addr).unwrap_or_else(|_| panic!()))
}
#[inline]
fn nat_traversal(&self, a: &Multiaddr, b: &Multiaddr) -> Option<Multiaddr> {
self.inner.nat_traversal(a, b)
}
}
let peer_id = PeerId::from_public_key(PublicKey::Ed25519(vec![1, 2, 3, 4]));
let underlying = UnderlyingTrans {
inner: TcpConfig::new(),
};
let transport = PeerIdTransport::new(underlying, {
let peer_id = peer_id.clone();
move |addr| {
assert_eq!(addr, peer_id);
vec!["/ip4/127.0.0.1/tcp/12345".parse().unwrap()]
}
});
let future = transport
.dial(iter::once(AddrComponent::P2P(peer_id.into())).collect())
.unwrap_or_else(|_| panic!())
.then::<_, Result<(), ()>>(|_| Ok(()));
let _ = tokio_current_thread::block_on_all(future).unwrap();
}
}

View File

@ -0,0 +1,311 @@
// 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.
use bytes::{Bytes, BytesMut};
use futures::{future, Future, Sink, Stream};
use libp2p_core::{ConnectionUpgrade, Endpoint, PublicKey};
use multiaddr::Multiaddr;
use protobuf::Message as ProtobufMessage;
use protobuf::parse_from_bytes as protobuf_parse_from_bytes;
use protobuf::RepeatedField;
use std::io::{Error as IoError, ErrorKind as IoErrorKind};
use std::iter;
use structs_proto;
use tokio_codec::Framed;
use tokio_io::{AsyncRead, AsyncWrite};
use unsigned_varint::codec;
/// Configuration for an upgrade to the identity protocol.
#[derive(Debug, Clone)]
pub struct IdentifyProtocolConfig;
/// Output of the connection upgrade.
pub enum IdentifyOutput<T> {
/// We obtained information from the remote. Happens when we are the dialer.
RemoteInfo {
/// Information about the remote.
info: IdentifyInfo,
/// Address the remote sees for us.
observed_addr: Multiaddr,
},
/// We opened a connection to the remote and need to send it information. Happens when we are
/// the listener.
Sender {
/// Object used to send identify info to the client.
sender: IdentifySender<T>,
},
}
/// Object used to send back information to the client.
pub struct IdentifySender<T> {
inner: Framed<T, codec::UviBytes<Vec<u8>>>,
}
impl<'a, T> IdentifySender<T>
where
T: AsyncWrite + 'a,
{
/// Sends back information to the client. Returns a future that is signalled whenever the
/// info have been sent.
pub fn send(
self,
info: IdentifyInfo,
observed_addr: &Multiaddr,
) -> Box<Future<Item = (), Error = IoError> + 'a> {
debug!("Sending identify info to client");
trace!("Sending: {:?}", info);
let listen_addrs = info.listen_addrs
.into_iter()
.map(|addr| addr.into_bytes())
.collect();
let mut message = structs_proto::Identify::new();
message.set_agentVersion(info.agent_version);
message.set_protocolVersion(info.protocol_version);
message.set_publicKey(info.public_key.into_protobuf_encoding());
message.set_listenAddrs(listen_addrs);
message.set_observedAddr(observed_addr.to_bytes());
message.set_protocols(RepeatedField::from_vec(info.protocols));
let bytes = message
.write_to_bytes()
.expect("writing protobuf failed ; should never happen");
let future = self.inner.send(bytes).map(|_| ());
Box::new(future) as Box<_>
}
}
/// Information sent from the listener to the dialer.
#[derive(Debug, Clone)]
pub struct IdentifyInfo {
/// Public key of the node.
pub public_key: PublicKey,
/// Version of the "global" protocol, eg. `ipfs/1.0.0` or `polkadot/1.0.0`.
pub protocol_version: String,
/// Name and version of the client. Can be thought as similar to the `User-Agent` header
/// of HTTP.
pub agent_version: String,
/// Addresses that the node is listening on.
pub listen_addrs: Vec<Multiaddr>,
/// Protocols supported by the node, eg. `/ipfs/ping/1.0.0`.
pub protocols: Vec<String>,
}
impl<C, Maf> ConnectionUpgrade<C, Maf> for IdentifyProtocolConfig
where
C: AsyncRead + AsyncWrite + 'static,
Maf: Future<Item = Multiaddr, Error = IoError> + 'static,
{
type NamesIter = iter::Once<(Bytes, Self::UpgradeIdentifier)>;
type UpgradeIdentifier = ();
type Output = IdentifyOutput<C>;
type MultiaddrFuture = future::Either<future::FutureResult<Multiaddr, IoError>, Maf>;
type Future = Box<Future<Item = (Self::Output, Self::MultiaddrFuture), Error = IoError>>;
#[inline]
fn protocol_names(&self) -> Self::NamesIter {
iter::once((Bytes::from("/ipfs/id/1.0.0"), ()))
}
fn upgrade(self, socket: C, _: (), ty: Endpoint, remote_addr: Maf) -> Self::Future {
trace!("Upgrading connection as {:?}", ty);
let socket = Framed::new(socket, codec::UviBytes::default());
match ty {
Endpoint::Dialer => {
let future = socket
.into_future()
.map(|(msg, _)| msg)
.map_err(|(err, _)| err)
.and_then(|msg| {
debug!("Received identify message");
if let Some(msg) = msg {
let (info, observed_addr) = match parse_proto_msg(msg) {
Ok(v) => v,
Err(err) => {
debug!("Failed to parse protobuf message ; error = {:?}", err);
return Err(err.into());
}
};
trace!("Remote observes us as {:?}", observed_addr);
trace!("Information received: {:?}", info);
let out = IdentifyOutput::RemoteInfo {
info,
observed_addr: observed_addr.clone(),
};
Ok((out, future::Either::A(future::ok(observed_addr))))
} else {
debug!("Identify protocol stream closed before receiving info");
Err(IoErrorKind::InvalidData.into())
}
});
Box::new(future) as Box<_>
}
Endpoint::Listener => {
let sender = IdentifySender { inner: socket };
let future = future::ok({
let io = IdentifyOutput::Sender {
sender,
};
(io, future::Either::B(remote_addr))
});
Box::new(future) as Box<_>
}
}
}
}
// Turns a protobuf message into an `IdentifyInfo` and an observed address. If something bad
// happens, turn it into an `IoError`.
fn parse_proto_msg(msg: BytesMut) -> Result<(IdentifyInfo, Multiaddr), IoError> {
match protobuf_parse_from_bytes::<structs_proto::Identify>(&msg) {
Ok(mut msg) => {
// Turn a `Vec<u8>` into a `Multiaddr`. If something bad happens, turn it into
// an `IoError`.
fn bytes_to_multiaddr(bytes: Vec<u8>) -> Result<Multiaddr, IoError> {
Multiaddr::from_bytes(bytes)
.map_err(|err| IoError::new(IoErrorKind::InvalidData, err))
}
let listen_addrs = {
let mut addrs = Vec::new();
for addr in msg.take_listenAddrs().into_iter() {
addrs.push(bytes_to_multiaddr(addr)?);
}
addrs
};
let observed_addr = bytes_to_multiaddr(msg.take_observedAddr())?;
let info = IdentifyInfo {
public_key: PublicKey::from_protobuf_encoding(msg.get_publicKey())?,
protocol_version: msg.take_protocolVersion(),
agent_version: msg.take_agentVersion(),
listen_addrs: listen_addrs,
protocols: msg.take_protocols().into_vec(),
};
Ok((info, observed_addr))
}
Err(err) => Err(IoError::new(IoErrorKind::InvalidData, err)),
}
}
#[cfg(test)]
mod tests {
extern crate libp2p_tcp_transport;
extern crate tokio_current_thread;
use self::libp2p_tcp_transport::TcpConfig;
use futures::{Future, Stream};
use libp2p_core::{PublicKey, Transport};
use std::sync::mpsc;
use std::thread;
use {IdentifyInfo, IdentifyOutput, IdentifyProtocolConfig};
#[test]
fn correct_transfer() {
// We open a server and a client, send info from the server to the client, and check that
// they were successfully received.
let (tx, rx) = mpsc::channel();
let bg_thread = thread::spawn(move || {
let transport = TcpConfig::new().with_upgrade(IdentifyProtocolConfig);
let (listener, addr) = transport
.listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap())
.unwrap();
tx.send(addr).unwrap();
let future = listener
.into_future()
.map_err(|(err, _)| err)
.and_then(|(client, _)| client.unwrap().map(|v| v.0))
.and_then(|identify| match identify {
IdentifyOutput::Sender { sender, .. } => sender.send(
IdentifyInfo {
public_key: PublicKey::Ed25519(vec![1, 2, 3, 4, 5, 7]),
protocol_version: "proto_version".to_owned(),
agent_version: "agent_version".to_owned(),
listen_addrs: vec![
"/ip4/80.81.82.83/tcp/500".parse().unwrap(),
"/ip6/::1/udp/1000".parse().unwrap(),
],
protocols: vec!["proto1".to_string(), "proto2".to_string()],
},
&"/ip4/100.101.102.103/tcp/5000".parse().unwrap(),
),
_ => panic!(),
});
let _ = tokio_current_thread::block_on_all(future).unwrap();
});
let transport = TcpConfig::new().with_upgrade(IdentifyProtocolConfig);
let future = transport
.dial(rx.recv().unwrap())
.unwrap_or_else(|_| panic!())
.and_then(|(identify, _)| match identify {
IdentifyOutput::RemoteInfo {
info,
observed_addr,
} => {
assert_eq!(
observed_addr,
"/ip4/100.101.102.103/tcp/5000".parse().unwrap()
);
assert_eq!(info.public_key, PublicKey::Ed25519(vec![1, 2, 3, 4, 5, 7]));
assert_eq!(info.protocol_version, "proto_version");
assert_eq!(info.agent_version, "agent_version");
assert_eq!(
info.listen_addrs,
&[
"/ip4/80.81.82.83/tcp/500".parse().unwrap(),
"/ip6/::1/udp/1000".parse().unwrap()
]
);
assert_eq!(
info.protocols,
&["proto1".to_string(), "proto2".to_string()]
);
Ok(())
}
_ => panic!(),
});
let _ = tokio_current_thread::block_on_all(future).unwrap();
bg_thread.join().unwrap();
}
}

View File

@ -0,0 +1,497 @@
// This file is generated by rust-protobuf 2.0.2. Do not edit
// @generated
// https://github.com/Manishearth/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy)]
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(trivial_casts)]
#![allow(unsafe_code)]
#![allow(unused_imports)]
#![allow(unused_results)]
use protobuf::Message as Message_imported_for_functions;
use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions;
#[derive(PartialEq,Clone,Default)]
pub struct Identify {
// message fields
protocolVersion: ::protobuf::SingularField<::std::string::String>,
agentVersion: ::protobuf::SingularField<::std::string::String>,
publicKey: ::protobuf::SingularField<::std::vec::Vec<u8>>,
listenAddrs: ::protobuf::RepeatedField<::std::vec::Vec<u8>>,
observedAddr: ::protobuf::SingularField<::std::vec::Vec<u8>>,
protocols: ::protobuf::RepeatedField<::std::string::String>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl Identify {
pub fn new() -> Identify {
::std::default::Default::default()
}
// optional string protocolVersion = 5;
pub fn clear_protocolVersion(&mut self) {
self.protocolVersion.clear();
}
pub fn has_protocolVersion(&self) -> bool {
self.protocolVersion.is_some()
}
// Param is passed by value, moved
pub fn set_protocolVersion(&mut self, v: ::std::string::String) {
self.protocolVersion = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_protocolVersion(&mut self) -> &mut ::std::string::String {
if self.protocolVersion.is_none() {
self.protocolVersion.set_default();
}
self.protocolVersion.as_mut().unwrap()
}
// Take field
pub fn take_protocolVersion(&mut self) -> ::std::string::String {
self.protocolVersion.take().unwrap_or_else(|| ::std::string::String::new())
}
pub fn get_protocolVersion(&self) -> &str {
match self.protocolVersion.as_ref() {
Some(v) => &v,
None => "",
}
}
// optional string agentVersion = 6;
pub fn clear_agentVersion(&mut self) {
self.agentVersion.clear();
}
pub fn has_agentVersion(&self) -> bool {
self.agentVersion.is_some()
}
// Param is passed by value, moved
pub fn set_agentVersion(&mut self, v: ::std::string::String) {
self.agentVersion = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_agentVersion(&mut self) -> &mut ::std::string::String {
if self.agentVersion.is_none() {
self.agentVersion.set_default();
}
self.agentVersion.as_mut().unwrap()
}
// Take field
pub fn take_agentVersion(&mut self) -> ::std::string::String {
self.agentVersion.take().unwrap_or_else(|| ::std::string::String::new())
}
pub fn get_agentVersion(&self) -> &str {
match self.agentVersion.as_ref() {
Some(v) => &v,
None => "",
}
}
// optional bytes publicKey = 1;
pub fn clear_publicKey(&mut self) {
self.publicKey.clear();
}
pub fn has_publicKey(&self) -> bool {
self.publicKey.is_some()
}
// Param is passed by value, moved
pub fn set_publicKey(&mut self, v: ::std::vec::Vec<u8>) {
self.publicKey = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_publicKey(&mut self) -> &mut ::std::vec::Vec<u8> {
if self.publicKey.is_none() {
self.publicKey.set_default();
}
self.publicKey.as_mut().unwrap()
}
// Take field
pub fn take_publicKey(&mut self) -> ::std::vec::Vec<u8> {
self.publicKey.take().unwrap_or_else(|| ::std::vec::Vec::new())
}
pub fn get_publicKey(&self) -> &[u8] {
match self.publicKey.as_ref() {
Some(v) => &v,
None => &[],
}
}
// repeated bytes listenAddrs = 2;
pub fn clear_listenAddrs(&mut self) {
self.listenAddrs.clear();
}
// Param is passed by value, moved
pub fn set_listenAddrs(&mut self, v: ::protobuf::RepeatedField<::std::vec::Vec<u8>>) {
self.listenAddrs = v;
}
// Mutable pointer to the field.
pub fn mut_listenAddrs(&mut self) -> &mut ::protobuf::RepeatedField<::std::vec::Vec<u8>> {
&mut self.listenAddrs
}
// Take field
pub fn take_listenAddrs(&mut self) -> ::protobuf::RepeatedField<::std::vec::Vec<u8>> {
::std::mem::replace(&mut self.listenAddrs, ::protobuf::RepeatedField::new())
}
pub fn get_listenAddrs(&self) -> &[::std::vec::Vec<u8>] {
&self.listenAddrs
}
// optional bytes observedAddr = 4;
pub fn clear_observedAddr(&mut self) {
self.observedAddr.clear();
}
pub fn has_observedAddr(&self) -> bool {
self.observedAddr.is_some()
}
// Param is passed by value, moved
pub fn set_observedAddr(&mut self, v: ::std::vec::Vec<u8>) {
self.observedAddr = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_observedAddr(&mut self) -> &mut ::std::vec::Vec<u8> {
if self.observedAddr.is_none() {
self.observedAddr.set_default();
}
self.observedAddr.as_mut().unwrap()
}
// Take field
pub fn take_observedAddr(&mut self) -> ::std::vec::Vec<u8> {
self.observedAddr.take().unwrap_or_else(|| ::std::vec::Vec::new())
}
pub fn get_observedAddr(&self) -> &[u8] {
match self.observedAddr.as_ref() {
Some(v) => &v,
None => &[],
}
}
// repeated string protocols = 3;
pub fn clear_protocols(&mut self) {
self.protocols.clear();
}
// Param is passed by value, moved
pub fn set_protocols(&mut self, v: ::protobuf::RepeatedField<::std::string::String>) {
self.protocols = v;
}
// Mutable pointer to the field.
pub fn mut_protocols(&mut self) -> &mut ::protobuf::RepeatedField<::std::string::String> {
&mut self.protocols
}
// Take field
pub fn take_protocols(&mut self) -> ::protobuf::RepeatedField<::std::string::String> {
::std::mem::replace(&mut self.protocols, ::protobuf::RepeatedField::new())
}
pub fn get_protocols(&self) -> &[::std::string::String] {
&self.protocols
}
}
impl ::protobuf::Message for Identify {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while !is.eof()? {
let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number {
5 => {
::protobuf::rt::read_singular_string_into(wire_type, is, &mut self.protocolVersion)?;
},
6 => {
::protobuf::rt::read_singular_string_into(wire_type, is, &mut self.agentVersion)?;
},
1 => {
::protobuf::rt::read_singular_bytes_into(wire_type, is, &mut self.publicKey)?;
},
2 => {
::protobuf::rt::read_repeated_bytes_into(wire_type, is, &mut self.listenAddrs)?;
},
4 => {
::protobuf::rt::read_singular_bytes_into(wire_type, is, &mut self.observedAddr)?;
},
3 => {
::protobuf::rt::read_repeated_string_into(wire_type, is, &mut self.protocols)?;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if let Some(ref v) = self.protocolVersion.as_ref() {
my_size += ::protobuf::rt::string_size(5, &v);
}
if let Some(ref v) = self.agentVersion.as_ref() {
my_size += ::protobuf::rt::string_size(6, &v);
}
if let Some(ref v) = self.publicKey.as_ref() {
my_size += ::protobuf::rt::bytes_size(1, &v);
}
for value in &self.listenAddrs {
my_size += ::protobuf::rt::bytes_size(2, &value);
};
if let Some(ref v) = self.observedAddr.as_ref() {
my_size += ::protobuf::rt::bytes_size(4, &v);
}
for value in &self.protocols {
my_size += ::protobuf::rt::string_size(3, &value);
};
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if let Some(ref v) = self.protocolVersion.as_ref() {
os.write_string(5, &v)?;
}
if let Some(ref v) = self.agentVersion.as_ref() {
os.write_string(6, &v)?;
}
if let Some(ref v) = self.publicKey.as_ref() {
os.write_bytes(1, &v)?;
}
for v in &self.listenAddrs {
os.write_bytes(2, &v)?;
};
if let Some(ref v) = self.observedAddr.as_ref() {
os.write_bytes(4, &v)?;
}
for v in &self.protocols {
os.write_string(3, &v)?;
};
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> {
self
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
Self::descriptor_static()
}
fn new() -> Identify {
Identify::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_singular_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
"protocolVersion",
|m: &Identify| { &m.protocolVersion },
|m: &mut Identify| { &mut m.protocolVersion },
));
fields.push(::protobuf::reflect::accessor::make_singular_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
"agentVersion",
|m: &Identify| { &m.agentVersion },
|m: &mut Identify| { &mut m.agentVersion },
));
fields.push(::protobuf::reflect::accessor::make_singular_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"publicKey",
|m: &Identify| { &m.publicKey },
|m: &mut Identify| { &mut m.publicKey },
));
fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"listenAddrs",
|m: &Identify| { &m.listenAddrs },
|m: &mut Identify| { &mut m.listenAddrs },
));
fields.push(::protobuf::reflect::accessor::make_singular_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"observedAddr",
|m: &Identify| { &m.observedAddr },
|m: &mut Identify| { &mut m.observedAddr },
));
fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
"protocols",
|m: &Identify| { &m.protocols },
|m: &mut Identify| { &mut m.protocols },
));
::protobuf::reflect::MessageDescriptor::new::<Identify>(
"Identify",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static Identify {
static mut instance: ::protobuf::lazy::Lazy<Identify> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const Identify,
};
unsafe {
instance.get(Identify::new)
}
}
}
impl ::protobuf::Clear for Identify {
fn clear(&mut self) {
self.clear_protocolVersion();
self.clear_agentVersion();
self.clear_publicKey();
self.clear_listenAddrs();
self.clear_observedAddr();
self.clear_protocols();
self.unknown_fields.clear();
}
}
impl ::std::fmt::Debug for Identify {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for Identify {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef {
::protobuf::reflect::ProtobufValueRef::Message(self)
}
}
static file_descriptor_proto_data: &'static [u8] = b"\
\n\rstructs.proto\"\xda\x01\n\x08Identify\x12(\n\x0fprotocolVersion\x18\
\x05\x20\x01(\tR\x0fprotocolVersion\x12\"\n\x0cagentVersion\x18\x06\x20\
\x01(\tR\x0cagentVersion\x12\x1c\n\tpublicKey\x18\x01\x20\x01(\x0cR\tpub\
licKey\x12\x20\n\x0blistenAddrs\x18\x02\x20\x03(\x0cR\x0blistenAddrs\x12\
\"\n\x0cobservedAddr\x18\x04\x20\x01(\x0cR\x0cobservedAddr\x12\x1c\n\tpr\
otocols\x18\x03\x20\x03(\tR\tprotocolsJ\xc2\t\n\x06\x12\x04\0\0\x16\x01\
\n\n\n\x02\x04\0\x12\x04\0\0\x16\x01\n\n\n\x03\x04\0\x01\x12\x03\0\x08\
\x10\nX\n\x04\x04\0\x02\0\x12\x03\x02\x02&\x1a8\x20protocolVersion\x20de\
termines\x20compatibility\x20between\x20peers\n\"\x11\x20e.g.\x20ipfs/1.\
0.0\n\n\x0c\n\x05\x04\0\x02\0\x04\x12\x03\x02\x02\n\n\x0c\n\x05\x04\0\
\x02\0\x05\x12\x03\x02\x0b\x11\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x02\
\x12!\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x02$%\n\x9f\x01\n\x04\x04\0\
\x02\x01\x12\x03\x06\x02#\x1a|\x20agentVersion\x20is\x20like\x20a\x20Use\
rAgent\x20string\x20in\x20browsers,\x20or\x20client\x20version\x20in\x20\
bittorrent\n\x20includes\x20the\x20client\x20name\x20and\x20client.\n\"\
\x14\x20e.g.\x20go-ipfs/0.1.0\n\n\x0c\n\x05\x04\0\x02\x01\x04\x12\x03\
\x06\x02\n\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x06\x0b\x11\n\x0c\n\x05\
\x04\0\x02\x01\x01\x12\x03\x06\x12\x1e\n\x0c\n\x05\x04\0\x02\x01\x03\x12\
\x03\x06!\"\n\xe3\x01\n\x04\x04\0\x02\x02\x12\x03\x0b\x02\x1f\x1a\xd5\
\x01\x20publicKey\x20is\x20this\x20node's\x20public\x20key\x20(which\x20\
also\x20gives\x20its\x20node.ID)\n\x20-\x20may\x20not\x20need\x20to\x20b\
e\x20sent,\x20as\x20secure\x20channel\x20implies\x20it\x20has\x20been\
\x20sent.\n\x20-\x20then\x20again,\x20if\x20we\x20change\x20/\x20disable\
\x20secure\x20channel,\x20may\x20still\x20want\x20it.\n\n\x0c\n\x05\x04\
\0\x02\x02\x04\x12\x03\x0b\x02\n\n\x0c\n\x05\x04\0\x02\x02\x05\x12\x03\
\x0b\x0b\x10\n\x0c\n\x05\x04\0\x02\x02\x01\x12\x03\x0b\x11\x1a\n\x0c\n\
\x05\x04\0\x02\x02\x03\x12\x03\x0b\x1d\x1e\n]\n\x04\x04\0\x02\x03\x12\
\x03\x0e\x02!\x1aP\x20listenAddrs\x20are\x20the\x20multiaddrs\x20the\x20\
sender\x20node\x20listens\x20for\x20open\x20connections\x20on\n\n\x0c\n\
\x05\x04\0\x02\x03\x04\x12\x03\x0e\x02\n\n\x0c\n\x05\x04\0\x02\x03\x05\
\x12\x03\x0e\x0b\x10\n\x0c\n\x05\x04\0\x02\x03\x01\x12\x03\x0e\x11\x1c\n\
\x0c\n\x05\x04\0\x02\x03\x03\x12\x03\x0e\x1f\x20\n\x81\x02\n\x04\x04\0\
\x02\x04\x12\x03\x13\x02\"\x1a\xf3\x01\x20oservedAddr\x20is\x20the\x20mu\
ltiaddr\x20of\x20the\x20remote\x20endpoint\x20that\x20the\x20sender\x20n\
ode\x20perceives\n\x20this\x20is\x20useful\x20information\x20to\x20conve\
y\x20to\x20the\x20other\x20side,\x20as\x20it\x20helps\x20the\x20remote\
\x20endpoint\n\x20determine\x20whether\x20its\x20connection\x20to\x20the\
\x20local\x20peer\x20goes\x20through\x20NAT.\n\n\x0c\n\x05\x04\0\x02\x04\
\x04\x12\x03\x13\x02\n\n\x0c\n\x05\x04\0\x02\x04\x05\x12\x03\x13\x0b\x10\
\n\x0c\n\x05\x04\0\x02\x04\x01\x12\x03\x13\x11\x1d\n\x0c\n\x05\x04\0\x02\
\x04\x03\x12\x03\x13\x20!\n\x0b\n\x04\x04\0\x02\x05\x12\x03\x15\x02\x20\
\n\x0c\n\x05\x04\0\x02\x05\x04\x12\x03\x15\x02\n\n\x0c\n\x05\x04\0\x02\
\x05\x05\x12\x03\x15\x0b\x11\n\x0c\n\x05\x04\0\x02\x05\x01\x12\x03\x15\
\x12\x1b\n\x0c\n\x05\x04\0\x02\x05\x03\x12\x03\x15\x1e\x1f\
";
static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto,
};
fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {
::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap()
}
pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
unsafe {
file_descriptor_proto_lazy.get(|| {
parse_descriptor_proto()
})
}
}