Merge pull request #28 from fluencelabs/merge_upstream

Merge upstream
This commit is contained in:
folex 2020-07-30 17:14:44 +03:00 committed by GitHub
commit 3fb829f61b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
101 changed files with 1000 additions and 881 deletions

View File

@ -23,6 +23,18 @@
- [`parity-multiaddr` CHANGELOG](misc/multiaddr/CHANGELOG.md) - [`parity-multiaddr` CHANGELOG](misc/multiaddr/CHANGELOG.md)
- [`libp2p-core-derive` CHANGELOG](misc/core-derive/CHANGELOG.md) - [`libp2p-core-derive` CHANGELOG](misc/core-derive/CHANGELOG.md)
# Version 0.23.0 (2020-??-??)
- Refactored bandwidth logging ([PR 1670](https://github.com/libp2p/rust-libp2p/pull/1670)).
# Version 0.22.0 (2020-07-17)
**NOTE**: For a smooth upgrade path from `0.21` to `> 0.22`
on an existing deployment using `libp2p-noise`, this version
must not be skipped!
- Bump `libp2p-noise` dependency to `0.21`.
# Version 0.21.1 (2020-07-02) # Version 0.21.1 (2020-07-02)
- Bump `libp2p-websockets` lower bound. - Bump `libp2p-websockets` lower bound.

View File

@ -2,7 +2,7 @@
name = "libp2p" name = "libp2p"
edition = "2018" edition = "2018"
description = "Peer-to-peer networking library" description = "Peer-to-peer networking library"
version = "0.21.1" version = "0.22.0"
authors = ["Parity Technologies <admin@parity.io>"] authors = ["Parity Technologies <admin@parity.io>"]
license = "MIT" license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p" repository = "https://github.com/libp2p/rust-libp2p"
@ -58,6 +58,7 @@ secp256k1 = ["libp2p-core/secp256k1", "libp2p-secio/secp256k1"]
all-features = true all-features = true
[dependencies] [dependencies]
atomic = "0.4.6"
bytes = "0.5" bytes = "0.5"
futures = "0.3.1" futures = "0.3.1"
lazy_static = "1.2" lazy_static = "1.2"
@ -68,7 +69,7 @@ libp2p-gossipsub = { version = "0.20.0", path = "./protocols/gossipsub", optiona
libp2p-identify = { version = "0.20.0", path = "protocols/identify", optional = true } libp2p-identify = { version = "0.20.0", path = "protocols/identify", optional = true }
libp2p-kad = { version = "0.21.0", path = "protocols/kad", optional = true } libp2p-kad = { version = "0.21.0", path = "protocols/kad", optional = true }
libp2p-mplex = { version = "0.20.0", path = "muxers/mplex", optional = true } libp2p-mplex = { version = "0.20.0", path = "muxers/mplex", optional = true }
libp2p-noise = { version = "0.20.0", path = "protocols/noise", optional = true } libp2p-noise = { version = "0.21.0", path = "protocols/noise", optional = true }
libp2p-ping = { version = "0.20.0", path = "protocols/ping", optional = true } libp2p-ping = { version = "0.20.0", path = "protocols/ping", optional = true }
libp2p-plaintext = { version = "0.20.0", path = "protocols/plaintext", optional = true } libp2p-plaintext = { version = "0.20.0", path = "protocols/plaintext", optional = true }
libp2p-pnet = { version = "0.19.1", path = "protocols/pnet", optional = true } libp2p-pnet = { version = "0.19.1", path = "protocols/pnet", optional = true }

View File

@ -257,7 +257,7 @@ where
/// Polls the connection for events produced by the associated handler /// Polls the connection for events produced by the associated handler
/// as a result of I/O activity on the substream multiplexer. /// as a result of I/O activity on the substream multiplexer.
pub fn poll(mut self: Pin<&mut Self>, cx: &mut Context) pub fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>)
-> Poll<Result<Event<THandler::OutEvent>, ConnectionError<THandler::Error>>> -> Poll<Result<Event<THandler::OutEvent>, ConnectionError<THandler::Error>>>
{ {
loop { loop {

View File

@ -64,7 +64,7 @@ pub trait ConnectionHandler {
/// Polls the handler for events. /// Polls the handler for events.
/// ///
/// Returning an error will close the connection to the remote. /// Returning an error will close the connection to the remote.
fn poll(&mut self, cx: &mut Context) fn poll(&mut self, cx: &mut Context<'_>)
-> Poll<Result<ConnectionHandlerEvent<Self::OutboundOpenInfo, Self::OutEvent>, Self::Error>>; -> Poll<Result<ConnectionHandlerEvent<Self::OutboundOpenInfo, Self::OutEvent>, Self::Error>>;
} }

View File

@ -230,7 +230,7 @@ where
} }
/// Provides an API similar to `Stream`, except that it cannot end. /// Provides an API similar to `Stream`, except that it cannot end.
pub fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<ListenersEvent<TTrans>> { pub fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<ListenersEvent<TTrans>> {
// We remove each element from `listeners` one by one and add them back. // We remove each element from `listeners` one by one and add them back.
let mut remaining = self.listeners.len(); let mut remaining = self.listeners.len();
while let Some(mut listener) = self.listeners.pop_back() { while let Some(mut listener) = self.listeners.pop_back() {
@ -310,7 +310,7 @@ where
{ {
type Item = ListenersEvent<TTrans>; type Item = ListenersEvent<TTrans>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
ListenersStream::poll(self, cx).map(Option::Some) ListenersStream::poll(self, cx).map(Option::Some)
} }
} }

View File

@ -125,7 +125,7 @@ impl<I, O, H, E, HE, C> fmt::Debug for Manager<I, O, H, E, HE, C>
where where
C: fmt::Debug, C: fmt::Debug,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map() f.debug_map()
.entries(self.tasks.iter().map(|(id, task)| (id, &task.state))) .entries(self.tasks.iter().map(|(id, task)| (id, &task.state)))
.finish() .finish()
@ -346,7 +346,7 @@ impl<I, O, H, TE, HE, C> Manager<I, O, H, TE, HE, C> {
} }
/// Polls the manager for events relating to the managed connections. /// Polls the manager for events relating to the managed connections.
pub fn poll<'a>(&'a mut self, cx: &mut Context) -> Poll<Event<'a, I, O, H, TE, HE, C>> { pub fn poll<'a>(&'a mut self, cx: &mut Context<'_>) -> Poll<Event<'a, I, O, H, TE, HE, C>> {
// Advance the content of `local_spawns`. // Advance the content of `local_spawns`.
while let Poll::Ready(Some(_)) = Stream::poll_next(Pin::new(&mut self.local_spawns), cx) {} while let Poll::Ready(Some(_)) = Stream::poll_next(Pin::new(&mut self.local_spawns), cx) {}
@ -468,7 +468,7 @@ impl<'a, I, C> EstablishedEntry<'a, I, C> {
/// ///
/// Returns `Err(())` if the background task associated with the connection /// Returns `Err(())` if the background task associated with the connection
/// is terminating and the connection is about to close. /// is terminating and the connection is about to close.
pub fn poll_ready_notify_handler(&mut self, cx: &mut Context) -> Poll<Result<(),()>> { pub fn poll_ready_notify_handler(&mut self, cx: &mut Context<'_>) -> Poll<Result<(),()>> {
self.task.get_mut().sender.poll_ready(cx).map_err(|_| ()) self.task.get_mut().sender.poll_ready(cx).map_err(|_| ())
} }

View File

@ -190,7 +190,7 @@ where
// NOTE: It is imperative to always consume all incoming commands from // NOTE: It is imperative to always consume all incoming commands from
// the manager first, in order to not prevent it from making progress because // the manager first, in order to not prevent it from making progress because
// it is blocked on the channel capacity. // it is blocked on the channel capacity.
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let this = &mut *self; let this = &mut *self;
let id = this.id; let id = this.id;

View File

@ -217,7 +217,7 @@ where
&mut self, &mut self,
future: TFut, future: TFut,
handler: THandler, handler: THandler,
info: IncomingInfo, info: IncomingInfo<'_>,
) -> Result<ConnectionId, ConnectionLimit> ) -> Result<ConnectionId, ConnectionLimit>
where where
TConnInfo: ConnectionInfo<PeerId = TPeerId> + Send + 'static, TConnInfo: ConnectionInfo<PeerId = TPeerId> + Send + 'static,
@ -254,7 +254,7 @@ where
&mut self, &mut self,
future: TFut, future: TFut,
handler: THandler, handler: THandler,
info: OutgoingInfo<TPeerId>, info: OutgoingInfo<'_, TPeerId>,
) -> Result<ConnectionId, ConnectionLimit> ) -> Result<ConnectionId, ConnectionLimit>
where where
TConnInfo: ConnectionInfo<PeerId = TPeerId> + Send + 'static, TConnInfo: ConnectionInfo<PeerId = TPeerId> + Send + 'static,
@ -562,7 +562,7 @@ where
/// ///
/// > **Note**: We use a regular `poll` method instead of implementing `Stream`, /// > **Note**: We use a regular `poll` method instead of implementing `Stream`,
/// > because we want the `Pool` to stay borrowed if necessary. /// > because we want the `Pool` to stay borrowed if necessary.
pub fn poll<'a>(&'a mut self, cx: &mut Context) -> Poll< pub fn poll<'a>(&'a mut self, cx: &mut Context<'_>) -> Poll<
PoolEvent<'a, TInEvent, TOutEvent, THandler, TTransErr, THandlerErr, TConnInfo, TPeerId> PoolEvent<'a, TInEvent, TOutEvent, THandler, TTransErr, THandlerErr, TConnInfo, TPeerId>
> where > where
TConnInfo: ConnectionInfo<PeerId = TPeerId> + Clone, TConnInfo: ConnectionInfo<PeerId = TPeerId> + Clone,
@ -793,7 +793,7 @@ where
/// ///
/// Returns `Err(())` if the background task associated with the connection /// Returns `Err(())` if the background task associated with the connection
/// is terminating and the connection is about to close. /// is terminating and the connection is about to close.
pub fn poll_ready_notify_handler(&mut self, cx: &mut Context) -> Poll<Result<(),()>> { pub fn poll_ready_notify_handler(&mut self, cx: &mut Context<'_>) -> Poll<Result<(),()>> {
self.entry.poll_ready_notify_handler(cx) self.entry.poll_ready_notify_handler(cx)
} }

View File

@ -150,7 +150,7 @@ where
} }
/// Provides an API similar to `Future`. /// Provides an API similar to `Future`.
pub fn poll(&mut self, cx: &mut Context) -> Poll<Result<SubstreamEvent<TMuxer, TUserData>, IoError>> { pub fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Result<SubstreamEvent<TMuxer, TUserData>, IoError>> {
// Polling inbound substream. // Polling inbound substream.
match self.inner.poll_event(cx) { match self.inner.poll_event(cx) {
Poll::Ready(Ok(StreamMuxerEvent::InboundSubstream(substream))) => { Poll::Ready(Ok(StreamMuxerEvent::InboundSubstream(substream))) => {
@ -224,7 +224,7 @@ where
{ {
type Output = Result<(), IoError>; type Output = Result<(), IoError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.muxer.close(cx) { match self.muxer.close(cx) {
Poll::Pending => Poll::Pending, Poll::Pending => Poll::Pending,
Poll::Ready(Ok(())) => Poll::Ready(Ok(())), Poll::Ready(Ok(())) => Poll::Ready(Ok(())),

View File

@ -74,14 +74,14 @@ where
A: AsyncRead, A: AsyncRead,
B: AsyncRead, B: AsyncRead,
{ {
fn poll_read(self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<Result<usize, IoError>> { fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize, IoError>> {
match self.project() { match self.project() {
EitherOutputProj::First(a) => AsyncRead::poll_read(a, cx, buf), EitherOutputProj::First(a) => AsyncRead::poll_read(a, cx, buf),
EitherOutputProj::Second(b) => AsyncRead::poll_read(b, cx, buf), EitherOutputProj::Second(b) => AsyncRead::poll_read(b, cx, buf),
} }
} }
fn poll_read_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &mut [IoSliceMut]) fn poll_read_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>])
-> Poll<Result<usize, IoError>> -> Poll<Result<usize, IoError>>
{ {
match self.project() { match self.project() {
@ -96,14 +96,14 @@ where
A: AsyncWrite, A: AsyncWrite,
B: AsyncWrite, B: AsyncWrite,
{ {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<Result<usize, IoError>> { fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize, IoError>> {
match self.project() { match self.project() {
EitherOutputProj::First(a) => AsyncWrite::poll_write(a, cx, buf), EitherOutputProj::First(a) => AsyncWrite::poll_write(a, cx, buf),
EitherOutputProj::Second(b) => AsyncWrite::poll_write(b, cx, buf), EitherOutputProj::Second(b) => AsyncWrite::poll_write(b, cx, buf),
} }
} }
fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &[IoSlice]) fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>])
-> Poll<Result<usize, IoError>> -> Poll<Result<usize, IoError>>
{ {
match self.project() { match self.project() {
@ -112,14 +112,14 @@ where
} }
} }
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), IoError>> { fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), IoError>> {
match self.project() { match self.project() {
EitherOutputProj::First(a) => AsyncWrite::poll_flush(a, cx), EitherOutputProj::First(a) => AsyncWrite::poll_flush(a, cx),
EitherOutputProj::Second(b) => AsyncWrite::poll_flush(b, cx), EitherOutputProj::Second(b) => AsyncWrite::poll_flush(b, cx),
} }
} }
fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), IoError>> { fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), IoError>> {
match self.project() { match self.project() {
EitherOutputProj::First(a) => AsyncWrite::poll_close(a, cx), EitherOutputProj::First(a) => AsyncWrite::poll_close(a, cx),
EitherOutputProj::Second(b) => AsyncWrite::poll_close(b, cx), EitherOutputProj::Second(b) => AsyncWrite::poll_close(b, cx),
@ -134,7 +134,7 @@ where
{ {
type Item = Result<I, EitherError<A::Error, B::Error>>; type Item = Result<I, EitherError<A::Error, B::Error>>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.project() { match self.project() {
EitherOutputProj::First(a) => TryStream::try_poll_next(a, cx) EitherOutputProj::First(a) => TryStream::try_poll_next(a, cx)
.map(|v| v.map(|r| r.map_err(EitherError::A))), .map(|v| v.map(|r| r.map_err(EitherError::A))),
@ -151,7 +151,7 @@ where
{ {
type Error = EitherError<A::Error, B::Error>; type Error = EitherError<A::Error, B::Error>;
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match self.project() { match self.project() {
EitherOutputProj::First(a) => Sink::poll_ready(a, cx).map_err(EitherError::A), EitherOutputProj::First(a) => Sink::poll_ready(a, cx).map_err(EitherError::A),
EitherOutputProj::Second(b) => Sink::poll_ready(b, cx).map_err(EitherError::B), EitherOutputProj::Second(b) => Sink::poll_ready(b, cx).map_err(EitherError::B),
@ -165,14 +165,14 @@ where
} }
} }
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match self.project() { match self.project() {
EitherOutputProj::First(a) => Sink::poll_flush(a, cx).map_err(EitherError::A), EitherOutputProj::First(a) => Sink::poll_flush(a, cx).map_err(EitherError::A),
EitherOutputProj::Second(b) => Sink::poll_flush(b, cx).map_err(EitherError::B), EitherOutputProj::Second(b) => Sink::poll_flush(b, cx).map_err(EitherError::B),
} }
} }
fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match self.project() { match self.project() {
EitherOutputProj::First(a) => Sink::poll_close(a, cx).map_err(EitherError::A), EitherOutputProj::First(a) => Sink::poll_close(a, cx).map_err(EitherError::A),
EitherOutputProj::Second(b) => Sink::poll_close(b, cx).map_err(EitherError::B), EitherOutputProj::Second(b) => Sink::poll_close(b, cx).map_err(EitherError::B),
@ -189,7 +189,7 @@ where
type OutboundSubstream = EitherOutbound<A, B>; type OutboundSubstream = EitherOutbound<A, B>;
type Error = IoError; type Error = IoError;
fn poll_event(&self, cx: &mut Context) -> Poll<Result<StreamMuxerEvent<Self::Substream>, Self::Error>> { fn poll_event(&self, cx: &mut Context<'_>) -> Poll<Result<StreamMuxerEvent<Self::Substream>, Self::Error>> {
match self { match self {
EitherOutput::First(inner) => inner.poll_event(cx).map(|result| { EitherOutput::First(inner) => inner.poll_event(cx).map(|result| {
result.map_err(|e| e.into()).map(|event| { result.map_err(|e| e.into()).map(|event| {
@ -219,7 +219,7 @@ where
} }
} }
fn poll_outbound(&self, cx: &mut Context, substream: &mut Self::OutboundSubstream) -> Poll<Result<Self::Substream, Self::Error>> { fn poll_outbound(&self, cx: &mut Context<'_>, substream: &mut Self::OutboundSubstream) -> Poll<Result<Self::Substream, Self::Error>> {
match (self, substream) { match (self, substream) {
(EitherOutput::First(ref inner), EitherOutbound::A(ref mut substream)) => { (EitherOutput::First(ref inner), EitherOutbound::A(ref mut substream)) => {
inner.poll_outbound(cx, substream).map(|p| p.map(EitherOutput::First)).map_err(|e| e.into()) inner.poll_outbound(cx, substream).map(|p| p.map(EitherOutput::First)).map_err(|e| e.into())
@ -248,7 +248,7 @@ where
} }
} }
fn read_substream(&self, cx: &mut Context, sub: &mut Self::Substream, buf: &mut [u8]) -> Poll<Result<usize, Self::Error>> { fn read_substream(&self, cx: &mut Context<'_>, sub: &mut Self::Substream, buf: &mut [u8]) -> Poll<Result<usize, Self::Error>> {
match (self, sub) { match (self, sub) {
(EitherOutput::First(ref inner), EitherOutput::First(ref mut sub)) => { (EitherOutput::First(ref inner), EitherOutput::First(ref mut sub)) => {
inner.read_substream(cx, sub, buf).map_err(|e| e.into()) inner.read_substream(cx, sub, buf).map_err(|e| e.into())
@ -260,7 +260,7 @@ where
} }
} }
fn write_substream(&self, cx: &mut Context, sub: &mut Self::Substream, buf: &[u8]) -> Poll<Result<usize, Self::Error>> { fn write_substream(&self, cx: &mut Context<'_>, sub: &mut Self::Substream, buf: &[u8]) -> Poll<Result<usize, Self::Error>> {
match (self, sub) { match (self, sub) {
(EitherOutput::First(ref inner), EitherOutput::First(ref mut sub)) => { (EitherOutput::First(ref inner), EitherOutput::First(ref mut sub)) => {
inner.write_substream(cx, sub, buf).map_err(|e| e.into()) inner.write_substream(cx, sub, buf).map_err(|e| e.into())
@ -272,7 +272,7 @@ where
} }
} }
fn flush_substream(&self, cx: &mut Context, sub: &mut Self::Substream) -> Poll<Result<(), Self::Error>> { fn flush_substream(&self, cx: &mut Context<'_>, sub: &mut Self::Substream) -> Poll<Result<(), Self::Error>> {
match (self, sub) { match (self, sub) {
(EitherOutput::First(ref inner), EitherOutput::First(ref mut sub)) => { (EitherOutput::First(ref inner), EitherOutput::First(ref mut sub)) => {
inner.flush_substream(cx, sub).map_err(|e| e.into()) inner.flush_substream(cx, sub).map_err(|e| e.into())
@ -284,7 +284,7 @@ where
} }
} }
fn shutdown_substream(&self, cx: &mut Context, sub: &mut Self::Substream) -> Poll<Result<(), Self::Error>> { fn shutdown_substream(&self, cx: &mut Context<'_>, sub: &mut Self::Substream) -> Poll<Result<(), Self::Error>> {
match (self, sub) { match (self, sub) {
(EitherOutput::First(ref inner), EitherOutput::First(ref mut sub)) => { (EitherOutput::First(ref inner), EitherOutput::First(ref mut sub)) => {
inner.shutdown_substream(cx, sub).map_err(|e| e.into()) inner.shutdown_substream(cx, sub).map_err(|e| e.into())
@ -313,14 +313,14 @@ where
} }
} }
fn close(&self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn close(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match self { match self {
EitherOutput::First(inner) => inner.close(cx).map_err(|e| e.into()), EitherOutput::First(inner) => inner.close(cx).map_err(|e| e.into()),
EitherOutput::Second(inner) => inner.close(cx).map_err(|e| e.into()), EitherOutput::Second(inner) => inner.close(cx).map_err(|e| e.into()),
} }
} }
fn flush_all(&self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn flush_all(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match self { match self {
EitherOutput::First(inner) => inner.flush_all(cx).map_err(|e| e.into()), EitherOutput::First(inner) => inner.flush_all(cx).map_err(|e| e.into()),
EitherOutput::Second(inner) => inner.flush_all(cx).map_err(|e| e.into()), EitherOutput::Second(inner) => inner.flush_all(cx).map_err(|e| e.into()),
@ -351,7 +351,7 @@ where
{ {
type Item = Result<ListenerEvent<EitherFuture<AInner, BInner>, EitherError<AError, BError>>, EitherError<AError, BError>>; type Item = Result<ListenerEvent<EitherFuture<AInner, BInner>, EitherError<AError, BError>>, EitherError<AError, BError>>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.project() { match self.project() {
EitherListenStreamProj::First(a) => match TryStream::try_poll_next(a, cx) { EitherListenStreamProj::First(a) => match TryStream::try_poll_next(a, cx) {
Poll::Pending => Poll::Pending, Poll::Pending => Poll::Pending,
@ -385,7 +385,7 @@ where
{ {
type Output = Result<EitherOutput<AInner, BInner>, EitherError<AFuture::Error, BFuture::Error>>; type Output = Result<EitherOutput<AInner, BInner>, EitherError<AFuture::Error, BFuture::Error>>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.project() { match self.project() {
EitherFutureProj::First(a) => TryFuture::try_poll(a, cx) EitherFutureProj::First(a) => TryFuture::try_poll(a, cx)
.map_ok(EitherOutput::First).map_err(EitherError::A), .map_ok(EitherOutput::First).map_err(EitherError::A),
@ -407,7 +407,7 @@ where
{ {
type Output = Result<EitherOutput<AItem, BItem>, EitherError<AError, BError>>; type Output = Result<EitherOutput<AItem, BItem>, EitherError<AError, BError>>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.project() { match self.project() {
EitherFuture2Proj::A(a) => TryFuture::try_poll(a, cx) EitherFuture2Proj::A(a) => TryFuture::try_poll(a, cx)
.map_ok(EitherOutput::First).map_err(EitherError::A), .map_ok(EitherOutput::First).map_err(EitherError::A),

View File

@ -41,7 +41,7 @@ impl DecodingError {
} }
impl fmt::Display for DecodingError { impl fmt::Display for DecodingError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Key decoding error: {}", self.msg) write!(f, "Key decoding error: {}", self.msg)
} }
} }
@ -71,7 +71,7 @@ impl SigningError {
} }
impl fmt::Display for SigningError { impl fmt::Display for SigningError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Key signing error: {}", self.msg) write!(f, "Key signing error: {}", self.msg)
} }
} }

View File

@ -230,7 +230,7 @@ mod tests {
struct SomeKeypair(Keypair); struct SomeKeypair(Keypair);
impl fmt::Debug for SomeKeypair { impl fmt::Debug for SomeKeypair {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SomeKeypair") write!(f, "SomeKeypair")
} }
} }

View File

@ -92,7 +92,7 @@ pub trait StreamMuxer {
/// Only the latest task that was used to call this method may be notified. /// Only the latest task that was used to call this method may be notified.
/// ///
/// An error can be generated if the connection has been closed. /// An error can be generated if the connection has been closed.
fn poll_event(&self, cx: &mut Context) -> Poll<Result<StreamMuxerEvent<Self::Substream>, Self::Error>>; fn poll_event(&self, cx: &mut Context<'_>) -> Poll<Result<StreamMuxerEvent<Self::Substream>, Self::Error>>;
/// Opens a new outgoing substream, and produces the equivalent to a future that will be /// Opens a new outgoing substream, and produces the equivalent to a future that will be
/// resolved when it becomes available. /// resolved when it becomes available.
@ -110,7 +110,7 @@ pub trait StreamMuxer {
/// ///
/// May panic or produce an undefined result if an earlier polling of the same substream /// May panic or produce an undefined result if an earlier polling of the same substream
/// returned `Ready` or `Err`. /// returned `Ready` or `Err`.
fn poll_outbound(&self, cx: &mut Context, s: &mut Self::OutboundSubstream) fn poll_outbound(&self, cx: &mut Context<'_>, s: &mut Self::OutboundSubstream)
-> Poll<Result<Self::Substream, Self::Error>>; -> Poll<Result<Self::Substream, Self::Error>>;
/// Destroys an outbound substream future. Use this after the outbound substream has finished, /// Destroys an outbound substream future. Use this after the outbound substream has finished,
@ -128,7 +128,7 @@ pub trait StreamMuxer {
/// ///
/// An error can be generated if the connection has been closed, or if a protocol misbehaviour /// An error can be generated if the connection has been closed, or if a protocol misbehaviour
/// happened. /// happened.
fn read_substream(&self, cx: &mut Context, s: &mut Self::Substream, buf: &mut [u8]) fn read_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream, buf: &mut [u8])
-> Poll<Result<usize, Self::Error>>; -> Poll<Result<usize, Self::Error>>;
/// Write data to a substream. The behaviour is the same as `futures::AsyncWrite::poll_write`. /// Write data to a substream. The behaviour is the same as `futures::AsyncWrite::poll_write`.
@ -142,7 +142,7 @@ pub trait StreamMuxer {
/// ///
/// It is incorrect to call this method on a substream if you called `shutdown_substream` on /// It is incorrect to call this method on a substream if you called `shutdown_substream` on
/// this substream earlier. /// this substream earlier.
fn write_substream(&self, cx: &mut Context, s: &mut Self::Substream, buf: &[u8]) fn write_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream, buf: &[u8])
-> Poll<Result<usize, Self::Error>>; -> Poll<Result<usize, Self::Error>>;
/// Flushes a substream. The behaviour is the same as `futures::AsyncWrite::poll_flush`. /// Flushes a substream. The behaviour is the same as `futures::AsyncWrite::poll_flush`.
@ -155,7 +155,7 @@ pub trait StreamMuxer {
/// call this method may be notified. /// call this method may be notified.
/// ///
/// > **Note**: This method may be implemented as a call to `flush_all`. /// > **Note**: This method may be implemented as a call to `flush_all`.
fn flush_substream(&self, cx: &mut Context, s: &mut Self::Substream) fn flush_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream)
-> Poll<Result<(), Self::Error>>; -> Poll<Result<(), Self::Error>>;
/// Attempts to shut down the writing side of a substream. The behaviour is similar to /// Attempts to shut down the writing side of a substream. The behaviour is similar to
@ -169,7 +169,7 @@ pub trait StreamMuxer {
/// ///
/// An error can be generated if the connection has been closed, or if a protocol misbehaviour /// An error can be generated if the connection has been closed, or if a protocol misbehaviour
/// happened. /// happened.
fn shutdown_substream(&self, cx: &mut Context, s: &mut Self::Substream) fn shutdown_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream)
-> Poll<Result<(), Self::Error>>; -> Poll<Result<(), Self::Error>>;
/// Destroys a substream. /// Destroys a substream.
@ -198,14 +198,14 @@ pub trait StreamMuxer {
/// > that the remote is properly informed of the shutdown. However, apart from /// > that the remote is properly informed of the shutdown. However, apart from
/// > properly informing the remote, there is no difference between this and /// > properly informing the remote, there is no difference between this and
/// > immediately dropping the muxer. /// > immediately dropping the muxer.
fn close(&self, cx: &mut Context) -> Poll<Result<(), Self::Error>>; fn close(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
/// Flush this `StreamMuxer`. /// Flush this `StreamMuxer`.
/// ///
/// This drains any write buffers of substreams and delivers any pending shutdown notifications /// This drains any write buffers of substreams and delivers any pending shutdown notifications
/// due to `shutdown_substream` or `close`. One may thus shutdown groups of substreams /// due to `shutdown_substream` or `close`. One may thus shutdown groups of substreams
/// followed by a final `flush_all` instead of having to do `flush_substream` for each. /// followed by a final `flush_all` instead of having to do `flush_substream` for each.
fn flush_all(&self, cx: &mut Context) -> Poll<Result<(), Self::Error>>; fn flush_all(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
} }
/// Event about a connection, reported by an implementation of [`StreamMuxer`]. /// Event about a connection, reported by an implementation of [`StreamMuxer`].
@ -280,7 +280,7 @@ where
{ {
type Output = Result<SubstreamRef<P>, <P::Target as StreamMuxer>::Error>; type Output = Result<SubstreamRef<P>, <P::Target as StreamMuxer>::Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match Future::poll(Pin::new(&mut self.inner), cx) { match Future::poll(Pin::new(&mut self.inner), cx) {
Poll::Ready(Ok(substream)) => { Poll::Ready(Ok(substream)) => {
let out = substream_from_ref(self.inner.muxer.clone(), substream); let out = substream_from_ref(self.inner.muxer.clone(), substream);
@ -329,7 +329,7 @@ where
{ {
type Output = Result<<P::Target as StreamMuxer>::Substream, <P::Target as StreamMuxer>::Error>; type Output = Result<<P::Target as StreamMuxer>::Substream, <P::Target as StreamMuxer>::Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
// We use a `this` because the compiler isn't smart enough to allow mutably borrowing // We use a `this` because the compiler isn't smart enough to allow mutably borrowing
// multiple different fields from the `Pin` at the same time. // multiple different fields from the `Pin` at the same time.
let this = &mut *self; let this = &mut *self;
@ -405,7 +405,7 @@ where
P: Deref, P: Deref,
P::Target: StreamMuxer, P::Target: StreamMuxer,
{ {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<Result<usize, io::Error>> { fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize, io::Error>> {
// We use a `this` because the compiler isn't smart enough to allow mutably borrowing // We use a `this` because the compiler isn't smart enough to allow mutably borrowing
// multiple different fields from the `Pin` at the same time. // multiple different fields from the `Pin` at the same time.
let this = &mut *self; let this = &mut *self;
@ -420,7 +420,7 @@ where
P: Deref, P: Deref,
P::Target: StreamMuxer, P::Target: StreamMuxer,
{ {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<Result<usize, io::Error>> { fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize, io::Error>> {
// We use a `this` because the compiler isn't smart enough to allow mutably borrowing // We use a `this` because the compiler isn't smart enough to allow mutably borrowing
// multiple different fields from the `Pin` at the same time. // multiple different fields from the `Pin` at the same time.
let this = &mut *self; let this = &mut *self;
@ -429,7 +429,7 @@ where
this.muxer.write_substream(cx, s, buf).map_err(|e| e.into()) this.muxer.write_substream(cx, s, buf).map_err(|e| e.into())
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
// We use a `this` because the compiler isn't smart enough to allow mutably borrowing // We use a `this` because the compiler isn't smart enough to allow mutably borrowing
// multiple different fields from the `Pin` at the same time. // multiple different fields from the `Pin` at the same time.
let this = &mut *self; let this = &mut *self;
@ -458,7 +458,7 @@ where
} }
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
// We use a `this` because the compiler isn't smart enough to allow mutably borrowing // We use a `this` because the compiler isn't smart enough to allow mutably borrowing
// multiple different fields from the `Pin` at the same time. // multiple different fields from the `Pin` at the same time.
let this = &mut *self; let this = &mut *self;
@ -511,7 +511,7 @@ impl StreamMuxer for StreamMuxerBox {
type Error = io::Error; type Error = io::Error;
#[inline] #[inline]
fn poll_event(&self, cx: &mut Context) -> Poll<Result<StreamMuxerEvent<Self::Substream>, Self::Error>> { fn poll_event(&self, cx: &mut Context<'_>) -> Poll<Result<StreamMuxerEvent<Self::Substream>, Self::Error>> {
self.inner.poll_event(cx) self.inner.poll_event(cx)
} }
@ -521,7 +521,7 @@ impl StreamMuxer for StreamMuxerBox {
} }
#[inline] #[inline]
fn poll_outbound(&self, cx: &mut Context, s: &mut Self::OutboundSubstream) -> Poll<Result<Self::Substream, Self::Error>> { fn poll_outbound(&self, cx: &mut Context<'_>, s: &mut Self::OutboundSubstream) -> Poll<Result<Self::Substream, Self::Error>> {
self.inner.poll_outbound(cx, s) self.inner.poll_outbound(cx, s)
} }
@ -531,22 +531,22 @@ impl StreamMuxer for StreamMuxerBox {
} }
#[inline] #[inline]
fn read_substream(&self, cx: &mut Context, s: &mut Self::Substream, buf: &mut [u8]) -> Poll<Result<usize, Self::Error>> { fn read_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream, buf: &mut [u8]) -> Poll<Result<usize, Self::Error>> {
self.inner.read_substream(cx, s, buf) self.inner.read_substream(cx, s, buf)
} }
#[inline] #[inline]
fn write_substream(&self, cx: &mut Context, s: &mut Self::Substream, buf: &[u8]) -> Poll<Result<usize, Self::Error>> { fn write_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream, buf: &[u8]) -> Poll<Result<usize, Self::Error>> {
self.inner.write_substream(cx, s, buf) self.inner.write_substream(cx, s, buf)
} }
#[inline] #[inline]
fn flush_substream(&self, cx: &mut Context, s: &mut Self::Substream) -> Poll<Result<(), Self::Error>> { fn flush_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream) -> Poll<Result<(), Self::Error>> {
self.inner.flush_substream(cx, s) self.inner.flush_substream(cx, s)
} }
#[inline] #[inline]
fn shutdown_substream(&self, cx: &mut Context, s: &mut Self::Substream) -> Poll<Result<(), Self::Error>> { fn shutdown_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream) -> Poll<Result<(), Self::Error>> {
self.inner.shutdown_substream(cx, s) self.inner.shutdown_substream(cx, s)
} }
@ -556,12 +556,12 @@ impl StreamMuxer for StreamMuxerBox {
} }
#[inline] #[inline]
fn close(&self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn close(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.close(cx) self.inner.close(cx)
} }
#[inline] #[inline]
fn flush_all(&self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn flush_all(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.flush_all(cx) self.inner.flush_all(cx)
} }
} }
@ -583,7 +583,7 @@ where
type Error = io::Error; type Error = io::Error;
#[inline] #[inline]
fn poll_event(&self, cx: &mut Context) -> Poll<Result<StreamMuxerEvent<Self::Substream>, Self::Error>> { fn poll_event(&self, cx: &mut Context<'_>) -> Poll<Result<StreamMuxerEvent<Self::Substream>, Self::Error>> {
let substream = match self.inner.poll_event(cx) { let substream = match self.inner.poll_event(cx) {
Poll::Pending => return Poll::Pending, Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(StreamMuxerEvent::AddressChange(a))) => Poll::Ready(Ok(StreamMuxerEvent::AddressChange(a))) =>
@ -608,7 +608,7 @@ where
#[inline] #[inline]
fn poll_outbound( fn poll_outbound(
&self, &self,
cx: &mut Context, cx: &mut Context<'_>,
substream: &mut Self::OutboundSubstream, substream: &mut Self::OutboundSubstream,
) -> Poll<Result<Self::Substream, Self::Error>> { ) -> Poll<Result<Self::Substream, Self::Error>> {
let mut list = self.outbound.lock(); let mut list = self.outbound.lock();
@ -629,25 +629,25 @@ where
} }
#[inline] #[inline]
fn read_substream(&self, cx: &mut Context, s: &mut Self::Substream, buf: &mut [u8]) -> Poll<Result<usize, Self::Error>> { fn read_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream, buf: &mut [u8]) -> Poll<Result<usize, Self::Error>> {
let mut list = self.substreams.lock(); let mut list = self.substreams.lock();
self.inner.read_substream(cx, list.get_mut(s).unwrap(), buf).map_err(|e| e.into()) self.inner.read_substream(cx, list.get_mut(s).unwrap(), buf).map_err(|e| e.into())
} }
#[inline] #[inline]
fn write_substream(&self, cx: &mut Context, s: &mut Self::Substream, buf: &[u8]) -> Poll<Result<usize, Self::Error>> { fn write_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream, buf: &[u8]) -> Poll<Result<usize, Self::Error>> {
let mut list = self.substreams.lock(); let mut list = self.substreams.lock();
self.inner.write_substream(cx, list.get_mut(s).unwrap(), buf).map_err(|e| e.into()) self.inner.write_substream(cx, list.get_mut(s).unwrap(), buf).map_err(|e| e.into())
} }
#[inline] #[inline]
fn flush_substream(&self, cx: &mut Context, s: &mut Self::Substream) -> Poll<Result<(), Self::Error>> { fn flush_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream) -> Poll<Result<(), Self::Error>> {
let mut list = self.substreams.lock(); let mut list = self.substreams.lock();
self.inner.flush_substream(cx, list.get_mut(s).unwrap()).map_err(|e| e.into()) self.inner.flush_substream(cx, list.get_mut(s).unwrap()).map_err(|e| e.into())
} }
#[inline] #[inline]
fn shutdown_substream(&self, cx: &mut Context, s: &mut Self::Substream) -> Poll<Result<(), Self::Error>> { fn shutdown_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream) -> Poll<Result<(), Self::Error>> {
let mut list = self.substreams.lock(); let mut list = self.substreams.lock();
self.inner.shutdown_substream(cx, list.get_mut(s).unwrap()).map_err(|e| e.into()) self.inner.shutdown_substream(cx, list.get_mut(s).unwrap()).map_err(|e| e.into())
} }
@ -659,12 +659,12 @@ where
} }
#[inline] #[inline]
fn close(&self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn close(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.close(cx).map_err(|e| e.into()) self.inner.close(cx).map_err(|e| e.into())
} }
#[inline] #[inline]
fn flush_all(&self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn flush_all(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.flush_all(cx).map_err(|e| e.into()) self.inner.flush_all(cx).map_err(|e| e.into())
} }
} }

View File

@ -65,7 +65,7 @@ where
type OutboundSubstream = OutboundSubstream; type OutboundSubstream = OutboundSubstream;
type Error = io::Error; type Error = io::Error;
fn poll_event(&self, _: &mut Context) -> Poll<Result<StreamMuxerEvent<Self::Substream>, io::Error>> { fn poll_event(&self, _: &mut Context<'_>) -> Poll<Result<StreamMuxerEvent<Self::Substream>, io::Error>> {
match self.endpoint { match self.endpoint {
Endpoint::Dialer => return Poll::Pending, Endpoint::Dialer => return Poll::Pending,
Endpoint::Listener => {} Endpoint::Listener => {}
@ -82,7 +82,7 @@ where
OutboundSubstream {} OutboundSubstream {}
} }
fn poll_outbound(&self, _: &mut Context, _: &mut Self::OutboundSubstream) -> Poll<Result<Self::Substream, io::Error>> { fn poll_outbound(&self, _: &mut Context<'_>, _: &mut Self::OutboundSubstream) -> Poll<Result<Self::Substream, io::Error>> {
match self.endpoint { match self.endpoint {
Endpoint::Listener => return Poll::Pending, Endpoint::Listener => return Poll::Pending,
Endpoint::Dialer => {} Endpoint::Dialer => {}
@ -98,31 +98,31 @@ where
fn destroy_outbound(&self, _: Self::OutboundSubstream) { fn destroy_outbound(&self, _: Self::OutboundSubstream) {
} }
fn read_substream(&self, cx: &mut Context, _: &mut Self::Substream, buf: &mut [u8]) -> Poll<Result<usize, io::Error>> { fn read_substream(&self, cx: &mut Context<'_>, _: &mut Self::Substream, buf: &mut [u8]) -> Poll<Result<usize, io::Error>> {
AsyncRead::poll_read(Pin::new(&mut *self.inner.lock()), cx, buf) AsyncRead::poll_read(Pin::new(&mut *self.inner.lock()), cx, buf)
} }
fn write_substream(&self, cx: &mut Context, _: &mut Self::Substream, buf: &[u8]) -> Poll<Result<usize, io::Error>> { fn write_substream(&self, cx: &mut Context<'_>, _: &mut Self::Substream, buf: &[u8]) -> Poll<Result<usize, io::Error>> {
AsyncWrite::poll_write(Pin::new(&mut *self.inner.lock()), cx, buf) AsyncWrite::poll_write(Pin::new(&mut *self.inner.lock()), cx, buf)
} }
fn flush_substream(&self, cx: &mut Context, _: &mut Self::Substream) -> Poll<Result<(), io::Error>> { fn flush_substream(&self, cx: &mut Context<'_>, _: &mut Self::Substream) -> Poll<Result<(), io::Error>> {
AsyncWrite::poll_flush(Pin::new(&mut *self.inner.lock()), cx) AsyncWrite::poll_flush(Pin::new(&mut *self.inner.lock()), cx)
} }
fn shutdown_substream(&self, cx: &mut Context, _: &mut Self::Substream) -> Poll<Result<(), io::Error>> { fn shutdown_substream(&self, cx: &mut Context<'_>, _: &mut Self::Substream) -> Poll<Result<(), io::Error>> {
AsyncWrite::poll_close(Pin::new(&mut *self.inner.lock()), cx) AsyncWrite::poll_close(Pin::new(&mut *self.inner.lock()), cx)
} }
fn destroy_substream(&self, _: Self::Substream) { fn destroy_substream(&self, _: Self::Substream) {
} }
fn close(&self, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn close(&self, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
// The `StreamMuxer` trait requires that `close()` implies `flush_all()`. // The `StreamMuxer` trait requires that `close()` implies `flush_all()`.
self.flush_all(cx) self.flush_all(cx)
} }
fn flush_all(&self, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn flush_all(&self, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
AsyncWrite::poll_flush(Pin::new(&mut *self.inner.lock()), cx) AsyncWrite::poll_flush(Pin::new(&mut *self.inner.lock()), cx)
} }
} }

View File

@ -327,7 +327,7 @@ where
} }
/// Provides an API similar to `Stream`, except that it cannot error. /// Provides an API similar to `Stream`, except that it cannot error.
pub fn poll<'a>(&'a mut self, cx: &mut Context) -> Poll<NetworkEvent<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>> pub fn poll<'a>(&'a mut self, cx: &mut Context<'_>) -> Poll<NetworkEvent<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>>
where where
TTrans: Transport<Output = (TConnInfo, TMuxer)>, TTrans: Transport<Output = (TConnInfo, TMuxer)>,
TTrans::Error: Send + 'static, TTrans::Error: Send + 'static,

View File

@ -94,7 +94,7 @@ where
EitherError<TTransErr, TMapOut::Error> EitherError<TTransErr, TMapOut::Error>
>; >;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project(); let this = self.project();
match TryStream::try_poll_next(this.stream, cx) { match TryStream::try_poll_next(this.stream, cx) {
Poll::Ready(Some(Ok(event))) => { Poll::Ready(Some(Ok(event))) => {
@ -146,7 +146,7 @@ where
{ {
type Output = Result<TMapOut::Ok, EitherError<TFut::Error, TMapOut::Error>>; type Output = Result<TMapOut::Ok, EitherError<TFut::Error, TMapOut::Error>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop { loop {
let future = match &mut self.inner { let future = match &mut self.inner {
Either::Left(future) => { Either::Left(future) => {

View File

@ -42,7 +42,7 @@ impl<TOut> Default for DummyTransport<TOut> {
} }
impl<TOut> fmt::Debug for DummyTransport<TOut> { impl<TOut> fmt::Debug for DummyTransport<TOut> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "DummyTransport") write!(f, "DummyTransport")
} }
} }
@ -73,13 +73,13 @@ impl<TOut> Transport for DummyTransport<TOut> {
pub struct DummyStream(()); pub struct DummyStream(());
impl fmt::Debug for DummyStream { impl fmt::Debug for DummyStream {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "DummyStream") write!(f, "DummyStream")
} }
} }
impl AsyncRead for DummyStream { impl AsyncRead for DummyStream {
fn poll_read(self: Pin<&mut Self>, _: &mut Context, _: &mut [u8]) fn poll_read(self: Pin<&mut Self>, _: &mut Context<'_>, _: &mut [u8])
-> Poll<Result<usize, io::Error>> -> Poll<Result<usize, io::Error>>
{ {
Poll::Ready(Err(io::ErrorKind::Other.into())) Poll::Ready(Err(io::ErrorKind::Other.into()))
@ -87,19 +87,19 @@ impl AsyncRead for DummyStream {
} }
impl AsyncWrite for DummyStream { impl AsyncWrite for DummyStream {
fn poll_write(self: Pin<&mut Self>, _: &mut Context, _: &[u8]) fn poll_write(self: Pin<&mut Self>, _: &mut Context<'_>, _: &[u8])
-> Poll<Result<usize, io::Error>> -> Poll<Result<usize, io::Error>>
{ {
Poll::Ready(Err(io::ErrorKind::Other.into())) Poll::Ready(Err(io::ErrorKind::Other.into()))
} }
fn poll_flush(self: Pin<&mut Self>, _: &mut Context) fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>)
-> Poll<Result<(), io::Error>> -> Poll<Result<(), io::Error>>
{ {
Poll::Ready(Err(io::ErrorKind::Other.into())) Poll::Ready(Err(io::ErrorKind::Other.into()))
} }
fn poll_close(self: Pin<&mut Self>, _: &mut Context) fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>)
-> Poll<Result<(), io::Error>> -> Poll<Result<(), io::Error>>
{ {
Poll::Ready(Err(io::ErrorKind::Other.into())) Poll::Ready(Err(io::ErrorKind::Other.into()))

View File

@ -74,7 +74,7 @@ where
{ {
type Item = Result<ListenerEvent<MapFuture<X, F>, E>, E>; type Item = Result<ListenerEvent<MapFuture<X, F>, E>, E>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project(); let this = self.project();
match TryStream::try_poll_next(this.stream, cx) { match TryStream::try_poll_next(this.stream, cx) {
Poll::Ready(Some(Ok(event))) => { Poll::Ready(Some(Ok(event))) => {
@ -124,7 +124,7 @@ where
{ {
type Output = Result<B, T::Error>; type Output = Result<B, T::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
let item = match TryFuture::try_poll(this.inner, cx) { let item = match TryFuture::try_poll(this.inner, cx) {
Poll::Pending => return Poll::Pending, Poll::Pending => return Poll::Pending,

View File

@ -82,7 +82,7 @@ where
{ {
type Item = Result<ListenerEvent<MapErrListenerUpgrade<T, F>, TErr>, TErr>; type Item = Result<ListenerEvent<MapErrListenerUpgrade<T, F>, TErr>, TErr>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project(); let this = self.project();
match TryStream::try_poll_next(this.inner, cx) { match TryStream::try_poll_next(this.inner, cx) {
Poll::Ready(Some(Ok(event))) => { Poll::Ready(Some(Ok(event))) => {
@ -118,7 +118,7 @@ where T: Transport,
{ {
type Output = Result<T::Output, TErr>; type Output = Result<T::Output, TErr>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
match Future::poll(this.inner, cx) { match Future::poll(this.inner, cx) {
Poll::Ready(Ok(value)) => Poll::Ready(Ok(value)), Poll::Ready(Ok(value)) => Poll::Ready(Ok(value)),
@ -146,7 +146,7 @@ where
{ {
type Output = Result<T::Output, TErr>; type Output = Result<T::Output, TErr>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
match Future::poll(this.inner, cx) { match Future::poll(this.inner, cx) {
Poll::Ready(Ok(value)) => Poll::Ready(Ok(value)), Poll::Ready(Ok(value)) => Poll::Ready(Ok(value)),

View File

@ -46,7 +46,7 @@ pub struct DialFuture {
impl Future for DialFuture { impl Future for DialFuture {
type Output = Result<Channel<Vec<u8>>, MemoryTransportError>; type Output = Result<Channel<Vec<u8>>, MemoryTransportError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.sender.poll_ready(cx) { match self.sender.poll_ready(cx) {
Poll::Pending => return Poll::Pending, Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(())) => {}, Poll::Ready(Ok(())) => {},
@ -175,7 +175,7 @@ pub struct Listener {
impl Stream for Listener { impl Stream for Listener {
type Item = Result<ListenerEvent<Ready<Result<Channel<Vec<u8>>, MemoryTransportError>>, MemoryTransportError>, MemoryTransportError>; type Item = Result<ListenerEvent<Ready<Result<Channel<Vec<u8>>, MemoryTransportError>>, MemoryTransportError>, MemoryTransportError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if self.tell_listen_addr { if self.tell_listen_addr {
self.tell_listen_addr = false; self.tell_listen_addr = false;
return Poll::Ready(Some(Ok(ListenerEvent::NewAddress(self.addr.clone())))) return Poll::Ready(Some(Ok(ListenerEvent::NewAddress(self.addr.clone()))))
@ -240,7 +240,7 @@ impl<T> Unpin for Chan<T> {
impl<T> Stream for Chan<T> { impl<T> Stream for Chan<T> {
type Item = Result<T, io::Error>; type Item = Result<T, io::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match Stream::poll_next(Pin::new(&mut self.incoming), cx) { match Stream::poll_next(Pin::new(&mut self.incoming), cx) {
Poll::Pending => Poll::Pending, Poll::Pending => Poll::Pending,
Poll::Ready(None) => Poll::Ready(Some(Err(io::ErrorKind::BrokenPipe.into()))), Poll::Ready(None) => Poll::Ready(Some(Err(io::ErrorKind::BrokenPipe.into()))),
@ -252,7 +252,7 @@ impl<T> Stream for Chan<T> {
impl<T> Sink<T> for Chan<T> { impl<T> Sink<T> for Chan<T> {
type Error = io::Error; type Error = io::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.outgoing.poll_ready(cx) self.outgoing.poll_ready(cx)
.map(|v| v.map_err(|_| io::ErrorKind::BrokenPipe.into())) .map(|v| v.map_err(|_| io::ErrorKind::BrokenPipe.into()))
} }
@ -261,11 +261,11 @@ impl<T> Sink<T> for Chan<T> {
self.outgoing.start_send(item).map_err(|_| io::ErrorKind::BrokenPipe.into()) self.outgoing.start_send(item).map_err(|_| io::ErrorKind::BrokenPipe.into())
} }
fn poll_flush(self: Pin<&mut Self>, _: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
fn poll_close(self: Pin<&mut Self>, _: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
} }

View File

@ -118,7 +118,7 @@ where
{ {
type Item = Result<ListenerEvent<Timeout<O>, TransportTimeoutError<E>>, TransportTimeoutError<E>>; type Item = Result<ListenerEvent<Timeout<O>, TransportTimeoutError<E>>, TransportTimeoutError<E>>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project(); let this = self.project();
let poll_out = match TryStream::try_poll_next(this.inner, cx) { let poll_out = match TryStream::try_poll_next(this.inner, cx) {
@ -160,7 +160,7 @@ where
{ {
type Output = Result<InnerFut::Ok, TransportTimeoutError<InnerFut::Error>>; type Output = Result<InnerFut::Ok, TransportTimeoutError<InnerFut::Error>>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
// It is debatable whether we should poll the inner future first or the timer first. // It is debatable whether we should poll the inner future first or the timer first.
// For example, if you start dialing with a timeout of 10 seconds, then after 15 seconds // For example, if you start dialing with a timeout of 10 seconds, then after 15 seconds
// the dialing succeeds on the wire, then after 20 seconds you poll, then depending on // the dialing succeeds on the wire, then after 20 seconds you poll, then depending on

View File

@ -194,7 +194,7 @@ where
{ {
type Output = <EitherUpgrade<C, U> as Future>::Output; type Output = <EitherUpgrade<C, U> as Future>::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
Future::poll(this.inner, cx) Future::poll(this.inner, cx)
} }
@ -223,7 +223,7 @@ where
{ {
type Output = Result<(I, M), UpgradeError<E>>; type Output = Result<(I, M), UpgradeError<E>>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
let m = match ready!(Future::poll(this.upgrade, cx)) { let m = match ready!(Future::poll(this.upgrade, cx)) {
Ok(m) => m, Ok(m) => m,
@ -337,7 +337,7 @@ where
{ {
type Output = Result<(I, D), TransportUpgradeError<F::Error, U::Error>>; type Output = Result<(I, D), TransportUpgradeError<F::Error, U::Error>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
// We use a `this` variable because the compiler can't mutably borrow multiple times // We use a `this` variable because the compiler can't mutably borrow multiple times
// accross a `Deref`. // accross a `Deref`.
let this = &mut *self; let this = &mut *self;
@ -387,7 +387,7 @@ where
{ {
type Item = Result<ListenerEvent<ListenerUpgradeFuture<F, U, I, C>, TransportUpgradeError<E, U::Error>>, TransportUpgradeError<E, U::Error>>; type Item = Result<ListenerEvent<ListenerUpgradeFuture<F, U, I, C>, TransportUpgradeError<E, U::Error>>, TransportUpgradeError<E, U::Error>>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match ready!(TryStream::try_poll_next(self.stream.as_mut(), cx)) { match ready!(TryStream::try_poll_next(self.stream.as_mut(), cx)) {
Some(Ok(event)) => { Some(Ok(event)) => {
let event = event let event = event
@ -430,7 +430,7 @@ where
{ {
type Output = Result<(I, D), TransportUpgradeError<F::Error, U::Error>>; type Output = Result<(I, D), TransportUpgradeError<F::Error, U::Error>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
// We use a `this` variable because the compiler can't mutably borrow multiple times // We use a `this` variable because the compiler can't mutably borrow multiple times
// accross a `Deref`. // accross a `Deref`.
let this = &mut *self; let this = &mut *self;

View File

@ -105,7 +105,7 @@ where
{ {
type Output = Result<U::Output, UpgradeError<U::Error>>; type Output = Result<U::Output, UpgradeError<U::Error>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop { loop {
match mem::replace(&mut self.inner, InboundUpgradeApplyState::Undefined) { match mem::replace(&mut self.inner, InboundUpgradeApplyState::Undefined) {
InboundUpgradeApplyState::Init { mut future, upgrade } => { InboundUpgradeApplyState::Init { mut future, upgrade } => {
@ -181,7 +181,7 @@ where
{ {
type Output = Result<U::Output, UpgradeError<U::Error>>; type Output = Result<U::Output, UpgradeError<U::Error>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop { loop {
match mem::replace(&mut self.inner, OutboundUpgradeApplyState::Undefined) { match mem::replace(&mut self.inner, OutboundUpgradeApplyState::Undefined) {
OutboundUpgradeApplyState::Init { mut future, upgrade } => { OutboundUpgradeApplyState::Init { mut future, upgrade } => {

View File

@ -244,7 +244,7 @@ where
{ {
type Output = Result<TOut, TInnerFut::Error>; type Output = Result<TOut, TInnerFut::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
let item = match TryFuture::try_poll(this.inner, cx) { let item = match TryFuture::try_poll(this.inner, cx) {
Poll::Ready(Ok(v)) => v, Poll::Ready(Ok(v)) => v,
@ -271,7 +271,7 @@ where
{ {
type Output = Result<T::Ok, A>; type Output = Result<T::Ok, A>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
match TryFuture::try_poll(this.fut, cx) { match TryFuture::try_poll(this.fut, cx) {
Poll::Pending => Poll::Pending, Poll::Pending => Poll::Pending,

View File

@ -32,7 +32,7 @@ impl ConnectionHandler for TestHandler {
fn inject_address_change(&mut self, _: &Multiaddr) fn inject_address_change(&mut self, _: &Multiaddr)
{} {}
fn poll(&mut self, _: &mut Context) fn poll(&mut self, _: &mut Context<'_>)
-> Poll<Result<ConnectionHandlerEvent<Self::OutboundOpenInfo, Self::OutEvent>, Self::Error>> -> Poll<Result<ConnectionHandlerEvent<Self::OutboundOpenInfo, Self::OutEvent>, Self::Error>>
{ {
Poll::Ready(Ok(ConnectionHandlerEvent::Custom(()))) Poll::Ready(Ok(ConnectionHandlerEvent::Custom(())))
@ -63,7 +63,7 @@ where
{ {
type Output = Result<M, M::Error>; type Output = Result<M, M::Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop { loop {
match std::mem::replace(&mut self.state, CloseMuxerState::Done) { match std::mem::replace(&mut self.state, CloseMuxerState::Done) {
CloseMuxerState::Close(muxer) => { CloseMuxerState::Close(muxer) => {

View File

@ -147,7 +147,7 @@ fn main() -> Result<(), Box<dyn Error>> {
// Kick it off // Kick it off
let mut listening = false; let mut listening = false;
task::block_on(future::poll_fn(move |cx: &mut Context| { task::block_on(future::poll_fn(move |cx: &mut Context<'_>| {
loop { loop {
match stdin.try_poll_next_unpin(cx)? { match stdin.try_poll_next_unpin(cx)? {
Poll::Ready(Some(line)) => swarm.floodsub.publish(floodsub_topic.clone(), line.as_bytes()), Poll::Ready(Some(line)) => swarm.floodsub.publish(floodsub_topic.clone(), line.as_bytes()),

View File

@ -141,7 +141,7 @@ fn main() -> Result<(), Box<dyn Error>> {
// Kick it off. // Kick it off.
let mut listening = false; let mut listening = false;
task::block_on(future::poll_fn(move |cx: &mut Context| { task::block_on(future::poll_fn(move |cx: &mut Context<'_>| {
loop { loop {
match stdin.try_poll_next_unpin(cx)? { match stdin.try_poll_next_unpin(cx)? {
Poll::Ready(Some(line)) => handle_input_line(&mut swarm.kademlia, line), Poll::Ready(Some(line)) => handle_input_line(&mut swarm.kademlia, line),

View File

@ -118,7 +118,7 @@ fn main() -> Result<(), Box<dyn Error>> {
// Kick it off // Kick it off
let mut listening = false; let mut listening = false;
task::block_on(future::poll_fn(move |cx: &mut Context| { task::block_on(future::poll_fn(move |cx: &mut Context<'_>| {
loop { loop {
match stdin.try_poll_next_unpin(cx)? { match stdin.try_poll_next_unpin(cx)? {
Poll::Ready(Some(line)) => swarm.publish(&topic, line.as_bytes()), Poll::Ready(Some(line)) => swarm.publish(&topic, line.as_bytes()),

View File

@ -278,7 +278,7 @@ fn main() -> Result<(), Box<dyn Error>> {
// Kick it off // Kick it off
let mut listening = false; let mut listening = false;
task::block_on(future::poll_fn(move |cx: &mut Context| { task::block_on(future::poll_fn(move |cx: &mut Context<'_>| {
loop { loop {
match stdin.try_poll_next_unpin(cx)? { match stdin.try_poll_next_unpin(cx)? {
Poll::Ready(Some(line)) => { Poll::Ready(Some(line)) => {

View File

@ -77,7 +77,7 @@ fn main() -> Result<(), Box<dyn Error>> {
Swarm::listen_on(&mut swarm, "/ip4/0.0.0.0/tcp/0".parse()?)?; Swarm::listen_on(&mut swarm, "/ip4/0.0.0.0/tcp/0".parse()?)?;
let mut listening = false; let mut listening = false;
task::block_on(future::poll_fn(move |cx: &mut Context| { task::block_on(future::poll_fn(move |cx: &mut Context<'_>| {
loop { loop {
match swarm.poll_next_unpin(cx) { match swarm.poll_next_unpin(cx) {
Poll::Ready(Some(event)) => println!("{:?}", event), Poll::Ready(Some(event)) => println!("{:?}", event),

View File

@ -1,3 +1,8 @@
# 0.20.2 [2020-07-28]
- Generate fully-qualified method name for `poll` to avoid
ambiguity. [PR 1681](https://github.com/libp2p/rust-libp2p/pull/1681).
# 0.20.1 [2020-07-08] # 0.20.1 [2020-07-08]
- Allow users to opt out of the `NetworkBehaviourEventProcess` - Allow users to opt out of the `NetworkBehaviourEventProcess`

View File

@ -2,7 +2,7 @@
name = "libp2p-core-derive" name = "libp2p-core-derive"
edition = "2018" edition = "2018"
description = "Procedural macros of libp2p-core" description = "Procedural macros of libp2p-core"
version = "0.20.1" version = "0.20.2"
authors = ["Parity Technologies <admin@parity.io>"] authors = ["Parity Technologies <admin@parity.io>"]
license = "MIT" license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p" repository = "https://github.com/libp2p/rust-libp2p"

View File

@ -20,7 +20,7 @@
#![recursion_limit = "256"] #![recursion_limit = "256"]
extern crate proc_macro;
use quote::quote; use quote::quote;
use proc_macro::TokenStream; use proc_macro::TokenStream;
@ -435,7 +435,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream {
Some(quote!{ Some(quote!{
loop { loop {
match #field_name.poll(cx, poll_params) { match #trait_to_impl::poll(&mut #field_name, cx, poll_params) {
#generate_event_match_arm #generate_event_match_arm
std::task::Poll::Ready(#network_behaviour_action::DialAddress { address }) => { std::task::Poll::Ready(#network_behaviour_action::DialAddress { address }) => {
return std::task::Poll::Ready(#network_behaviour_action::DialAddress { address }); return std::task::Poll::Ready(#network_behaviour_action::DialAddress { address });

View File

@ -121,7 +121,7 @@ pub enum FromUrlErr {
} }
impl fmt::Display for FromUrlErr { impl fmt::Display for FromUrlErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
FromUrlErr::BadUrl => write!(f, "Bad URL"), FromUrlErr::BadUrl => write!(f, "Bad URL"),
FromUrlErr::UnsupportedScheme => write!(f, "Unrecognized URL scheme"), FromUrlErr::UnsupportedScheme => write!(f, "Unrecognized URL scheme"),

View File

@ -143,7 +143,7 @@ impl Multiaddr {
/// updated `Protocol` at position `at` will be returned. /// updated `Protocol` at position `at` will be returned.
pub fn replace<'a, F>(&self, at: usize, by: F) -> Option<Multiaddr> pub fn replace<'a, F>(&self, at: usize, by: F) -> Option<Multiaddr>
where where
F: FnOnce(&Protocol) -> Option<Protocol<'a>> F: FnOnce(&Protocol<'_>) -> Option<Protocol<'a>>
{ {
let mut address = Multiaddr::with_capacity(self.len()); let mut address = Multiaddr::with_capacity(self.len());
let mut fun = Some(by); let mut fun = Some(by);

View File

@ -335,7 +335,7 @@ fn append() {
assert_eq!(None, i.next()) assert_eq!(None, i.next())
} }
fn replace_ip_addr(a: &Multiaddr, p: Protocol) -> Option<Multiaddr> { fn replace_ip_addr(a: &Multiaddr, p: Protocol<'_>) -> Option<Multiaddr> {
a.replace(0, move |x| match x { a.replace(0, move |x| match x {
Protocol::Ip4(_) | Protocol::Ip6(_) => Some(p), Protocol::Ip4(_) | Protocol::Ip6(_) => Some(p),
_ => None _ => None

View File

@ -163,7 +163,7 @@ where
{ {
type Output = Result<(I::Item, Negotiated<R>), NegotiationError>; type Output = Result<(I::Item, Negotiated<R>), NegotiationError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
loop { loop {
@ -300,7 +300,7 @@ where
{ {
type Output = Result<(I::Item, Negotiated<R>), NegotiationError>; type Output = Result<(I::Item, Negotiated<R>), NegotiationError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
loop { loop {

View File

@ -110,7 +110,7 @@ impl<R> LengthDelimited<R> {
/// ///
/// After this method returns `Poll::Ready`, the write buffer of frames /// After this method returns `Poll::Ready`, the write buffer of frames
/// submitted to the `Sink` is guaranteed to be empty. /// submitted to the `Sink` is guaranteed to be empty.
pub fn poll_write_buffer(self: Pin<&mut Self>, cx: &mut Context) pub fn poll_write_buffer(self: Pin<&mut Self>, cx: &mut Context<'_>)
-> Poll<Result<(), io::Error>> -> Poll<Result<(), io::Error>>
where where
R: AsyncWrite R: AsyncWrite
@ -140,7 +140,7 @@ where
{ {
type Item = Result<Bytes, io::Error>; type Item = Result<Bytes, io::Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project(); let mut this = self.project();
loop { loop {
@ -212,7 +212,7 @@ where
{ {
type Error = io::Error; type Error = io::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
// Use the maximum frame length also as a (soft) upper limit // Use the maximum frame length also as a (soft) upper limit
// for the entire write buffer. The actual (hard) limit is thus // for the entire write buffer. The actual (hard) limit is thus
// implied to be roughly 2 * MAX_FRAME_SIZE. // implied to be roughly 2 * MAX_FRAME_SIZE.
@ -250,7 +250,7 @@ where
Ok(()) Ok(())
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
// Write all buffered frame data to the underlying I/O stream. // Write all buffered frame data to the underlying I/O stream.
match LengthDelimited::poll_write_buffer(self.as_mut(), cx) { match LengthDelimited::poll_write_buffer(self.as_mut(), cx) {
Poll::Ready(Ok(())) => {}, Poll::Ready(Ok(())) => {},
@ -265,7 +265,7 @@ where
this.inner.poll_flush(cx) this.inner.poll_flush(cx)
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
// Write all buffered frame data to the underlying I/O stream. // Write all buffered frame data to the underlying I/O stream.
match LengthDelimited::poll_write_buffer(self.as_mut(), cx) { match LengthDelimited::poll_write_buffer(self.as_mut(), cx) {
Poll::Ready(Ok(())) => {}, Poll::Ready(Ok(())) => {},
@ -314,7 +314,7 @@ where
{ {
type Item = Result<Bytes, io::Error>; type Item = Result<Bytes, io::Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.project().inner.poll_next(cx) self.project().inner.poll_next(cx)
} }
} }
@ -323,7 +323,7 @@ impl<R> AsyncWrite for LengthDelimitedReader<R>
where where
R: AsyncWrite R: AsyncWrite
{ {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8])
-> Poll<Result<usize, io::Error>> -> Poll<Result<usize, io::Error>>
{ {
// `this` here designates the `LengthDelimited`. // `this` here designates the `LengthDelimited`.
@ -340,15 +340,15 @@ where
this.project().inner.poll_write(cx, buf) this.project().inner.poll_write(cx, buf)
} }
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
self.project().inner.poll_flush(cx) self.project().inner.poll_flush(cx)
} }
fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
self.project().inner.poll_close(cx) self.project().inner.poll_close(cx)
} }
fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &[IoSlice]) fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>])
-> Poll<Result<usize, io::Error>> -> Poll<Result<usize, io::Error>>
{ {
// `this` here designates the `LengthDelimited`. // `this` here designates the `LengthDelimited`.

View File

@ -101,7 +101,7 @@ where
{ {
type Output = Result<(N, Negotiated<R>), NegotiationError>; type Output = Result<(N, Negotiated<R>), NegotiationError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
loop { loop {

View File

@ -57,7 +57,7 @@ where
{ {
type Output = Result<Negotiated<TInner>, NegotiationError>; type Output = Result<Negotiated<TInner>, NegotiationError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut io = self.inner.take().expect("NegotiatedFuture called after completion."); let mut io = self.inner.take().expect("NegotiatedFuture called after completion.");
match Negotiated::poll(Pin::new(&mut io), cx) { match Negotiated::poll(Pin::new(&mut io), cx) {
Poll::Pending => { Poll::Pending => {
@ -87,7 +87,7 @@ impl<TInner> Negotiated<TInner> {
} }
/// Polls the `Negotiated` for completion. /// Polls the `Negotiated` for completion.
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), NegotiationError>> fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), NegotiationError>>
where where
TInner: AsyncRead + AsyncWrite + Unpin TInner: AsyncRead + AsyncWrite + Unpin
{ {
@ -191,7 +191,7 @@ impl<TInner> AsyncRead for Negotiated<TInner>
where where
TInner: AsyncRead + AsyncWrite + Unpin TInner: AsyncRead + AsyncWrite + Unpin
{ {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8])
-> Poll<Result<usize, io::Error>> -> Poll<Result<usize, io::Error>>
{ {
loop { loop {
@ -225,7 +225,7 @@ where
} }
}*/ }*/
fn poll_read_vectored(mut self: Pin<&mut Self>, cx: &mut Context, bufs: &mut [IoSliceMut]) fn poll_read_vectored(mut self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>])
-> Poll<Result<usize, io::Error>> -> Poll<Result<usize, io::Error>>
{ {
loop { loop {
@ -255,7 +255,7 @@ impl<TInner> AsyncWrite for Negotiated<TInner>
where where
TInner: AsyncWrite + AsyncRead + Unpin TInner: AsyncWrite + AsyncRead + Unpin
{ {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<Result<usize, io::Error>> { fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize, io::Error>> {
match self.project().state.project() { match self.project().state.project() {
StateProj::Completed { mut io, remaining } => { StateProj::Completed { mut io, remaining } => {
while !remaining.is_empty() { while !remaining.is_empty() {
@ -272,7 +272,7 @@ where
} }
} }
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
match self.project().state.project() { match self.project().state.project() {
StateProj::Completed { mut io, remaining } => { StateProj::Completed { mut io, remaining } => {
while !remaining.is_empty() { while !remaining.is_empty() {
@ -289,7 +289,7 @@ where
} }
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
// Ensure all data has been flushed and expected negotiation messages // Ensure all data has been flushed and expected negotiation messages
// have been received. // have been received.
ready!(self.as_mut().poll(cx).map_err(Into::<io::Error>::into)?); ready!(self.as_mut().poll(cx).map_err(Into::<io::Error>::into)?);
@ -303,7 +303,7 @@ where
} }
} }
fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &[IoSlice]) fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>])
-> Poll<Result<usize, io::Error>> -> Poll<Result<usize, io::Error>>
{ {
match self.project().state.project() { match self.project().state.project() {
@ -384,13 +384,13 @@ mod tests {
struct Capped { buf: Vec<u8>, step: usize } struct Capped { buf: Vec<u8>, step: usize }
impl AsyncRead for Capped { impl AsyncRead for Capped {
fn poll_read(self: Pin<&mut Self>, _: &mut Context, _: &mut [u8]) -> Poll<Result<usize, io::Error>> { fn poll_read(self: Pin<&mut Self>, _: &mut Context<'_>, _: &mut [u8]) -> Poll<Result<usize, io::Error>> {
unreachable!() unreachable!()
} }
} }
impl AsyncWrite for Capped { impl AsyncWrite for Capped {
fn poll_write(mut self: Pin<&mut Self>, _: &mut Context, buf: &[u8]) -> Poll<Result<usize, io::Error>> { fn poll_write(mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize, io::Error>> {
if self.buf.len() + buf.len() > self.buf.capacity() { if self.buf.len() + buf.len() > self.buf.capacity() {
return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) return Poll::Ready(Err(io::ErrorKind::WriteZero.into()))
} }
@ -399,11 +399,11 @@ mod tests {
Poll::Ready(Ok(n)) Poll::Ready(Ok(n))
} }
fn poll_flush(self: Pin<&mut Self>, _: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
fn poll_close(self: Pin<&mut Self>, _: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
} }

View File

@ -316,7 +316,7 @@ where
{ {
type Error = ProtocolError; type Error = ProtocolError;
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.project().inner.poll_ready(cx).map_err(From::from) self.project().inner.poll_ready(cx).map_err(From::from)
} }
@ -326,11 +326,11 @@ where
self.project().inner.start_send(buf.freeze()).map_err(From::from) self.project().inner.start_send(buf.freeze()).map_err(From::from)
} }
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.project().inner.poll_flush(cx).map_err(From::from) self.project().inner.poll_flush(cx).map_err(From::from)
} }
fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.project().inner.poll_close(cx).map_err(From::from) self.project().inner.poll_close(cx).map_err(From::from)
} }
} }
@ -341,7 +341,7 @@ where
{ {
type Item = Result<Message, ProtocolError>; type Item = Result<Message, ProtocolError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match poll_stream(self.project().inner, cx) { match poll_stream(self.project().inner, cx) {
Poll::Pending => Poll::Pending, Poll::Pending => Poll::Pending,
Poll::Ready(None) => Poll::Ready(None), Poll::Ready(None) => Poll::Ready(None),
@ -388,7 +388,7 @@ where
{ {
type Item = Result<Message, ProtocolError>; type Item = Result<Message, ProtocolError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
poll_stream(self.project().inner, cx) poll_stream(self.project().inner, cx)
} }
} }
@ -397,24 +397,24 @@ impl<TInner> AsyncWrite for MessageReader<TInner>
where where
TInner: AsyncWrite TInner: AsyncWrite
{ {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<Result<usize, io::Error>> { fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize, io::Error>> {
self.project().inner.poll_write(cx, buf) self.project().inner.poll_write(cx, buf)
} }
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
self.project().inner.poll_flush(cx) self.project().inner.poll_flush(cx)
} }
fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
self.project().inner.poll_close(cx) self.project().inner.poll_close(cx)
} }
fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &[IoSlice]) -> Poll<Result<usize, io::Error>> { fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) -> Poll<Result<usize, io::Error>> {
self.project().inner.poll_write_vectored(cx, bufs) self.project().inner.poll_write_vectored(cx, bufs)
} }
} }
fn poll_stream<S>(stream: Pin<&mut S>, cx: &mut Context) -> Poll<Option<Result<Message, ProtocolError>>> fn poll_stream<S>(stream: Pin<&mut S>, cx: &mut Context<'_>) -> Poll<Option<Result<Message, ProtocolError>>>
where where
S: Stream<Item = Result<Bytes, io::Error>>, S: Stream<Item = Result<Bytes, io::Error>>,
{ {

View File

@ -245,7 +245,7 @@ impl ArcWake for Notifier {
/// ///
/// If `Pending` is returned, the waker is kept and notified later, just like with any `Poll`. /// If `Pending` is returned, the waker is kept and notified later, just like with any `Poll`.
/// `Ready(Ok())` is almost always returned. An error is returned if the stream is EOF. /// `Ready(Ok())` is almost always returned. An error is returned if the stream is EOF.
fn next_match<C, F, O>(inner: &mut MultiplexInner<C>, cx: &mut Context, mut filter: F) -> Poll<Result<O, IoError>> fn next_match<C, F, O>(inner: &mut MultiplexInner<C>, cx: &mut Context<'_>, mut filter: F) -> Poll<Result<O, IoError>>
where C: AsyncRead + AsyncWrite + Unpin, where C: AsyncRead + AsyncWrite + Unpin,
F: FnMut(&codec::Elem) -> Option<O>, F: FnMut(&codec::Elem) -> Option<O>,
{ {
@ -324,7 +324,7 @@ where C: AsyncRead + AsyncWrite + Unpin,
} }
// Small convenience function that tries to write `elem` to the stream. // Small convenience function that tries to write `elem` to the stream.
fn poll_send<C>(inner: &mut MultiplexInner<C>, cx: &mut Context, elem: codec::Elem) -> Poll<Result<(), IoError>> fn poll_send<C>(inner: &mut MultiplexInner<C>, cx: &mut Context<'_>, elem: codec::Elem) -> Poll<Result<(), IoError>>
where C: AsyncRead + AsyncWrite + Unpin where C: AsyncRead + AsyncWrite + Unpin
{ {
ensure_no_error_no_close(inner)?; ensure_no_error_no_close(inner)?;
@ -366,7 +366,7 @@ where C: AsyncRead + AsyncWrite + Unpin
type OutboundSubstream = OutboundSubstream; type OutboundSubstream = OutboundSubstream;
type Error = IoError; type Error = IoError;
fn poll_event(&self, cx: &mut Context) -> Poll<Result<StreamMuxerEvent<Self::Substream>, IoError>> { fn poll_event(&self, cx: &mut Context<'_>) -> Poll<Result<StreamMuxerEvent<Self::Substream>, IoError>> {
let mut inner = self.inner.lock(); let mut inner = self.inner.lock();
if inner.opened_substreams.len() >= inner.config.max_substreams { if inner.opened_substreams.len() >= inner.config.max_substreams {
@ -416,7 +416,7 @@ where C: AsyncRead + AsyncWrite + Unpin
} }
} }
fn poll_outbound(&self, cx: &mut Context, substream: &mut Self::OutboundSubstream) -> Poll<Result<Self::Substream, IoError>> { fn poll_outbound(&self, cx: &mut Context<'_>, substream: &mut Self::OutboundSubstream) -> Poll<Result<Self::Substream, IoError>> {
loop { loop {
let mut inner = self.inner.lock(); let mut inner = self.inner.lock();
@ -475,7 +475,7 @@ where C: AsyncRead + AsyncWrite + Unpin
// Nothing to do. // Nothing to do.
} }
fn read_substream(&self, cx: &mut Context, substream: &mut Self::Substream, buf: &mut [u8]) -> Poll<Result<usize, IoError>> { fn read_substream(&self, cx: &mut Context<'_>, substream: &mut Self::Substream, buf: &mut [u8]) -> Poll<Result<usize, IoError>> {
loop { loop {
// First, transfer from `current_data`. // First, transfer from `current_data`.
if !substream.current_data.is_empty() { if !substream.current_data.is_empty() {
@ -529,7 +529,7 @@ where C: AsyncRead + AsyncWrite + Unpin
} }
} }
fn write_substream(&self, cx: &mut Context, substream: &mut Self::Substream, buf: &[u8]) -> Poll<Result<usize, IoError>> { fn write_substream(&self, cx: &mut Context<'_>, substream: &mut Self::Substream, buf: &[u8]) -> Poll<Result<usize, IoError>> {
if !substream.local_open { if !substream.local_open {
return Poll::Ready(Err(IoErrorKind::BrokenPipe.into())); return Poll::Ready(Err(IoErrorKind::BrokenPipe.into()));
} }
@ -551,7 +551,7 @@ where C: AsyncRead + AsyncWrite + Unpin
} }
} }
fn flush_substream(&self, cx: &mut Context, _substream: &mut Self::Substream) -> Poll<Result<(), IoError>> { fn flush_substream(&self, cx: &mut Context<'_>, _substream: &mut Self::Substream) -> Poll<Result<(), IoError>> {
let mut inner = self.inner.lock(); let mut inner = self.inner.lock();
ensure_no_error_no_close(&mut inner)?; ensure_no_error_no_close(&mut inner)?;
let inner = &mut *inner; // Avoids borrow errors let inner = &mut *inner; // Avoids borrow errors
@ -563,7 +563,7 @@ where C: AsyncRead + AsyncWrite + Unpin
result result
} }
fn shutdown_substream(&self, cx: &mut Context, sub: &mut Self::Substream) -> Poll<Result<(), IoError>> { fn shutdown_substream(&self, cx: &mut Context<'_>, sub: &mut Self::Substream) -> Poll<Result<(), IoError>> {
if !sub.local_open { if !sub.local_open {
return Poll::Ready(Ok(())); return Poll::Ready(Ok(()));
} }
@ -587,7 +587,7 @@ where C: AsyncRead + AsyncWrite + Unpin
}) })
} }
fn close(&self, cx: &mut Context) -> Poll<Result<(), IoError>> { fn close(&self, cx: &mut Context<'_>) -> Poll<Result<(), IoError>> {
let inner = &mut *self.inner.lock(); let inner = &mut *self.inner.lock();
if inner.is_shutdown { if inner.is_shutdown {
return Poll::Ready(Ok(())) return Poll::Ready(Ok(()))
@ -609,7 +609,7 @@ where C: AsyncRead + AsyncWrite + Unpin
} }
} }
fn flush_all(&self, cx: &mut Context) -> Poll<Result<(), IoError>> { fn flush_all(&self, cx: &mut Context<'_>) -> Poll<Result<(), IoError>> {
let inner = &mut *self.inner.lock(); let inner = &mut *self.inner.lock();
if inner.is_shutdown { if inner.is_shutdown {
return Poll::Ready(Ok(())) return Poll::Ready(Ok(()))

View File

@ -37,7 +37,7 @@ pub use yamux::WindowUpdateMode;
pub struct Yamux<S>(Mutex<Inner<S>>); pub struct Yamux<S>(Mutex<Inner<S>>);
impl<S> fmt::Debug for Yamux<S> { impl<S> fmt::Debug for Yamux<S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Yamux") f.write_str("Yamux")
} }
} }
@ -103,7 +103,7 @@ where
type OutboundSubstream = OpenSubstreamToken; type OutboundSubstream = OpenSubstreamToken;
type Error = YamuxError; type Error = YamuxError;
fn poll_event(&self, c: &mut Context) -> Poll<StreamMuxerEvent<Self::Substream>> { fn poll_event(&self, c: &mut Context<'_>) -> Poll<StreamMuxerEvent<Self::Substream>> {
let mut inner = self.0.lock(); let mut inner = self.0.lock();
match ready!(inner.incoming.poll_next_unpin(c)) { match ready!(inner.incoming.poll_next_unpin(c)) {
Some(Ok(s)) => Poll::Ready(Ok(StreamMuxerEvent::InboundSubstream(s))), Some(Ok(s)) => Poll::Ready(Ok(StreamMuxerEvent::InboundSubstream(s))),
@ -116,7 +116,7 @@ where
OpenSubstreamToken(()) OpenSubstreamToken(())
} }
fn poll_outbound(&self, c: &mut Context, _: &mut OpenSubstreamToken) -> Poll<Self::Substream> { fn poll_outbound(&self, c: &mut Context<'_>, _: &mut OpenSubstreamToken) -> Poll<Self::Substream> {
let mut inner = self.0.lock(); let mut inner = self.0.lock();
Pin::new(&mut inner.control).poll_open_stream(c).map_err(YamuxError) Pin::new(&mut inner.control).poll_open_stream(c).map_err(YamuxError)
} }
@ -125,25 +125,25 @@ where
self.0.lock().control.abort_open_stream() self.0.lock().control.abort_open_stream()
} }
fn read_substream(&self, c: &mut Context, s: &mut Self::Substream, b: &mut [u8]) -> Poll<usize> { fn read_substream(&self, c: &mut Context<'_>, s: &mut Self::Substream, b: &mut [u8]) -> Poll<usize> {
Pin::new(s).poll_read(c, b).map_err(|e| YamuxError(e.into())) Pin::new(s).poll_read(c, b).map_err(|e| YamuxError(e.into()))
} }
fn write_substream(&self, c: &mut Context, s: &mut Self::Substream, b: &[u8]) -> Poll<usize> { fn write_substream(&self, c: &mut Context<'_>, s: &mut Self::Substream, b: &[u8]) -> Poll<usize> {
Pin::new(s).poll_write(c, b).map_err(|e| YamuxError(e.into())) Pin::new(s).poll_write(c, b).map_err(|e| YamuxError(e.into()))
} }
fn flush_substream(&self, c: &mut Context, s: &mut Self::Substream) -> Poll<()> { fn flush_substream(&self, c: &mut Context<'_>, s: &mut Self::Substream) -> Poll<()> {
Pin::new(s).poll_flush(c).map_err(|e| YamuxError(e.into())) Pin::new(s).poll_flush(c).map_err(|e| YamuxError(e.into()))
} }
fn shutdown_substream(&self, c: &mut Context, s: &mut Self::Substream) -> Poll<()> { fn shutdown_substream(&self, c: &mut Context<'_>, s: &mut Self::Substream) -> Poll<()> {
Pin::new(s).poll_close(c).map_err(|e| YamuxError(e.into())) Pin::new(s).poll_close(c).map_err(|e| YamuxError(e.into()))
} }
fn destroy_substream(&self, _: Self::Substream) { } fn destroy_substream(&self, _: Self::Substream) { }
fn close(&self, c: &mut Context) -> Poll<()> { fn close(&self, c: &mut Context<'_>) -> Poll<()> {
let mut inner = self.0.lock(); let mut inner = self.0.lock();
if let std::task::Poll::Ready(x) = Pin::new(&mut inner.control).poll_close(c) { if let std::task::Poll::Ready(x) = Pin::new(&mut inner.control).poll_close(c) {
return Poll::Ready(x.map_err(YamuxError)) return Poll::Ready(x.map_err(YamuxError))
@ -158,7 +158,7 @@ where
Poll::Pending Poll::Pending
} }
fn flush_all(&self, _: &mut Context) -> Poll<()> { fn flush_all(&self, _: &mut Context<'_>) -> Poll<()> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
} }
@ -290,7 +290,7 @@ pub struct Incoming<T> {
} }
impl<T> fmt::Debug for Incoming<T> { impl<T> fmt::Debug for Incoming<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Incoming") f.write_str("Incoming")
} }
} }
@ -302,7 +302,7 @@ pub struct LocalIncoming<T> {
} }
impl<T> fmt::Debug for LocalIncoming<T> { impl<T> fmt::Debug for LocalIncoming<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("LocalIncoming") f.write_str("LocalIncoming")
} }
} }
@ -310,7 +310,7 @@ impl<T> fmt::Debug for LocalIncoming<T> {
impl<T> Stream for Incoming<T> { impl<T> Stream for Incoming<T> {
type Item = Result<yamux::Stream, YamuxError>; type Item = Result<yamux::Stream, YamuxError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> std::task::Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> std::task::Poll<Option<Self::Item>> {
self.stream.as_mut().poll_next_unpin(cx) self.stream.as_mut().poll_next_unpin(cx)
} }
@ -325,7 +325,7 @@ impl<T> Unpin for Incoming<T> {
impl<T> Stream for LocalIncoming<T> { impl<T> Stream for LocalIncoming<T> {
type Item = Result<yamux::Stream, YamuxError>; type Item = Result<yamux::Stream, YamuxError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> std::task::Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> std::task::Poll<Option<Self::Item>> {
self.stream.as_mut().poll_next_unpin(cx) self.stream.as_mut().poll_next_unpin(cx)
} }

View File

@ -104,7 +104,7 @@ impl<S> DeflateOutput<S> {
/// Tries to write the content of `self.write_out` to `self.inner`. /// Tries to write the content of `self.write_out` to `self.inner`.
/// Returns `Ready(Ok(()))` if `self.write_out` is empty. /// Returns `Ready(Ok(()))` if `self.write_out` is empty.
fn flush_write_out(&mut self, cx: &mut Context) -> Poll<Result<(), io::Error>> fn flush_write_out(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>>
where S: AsyncWrite + Unpin where S: AsyncWrite + Unpin
{ {
loop { loop {
@ -125,7 +125,7 @@ impl<S> DeflateOutput<S> {
impl<S> AsyncRead for DeflateOutput<S> impl<S> AsyncRead for DeflateOutput<S>
where S: AsyncRead + Unpin where S: AsyncRead + Unpin
{ {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<Result<usize, io::Error>> { fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize, io::Error>> {
// We use a `this` variable because the compiler doesn't allow multiple mutable borrows // We use a `this` variable because the compiler doesn't allow multiple mutable borrows
// across a `Deref`. // across a `Deref`.
let this = &mut *self; let this = &mut *self;
@ -177,7 +177,7 @@ impl<S> AsyncRead for DeflateOutput<S>
impl<S> AsyncWrite for DeflateOutput<S> impl<S> AsyncWrite for DeflateOutput<S>
where S: AsyncWrite + Unpin where S: AsyncWrite + Unpin
{ {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8])
-> Poll<Result<usize, io::Error>> -> Poll<Result<usize, io::Error>>
{ {
// We use a `this` variable because the compiler doesn't allow multiple mutable borrows // We use a `this` variable because the compiler doesn't allow multiple mutable borrows
@ -208,7 +208,7 @@ impl<S> AsyncWrite for DeflateOutput<S>
} }
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
// We use a `this` variable because the compiler doesn't allow multiple mutable borrows // We use a `this` variable because the compiler doesn't allow multiple mutable borrows
// across a `Deref`. // across a `Deref`.
let this = &mut *self; let this = &mut *self;
@ -231,7 +231,7 @@ impl<S> AsyncWrite for DeflateOutput<S>
AsyncWrite::poll_flush(Pin::new(&mut this.inner), cx) AsyncWrite::poll_flush(Pin::new(&mut this.inner), cx)
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
// We use a `this` variable because the compiler doesn't allow multiple mutable borrows // We use a `this` variable because the compiler doesn't allow multiple mutable borrows
// across a `Deref`. // across a `Deref`.
let this = &mut *self; let this = &mut *self;

View File

@ -370,7 +370,7 @@ impl NetworkBehaviour for Floodsub {
fn poll( fn poll(
&mut self, &mut self,
_: &mut Context, _: &mut Context<'_>,
_: &mut impl PollParameters, _: &mut impl PollParameters,
) -> Poll< ) -> Poll<
NetworkBehaviourAction< NetworkBehaviourAction<

View File

@ -1,3 +1,7 @@
# 0.??.? [????-??-??]
- `Debug` instance for `Gossipsub`. [PR 1673](https://github.com/libp2p/rust-libp2p/pull/1673).
# 0.20.0 [2020-07-01] # 0.20.0 [2020-07-01]
- Updated dependencies. - Updated dependencies.

View File

@ -26,6 +26,7 @@ base64 = "0.11.0"
lru = "0.4.3" lru = "0.4.3"
smallvec = "1.1.0" smallvec = "1.1.0"
prost = "0.6.1" prost = "0.6.1"
hex_fmt = "0.3.0"
[dev-dependencies] [dev-dependencies]
async-std = "1.6.2" async-std = "1.6.2"

View File

@ -51,6 +51,7 @@ use wasm_timer::{Instant, Interval};
mod tests; mod tests;
#[derive(Debug)]
/// Network behaviour that handles the gossipsub protocol. /// Network behaviour that handles the gossipsub protocol.
pub struct Gossipsub { pub struct Gossipsub {
/// Configuration providing gossipsub performance parameters. /// Configuration providing gossipsub performance parameters.
@ -1133,7 +1134,7 @@ impl NetworkBehaviour for Gossipsub {
fn poll( fn poll(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
_: &mut impl PollParameters, _: &mut impl PollParameters,
) -> Poll< ) -> Poll<
NetworkBehaviourAction< NetworkBehaviourAction<

View File

@ -230,9 +230,13 @@ impl GossipsubConfigBuilder {
} }
impl std::fmt::Debug for GossipsubConfig { impl std::fmt::Debug for GossipsubConfig {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut builder = f.debug_struct("GossipsubConfig"); let mut builder = f.debug_struct("GossipsubConfig");
let _ = builder.field("protocol_id", &self.protocol_id); let _ = if let Ok(text) = std::str::from_utf8(&self.protocol_id) {
builder.field("protocol_id", &text)
} else {
builder.field("protocol_id", &hex_fmt::HexFmt(&self.protocol_id))
};
let _ = builder.field("history_length", &self.history_length); let _ = builder.field("history_length", &self.history_length);
let _ = builder.field("history_gossip", &self.history_gossip); let _ = builder.field("history_gossip", &self.history_gossip);
let _ = builder.field("mesh_n", &self.mesh_n); let _ = builder.field("mesh_n", &self.mesh_n);

View File

@ -165,7 +165,7 @@ impl ProtocolsHandler for GossipsubHandler {
fn poll( fn poll(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ProtocolsHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,

View File

@ -18,11 +18,11 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
extern crate fnv;
use crate::protocol::{GossipsubMessage, MessageId}; use crate::protocol::{GossipsubMessage, MessageId};
use crate::topic::TopicHash; use crate::topic::TopicHash;
use std::collections::HashMap; use std::{collections::HashMap, fmt};
/// CacheEntry stored in the history. /// CacheEntry stored in the history.
#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Clone, PartialEq, Eq, Hash)]
@ -40,6 +40,16 @@ pub struct MessageCache {
msg_id: fn(&GossipsubMessage) -> MessageId, msg_id: fn(&GossipsubMessage) -> MessageId,
} }
impl fmt::Debug for MessageCache {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MessageCache")
.field("msgs", &self.msgs)
.field("history", &self.history)
.field("gossip", &self.gossip)
.finish()
}
}
/// Implementation of the MessageCache. /// Implementation of the MessageCache.
impl MessageCache { impl MessageCache {
pub fn new( pub fn new(

View File

@ -29,7 +29,7 @@ use futures::prelude::*;
use futures_codec::{Decoder, Encoder, Framed}; use futures_codec::{Decoder, Encoder, Framed};
use libp2p_core::{InboundUpgrade, OutboundUpgrade, PeerId, UpgradeInfo}; use libp2p_core::{InboundUpgrade, OutboundUpgrade, PeerId, UpgradeInfo};
use prost::Message as ProtobufMessage; use prost::Message as ProtobufMessage;
use std::{borrow::Cow, io, iter, pin::Pin}; use std::{borrow::Cow, fmt, io, iter, pin::Pin};
use unsigned_varint::codec; use unsigned_varint::codec;
/// Implementation of the `ConnectionUpgrade` for the Gossipsub protocol. /// Implementation of the `ConnectionUpgrade` for the Gossipsub protocol.
@ -336,7 +336,7 @@ impl Into<String> for MessageId {
} }
/// A message received by the gossipsub system. /// A message received by the gossipsub system.
#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[derive(Clone, PartialEq, Eq, Hash)]
pub struct GossipsubMessage { pub struct GossipsubMessage {
/// Id of the peer that published this message. /// Id of the peer that published this message.
pub source: PeerId, pub source: PeerId,
@ -353,6 +353,17 @@ pub struct GossipsubMessage {
pub topics: Vec<TopicHash>, pub topics: Vec<TopicHash>,
} }
impl fmt::Debug for GossipsubMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GossipsubMessage")
.field("data",&format_args!("{:<20}", &hex_fmt::HexFmt(&self.data)))
.field("source", &self.source)
.field("sequence_number", &self.sequence_number)
.field("topics", &self.topics)
.finish()
}
}
/// A subscription received by the gossipsub system. /// A subscription received by the gossipsub system.
#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GossipsubSubscription { pub struct GossipsubSubscription {

View File

@ -81,13 +81,13 @@ impl Topic {
} }
impl fmt::Display for Topic { impl fmt::Display for Topic {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.topic) write!(f, "{}", self.topic)
} }
} }
impl fmt::Display for TopicHash { impl fmt::Display for TopicHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.hash) write!(f, "{}", self.hash)
} }
} }

View File

@ -50,7 +50,7 @@ struct Graph {
impl Future for Graph { impl Future for Graph {
type Output = (Multiaddr, GossipsubEvent); type Output = (Multiaddr, GossipsubEvent);
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
for (addr, node) in &mut self.nodes { for (addr, node) in &mut self.nodes {
match node.poll_next_unpin(cx) { match node.poll_next_unpin(cx) {
Poll::Ready(Some(event)) => return Poll::Ready((addr.clone(), event)), Poll::Ready(Some(event)) => return Poll::Ready((addr.clone(), event)),

View File

@ -132,7 +132,7 @@ impl ProtocolsHandler for IdentifyHandler {
self.keep_alive self.keep_alive
} }
fn poll(&mut self, cx: &mut Context) -> Poll< fn poll(&mut self, cx: &mut Context<'_>) -> Poll<
ProtocolsHandlerEvent< ProtocolsHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,

View File

@ -167,7 +167,7 @@ impl NetworkBehaviour for Identify {
fn poll( fn poll(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
params: &mut impl PollParameters, params: &mut impl PollParameters,
) -> Poll< ) -> Poll<
NetworkBehaviourAction< NetworkBehaviourAction<

View File

@ -108,7 +108,7 @@ impl From<SmallVec<[Multiaddr; 6]>> for Addresses {
} }
impl fmt::Debug for Addresses { impl fmt::Debug for Addresses {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list() f.debug_list()
.entries(self.addrs.iter()) .entries(self.addrs.iter())
.finish() .finish()

View File

@ -549,7 +549,7 @@ where
/// Returns an iterator over all non-empty buckets in the routing table. /// Returns an iterator over all non-empty buckets in the routing table.
pub fn kbuckets(&mut self) pub fn kbuckets(&mut self)
-> impl Iterator<Item = kbucket::KBucketRef<kbucket::Key<PeerId>, Contact>> -> impl Iterator<Item = kbucket::KBucketRef<'_, kbucket::Key<PeerId>, Contact>>
{ {
self.kbuckets.iter().filter(|b| !b.is_empty()) self.kbuckets.iter().filter(|b| !b.is_empty())
} }
@ -558,7 +558,7 @@ where
/// ///
/// Returns `None` if the given key refers to the local key. /// Returns `None` if the given key refers to the local key.
pub fn kbucket<K>(&mut self, key: K) pub fn kbucket<K>(&mut self, key: K)
-> Option<kbucket::KBucketRef<kbucket::Key<PeerId>, Contact>> -> Option<kbucket::KBucketRef<'_, kbucket::Key<PeerId>, Contact>>
where where
K: Borrow<[u8]> + Clone K: Borrow<[u8]> + Clone
{ {
@ -1990,7 +1990,7 @@ where
}; };
} }
fn poll(&mut self, cx: &mut Context, parameters: &mut impl PollParameters) -> Poll< fn poll(&mut self, cx: &mut Context<'_>, parameters: &mut impl PollParameters) -> Poll<
NetworkBehaviourAction< NetworkBehaviourAction<
<KademliaHandler<QueryId> as ProtocolsHandler>::InEvent, <KademliaHandler<QueryId> as ProtocolsHandler>::InEvent,
Self::OutEvent, Self::OutEvent,

View File

@ -109,7 +109,7 @@ impl<TUserData> SubstreamState<TUserData> {
/// Tries to close the substream. /// Tries to close the substream.
/// ///
/// If the substream is not ready to be closed, returns it back. /// If the substream is not ready to be closed, returns it back.
fn try_close(&mut self, cx: &mut Context) -> Poll<()> { fn try_close(&mut self, cx: &mut Context<'_>) -> Poll<()> {
match self { match self {
SubstreamState::OutPendingOpen(_, _) SubstreamState::OutPendingOpen(_, _)
| SubstreamState::OutReportError(_, _) => Poll::Ready(()), | SubstreamState::OutReportError(_, _) => Poll::Ready(()),
@ -612,7 +612,7 @@ where
fn poll( fn poll(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>, ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>,
> { > {
@ -679,7 +679,7 @@ impl Default for KademliaHandlerConfig {
fn advance_substream<TUserData>( fn advance_substream<TUserData>(
state: SubstreamState<TUserData>, state: SubstreamState<TUserData>,
upgrade: KademliaProtocolConfig, upgrade: KademliaProtocolConfig,
cx: &mut Context, cx: &mut Context<'_>,
) -> ( ) -> (
Option<SubstreamState<TUserData>>, Option<SubstreamState<TUserData>>,
Option< Option<

View File

@ -107,7 +107,7 @@ impl<T> PeriodicJob<T> {
/// Returns `true` if the job is currently not running but ready /// Returns `true` if the job is currently not running but ready
/// to be run, `false` otherwise. /// to be run, `false` otherwise.
fn is_ready(&mut self, cx: &mut Context, now: Instant) -> bool { fn is_ready(&mut self, cx: &mut Context<'_>, now: Instant) -> bool {
if let PeriodicJobState::Waiting(delay, deadline) = &mut self.state { if let PeriodicJobState::Waiting(delay, deadline) = &mut self.state {
if now >= *deadline || !Future::poll(Pin::new(delay), cx).is_pending() { if now >= *deadline || !Future::poll(Pin::new(delay), cx).is_pending() {
return true return true
@ -190,7 +190,7 @@ impl PutRecordJob {
/// Must be called in the context of a task. When `NotReady` is returned, /// Must be called in the context of a task. When `NotReady` is returned,
/// the current task is registered to be notified when the job is ready /// the current task is registered to be notified when the job is ready
/// to be run. /// to be run.
pub fn poll<T>(&mut self, cx: &mut Context, store: &mut T, now: Instant) -> Poll<Record> pub fn poll<T>(&mut self, cx: &mut Context<'_>, store: &mut T, now: Instant) -> Poll<Record>
where where
for<'a> T: RecordStore<'a> for<'a> T: RecordStore<'a>
{ {
@ -288,7 +288,7 @@ impl AddProviderJob {
/// Must be called in the context of a task. When `NotReady` is returned, /// Must be called in the context of a task. When `NotReady` is returned,
/// the current task is registered to be notified when the job is ready /// the current task is registered to be notified when the job is ready
/// to be run. /// to be run.
pub fn poll<T>(&mut self, cx: &mut Context, store: &mut T, now: Instant) -> Poll<ProviderRecord> pub fn poll<T>(&mut self, cx: &mut Context<'_>, store: &mut T, now: Instant) -> Poll<ProviderRecord>
where where
for<'a> T: RecordStore<'a> for<'a> T: RecordStore<'a>
{ {

View File

@ -193,7 +193,7 @@ impl<TInner> QueryPool<TInner> {
} }
/// Polls the pool to advance the queries. /// Polls the pool to advance the queries.
pub fn poll(&mut self, now: Instant) -> QueryPoolState<TInner> { pub fn poll(&mut self, now: Instant) -> QueryPoolState<'_, TInner> {
let mut finished = None; let mut finished = None;
let mut timeout = None; let mut timeout = None;
let mut waiting = None; let mut waiting = None;
@ -389,7 +389,7 @@ impl<TInner> Query<TInner> {
} }
/// Advances the state of the underlying peer iterator. /// Advances the state of the underlying peer iterator.
fn next(&mut self, now: Instant) -> PeersIterState { fn next(&mut self, now: Instant) -> PeersIterState<'_> {
use PeersIterState::*; use PeersIterState::*;
// First query weighted iter // First query weighted iter

View File

@ -278,7 +278,7 @@ impl ClosestPeersIter {
} }
/// Advances the state of the iterator, potentially getting a new peer to contact. /// Advances the state of the iterator, potentially getting a new peer to contact.
pub fn next(&mut self, now: Instant) -> PeersIterState { pub fn next(&mut self, now: Instant) -> PeersIterState<'_> {
if let State::Finished = self.state { if let State::Finished = self.state {
return PeersIterState::Finished return PeersIterState::Finished
} }

View File

@ -181,7 +181,7 @@ impl ClosestDisjointPeersIter {
self.iters.iter().any(|i| i.is_waiting(peer)) self.iters.iter().any(|i| i.is_waiting(peer))
} }
pub fn next(&mut self, now: Instant) -> PeersIterState { pub fn next(&mut self, now: Instant) -> PeersIterState<'_> {
let mut state = None; let mut state = None;
// Ensure querying each iterator at most once. // Ensure querying each iterator at most once.
@ -713,7 +713,7 @@ mod tests {
struct Graph(HashMap<PeerId, Peer>); struct Graph(HashMap<PeerId, Peer>);
impl std::fmt::Debug for Graph { impl std::fmt::Debug for Graph {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt.debug_list().entries(self.0.iter().map(|(id, _)| id)).finish() fmt.debug_list().entries(self.0.iter().map(|(id, _)| id)).finish()
} }
} }
@ -807,7 +807,7 @@ mod tests {
} }
impl PeerIterator { impl PeerIterator {
fn next(&mut self, now: Instant) -> PeersIterState { fn next(&mut self, now: Instant) -> PeersIterState<'_> {
match self { match self {
PeerIterator::Disjoint(iter) => iter.next(now), PeerIterator::Disjoint(iter) => iter.next(now),
PeerIterator::Closest(iter) => iter.next(now), PeerIterator::Closest(iter) => iter.next(now),

View File

@ -129,7 +129,7 @@ impl FixedPeersIter {
self.state == State::Finished self.state == State::Finished
} }
pub fn next(&mut self) -> PeersIterState { pub fn next(&mut self) -> PeersIterState<'_> {
match &mut self.state { match &mut self.state {
State::Finished => return PeersIterState::Finished, State::Finished => return PeersIterState::Finished,
State::Waiting { num_waiting } => { State::Waiting { num_waiting } => {

View File

@ -64,7 +64,7 @@ pub trait RecordStore<'a> {
type ProvidedIter: Iterator<Item = Cow<'a, ProviderRecord>>; type ProvidedIter: Iterator<Item = Cow<'a, ProviderRecord>>;
/// Gets a record from the store, given its key. /// Gets a record from the store, given its key.
fn get(&'a self, k: &Key) -> Option<Cow<Record>>; fn get(&'a self, k: &Key) -> Option<Cow<'_, Record>>;
/// Puts a record into the store. /// Puts a record into the store.
fn put(&'a mut self, r: Record) -> Result<()>; fn put(&'a mut self, r: Record) -> Result<()>;

View File

@ -106,7 +106,7 @@ impl<'a> RecordStore<'a> for MemoryStore {
fn(&'a ProviderRecord) -> Cow<'a, ProviderRecord> fn(&'a ProviderRecord) -> Cow<'a, ProviderRecord>
>; >;
fn get(&'a self, k: &Key) -> Option<Cow<Record>> { fn get(&'a self, k: &Key) -> Option<Cow<'_, Record>> {
self.records.get(k).map(Cow::Borrowed) self.records.get(k).map(Cow::Borrowed)
} }

View File

@ -213,7 +213,7 @@ impl NetworkBehaviour for Mdns {
fn poll( fn poll(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
params: &mut impl PollParameters, params: &mut impl PollParameters,
) -> Poll< ) -> Poll<
NetworkBehaviourAction< NetworkBehaviourAction<

View File

@ -397,7 +397,7 @@ pub struct MdnsResponse {
impl MdnsResponse { impl MdnsResponse {
/// Creates a new `MdnsResponse` based on the provided `Packet`. /// Creates a new `MdnsResponse` based on the provided `Packet`.
fn new(packet: Packet, from: SocketAddr) -> MdnsResponse { fn new(packet: Packet<'_>, from: SocketAddr) -> MdnsResponse {
let peers = packet.answers.iter().filter_map(|record| { let peers = packet.answers.iter().filter_map(|record| {
if record.name.to_string().as_bytes() != SERVICE_NAME { if record.name.to_string().as_bytes() != SERVICE_NAME {
return None; return None;
@ -471,7 +471,7 @@ pub struct MdnsPeer {
impl MdnsPeer { impl MdnsPeer {
/// Creates a new `MdnsPeer` based on the provided `Packet`. /// Creates a new `MdnsPeer` based on the provided `Packet`.
pub fn new(packet: &Packet, record_value: String, my_peer_id: PeerId, ttl: u32) -> MdnsPeer { pub fn new(packet: &Packet<'_>, record_value: String, my_peer_id: PeerId, ttl: u32) -> MdnsPeer {
let addrs = packet let addrs = packet
.additional .additional
.iter() .iter()

View File

@ -1,3 +1,14 @@
# 0.21.0 [2020-07-17]
**NOTE**: For a smooth upgrade path from `0.20` to `> 0.21`
on an existing deployment, this version must not be skipped!
- Add support for reading handshake protobuf frames without
length prefixes in preparation for no longer sending them.
See [issue 1631](https://github.com/libp2p/rust-libp2p/issues/1631).
- Update the `snow` dependency to the latest patch version.
# 0.20.0 [2020-07-01] # 0.20.0 [2020-07-01]
- Updated dependencies. - Updated dependencies.

View File

@ -1,13 +1,14 @@
[package] [package]
name = "libp2p-noise" name = "libp2p-noise"
description = "Cryptographic handshake protocol using the noise framework." description = "Cryptographic handshake protocol using the noise framework."
version = "0.20.0" version = "0.21.0"
authors = ["Parity Technologies <admin@parity.io>"] authors = ["Parity Technologies <admin@parity.io>"]
license = "MIT" license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p" repository = "https://github.com/libp2p/rust-libp2p"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
bytes = "0.5"
curve25519-dalek = "2.0.0" curve25519-dalek = "2.0.0"
futures = "0.3.1" futures = "0.3.1"
lazy_static = "1.2" lazy_static = "1.2"
@ -21,10 +22,10 @@ x25519-dalek = "0.6.0"
zeroize = "1" zeroize = "1"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies] [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
snow = { version = "0.7.0", features = ["ring-resolver"], default-features = false } snow = { version = "0.7.1", features = ["ring-resolver"], default-features = false }
[target.'cfg(target_arch = "wasm32")'.dependencies] [target.'cfg(target_arch = "wasm32")'.dependencies]
snow = { version = "0.7.0", features = ["default-resolver"], default-features = false } snow = { version = "0.7.1", features = ["default-resolver"], default-features = false }
[dev-dependencies] [dev-dependencies]
env_logger = "0.7.1" env_logger = "0.7.1"

View File

@ -20,448 +20,122 @@
//! Noise protocol I/O. //! Noise protocol I/O.
mod framed;
pub mod handshake; pub mod handshake;
use bytes::Bytes;
use framed::{MAX_FRAME_LEN, NoiseFramed};
use futures::ready; use futures::ready;
use futures::prelude::*; use futures::prelude::*;
use log::{debug, trace}; use log::trace;
use snow; use std::{cmp::min, fmt, io, pin::Pin, task::{Context, Poll}};
use std::{cmp::min, fmt, io, pin::Pin, ops::DerefMut, task::{Context, Poll}};
/// Max. size of a noise package.
const MAX_NOISE_PKG_LEN: usize = 65535;
/// Extra space given to the encryption buffer to hold key material.
const EXTRA_ENCRYPT_SPACE: usize = 1024;
/// Max. output buffer size before forcing a flush.
const MAX_WRITE_BUF_LEN: usize = MAX_NOISE_PKG_LEN - EXTRA_ENCRYPT_SPACE;
static_assertions::const_assert! {
MAX_WRITE_BUF_LEN + EXTRA_ENCRYPT_SPACE <= MAX_NOISE_PKG_LEN
}
/// A passthrough enum for the two kinds of state machines in `snow`
pub(crate) enum SnowState {
Transport(snow::TransportState),
Handshake(snow::HandshakeState)
}
impl SnowState {
pub fn read_message(&mut self, message: &[u8], payload: &mut [u8]) -> Result<usize, snow::Error> {
match self {
SnowState::Handshake(session) => session.read_message(message, payload),
SnowState::Transport(session) => session.read_message(message, payload),
}
}
pub fn write_message(&mut self, message: &[u8], payload: &mut [u8]) -> Result<usize, snow::Error> {
match self {
SnowState::Handshake(session) => session.write_message(message, payload),
SnowState::Transport(session) => session.write_message(message, payload),
}
}
pub fn get_remote_static(&self) -> Option<&[u8]> {
match self {
SnowState::Handshake(session) => session.get_remote_static(),
SnowState::Transport(session) => session.get_remote_static(),
}
}
pub fn into_transport_mode(self) -> Result<snow::TransportState, snow::Error> {
match self {
SnowState::Handshake(session) => session.into_transport_mode(),
SnowState::Transport(_) => Err(snow::Error::State(snow::error::StateProblem::HandshakeAlreadyFinished)),
}
}
}
/// A noise session to a remote. /// A noise session to a remote.
/// ///
/// `T` is the type of the underlying I/O resource. /// `T` is the type of the underlying I/O resource.
pub struct NoiseOutput<T> { pub struct NoiseOutput<T> {
io: T, io: NoiseFramed<T, snow::TransportState>,
session: SnowState, recv_buffer: Bytes,
read_state: ReadState, recv_offset: usize,
write_state: WriteState, send_buffer: Vec<u8>,
read_buffer: Vec<u8>, send_offset: usize,
write_buffer: Vec<u8>,
decrypt_buffer: Vec<u8>,
encrypt_buffer: Vec<u8>
} }
impl<T> fmt::Debug for NoiseOutput<T> { impl<T> fmt::Debug for NoiseOutput<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NoiseOutput") f.debug_struct("NoiseOutput")
.field("read_state", &self.read_state) .field("io", &self.io)
.field("write_state", &self.write_state)
.finish() .finish()
} }
} }
impl<T> NoiseOutput<T> { impl<T> NoiseOutput<T> {
fn new(io: T, session: SnowState) -> Self { fn new(io: NoiseFramed<T, snow::TransportState>) -> Self {
NoiseOutput { NoiseOutput {
io, io,
session, recv_buffer: Bytes::new(),
read_state: ReadState::Init, recv_offset: 0,
write_state: WriteState::Init, send_buffer: Vec::new(),
read_buffer: Vec::new(), send_offset: 0,
write_buffer: Vec::new(),
decrypt_buffer: Vec::new(),
encrypt_buffer: Vec::new()
} }
} }
} }
/// The various states of reading a noise session transitions through.
#[derive(Debug)]
enum ReadState {
/// initial state
Init,
/// read frame length
ReadLen { buf: [u8; 2], off: usize },
/// read encrypted frame data
ReadData { len: usize, off: usize },
/// copy decrypted frame data
CopyData { len: usize, off: usize },
/// end of file has been reached (terminal state)
/// The associated result signals if the EOF was unexpected or not.
Eof(Result<(), ()>),
/// decryption error (terminal state)
DecErr
}
/// The various states of writing a noise session transitions through.
#[derive(Debug)]
enum WriteState {
/// initial state
Init,
/// accumulate write data
BufferData { off: usize },
/// write frame length
WriteLen { len: usize, buf: [u8; 2], off: usize },
/// write out encrypted data
WriteData { len: usize, off: usize },
/// end of file has been reached (terminal state)
Eof,
/// encryption error (terminal state)
EncErr
}
impl<T: AsyncRead + Unpin> AsyncRead for NoiseOutput<T> { impl<T: AsyncRead + Unpin> AsyncRead for NoiseOutput<T> {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<io::Result<usize>> { fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> {
let mut this = self.deref_mut();
loop { loop {
trace!("read state: {:?}", this.read_state); let len = self.recv_buffer.len();
match this.read_state { let off = self.recv_offset;
ReadState::Init => { if len > 0 {
this.read_state = ReadState::ReadLen { buf: [0, 0], off: 0 }; let n = min(len - off, buf.len());
} buf[.. n].copy_from_slice(&self.recv_buffer[off .. off + n]);
ReadState::ReadLen { mut buf, mut off } => { trace!("read: copied {}/{} bytes", off + n, len);
let n = match read_frame_len(&mut this.io, cx, &mut buf, &mut off) { self.recv_offset += n;
Poll::Ready(Ok(Some(n))) => n, if len == self.recv_offset {
Poll::Ready(Ok(None)) => { trace!("read: frame consumed");
trace!("read: eof"); // Drop the existing view so `NoiseFramed` can reuse
this.read_state = ReadState::Eof(Ok(())); // the buffer when polling for the next frame below.
return Poll::Ready(Ok(0)) self.recv_buffer = Bytes::new();
}
Poll::Ready(Err(e)) => {
return Poll::Ready(Err(e))
}
Poll::Pending => {
this.read_state = ReadState::ReadLen { buf, off };
return Poll::Pending;
}
};
trace!("read: next frame len = {}", n);
if n == 0 {
trace!("read: empty frame");
this.read_state = ReadState::Init;
continue
}
this.read_buffer.resize(usize::from(n), 0u8);
this.read_state = ReadState::ReadData { len: usize::from(n), off: 0 }
}
ReadState::ReadData { len, ref mut off } => {
let n = {
let f = Pin::new(&mut this.io).poll_read(cx, &mut this.read_buffer[*off .. len]);
match ready!(f) {
Ok(n) => n,
Err(e) => return Poll::Ready(Err(e)),
}
};
trace!("read: read {}/{} bytes", *off + n, len);
if n == 0 {
trace!("read: eof");
this.read_state = ReadState::Eof(Err(()));
return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into()))
}
*off += n;
if len == *off {
trace!("read: decrypting {} bytes", len);
this.decrypt_buffer.resize(len, 0u8);
if let Ok(n) = this.session.read_message(&this.read_buffer, &mut this.decrypt_buffer) {
trace!("read: payload len = {} bytes", n);
this.read_state = ReadState::CopyData { len: n, off: 0 }
} else {
debug!("decryption error");
this.read_state = ReadState::DecErr;
return Poll::Ready(Err(io::ErrorKind::InvalidData.into()))
}
}
}
ReadState::CopyData { len, ref mut off } => {
let n = min(len - *off, buf.len());
buf[.. n].copy_from_slice(&this.decrypt_buffer[*off .. *off + n]);
trace!("read: copied {}/{} bytes", *off + n, len);
*off += n;
if len == *off {
this.read_state = ReadState::ReadLen { buf: [0, 0], off: 0 };
} }
return Poll::Ready(Ok(n)) return Poll::Ready(Ok(n))
} }
ReadState::Eof(Ok(())) => {
trace!("read: eof"); match Pin::new(&mut self.io).poll_next(cx) {
return Poll::Ready(Ok(0)) Poll::Pending => return Poll::Pending,
Poll::Ready(None) => return Poll::Ready(Ok(0)),
Poll::Ready(Some(Err(e))) => return Poll::Ready(Err(e)),
Poll::Ready(Some(Ok(frame))) => {
self.recv_buffer = frame;
self.recv_offset = 0;
} }
ReadState::Eof(Err(())) => {
trace!("read: eof (unexpected)");
return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into()))
}
ReadState::DecErr => return Poll::Ready(Err(io::ErrorKind::InvalidData.into()))
} }
} }
} }
} }
impl<T: AsyncWrite + Unpin> AsyncWrite for NoiseOutput<T> { impl<T: AsyncWrite + Unpin> AsyncWrite for NoiseOutput<T> {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<io::Result<usize>> { fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
let mut this = self.deref_mut(); let this = Pin::into_inner(self);
loop { let mut io = Pin::new(&mut this.io);
trace!("write state: {:?}", this.write_state); let frame_buf = &mut this.send_buffer;
match this.write_state {
WriteState::Init => { // The MAX_FRAME_LEN is the maximum buffer size before a frame must be sent.
this.write_state = WriteState::BufferData { off: 0 } if this.send_offset == MAX_FRAME_LEN {
} trace!("write: sending {} bytes", MAX_FRAME_LEN);
WriteState::BufferData { ref mut off } => { ready!(io.as_mut().poll_ready(cx))?;
let n = min(MAX_WRITE_BUF_LEN, off.saturating_add(buf.len())); io.as_mut().start_send(&frame_buf)?;
this.write_buffer.resize(n, 0u8); this.send_offset = 0;
let n = min(MAX_WRITE_BUF_LEN - *off, buf.len());
this.write_buffer[*off .. *off + n].copy_from_slice(&buf[.. n]);
trace!("write: buffered {} bytes", *off + n);
*off += n;
if *off == MAX_WRITE_BUF_LEN {
trace!("write: encrypting {} bytes", *off);
this.encrypt_buffer.resize(MAX_WRITE_BUF_LEN + EXTRA_ENCRYPT_SPACE, 0u8);
match this.session.write_message(&this.write_buffer, &mut this.encrypt_buffer) {
Ok(n) => {
trace!("write: cipher text len = {} bytes", n);
this.write_state = WriteState::WriteLen {
len: n,
buf: u16::to_be_bytes(n as u16),
off: 0
}
}
Err(e) => {
debug!("encryption error: {:?}", e);
this.write_state = WriteState::EncErr;
return Poll::Ready(Err(io::ErrorKind::InvalidData.into()))
}
}
} }
let off = this.send_offset;
let n = min(MAX_FRAME_LEN, off.saturating_add(buf.len()));
this.send_buffer.resize(n, 0u8);
let n = min(MAX_FRAME_LEN - off, buf.len());
this.send_buffer[off .. off + n].copy_from_slice(&buf[.. n]);
this.send_offset += n;
trace!("write: buffered {} bytes", this.send_offset);
return Poll::Ready(Ok(n)) return Poll::Ready(Ok(n))
} }
WriteState::WriteLen { len, mut buf, mut off } => {
trace!("write: writing len ({}, {:?}, {}/2)", len, buf, off);
match write_frame_len(&mut this.io, cx, &mut buf, &mut off) {
Poll::Ready(Ok(true)) => (),
Poll::Ready(Ok(false)) => {
trace!("write: eof");
this.write_state = WriteState::Eof;
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()))
}
Poll::Ready(Err(e)) => {
return Poll::Ready(Err(e))
}
Poll::Pending => {
this.write_state = WriteState::WriteLen{ len, buf, off };
return Poll::Pending fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
} let this = Pin::into_inner(self);
} let mut io = Pin::new(&mut this.io);
this.write_state = WriteState::WriteData { len, off: 0 } let frame_buf = &mut this.send_buffer;
}
WriteState::WriteData { len, ref mut off } => { // Check if there is still one more frame to send.
let n = { if this.send_offset > 0 {
let f = Pin::new(&mut this.io).poll_write(cx, &this.encrypt_buffer[*off .. len]); ready!(io.as_mut().poll_ready(cx))?;
match ready!(f) { trace!("flush: sending {} bytes", this.send_offset);
Ok(n) => n, io.as_mut().start_send(&frame_buf)?;
Err(e) => return Poll::Ready(Err(e)) this.send_offset = 0;
}
};
trace!("write: wrote {}/{} bytes", *off + n, len);
if n == 0 {
trace!("write: eof");
this.write_state = WriteState::Eof;
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()))
}
*off += n;
if len == *off {
trace!("write: finished writing {} bytes", len);
this.write_state = WriteState::Init
}
}
WriteState::Eof => {
trace!("write: eof");
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()))
}
WriteState::EncErr => return Poll::Ready(Err(io::ErrorKind::InvalidData.into()))
}
}
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { io.as_mut().poll_flush(cx)
let mut this = self.deref_mut();
loop {
match this.write_state {
WriteState::Init => {
return Pin::new(&mut this.io).poll_flush(cx)
}
WriteState::BufferData { off } => {
trace!("flush: encrypting {} bytes", off);
this.encrypt_buffer.resize(off + EXTRA_ENCRYPT_SPACE, 0u8);
match this.session.write_message(&this.write_buffer[.. off], &mut this.encrypt_buffer) {
Ok(n) => {
trace!("flush: cipher text len = {} bytes", n);
this.write_state = WriteState::WriteLen {
len: n,
buf: u16::to_be_bytes(n as u16),
off: 0
}
}
Err(e) => {
debug!("encryption error: {:?}", e);
this.write_state = WriteState::EncErr;
return Poll::Ready(Err(io::ErrorKind::InvalidData.into()))
}
}
}
WriteState::WriteLen { len, mut buf, mut off } => {
trace!("flush: writing len ({}, {:?}, {}/2)", len, buf, off);
match write_frame_len(&mut this.io, cx, &mut buf, &mut off) {
Poll::Ready(Ok(true)) => (),
Poll::Ready(Ok(false)) => {
trace!("write: eof");
this.write_state = WriteState::Eof;
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()))
}
Poll::Ready(Err(e)) => {
return Poll::Ready(Err(e))
}
Poll::Pending => {
this.write_state = WriteState::WriteLen { len, buf, off };
return Poll::Pending
}
}
this.write_state = WriteState::WriteData { len, off: 0 }
}
WriteState::WriteData { len, ref mut off } => {
let n = {
let f = Pin::new(&mut this.io).poll_write(cx, &this.encrypt_buffer[*off .. len]);
match ready!(f) {
Ok(n) => n,
Err(e) => return Poll::Ready(Err(e)),
}
};
trace!("flush: wrote {}/{} bytes", *off + n, len);
if n == 0 {
trace!("flush: eof");
this.write_state = WriteState::Eof;
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()))
}
*off += n;
if len == *off {
trace!("flush: finished writing {} bytes", len);
this.write_state = WriteState::Init;
}
}
WriteState::Eof => {
trace!("flush: eof");
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()))
}
WriteState::EncErr => return Poll::Ready(Err(io::ErrorKind::InvalidData.into()))
}
}
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>>{ fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>>{
ready!(self.as_mut().poll_flush(cx))?; ready!(self.as_mut().poll_flush(cx))?;
Pin::new(&mut self.io).poll_close(cx) Pin::new(&mut self.io).poll_close(cx)
} }
} }
/// Read 2 bytes as frame length from the given source into the given buffer.
///
/// Panics if `off >= 2`.
///
/// When [`Poll::Pending`] is returned, the given buffer and offset
/// may have been updated (i.e. a byte may have been read) and must be preserved
/// for the next invocation.
///
/// Returns `None` if EOF has been encountered.
fn read_frame_len<R: AsyncRead + Unpin>(
mut io: &mut R,
cx: &mut Context<'_>,
buf: &mut [u8; 2],
off: &mut usize,
) -> Poll<io::Result<Option<u16>>> {
loop {
match ready!(Pin::new(&mut io).poll_read(cx, &mut buf[*off ..])) {
Ok(n) => {
if n == 0 {
return Poll::Ready(Ok(None));
}
*off += n;
if *off == 2 {
return Poll::Ready(Ok(Some(u16::from_be_bytes(*buf))));
}
},
Err(e) => {
return Poll::Ready(Err(e));
},
}
}
}
/// Write 2 bytes as frame length from the given buffer into the given sink.
///
/// Panics if `off >= 2`.
///
/// When [`Poll::Pending`] is returned, the given offset
/// may have been updated (i.e. a byte may have been written) and must
/// be preserved for the next invocation.
///
/// Returns `false` if EOF has been encountered.
fn write_frame_len<W: AsyncWrite + Unpin>(
mut io: &mut W,
cx: &mut Context<'_>,
buf: &[u8; 2],
off: &mut usize,
) -> Poll<io::Result<bool>> {
loop {
match ready!(Pin::new(&mut io).poll_write(cx, &buf[*off ..])) {
Ok(n) => {
if n == 0 {
return Poll::Ready(Ok(false))
}
*off += n;
if *off == 2 {
return Poll::Ready(Ok(true))
}
}
Err(e) => {
return Poll::Ready(Err(e));
}
}
}
}

View File

@ -0,0 +1,439 @@
// Copyright 2020 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//! This module provides a `Sink` and `Stream` for length-delimited
//! Noise protocol messages in form of [`NoiseFramed`].
use bytes::{Bytes, BytesMut};
use crate::{NoiseError, Protocol, PublicKey};
use crate::io::NoiseOutput;
use futures::ready;
use futures::prelude::*;
use log::{debug, trace};
use snow;
use std::{fmt, io, pin::Pin, task::{Context, Poll}};
/// Max. size of a noise message.
const MAX_NOISE_MSG_LEN: usize = 65535;
/// Space given to the encryption buffer to hold key material.
const EXTRA_ENCRYPT_SPACE: usize = 1024;
/// Max. length for Noise protocol message payloads.
pub const MAX_FRAME_LEN: usize = MAX_NOISE_MSG_LEN - EXTRA_ENCRYPT_SPACE;
static_assertions::const_assert! {
MAX_FRAME_LEN + EXTRA_ENCRYPT_SPACE <= MAX_NOISE_MSG_LEN
}
/// A `NoiseFramed` is a `Sink` and `Stream` for length-delimited
/// Noise protocol messages.
///
/// `T` is the type of the underlying I/O resource and `S` the
/// type of the Noise session state.
pub struct NoiseFramed<T, S> {
io: T,
session: S,
read_state: ReadState,
write_state: WriteState,
read_buffer: Vec<u8>,
write_buffer: Vec<u8>,
decrypt_buffer: BytesMut,
}
impl<T, S> fmt::Debug for NoiseFramed<T, S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NoiseFramed")
.field("read_state", &self.read_state)
.field("write_state", &self.write_state)
.finish()
}
}
impl<T> NoiseFramed<T, snow::HandshakeState> {
/// Creates a nwe `NoiseFramed` for beginning a Noise protocol handshake.
pub fn new(io: T, state: snow::HandshakeState) -> Self {
NoiseFramed {
io,
session: state,
read_state: ReadState::Ready,
write_state: WriteState::Ready,
read_buffer: Vec::new(),
write_buffer: Vec::new(),
decrypt_buffer: BytesMut::new(),
}
}
/// Converts the `NoiseFramed` into a `NoiseOutput` encrypted data stream
/// once the handshake is complete, including the static DH [`PublicKey`]
/// of the remote, if received.
///
/// If the underlying Noise protocol session state does not permit
/// transitioning to transport mode because the handshake is incomplete,
/// an error is returned. Similarly if the remote's static DH key, if
/// present, cannot be parsed.
pub fn into_transport<C>(self) -> Result<(Option<PublicKey<C>>, NoiseOutput<T>), NoiseError>
where
C: Protocol<C> + AsRef<[u8]>
{
let dh_remote_pubkey = match self.session.get_remote_static() {
None => None,
Some(k) => match C::public_from_bytes(k) {
Err(e) => return Err(e),
Ok(dh_pk) => Some(dh_pk)
}
};
match self.session.into_transport_mode() {
Err(e) => Err(e.into()),
Ok(s) => {
let io = NoiseFramed {
session: s,
io: self.io,
read_state: ReadState::Ready,
write_state: WriteState::Ready,
read_buffer: self.read_buffer,
write_buffer: self.write_buffer,
decrypt_buffer: self.decrypt_buffer,
};
Ok((dh_remote_pubkey, NoiseOutput::new(io)))
}
}
}
}
/// The states for reading Noise protocol frames.
#[derive(Debug)]
enum ReadState {
/// Ready to read another frame.
Ready,
/// Reading frame length.
ReadLen { buf: [u8; 2], off: usize },
/// Reading frame data.
ReadData { len: usize, off: usize },
/// EOF has been reached (terminal state).
///
/// The associated result signals if the EOF was unexpected or not.
Eof(Result<(), ()>),
/// A decryption error occurred (terminal state).
DecErr
}
/// The states for writing Noise protocol frames.
#[derive(Debug)]
enum WriteState {
/// Ready to write another frame.
Ready,
/// Writing the frame length.
WriteLen { len: usize, buf: [u8; 2], off: usize },
/// Writing the frame data.
WriteData { len: usize, off: usize },
/// EOF has been reached unexpectedly (terminal state).
Eof,
/// An encryption error occurred (terminal state).
EncErr
}
impl WriteState {
fn is_ready(&self) -> bool {
if let WriteState::Ready = self {
return true
}
false
}
}
impl<T, S> futures::stream::Stream for NoiseFramed<T, S>
where
T: AsyncRead + Unpin,
S: SessionState + Unpin
{
type Item = io::Result<Bytes>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = Pin::into_inner(self);
loop {
trace!("read state: {:?}", this.read_state);
match this.read_state {
ReadState::Ready => {
this.read_state = ReadState::ReadLen { buf: [0, 0], off: 0 };
}
ReadState::ReadLen { mut buf, mut off } => {
let n = match read_frame_len(&mut this.io, cx, &mut buf, &mut off) {
Poll::Ready(Ok(Some(n))) => n,
Poll::Ready(Ok(None)) => {
trace!("read: eof");
this.read_state = ReadState::Eof(Ok(()));
return Poll::Ready(None)
}
Poll::Ready(Err(e)) => {
return Poll::Ready(Some(Err(e)))
}
Poll::Pending => {
this.read_state = ReadState::ReadLen { buf, off };
return Poll::Pending;
}
};
trace!("read: frame len = {}", n);
if n == 0 {
trace!("read: empty frame");
this.read_state = ReadState::Ready;
continue
}
this.read_buffer.resize(usize::from(n), 0u8);
this.read_state = ReadState::ReadData { len: usize::from(n), off: 0 }
}
ReadState::ReadData { len, ref mut off } => {
let n = {
let f = Pin::new(&mut this.io).poll_read(cx, &mut this.read_buffer[*off .. len]);
match ready!(f) {
Ok(n) => n,
Err(e) => return Poll::Ready(Some(Err(e))),
}
};
trace!("read: {}/{} bytes", *off + n, len);
if n == 0 {
trace!("read: eof");
this.read_state = ReadState::Eof(Err(()));
return Poll::Ready(Some(Err(io::ErrorKind::UnexpectedEof.into())))
}
*off += n;
if len == *off {
trace!("read: decrypting {} bytes", len);
this.decrypt_buffer.resize(len, 0);
if let Ok(n) = this.session.read_message(&this.read_buffer, &mut this.decrypt_buffer) {
this.decrypt_buffer.truncate(n);
trace!("read: payload len = {} bytes", n);
this.read_state = ReadState::Ready;
// Return an immutable view into the current buffer.
// If the view is dropped before the next frame is
// read, the `BytesMut` will reuse the same buffer
// for the next frame.
let view = this.decrypt_buffer.split().freeze();
return Poll::Ready(Some(Ok(view)))
} else {
debug!("read: decryption error");
this.read_state = ReadState::DecErr;
return Poll::Ready(Some(Err(io::ErrorKind::InvalidData.into())))
}
}
}
ReadState::Eof(Ok(())) => {
trace!("read: eof");
return Poll::Ready(None)
}
ReadState::Eof(Err(())) => {
trace!("read: eof (unexpected)");
return Poll::Ready(Some(Err(io::ErrorKind::UnexpectedEof.into())))
}
ReadState::DecErr => return Poll::Ready(Some(Err(io::ErrorKind::InvalidData.into())))
}
}
}
}
impl<T, S> futures::sink::Sink<&Vec<u8>> for NoiseFramed<T, S>
where
T: AsyncWrite + Unpin,
S: SessionState + Unpin
{
type Error = io::Error;
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let mut this = Pin::into_inner(self);
loop {
trace!("write state {:?}", this.write_state);
match this.write_state {
WriteState::Ready => {
return Poll::Ready(Ok(()));
}
WriteState::WriteLen { len, mut buf, mut off } => {
trace!("write: frame len ({}, {:?}, {}/2)", len, buf, off);
match write_frame_len(&mut this.io, cx, &mut buf, &mut off) {
Poll::Ready(Ok(true)) => (),
Poll::Ready(Ok(false)) => {
trace!("write: eof");
this.write_state = WriteState::Eof;
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()))
}
Poll::Ready(Err(e)) => {
return Poll::Ready(Err(e))
}
Poll::Pending => {
this.write_state = WriteState::WriteLen { len, buf, off };
return Poll::Pending
}
}
this.write_state = WriteState::WriteData { len, off: 0 }
}
WriteState::WriteData { len, ref mut off } => {
let n = {
let f = Pin::new(&mut this.io).poll_write(cx, &this.write_buffer[*off .. len]);
match ready!(f) {
Ok(n) => n,
Err(e) => return Poll::Ready(Err(e)),
}
};
if n == 0 {
trace!("write: eof");
this.write_state = WriteState::Eof;
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()))
}
*off += n;
trace!("write: {}/{} bytes written", *off, len);
if len == *off {
trace!("write: finished with {} bytes", len);
this.write_state = WriteState::Ready;
}
}
WriteState::Eof => {
trace!("write: eof");
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()))
}
WriteState::EncErr => return Poll::Ready(Err(io::ErrorKind::InvalidData.into()))
}
}
}
fn start_send(self: Pin<&mut Self>, frame: &Vec<u8>) -> Result<(), Self::Error> {
assert!(frame.len() <= MAX_FRAME_LEN);
let mut this = Pin::into_inner(self);
assert!(this.write_state.is_ready());
this.write_buffer.resize(frame.len() + EXTRA_ENCRYPT_SPACE, 0u8);
match this.session.write_message(frame, &mut this.write_buffer[..]) {
Ok(n) => {
trace!("write: cipher text len = {} bytes", n);
this.write_buffer.truncate(n);
this.write_state = WriteState::WriteLen {
len: n,
buf: u16::to_be_bytes(n as u16),
off: 0
};
return Ok(())
}
Err(e) => {
log::error!("encryption error: {:?}", e);
this.write_state = WriteState::EncErr;
return Err(io::ErrorKind::InvalidData.into())
}
}
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
ready!(self.as_mut().poll_ready(cx))?;
Pin::new(&mut self.io).poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
ready!(self.as_mut().poll_flush(cx))?;
Pin::new(&mut self.io).poll_close(cx)
}
}
/// A stateful context in which Noise protocol messages can be read and written.
pub trait SessionState {
fn read_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result<usize, snow::Error>;
fn write_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result<usize, snow::Error>;
}
impl SessionState for snow::HandshakeState {
fn read_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result<usize, snow::Error> {
self.read_message(msg, buf)
}
fn write_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result<usize, snow::Error> {
self.write_message(msg, buf)
}
}
impl SessionState for snow::TransportState {
fn read_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result<usize, snow::Error> {
self.read_message(msg, buf)
}
fn write_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result<usize, snow::Error> {
self.write_message(msg, buf)
}
}
/// Read 2 bytes as frame length from the given source into the given buffer.
///
/// Panics if `off >= 2`.
///
/// When [`Poll::Pending`] is returned, the given buffer and offset
/// may have been updated (i.e. a byte may have been read) and must be preserved
/// for the next invocation.
///
/// Returns `None` if EOF has been encountered.
fn read_frame_len<R: AsyncRead + Unpin>(
mut io: &mut R,
cx: &mut Context<'_>,
buf: &mut [u8; 2],
off: &mut usize,
) -> Poll<io::Result<Option<u16>>> {
loop {
match ready!(Pin::new(&mut io).poll_read(cx, &mut buf[*off ..])) {
Ok(n) => {
if n == 0 {
return Poll::Ready(Ok(None));
}
*off += n;
if *off == 2 {
return Poll::Ready(Ok(Some(u16::from_be_bytes(*buf))));
}
},
Err(e) => {
return Poll::Ready(Err(e));
},
}
}
}
/// Write 2 bytes as frame length from the given buffer into the given sink.
///
/// Panics if `off >= 2`.
///
/// When [`Poll::Pending`] is returned, the given offset
/// may have been updated (i.e. a byte may have been written) and must
/// be preserved for the next invocation.
///
/// Returns `false` if EOF has been encountered.
fn write_frame_len<W: AsyncWrite + Unpin>(
mut io: &mut W,
cx: &mut Context<'_>,
buf: &[u8; 2],
off: &mut usize,
) -> Poll<io::Result<bool>> {
loop {
match ready!(Pin::new(&mut io).poll_write(cx, &buf[*off ..])) {
Ok(n) => {
if n == 0 {
return Poll::Ready(Ok(false))
}
*off += n;
if *off == 2 {
return Poll::Ready(Ok(true))
}
}
Err(e) => {
return Poll::Ready(Err(e));
}
}
}
}

View File

@ -24,16 +24,15 @@ mod payload_proto {
include!(concat!(env!("OUT_DIR"), "/payload.proto.rs")); include!(concat!(env!("OUT_DIR"), "/payload.proto.rs"));
} }
use bytes::Bytes;
use crate::error::NoiseError; use crate::error::NoiseError;
use crate::protocol::{Protocol, PublicKey, KeypairIdentity}; use crate::protocol::{Protocol, PublicKey, KeypairIdentity};
use crate::io::SnowState; use crate::io::{NoiseOutput, framed::NoiseFramed};
use libp2p_core::identity; use libp2p_core::identity;
use futures::prelude::*; use futures::prelude::*;
use futures::task; use futures::task;
use futures::io::AsyncReadExt;
use prost::Message; use prost::Message;
use std::{pin::Pin, task::Context}; use std::{io, pin::Pin, task::Context};
use super::NoiseOutput;
/// The identity of the remote established during a handshake. /// The identity of the remote established during a handshake.
pub enum RemoteIdentity<C> { pub enum RemoteIdentity<C> {
@ -254,7 +253,7 @@ where
/// Handshake state. /// Handshake state.
struct State<T> { struct State<T> {
/// The underlying I/O resource. /// The underlying I/O resource.
io: NoiseOutput<T>, io: NoiseFramed<T, snow::HandshakeState>,
/// The associated public identity of the local node's static DH keypair, /// The associated public identity of the local node's static DH keypair,
/// which can be sent to the remote as part of an authenticated handshake. /// which can be sent to the remote as part of an authenticated handshake.
identity: KeypairIdentity, identity: KeypairIdentity,
@ -287,7 +286,7 @@ impl<T> State<T> {
session.map(|s| session.map(|s|
State { State {
identity, identity,
io: NoiseOutput::new(io, SnowState::Handshake(s)), io: NoiseFramed::new(io, s),
dh_remote_pubkey_sig: None, dh_remote_pubkey_sig: None,
id_remote_pubkey, id_remote_pubkey,
send_identity send_identity
@ -304,17 +303,8 @@ impl<T> State<T>
where where
C: Protocol<C> + AsRef<[u8]> C: Protocol<C> + AsRef<[u8]>
{ {
let dh_remote_pubkey = match self.io.session.get_remote_static() { let (pubkey, io) = self.io.into_transport()?;
None => None, let remote = match (self.id_remote_pubkey, pubkey) {
Some(k) => match C::public_from_bytes(k) {
Err(e) => return Err(e),
Ok(dh_pk) => Some(dh_pk)
}
};
match self.io.session.into_transport_mode() {
Err(e) => Err(e.into()),
Ok(s) => {
let remote = match (self.id_remote_pubkey, dh_remote_pubkey) {
(_, None) => RemoteIdentity::Unknown, (_, None) => RemoteIdentity::Unknown,
(None, Some(dh_pk)) => RemoteIdentity::StaticDhKey(dh_pk), (None, Some(dh_pk)) => RemoteIdentity::StaticDhKey(dh_pk),
(Some(id_pk), Some(dh_pk)) => { (Some(id_pk), Some(dh_pk)) => {
@ -325,21 +315,36 @@ impl<T> State<T>
} }
} }
}; };
Ok((remote, NoiseOutput { session: SnowState::Transport(s), .. self.io })) Ok((remote, io))
}
}
} }
} }
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
// Handshake Message Futures // Handshake Message Futures
/// A future for receiving a Noise handshake message.
async fn recv<T>(state: &mut State<T>) -> Result<Bytes, NoiseError>
where
T: AsyncRead + Unpin
{
match state.io.next().await {
None => Err(io::Error::new(io::ErrorKind::UnexpectedEof, "eof").into()),
Some(Err(e)) => Err(e.into()),
Some(Ok(m)) => Ok(m),
}
}
/// A future for receiving a Noise handshake message with an empty payload. /// A future for receiving a Noise handshake message with an empty payload.
async fn recv_empty<T>(state: &mut State<T>) -> Result<(), NoiseError> async fn recv_empty<T>(state: &mut State<T>) -> Result<(), NoiseError>
where where
T: AsyncRead + Unpin T: AsyncRead + Unpin
{ {
state.io.read(&mut []).await?; let msg = recv(state).await?;
if !msg.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Unexpected handshake payload.").into())
}
Ok(()) Ok(())
} }
@ -348,8 +353,7 @@ async fn send_empty<T>(state: &mut State<T>) -> Result<(), NoiseError>
where where
T: AsyncWrite + Unpin T: AsyncWrite + Unpin
{ {
state.io.write(&[]).await?; state.io.send(&Vec::new()).await?;
state.io.flush().await?;
Ok(()) Ok(())
} }
@ -359,13 +363,42 @@ async fn recv_identity<T>(state: &mut State<T>) -> Result<(), NoiseError>
where where
T: AsyncRead + Unpin, T: AsyncRead + Unpin,
{ {
let mut len_buf = [0,0]; let msg = recv(state).await?;
state.io.read_exact(&mut len_buf).await?;
let len = u16::from_be_bytes(len_buf) as usize;
let mut payload_buf = vec![0; len]; // NOTE: We first try to decode the entire frame as a protobuf message,
state.io.read_exact(&mut payload_buf).await?; // as required by the libp2p-noise spec. As long as the frame length
let pb = payload_proto::NoiseHandshakePayload::decode(&payload_buf[..])?; // is less than 256 bytes, which is the case for all protobuf payloads
// not containing RSA keys, there is no room for misinterpretation,
// since if a two-bytes length prefix is present the first byte will
// be 0, which is always an unexpected protobuf tag value because the
// fields in the .proto file start with 1 and decoding thus expects
// a non-zero first byte. We will therefore always correctly fall back to
// the legacy protobuf parsing in these cases (again, not considering
// RSA keys, for which there may be a probabilistically very small chance
// of misinterpretation).
//
// This is only temporary! Once a release is made that supports
// decoding without a length prefix, a follow-up release will
// change `send_identity` such that no length prefix is sent.
// In yet another release the fallback protobuf parsing can then
// be removed.
let pb = payload_proto::NoiseHandshakePayload::decode(&msg[..])
.or_else(|e| {
if msg.len() > 2 {
let mut buf = [0, 0];
buf.copy_from_slice(&msg[.. 2]);
// If there is a second length it must be 2 bytes shorter than the
// frame length, because each length is encoded as a `u16`.
if usize::from(u16::from_be_bytes(buf)) + 2 == msg.len() {
log::debug!("Attempting fallback legacy protobuf decoding.");
payload_proto::NoiseHandshakePayload::decode(&msg[2 ..])
} else {
Err(e)
}
} else {
Err(e)
}
})?;
if !pb.identity_key.is_empty() { if !pb.identity_key.is_empty() {
let pk = identity::PublicKey::from_protobuf_encoding(&pb.identity_key) let pk = identity::PublicKey::from_protobuf_encoding(&pb.identity_key)
@ -377,6 +410,7 @@ where
} }
state.id_remote_pubkey = Some(pk); state.id_remote_pubkey = Some(pk);
} }
if !pb.identity_sig.is_empty() { if !pb.identity_sig.is_empty() {
state.dh_remote_pubkey_sig = Some(pb.identity_sig); state.dh_remote_pubkey_sig = Some(pb.identity_sig);
} }
@ -396,11 +430,11 @@ where
if let Some(ref sig) = state.identity.signature { if let Some(ref sig) = state.identity.signature {
pb.identity_sig = sig.clone() pb.identity_sig = sig.clone()
} }
let mut buf = Vec::with_capacity(pb.encoded_len()); // NOTE: We temporarily need to continue sending the (legacy) length prefix
pb.encode(&mut buf).expect("Vec<u8> provides capacity as needed"); // for a short while to permit migration.
let len = (buf.len() as u16).to_be_bytes(); let mut msg = Vec::with_capacity(pb.encoded_len() + 2);
state.io.write_all(&len).await?; msg.extend_from_slice(&(pb.encoded_len() as u16).to_be_bytes());
state.io.write_all(&buf).await?; pb.encode(&mut msg).expect("Vec<u8> provides capacity as needed");
state.io.flush().await?; state.io.send(&msg).await?;
Ok(()) Ok(())
} }

View File

@ -136,7 +136,7 @@ pub enum PingFailure {
} }
impl fmt::Display for PingFailure { impl fmt::Display for PingFailure {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
PingFailure::Timeout => f.write_str("Ping timeout"), PingFailure::Timeout => f.write_str("Ping timeout"),
PingFailure::Other { error } => write!(f, "Ping error: {}", error) PingFailure::Other { error } => write!(f, "Ping error: {}", error)
@ -221,7 +221,7 @@ impl ProtocolsHandler for PingHandler {
} }
} }
fn poll(&mut self, cx: &mut Context) -> Poll<ProtocolsHandlerEvent<protocol::Ping, (), PingResult, Self::Error>> { fn poll(&mut self, cx: &mut Context<'_>) -> Poll<ProtocolsHandlerEvent<protocol::Ping, (), PingResult, Self::Error>> {
if let Some(result) = self.pending_results.pop_back() { if let Some(result) = self.pending_results.pop_back() {
if let Ok(PingSuccess::Ping { .. }) = result { if let Ok(PingSuccess::Ping { .. }) = result {
self.failures = 0; self.failures = 0;

View File

@ -108,7 +108,7 @@ impl NetworkBehaviour for Ping {
self.events.push_front(PingEvent { peer, result }) self.events.push_front(PingEvent { peer, result })
} }
fn poll(&mut self, _: &mut Context, _: &mut impl PollParameters) fn poll(&mut self, _: &mut Context<'_>, _: &mut impl PollParameters)
-> Poll<NetworkBehaviourAction<Void, PingEvent>> -> Poll<NetworkBehaviourAction<Void, PingEvent>>
{ {
if let Some(e) = self.events.pop_back() { if let Some(e) = self.events.pop_back() {

View File

@ -192,7 +192,7 @@ where
{ {
type Error = io::Error; type Error = io::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Sink::poll_ready(Pin::new(&mut self.inner), cx) Sink::poll_ready(Pin::new(&mut self.inner), cx)
} }
@ -200,11 +200,11 @@ where
Sink::start_send(Pin::new(&mut self.inner), item) Sink::start_send(Pin::new(&mut self.inner), item)
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Sink::poll_flush(Pin::new(&mut self.inner), cx) Sink::poll_flush(Pin::new(&mut self.inner), cx)
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Sink::poll_close(Pin::new(&mut self.inner), cx) Sink::poll_close(Pin::new(&mut self.inner), cx)
} }
} }
@ -232,7 +232,7 @@ where
} }
impl<S: AsyncRead + AsyncWrite + Unpin> AsyncRead for PlainTextOutput<S> { impl<S: AsyncRead + AsyncWrite + Unpin> AsyncRead for PlainTextOutput<S> {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8])
-> Poll<Result<usize, io::Error>> -> Poll<Result<usize, io::Error>>
{ {
AsyncRead::poll_read(Pin::new(&mut self.stream), cx, buf) AsyncRead::poll_read(Pin::new(&mut self.stream), cx, buf)
@ -240,19 +240,19 @@ impl<S: AsyncRead + AsyncWrite + Unpin> AsyncRead for PlainTextOutput<S> {
} }
impl<S: AsyncRead + AsyncWrite + Unpin> AsyncWrite for PlainTextOutput<S> { impl<S: AsyncRead + AsyncWrite + Unpin> AsyncWrite for PlainTextOutput<S> {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8])
-> Poll<Result<usize, io::Error>> -> Poll<Result<usize, io::Error>>
{ {
AsyncWrite::poll_write(Pin::new(&mut self.stream), cx, buf) AsyncWrite::poll_write(Pin::new(&mut self.stream), cx, buf)
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>)
-> Poll<Result<(), io::Error>> -> Poll<Result<(), io::Error>>
{ {
AsyncWrite::poll_flush(Pin::new(&mut self.stream), cx) AsyncWrite::poll_flush(Pin::new(&mut self.stream), cx)
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>)
-> Poll<Result<(), io::Error>> -> Poll<Result<(), io::Error>>
{ {
AsyncWrite::poll_close(Pin::new(&mut self.stream), cx) AsyncWrite::poll_close(Pin::new(&mut self.stream), cx)

View File

@ -243,7 +243,7 @@ impl<S: AsyncRead + AsyncWrite> PnetOutput<S> {
impl<S: AsyncRead + AsyncWrite> AsyncRead for PnetOutput<S> { impl<S: AsyncRead + AsyncWrite> AsyncRead for PnetOutput<S> {
fn poll_read( fn poll_read(
self: Pin<&mut Self>, self: Pin<&mut Self>,
cx: &mut Context, cx: &mut Context<'_>,
buf: &mut [u8], buf: &mut [u8],
) -> Poll<Result<usize, io::Error>> { ) -> Poll<Result<usize, io::Error>> {
let this = self.project(); let this = self.project();
@ -260,17 +260,17 @@ impl<S: AsyncRead + AsyncWrite> AsyncRead for PnetOutput<S> {
impl<S: AsyncRead + AsyncWrite> AsyncWrite for PnetOutput<S> { impl<S: AsyncRead + AsyncWrite> AsyncWrite for PnetOutput<S> {
fn poll_write( fn poll_write(
self: Pin<&mut Self>, self: Pin<&mut Self>,
cx: &mut Context, cx: &mut Context<'_>,
buf: &[u8], buf: &[u8],
) -> Poll<Result<usize, io::Error>> { ) -> Poll<Result<usize, io::Error>> {
self.project().inner.poll_write(cx, buf) self.project().inner.poll_write(cx, buf)
} }
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
self.project().inner.poll_flush(cx) self.project().inner.poll_flush(cx)
} }
fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
self.project().inner.poll_close(cx) self.project().inner.poll_close(cx)
} }
} }

View File

@ -258,7 +258,7 @@ where
fn poll( fn poll(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent<RequestProtocol<TCodec>, RequestId, Self::OutEvent, Self::Error>, ProtocolsHandlerEvent<RequestProtocol<TCodec>, RequestId, Self::OutEvent, Self::Error>,
> { > {

View File

@ -577,7 +577,7 @@ where
} }
} }
fn poll(&mut self, _: &mut Context, _: &mut impl PollParameters) fn poll(&mut self, _: &mut Context<'_>, _: &mut impl PollParameters)
-> Poll<NetworkBehaviourAction< -> Poll<NetworkBehaviourAction<
RequestProtocol<TCodec>, RequestProtocol<TCodec>,
RequestResponseEvent<TCodec::Request, TCodec::Response> RequestResponseEvent<TCodec::Request, TCodec::Response>

View File

@ -66,7 +66,7 @@ where
{ {
type Item = Result<Vec<u8>, SecioError>; type Item = Result<Vec<u8>, SecioError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project(); let this = self.project();
let frame = match TryStream::try_poll_next(this.raw_stream, cx) { let frame = match TryStream::try_poll_next(this.raw_stream, cx) {
@ -114,7 +114,7 @@ where
{ {
type Error = S::Error; type Error = S::Error;
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let this = self.project(); let this = self.project();
Sink::poll_ready(this.raw_stream, cx) Sink::poll_ready(this.raw_stream, cx)
} }
@ -124,12 +124,12 @@ where
Sink::start_send(this.raw_stream, item) Sink::start_send(this.raw_stream, item)
} }
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let this = self.project(); let this = self.project();
Sink::poll_flush(this.raw_stream, cx) Sink::poll_flush(this.raw_stream, cx)
} }
fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let this = self.project(); let this = self.project();
Sink::poll_close(this.raw_stream, cx) Sink::poll_close(this.raw_stream, cx)
} }

View File

@ -55,7 +55,7 @@ where
{ {
type Error = S::Error; type Error = S::Error;
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let this = self.project(); let this = self.project();
Sink::poll_ready(this.raw_sink, cx) Sink::poll_ready(this.raw_sink, cx)
} }
@ -69,12 +69,12 @@ where
Sink::start_send(this.raw_sink, data_buf) Sink::start_send(this.raw_sink, data_buf)
} }
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let this = self.project(); let this = self.project();
Sink::poll_flush(this.raw_sink, cx) Sink::poll_flush(this.raw_sink, cx)
} }
fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let this = self.project(); let this = self.project();
Sink::poll_close(this.raw_sink, cx) Sink::poll_close(this.raw_sink, cx)
} }
@ -86,7 +86,7 @@ where
{ {
type Item = S::Item; type Item = S::Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project(); let this = self.project();
Stream::poll_next(this.raw_sink, cx) Stream::poll_next(this.raw_sink, cx)
} }

View File

@ -30,7 +30,7 @@ pub struct LenPrefixCodec<T> {
} }
impl<T> fmt::Debug for LenPrefixCodec<T> { impl<T> fmt::Debug for LenPrefixCodec<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("LenPrefixCodec") f.write_str("LenPrefixCodec")
} }
} }
@ -95,7 +95,7 @@ where
{ {
type Item = io::Result<Vec<u8>>; type Item = io::Result<Vec<u8>>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.stream.poll_next_unpin(cx) self.stream.poll_next_unpin(cx)
} }
} }
@ -106,7 +106,7 @@ where
{ {
type Error = io::Error; type Error = io::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.sink).poll_ready(cx) Pin::new(&mut self.sink).poll_ready(cx)
} }
@ -114,11 +114,11 @@ where
Pin::new(&mut self.sink).start_send(item) Pin::new(&mut self.sink).start_send(item)
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.sink).poll_flush(cx) Pin::new(&mut self.sink).poll_flush(cx)
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.sink).poll_close(cx) Pin::new(&mut self.sink).poll_close(cx)
} }
} }

View File

@ -206,7 +206,7 @@ impl<S> AsyncRead for SecioOutput<S>
where where
S: AsyncRead + AsyncWrite + Unpin + Send + 'static S: AsyncRead + AsyncWrite + Unpin + Send + 'static
{ {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8])
-> Poll<Result<usize, io::Error>> -> Poll<Result<usize, io::Error>>
{ {
AsyncRead::poll_read(Pin::new(&mut self.stream), cx, buf) AsyncRead::poll_read(Pin::new(&mut self.stream), cx, buf)
@ -217,19 +217,19 @@ impl<S> AsyncWrite for SecioOutput<S>
where where
S: AsyncRead + AsyncWrite + Unpin + Send + 'static S: AsyncRead + AsyncWrite + Unpin + Send + 'static
{ {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8])
-> Poll<Result<usize, io::Error>> -> Poll<Result<usize, io::Error>>
{ {
AsyncWrite::poll_write(Pin::new(&mut self.stream), cx, buf) AsyncWrite::poll_write(Pin::new(&mut self.stream), cx, buf)
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>)
-> Poll<Result<(), io::Error>> -> Poll<Result<(), io::Error>>
{ {
AsyncWrite::poll_flush(Pin::new(&mut self.stream), cx) AsyncWrite::poll_flush(Pin::new(&mut self.stream), cx)
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>)
-> Poll<Result<(), io::Error>> -> Poll<Result<(), io::Error>>
{ {
AsyncWrite::poll_close(Pin::new(&mut self.stream), cx) AsyncWrite::poll_close(Pin::new(&mut self.stream), cx)
@ -273,7 +273,7 @@ where
{ {
type Error = io::Error; type Error = io::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Sink::poll_ready(Pin::new(&mut self.inner), cx) Sink::poll_ready(Pin::new(&mut self.inner), cx)
} }
@ -281,11 +281,11 @@ where
Sink::start_send(Pin::new(&mut self.inner), item) Sink::start_send(Pin::new(&mut self.inner), item)
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Sink::poll_flush(Pin::new(&mut self.inner), cx) Sink::poll_flush(Pin::new(&mut self.inner), cx)
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Sink::poll_close(Pin::new(&mut self.inner), cx) Sink::poll_close(Pin::new(&mut self.inner), cx)
} }
} }
@ -296,7 +296,7 @@ where
{ {
type Item = Result<Vec<u8>, SecioError>; type Item = Result<Vec<u8>, SecioError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Stream::poll_next(Pin::new(&mut self.inner), cx) Stream::poll_next(Pin::new(&mut self.inner), cx)
} }
} }

View File

@ -19,14 +19,15 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::{Multiaddr, core::{Transport, transport::{ListenerEvent, TransportError}}}; use crate::{Multiaddr, core::{Transport, transport::{ListenerEvent, TransportError}}};
use futures::{prelude::*, io::{IoSlice, IoSliceMut}, ready};
use lazy_static::lazy_static;
use parking_lot::Mutex;
use smallvec::{smallvec, SmallVec};
use std::{cmp, io, pin::Pin, sync::Arc, task::{Context, Poll}, time::Duration};
use wasm_timer::Instant;
/// Wraps around a `Transport` and logs the bandwidth that goes through all the opened connections. use atomic::Atomic;
use futures::{prelude::*, io::{IoSlice, IoSliceMut}, ready};
use std::{
convert::TryFrom as _, io, pin::Pin, sync::{atomic::Ordering, Arc}, task::{Context, Poll}
};
/// Wraps around a `Transport` and counts the number of bytes that go through all the opened
/// connections.
#[derive(Clone)] #[derive(Clone)]
pub struct BandwidthLogging<TInner> { pub struct BandwidthLogging<TInner> {
inner: TInner, inner: TInner,
@ -34,16 +35,11 @@ pub struct BandwidthLogging<TInner> {
} }
impl<TInner> BandwidthLogging<TInner> { impl<TInner> BandwidthLogging<TInner> {
/// Creates a new `BandwidthLogging` around the transport. /// Creates a new [`BandwidthLogging`] around the transport.
pub fn new(inner: TInner, period: Duration) -> (Self, Arc<BandwidthSinks>) { pub fn new(inner: TInner) -> (Self, Arc<BandwidthSinks>) {
let mut period_seconds = cmp::min(period.as_secs(), 86400) as u32;
if period.subsec_nanos() > 0 {
period_seconds += 1;
}
let sink = Arc::new(BandwidthSinks { let sink = Arc::new(BandwidthSinks {
download: Mutex::new(BandwidthSink::new(period_seconds)), inbound: Atomic::new(0),
upload: Mutex::new(BandwidthSink::new(period_seconds)), outbound: Atomic::new(0),
}); });
let trans = BandwidthLogging { let trans = BandwidthLogging {
@ -95,7 +91,7 @@ where
{ {
type Item = Result<ListenerEvent<BandwidthFuture<TConn>, TErr>, TErr>; type Item = Result<ListenerEvent<BandwidthFuture<TConn>, TErr>, TErr>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project(); let this = self.project();
let event = let event =
@ -126,7 +122,7 @@ pub struct BandwidthFuture<TInner> {
impl<TInner: TryFuture> Future for BandwidthFuture<TInner> { impl<TInner: TryFuture> Future for BandwidthFuture<TInner> {
type Output = Result<BandwidthConnecLogging<TInner::Ok>, TInner::Error>; type Output = Result<BandwidthConnecLogging<TInner::Ok>, TInner::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
let inner = ready!(this.inner.try_poll(cx)?); let inner = ready!(this.inner.try_poll(cx)?);
let logged = BandwidthConnecLogging { inner, sinks: this.sinks.clone() }; let logged = BandwidthConnecLogging { inner, sinks: this.sinks.clone() };
@ -134,21 +130,29 @@ impl<TInner: TryFuture> Future for BandwidthFuture<TInner> {
} }
} }
/// Allows obtaining the average bandwidth of the connections created from a `BandwidthLogging`. /// Allows obtaining the average bandwidth of the connections created from a [`BandwidthLogging`].
pub struct BandwidthSinks { pub struct BandwidthSinks {
download: Mutex<BandwidthSink>, inbound: Atomic<u64>,
upload: Mutex<BandwidthSink>, outbound: Atomic<u64>,
} }
impl BandwidthSinks { impl BandwidthSinks {
/// Returns the average number of bytes that have been downloaded in the period. /// Returns the total number of bytes that have been downloaded on all the connections spawned
pub fn average_download_per_sec(&self) -> u64 { /// through the [`BandwidthLogging`].
self.download.lock().get() ///
/// > **Note**: This method is by design subject to race conditions. The returned value should
/// > only ever be used for statistics purposes.
pub fn total_inbound(&self) -> u64 {
self.inbound.load(Ordering::Relaxed)
} }
/// Returns the average number of bytes that have been uploaded in the period. /// Returns the total number of bytes that have been uploaded on all the connections spawned
pub fn average_upload_per_sec(&self) -> u64 { /// through the [`BandwidthLogging`].
self.upload.lock().get() ///
/// > **Note**: This method is by design subject to race conditions. The returned value should
/// > only ever be used for statistics purposes.
pub fn total_outbound(&self) -> u64 {
self.outbound.load(Ordering::Relaxed)
} }
} }
@ -161,136 +165,43 @@ pub struct BandwidthConnecLogging<TInner> {
} }
impl<TInner: AsyncRead> AsyncRead for BandwidthConnecLogging<TInner> { impl<TInner: AsyncRead> AsyncRead for BandwidthConnecLogging<TInner> {
fn poll_read(self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<io::Result<usize>> { fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> {
let this = self.project(); let this = self.project();
let num_bytes = ready!(this.inner.poll_read(cx, buf))?; let num_bytes = ready!(this.inner.poll_read(cx, buf))?;
this.sinks.download.lock().inject(num_bytes); this.sinks.inbound.fetch_add(u64::try_from(num_bytes).unwrap_or(u64::max_value()), Ordering::Relaxed);
Poll::Ready(Ok(num_bytes)) Poll::Ready(Ok(num_bytes))
} }
fn poll_read_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &mut [IoSliceMut]) -> Poll<io::Result<usize>> { fn poll_read_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>]) -> Poll<io::Result<usize>> {
let this = self.project(); let this = self.project();
let num_bytes = ready!(this.inner.poll_read_vectored(cx, bufs))?; let num_bytes = ready!(this.inner.poll_read_vectored(cx, bufs))?;
this.sinks.download.lock().inject(num_bytes); this.sinks.inbound.fetch_add(u64::try_from(num_bytes).unwrap_or(u64::max_value()), Ordering::Relaxed);
Poll::Ready(Ok(num_bytes)) Poll::Ready(Ok(num_bytes))
} }
} }
impl<TInner: AsyncWrite> AsyncWrite for BandwidthConnecLogging<TInner> { impl<TInner: AsyncWrite> AsyncWrite for BandwidthConnecLogging<TInner> {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<io::Result<usize>> { fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
let this = self.project(); let this = self.project();
let num_bytes = ready!(this.inner.poll_write(cx, buf))?; let num_bytes = ready!(this.inner.poll_write(cx, buf))?;
this.sinks.upload.lock().inject(num_bytes); this.sinks.outbound.fetch_add(u64::try_from(num_bytes).unwrap_or(u64::max_value()), Ordering::Relaxed);
Poll::Ready(Ok(num_bytes)) Poll::Ready(Ok(num_bytes))
} }
fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &[IoSlice]) -> Poll<io::Result<usize>> { fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) -> Poll<io::Result<usize>> {
let this = self.project(); let this = self.project();
let num_bytes = ready!(this.inner.poll_write_vectored(cx, bufs))?; let num_bytes = ready!(this.inner.poll_write_vectored(cx, bufs))?;
this.sinks.upload.lock().inject(num_bytes); this.sinks.outbound.fetch_add(u64::try_from(num_bytes).unwrap_or(u64::max_value()), Ordering::Relaxed);
Poll::Ready(Ok(num_bytes)) Poll::Ready(Ok(num_bytes))
} }
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = self.project(); let this = self.project();
this.inner.poll_flush(cx) this.inner.poll_flush(cx)
} }
fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = self.project(); let this = self.project();
this.inner.poll_close(cx) this.inner.poll_close(cx)
} }
} }
/// Returns the number of seconds that have elapsed between an arbitrary EPOCH and now.
fn current_second() -> u32 {
lazy_static! {
static ref EPOCH: Instant = Instant::now();
}
EPOCH.elapsed().as_secs() as u32
}
/// Structure that calculates the average bandwidth over the last few seconds.
///
/// If you want to calculate for example both download and upload bandwidths, create two different
/// objects.
struct BandwidthSink {
/// Bytes sent over the past seconds. Contains `rolling_seconds + 1` elements, where
/// `rolling_seconds` is the value passed to `new`. Only the first `rolling_seconds` elements
/// are taken into account for the average, while the last element is the element to be
/// inserted later.
bytes: SmallVec<[u64; 8]>,
/// Number of seconds between `EPOCH` and the moment we have last updated `bytes`.
latest_update: u32,
}
impl BandwidthSink {
/// Initializes a `BandwidthSink`.
fn new(seconds: u32) -> Self {
BandwidthSink {
bytes: smallvec![0; seconds as usize + 1],
latest_update: current_second(),
}
}
/// Returns the number of bytes over the last few seconds. The number of seconds is the value
/// configured at initialization.
fn get(&mut self) -> u64 {
self.update();
let seconds = self.bytes.len() - 1;
self.bytes.iter()
.take(seconds)
.fold(0u64, |a, &b| a.saturating_add(b)) / seconds as u64
}
/// Notifies the `BandwidthSink` that a certain number of bytes have been transmitted at this
/// moment.
fn inject(&mut self, bytes: usize) {
self.update();
if let Some(last) = self.bytes.last_mut() {
*last = last.saturating_add(bytes as u64);
}
}
/// Updates the state of the `BandwidthSink` so that the last element of `bytes` contains the
/// current second.
fn update(&mut self) {
let current_second = current_second();
debug_assert!(current_second >= self.latest_update);
let num_iter = cmp::min(current_second - self.latest_update, self.bytes.len() as u32);
for _ in 0..num_iter {
self.bytes.remove(0);
self.bytes.push(0);
}
self.latest_update = current_second;
}
}
#[cfg(test)]
mod tests {
use std::{thread, time::Duration};
use super::*;
#[test]
fn sink_works() {
let mut sink = BandwidthSink::new(5);
sink.inject(100);
thread::sleep(Duration::from_millis(1000));
assert_eq!(sink.get(), 20);
sink.inject(100);
thread::sleep(Duration::from_millis(1000));
assert_eq!(sink.get(), 40);
sink.inject(100);
thread::sleep(Duration::from_millis(1000));
assert_eq!(sink.get(), 60);
sink.inject(100);
thread::sleep(Duration::from_millis(1000));
assert_eq!(sink.get(), 80);
sink.inject(100);
thread::sleep(Duration::from_millis(1000));
assert_eq!(sink.get(), 100);
thread::sleep(Duration::from_millis(1000));
assert_eq!(sink.get(), 80);
}
}

View File

@ -21,7 +21,7 @@
//! Provides the `TransportExt` trait. //! Provides the `TransportExt` trait.
use crate::{bandwidth::BandwidthLogging, bandwidth::BandwidthSinks, Transport}; use crate::{bandwidth::BandwidthLogging, bandwidth::BandwidthSinks, Transport};
use std::{sync::Arc, time::Duration}; use std::sync::Arc;
/// Trait automatically implemented on all objects that implement `Transport`. Provides some /// Trait automatically implemented on all objects that implement `Transport`. Provides some
/// additional utilities. /// additional utilities.
@ -29,13 +29,13 @@ pub trait TransportExt: Transport {
/// Adds a layer on the `Transport` that logs all trafic that passes through the sockets /// Adds a layer on the `Transport` that logs all trafic that passes through the sockets
/// created by it. /// created by it.
/// ///
/// This method returns an `Arc<BandwidthSinks>` that can be used to retreive the bandwidth /// This method returns an `Arc<BandwidthSinks>` that can be used to retreive the total number
/// values. /// of bytes transferred through the sockets.
fn with_bandwidth_logging(self, period: Duration) -> (BandwidthLogging<Self>, Arc<BandwidthSinks>) fn with_bandwidth_logging(self) -> (BandwidthLogging<Self>, Arc<BandwidthSinks>)
where where
Self: Sized Self: Sized
{ {
BandwidthLogging::new(self, period) BandwidthLogging::new(self)
} }
// TODO: add methods to easily upgrade for secio/mplex/yamux // TODO: add methods to easily upgrade for secio/mplex/yamux

View File

@ -171,7 +171,7 @@ pub trait NetworkBehaviour: Send + 'static {
/// ///
/// This API mimics the API of the `Stream` trait. The method may register the current task in /// This API mimics the API of the `Stream` trait. The method may register the current task in
/// order to wake it up at a later point in time. /// order to wake it up at a later point in time.
fn poll(&mut self, cx: &mut Context, params: &mut impl PollParameters) fn poll(&mut self, cx: &mut Context<'_>, params: &mut impl PollParameters)
-> Poll<NetworkBehaviourAction<<<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::InEvent, Self::OutEvent>>; -> Poll<NetworkBehaviourAction<<<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::InEvent, Self::OutEvent>>;
} }

View File

@ -481,7 +481,7 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
/// Internal function used by everything event-related. /// Internal function used by everything event-related.
/// ///
/// Polls the `Swarm` for the next event. /// Polls the `Swarm` for the next event.
fn poll_next_event(mut self: Pin<&mut Self>, cx: &mut Context) fn poll_next_event(mut self: Pin<&mut Self>, cx: &mut Context<'_>)
-> Poll<SwarmEvent<TBehaviour::OutEvent, THandleErr>> -> Poll<SwarmEvent<TBehaviour::OutEvent, THandleErr>>
{ {
// We use a `this` variable because the compiler can't mutably borrow multiple times // We use a `this` variable because the compiler can't mutably borrow multiple times
@ -779,7 +779,7 @@ enum PendingNotifyHandler {
fn notify_one<'a, TInEvent, TConnInfo, TPeerId>( fn notify_one<'a, TInEvent, TConnInfo, TPeerId>(
conn: &mut EstablishedConnection<'a, TInEvent, TConnInfo, TPeerId>, conn: &mut EstablishedConnection<'a, TInEvent, TConnInfo, TPeerId>,
event: TInEvent, event: TInEvent,
cx: &mut Context, cx: &mut Context<'_>,
) -> Option<TInEvent> ) -> Option<TInEvent>
where where
TPeerId: Eq + std::hash::Hash + Clone, TPeerId: Eq + std::hash::Hash + Clone,
@ -810,7 +810,7 @@ fn notify_any<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>(
ids: SmallVec<[ConnectionId; 10]>, ids: SmallVec<[ConnectionId; 10]>,
peer: &mut ConnectedPeer<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>, peer: &mut ConnectedPeer<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>,
event: TInEvent, event: TInEvent,
cx: &mut Context, cx: &mut Context<'_>,
) -> Option<(TInEvent, SmallVec<[ConnectionId; 10]>)> ) -> Option<(TInEvent, SmallVec<[ConnectionId; 10]>)>
where where
TTrans: Transport, TTrans: Transport,
@ -859,7 +859,7 @@ fn notify_all<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>(
ids: SmallVec<[ConnectionId; 10]>, ids: SmallVec<[ConnectionId; 10]>,
peer: &mut ConnectedPeer<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>, peer: &mut ConnectedPeer<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>,
event: TInEvent, event: TInEvent,
cx: &mut Context, cx: &mut Context<'_>,
) -> Option<(TInEvent, SmallVec<[ConnectionId; 10]>)> ) -> Option<(TInEvent, SmallVec<[ConnectionId; 10]>)>
where where
TTrans: Transport, TTrans: Transport,
@ -907,7 +907,7 @@ where TBehaviour: NetworkBehaviour<ProtocolsHandler = THandler>,
{ {
type Item = TBehaviour::OutEvent; type Item = TBehaviour::OutEvent;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
loop { loop {
let event = futures::ready!(ExpandedSwarm::poll_next_event(self.as_mut(), cx)); let event = futures::ready!(ExpandedSwarm::poll_next_event(self.as_mut(), cx));
if let SwarmEvent::Behaviour(event) = event { if let SwarmEvent::Behaviour(event) = event {
@ -1178,7 +1178,7 @@ impl NetworkBehaviour for DummyBehaviour {
fn inject_event(&mut self, _: PeerId, _: ConnectionId, fn inject_event(&mut self, _: PeerId, _: ConnectionId,
_: <Self::ProtocolsHandler as ProtocolsHandler>::OutEvent) {} _: <Self::ProtocolsHandler as ProtocolsHandler>::OutEvent) {}
fn poll(&mut self, _: &mut Context, _: &mut impl PollParameters) -> fn poll(&mut self, _: &mut Context<'_>, _: &mut impl PollParameters) ->
Poll<NetworkBehaviourAction<<Self::ProtocolsHandler as Poll<NetworkBehaviourAction<<Self::ProtocolsHandler as
ProtocolsHandler>::InEvent, Self::OutEvent>> ProtocolsHandler>::InEvent, Self::OutEvent>>
{ {

View File

@ -184,7 +184,7 @@ pub trait ProtocolsHandler: Send + 'static {
fn connection_keep_alive(&self) -> KeepAlive; fn connection_keep_alive(&self) -> KeepAlive;
/// Should behave like `Stream::poll()`. /// Should behave like `Stream::poll()`.
fn poll(&mut self, cx: &mut Context) -> Poll< fn poll(&mut self, cx: &mut Context<'_>) -> Poll<
ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error> ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>
>; >;

View File

@ -81,7 +81,7 @@ impl ProtocolsHandler for DummyProtocolsHandler {
#[inline] #[inline]
fn poll( fn poll(
&mut self, &mut self,
_: &mut Context, _: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>, ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>,
> { > {

View File

@ -104,7 +104,7 @@ where
#[inline] #[inline]
fn poll( fn poll(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>, ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>,
> { > {

View File

@ -100,7 +100,7 @@ where
#[inline] #[inline]
fn poll( fn poll(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>, ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>,
> { > {

View File

@ -58,7 +58,7 @@ where
K: fmt::Debug + Eq + Hash, K: fmt::Debug + Eq + Hash,
H: fmt::Debug H: fmt::Debug
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MultiHandler") f.debug_struct("MultiHandler")
.field("handlers", &self.handlers) .field("handlers", &self.handlers)
.finish() .finish()
@ -154,7 +154,7 @@ where
.unwrap_or(KeepAlive::No) .unwrap_or(KeepAlive::No)
} }
fn poll(&mut self, cx: &mut Context) fn poll(&mut self, cx: &mut Context<'_>)
-> Poll<ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>> -> Poll<ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>>
{ {
// Calling `gen_range(0, 0)` (see below) would panic, so we have return early to avoid // Calling `gen_range(0, 0)` (see below) would panic, so we have return early to avoid
@ -195,7 +195,7 @@ where
K: fmt::Debug + Eq + Hash, K: fmt::Debug + Eq + Hash,
H: fmt::Debug H: fmt::Debug
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IntoMultiHandler") f.debug_struct("IntoMultiHandler")
.field("handlers", &self.handlers) .field("handlers", &self.handlers)
.finish() .finish()
@ -266,7 +266,7 @@ where
K: fmt::Debug + Eq + Hash, K: fmt::Debug + Eq + Hash,
H: fmt::Debug H: fmt::Debug
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Upgrade") f.debug_struct("Upgrade")
.field("upgrades", &self.upgrades) .field("upgrades", &self.upgrades)
.finish() .finish()
@ -369,7 +369,7 @@ impl DuplicateProtonameError {
} }
impl fmt::Display for DuplicateProtonameError { impl fmt::Display for DuplicateProtonameError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Ok(s) = std::str::from_utf8(&self.0) { if let Ok(s) = std::str::from_utf8(&self.0) {
write!(f, "duplicate protocol name: {}", s) write!(f, "duplicate protocol name: {}", s)
} else { } else {

View File

@ -225,7 +225,7 @@ where
self.handler.inject_address_change(new_address); self.handler.inject_address_change(new_address);
} }
fn poll(&mut self, cx: &mut Context) -> Poll< fn poll(&mut self, cx: &mut Context<'_>) -> Poll<
Result<ConnectionHandlerEvent<Self::OutboundOpenInfo, Self::OutEvent>, Self::Error> Result<ConnectionHandlerEvent<Self::OutboundOpenInfo, Self::OutEvent>, Self::Error>
> { > {
// Continue negotiation of newly-opened substreams on the listening side. // Continue negotiation of newly-opened substreams on the listening side.

View File

@ -191,7 +191,7 @@ where
fn poll( fn poll(
&mut self, &mut self,
_: &mut Context, _: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>, ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>,
> { > {

View File

@ -187,7 +187,7 @@ where
cmp::max(self.proto1.connection_keep_alive(), self.proto2.connection_keep_alive()) cmp::max(self.proto1.connection_keep_alive(), self.proto2.connection_keep_alive())
} }
fn poll(&mut self, cx: &mut Context) -> Poll<ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>> { fn poll(&mut self, cx: &mut Context<'_>) -> Poll<ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>> {
match self.proto1.poll(cx) { match self.proto1.poll(cx) {
Poll::Ready(ProtocolsHandlerEvent::Custom(event)) => { Poll::Ready(ProtocolsHandlerEvent::Custom(event)) => {

View File

@ -141,7 +141,7 @@ where
} }
} }
fn poll(&mut self, cx: &mut Context, params: &mut impl PollParameters) fn poll(&mut self, cx: &mut Context<'_>, params: &mut impl PollParameters)
-> Poll<NetworkBehaviourAction<<<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::InEvent, Self::OutEvent>> -> Poll<NetworkBehaviourAction<<<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::InEvent, Self::OutEvent>>
{ {
if let Some(inner) = self.inner.as_mut() { if let Some(inner) = self.inner.as_mut() {
@ -252,7 +252,7 @@ where
fn poll( fn poll(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error> ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>
> { > {

View File

@ -330,22 +330,22 @@ codegen!("tokio", TokioTcpConfig, TokioTcpTransStream, TokioTcpListenStream, app
#[cfg(feature = "async-std")] #[cfg(feature = "async-std")]
impl AsyncRead for TcpTransStream { impl AsyncRead for TcpTransStream {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<Result<usize, io::Error>> { fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize, io::Error>> {
AsyncRead::poll_read(Pin::new(&mut self.inner), cx, buf) AsyncRead::poll_read(Pin::new(&mut self.inner), cx, buf)
} }
} }
#[cfg(feature = "async-std")] #[cfg(feature = "async-std")]
impl AsyncWrite for TcpTransStream { impl AsyncWrite for TcpTransStream {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<Result<usize, io::Error>> { fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize, io::Error>> {
AsyncWrite::poll_write(Pin::new(&mut self.inner), cx, buf) AsyncWrite::poll_write(Pin::new(&mut self.inner), cx, buf)
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
AsyncWrite::poll_flush(Pin::new(&mut self.inner), cx) AsyncWrite::poll_flush(Pin::new(&mut self.inner), cx)
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
AsyncWrite::poll_close(Pin::new(&mut self.inner), cx) AsyncWrite::poll_close(Pin::new(&mut self.inner), cx)
} }
} }

View File

@ -151,7 +151,7 @@ impl ExtTransport {
} }
impl fmt::Debug for ExtTransport { impl fmt::Debug for ExtTransport {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("ExtTransport").finish() f.debug_tuple("ExtTransport").finish()
} }
} }
@ -224,7 +224,7 @@ impl fmt::Debug for Dial {
impl Future for Dial { impl Future for Dial {
type Output = Result<Connection, JsErr>; type Output = Result<Connection, JsErr>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match Future::poll(Pin::new(&mut *self.inner), cx) { match Future::poll(Pin::new(&mut *self.inner), cx) {
Poll::Ready(Ok(connec)) => Poll::Ready(Ok(Connection::new(connec.into()))), Poll::Ready(Ok(connec)) => Poll::Ready(Ok(Connection::new(connec.into()))),
Poll::Pending => Poll::Pending, Poll::Pending => Poll::Pending,
@ -253,7 +253,7 @@ impl fmt::Debug for Listen {
impl Stream for Listen { impl Stream for Listen {
type Item = Result<ListenerEvent<Ready<Result<Connection, JsErr>>, JsErr>, JsErr>; type Item = Result<ListenerEvent<Ready<Result<Connection, JsErr>>, JsErr>, JsErr>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
loop { loop {
if let Some(ev) = self.pending_events.pop_front() { if let Some(ev) = self.pending_events.pop_front() {
return Poll::Ready(Some(Ok(ev))); return Poll::Ready(Some(Ok(ev)));
@ -371,7 +371,7 @@ impl fmt::Debug for Connection {
} }
impl AsyncRead for Connection { impl AsyncRead for Connection {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<Result<usize, io::Error>> { fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize, io::Error>> {
loop { loop {
match mem::replace(&mut self.read_state, ConnectionReadState::Finished) { match mem::replace(&mut self.read_state, ConnectionReadState::Finished) {
ConnectionReadState::Finished => break Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())), ConnectionReadState::Finished => break Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())),
@ -435,7 +435,7 @@ impl AsyncRead for Connection {
} }
impl AsyncWrite for Connection { impl AsyncWrite for Connection {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<Result<usize, io::Error>> { fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize, io::Error>> {
// Note: as explained in the doc-comments of `Connection`, each call to this function must // Note: as explained in the doc-comments of `Connection`, each call to this function must
// map to exactly one call to `self.inner.write()`. // map to exactly one call to `self.inner.write()`.
@ -457,12 +457,12 @@ impl AsyncWrite for Connection {
Poll::Ready(Ok(buf.len())) Poll::Ready(Ok(buf.len()))
} }
fn poll_flush(self: Pin<&mut Self>, _: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
// There's no flushing mechanism. In the FFI we consider that writing implicitly flushes. // There's no flushing mechanism. In the FFI we consider that writing implicitly flushes.
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
fn poll_close(self: Pin<&mut Self>, _: &mut Context) -> Poll<Result<(), io::Error>> { fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
// Shutting down is considered instantaneous. // Shutting down is considered instantaneous.
match self.inner.shutdown() { match self.inner.shutdown() {
Ok(()) => Poll::Ready(Ok(())), Ok(()) => Poll::Ready(Ok(())),

View File

@ -470,7 +470,7 @@ pub enum OutgoingData {
} }
impl<T> fmt::Debug for Connection<T> { impl<T> fmt::Debug for Connection<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Connection") f.write_str("Connection")
} }
} }
@ -547,7 +547,7 @@ where
{ {
type Item = io::Result<IncomingData>; type Item = io::Result<IncomingData>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let item = ready!(self.receiver.poll_next_unpin(cx)); let item = ready!(self.receiver.poll_next_unpin(cx));
let item = item.map(|result| { let item = item.map(|result| {
result.map_err(|e| io::Error::new(io::ErrorKind::Other, e)) result.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
@ -562,7 +562,7 @@ where
{ {
type Error = io::Error; type Error = io::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.sender) Pin::new(&mut self.sender)
.poll_ready(cx) .poll_ready(cx)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e)) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
@ -574,13 +574,13 @@ where
.map_err(|e| io::Error::new(io::ErrorKind::Other, e)) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.sender) Pin::new(&mut self.sender)
.poll_flush(cx) .poll_flush(cx)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e)) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.sender) Pin::new(&mut self.sender)
.poll_close(cx) .poll_close(cx)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e)) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))

View File

@ -143,7 +143,7 @@ where
{ {
type Item = io::Result<Vec<u8>>; type Item = io::Result<Vec<u8>>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
loop { loop {
if let Some(item) = ready!(self.0.try_poll_next_unpin(cx)?) { if let Some(item) = ready!(self.0.try_poll_next_unpin(cx)?) {
if item.is_data() { if item.is_data() {
@ -162,7 +162,7 @@ where
{ {
type Error = io::Error; type Error = io::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.0).poll_ready(cx) Pin::new(&mut self.0).poll_ready(cx)
} }
@ -170,11 +170,11 @@ where
Pin::new(&mut self.0).start_send(framed::OutgoingData::Binary(item)) Pin::new(&mut self.0).start_send(framed::OutgoingData::Binary(item))
} }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.0).poll_flush(cx) Pin::new(&mut self.0).poll_flush(cx)
} }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.0).poll_close(cx) Pin::new(&mut self.0).poll_close(cx)
} }
} }

Some files were not shown because too many files have changed in this diff Show More