-
Notifications
You must be signed in to change notification settings - Fork 963
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add a IdentifyTransport #569
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8ee99ac
Add a IdentifyTransport
tomaka 4747da2
Merge remote-tracking branch 'upstream/master' into peerid-retreiver
tomaka 7623752
Retreiver -> Retriever
tomaka 09599cf
Move the muxer in the IdRetrieverState
tomaka 6079d46
Merge remote-tracking branch 'upstream/master' into peerid-retreiver
tomaka 988d7b2
Merge branch 'master' into peerid-retreiver
tomaka File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,229 @@ | ||
// 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. | ||
|
||
//! Contains the `IdentifyTransport` type. | ||
|
||
use futures::prelude::*; | ||
use libp2p_core::{Endpoint, Multiaddr, PeerId, PublicKey, Transport, muxing, upgrade::apply}; | ||
use protocol::{IdentifyOutput, IdentifyProtocolConfig}; | ||
use std::io::{Error as IoError, ErrorKind as IoErrorKind}; | ||
use std::mem; | ||
use std::sync::Arc; | ||
|
||
/// Wraps around an implementation of `Transport` that yields a muxer. Will use the muxer to | ||
/// open a substream with the remote and retreive its peer id. Then yields a | ||
/// `(PeerId, impl StreamMuxer)`. | ||
/// | ||
/// This transport can be used if you don't use any encryption layer, or if you want to make | ||
/// encryption optional, in which case you have no other way to know the `PeerId` of the remote | ||
/// than to ask for it. | ||
/// | ||
/// > **Note**: If you use this transport, keep in mind that the `PeerId` returned by the remote | ||
/// > can be anything and shouldn't necessarily be trusted. | ||
#[derive(Debug, Clone)] | ||
pub struct IdentifyTransport<TTrans> { | ||
/// The underlying transport we wrap around. | ||
transport: TTrans, | ||
} | ||
|
||
impl<TTrans> IdentifyTransport<TTrans> { | ||
/// Creates an `IdentifyTransport` that wraps around the given transport. | ||
#[inline] | ||
pub fn new(transport: TTrans) -> Self { | ||
IdentifyTransport { | ||
transport, | ||
} | ||
} | ||
} | ||
|
||
// TODO: don't use boxes | ||
impl<TTrans, TMuxer> Transport for IdentifyTransport<TTrans> | ||
where | ||
TTrans: Transport<Output = TMuxer>, | ||
TMuxer: muxing::StreamMuxer + Send + Sync + 'static, // TODO: remove unnecessary bounds | ||
TMuxer::Substream: Send + Sync + 'static, // TODO: remove unnecessary bounds | ||
TMuxer::OutboundSubstream: Send + 'static, // TODO: remove unnecessary bounds | ||
TTrans::Dial: Send + Sync + 'static, | ||
TTrans::Listener: Send + 'static, | ||
TTrans::ListenerUpgrade: Send + 'static, | ||
{ | ||
type Output = (PeerId, TMuxer); | ||
type Listener = Box<Stream<Item = (Self::ListenerUpgrade, Multiaddr), Error = IoError> + Send>; | ||
type ListenerUpgrade = Box<Future<Item = Self::Output, Error = IoError> + Send>; | ||
type Dial = Box<Future<Item = Self::Output, Error = IoError> + Send>; | ||
|
||
#[inline] | ||
fn listen_on(self, addr: Multiaddr) -> Result<(Self::Listener, Multiaddr), (Self, Multiaddr)> { | ||
let (listener, new_addr) = match self.transport.listen_on(addr) { | ||
Ok((l, a)) => (l, a), | ||
Err((inner, addr)) => { | ||
let id = IdentifyTransport { | ||
transport: inner, | ||
}; | ||
return Err((id, addr)); | ||
} | ||
}; | ||
|
||
let listener = listener | ||
.map(move |(upgrade, remote_addr)| { | ||
let upgr = upgrade | ||
.and_then(move |muxer| { | ||
IdRetriever::new(muxer, IdentifyProtocolConfig, Endpoint::Listener) | ||
}); | ||
(Box::new(upgr) as Box<Future<Item = _, Error = _> + Send>, remote_addr) | ||
}); | ||
|
||
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.dial(addr.clone()) { | ||
Ok(d) => d, | ||
Err((transport, addr)) => { | ||
let id = IdentifyTransport { | ||
transport, | ||
}; | ||
return Err((id, addr)); | ||
} | ||
}; | ||
|
||
let dial = dial.and_then(move |muxer| { | ||
IdRetriever::new(muxer, IdentifyProtocolConfig, Endpoint::Dialer) | ||
}); | ||
|
||
Ok(Box::new(dial) as Box<_>) | ||
} | ||
|
||
#[inline] | ||
fn nat_traversal(&self, a: &Multiaddr, b: &Multiaddr) -> Option<Multiaddr> { | ||
self.transport.nat_traversal(a, b) | ||
} | ||
} | ||
|
||
/// Implementation of `Future` that asks the remote of its `PeerId`. | ||
// TODO: remove unneeded bounds | ||
struct IdRetriever<TMuxer> | ||
where TMuxer: muxing::StreamMuxer + Send + Sync + 'static, | ||
TMuxer::Substream: Send, | ||
{ | ||
/// Internal state. | ||
state: IdRetrieverState<TMuxer>, | ||
/// Whether we're dialing or listening. | ||
endpoint: Endpoint, | ||
} | ||
|
||
enum IdRetrieverState<TMuxer> | ||
where TMuxer: muxing::StreamMuxer + Send + Sync + 'static, | ||
TMuxer::Substream: Send, | ||
{ | ||
/// We are in the process of opening a substream with the remote. | ||
OpeningSubstream(Arc<TMuxer>, muxing::OutboundSubstreamRefWrapFuture<Arc<TMuxer>>, IdentifyProtocolConfig), | ||
/// We opened the substream and are currently negotiating the identify protocol. | ||
NegotiatingIdentify(Arc<TMuxer>, apply::UpgradeApplyFuture<muxing::SubstreamRef<Arc<TMuxer>>, IdentifyProtocolConfig>), | ||
/// We retreived the remote's public key and are ready to yield it when polled again. | ||
Finishing(Arc<TMuxer>, PublicKey), | ||
/// Something bad happend, or the `Future` is finished, and shouldn't be polled again. | ||
Poisoned, | ||
} | ||
|
||
impl<TMuxer> IdRetriever<TMuxer> | ||
where TMuxer: muxing::StreamMuxer + Send + Sync + 'static, | ||
TMuxer::Substream: Send, | ||
{ | ||
/// Creates a new `IdRetriever` ready to be polled. | ||
fn new(muxer: TMuxer, config: IdentifyProtocolConfig, endpoint: Endpoint) -> Self { | ||
let muxer = Arc::new(muxer); | ||
let opening = muxing::outbound_from_ref_and_wrap(muxer.clone()); | ||
|
||
IdRetriever { | ||
state: IdRetrieverState::OpeningSubstream(muxer, opening, config), | ||
endpoint, | ||
} | ||
} | ||
} | ||
|
||
impl<TMuxer> Future for IdRetriever<TMuxer> | ||
where TMuxer: muxing::StreamMuxer + Send + Sync + 'static, | ||
TMuxer::Substream: Send, | ||
{ | ||
type Item = (PeerId, TMuxer); | ||
type Error = IoError; | ||
|
||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { | ||
// This loop is here so that we can continue polling until we're ready. | ||
loop { | ||
// In order to satisfy the borrow checker, we extract the state and temporarily put | ||
// `Poisoned` instead. | ||
match mem::replace(&mut self.state, IdRetrieverState::Poisoned) { | ||
IdRetrieverState::OpeningSubstream(muxer, mut opening, config) => { | ||
match opening.poll() { | ||
Ok(Async::Ready(Some(substream))) => { | ||
let upgrade = apply::apply(substream, config, self.endpoint); | ||
self.state = IdRetrieverState::NegotiatingIdentify(muxer, upgrade); | ||
}, | ||
Ok(Async::Ready(None)) => { | ||
return Err(IoError::new(IoErrorKind::Other, "remote refused our identify attempt")); | ||
}, | ||
Ok(Async::NotReady) => { | ||
self.state = IdRetrieverState::OpeningSubstream(muxer, opening, config); | ||
return Ok(Async::NotReady); | ||
}, | ||
Err(err) => return Err(err), | ||
} | ||
}, | ||
IdRetrieverState::NegotiatingIdentify(muxer, mut nego) => { | ||
match nego.poll() { | ||
Ok(Async::Ready(IdentifyOutput::RemoteInfo { info, .. })) => { | ||
self.state = IdRetrieverState::Finishing(muxer, info.public_key); | ||
}, | ||
Ok(Async::Ready(IdentifyOutput::Sender { .. })) => { | ||
unreachable!("IdentifyOutput::Sender can never be the output from \ | ||
the dialing side"); | ||
}, | ||
Ok(Async::NotReady) => { | ||
self.state = IdRetrieverState::NegotiatingIdentify(muxer, nego); | ||
return Ok(Async::NotReady); | ||
}, | ||
Err(err) => return Err(err), | ||
} | ||
}, | ||
IdRetrieverState::Finishing(muxer, public_key) => { | ||
// Here is a tricky part: we need to get back the muxer in order to return | ||
// it, but it is in an `Arc`. | ||
let unwrapped = Arc::try_unwrap(muxer).unwrap_or_else(|_| { | ||
panic!("we clone the Arc only to put it into substreams ; once in the \ | ||
Finishing state, no substream or upgrade exists anymore ; \ | ||
therefore there exists only one instance of the Arc ; qed") | ||
}); | ||
|
||
// We leave `Poisoned` as the state when returning. | ||
return Ok(Async::Ready((public_key.into(), unwrapped))); | ||
}, | ||
IdRetrieverState::Poisoned => { | ||
panic!("Future state panicked inside poll() or is finished") | ||
}, | ||
} | ||
} | ||
} | ||
} | ||
|
||
// TODO: write basic working test |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why not removing the
Arc
and usingStreamMuxer::open_outbound
andStreamMuxer::poll_outbound
instead? (withTMuxer::Substream: AsyncRead + AsyncWrite ...
)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The "problem" is that we use the
ConnectionUpgrade
trait, and that takes ownership of the substream, which thus requires holding anArc
.I guess it could be possible to do everything manually, but I'm not sure if the extra complexity is worth.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I must be missing something because the change looks rather good to me: https://gist.github.com/twittner/3bbc474ba9599880fe063d8e7f82a47d
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's not correct though.
StreamMuxer::Substream
is an opaque type that isn't supposed to be implementing any trait.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah yes, I got carried away by just following compiler suggestions and forgot about the semantics of
StreamMuxer
, also because yamux streams do implement AsyncRead and AsyncWrite.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
However it does not feel right if the API leads to unwrap-or-else-panic idioms.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Well, this is a special case because we are at the level before the node handler comes into play.
Normally the code that handles a protocol only needs a substream and not the whole muxer.