1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
use futures::{prelude::*, future, try_ready};
use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, upgrade::Negotiated};
use log::debug;
use rand::{distributions::Standard, prelude::*, rngs::EntropyRng};
use std::{io, iter, time::Duration, time::Instant};
use tokio_io::{AsyncRead, AsyncWrite};
#[derive(Default, Debug, Copy, Clone)]
pub struct Ping;
impl UpgradeInfo for Ping {
type Info = &'static [u8];
type InfoIter = iter::Once<Self::Info>;
fn protocol_info(&self) -> Self::InfoIter {
iter::once(b"/ipfs/ping/1.0.0")
}
}
impl<TSocket> InboundUpgrade<TSocket> for Ping
where
TSocket: AsyncRead + AsyncWrite,
{
type Output = ();
type Error = io::Error;
type Future = future::Map<future::AndThen<future::AndThen<future::AndThen<tokio_io::io::ReadExact<Negotiated<TSocket>, [u8; 32]>, tokio_io::io::WriteAll<Negotiated<TSocket>, [u8; 32]>, fn((Negotiated<TSocket>, [u8; 32])) -> tokio_io::io::WriteAll<Negotiated<TSocket>, [u8; 32]>>, tokio_io::io::Flush<Negotiated<TSocket>>, fn((Negotiated<TSocket>, [u8; 32])) -> tokio_io::io::Flush<Negotiated<TSocket>>>, tokio_io::io::Shutdown<Negotiated<TSocket>>, fn(Negotiated<TSocket>) -> tokio_io::io::Shutdown<Negotiated<TSocket>>>, fn(Negotiated<TSocket>) -> ()>;
#[inline]
fn upgrade_inbound(self, socket: Negotiated<TSocket>, _: Self::Info) -> Self::Future {
tokio_io::io::read_exact(socket, [0; 32])
.and_then::<fn(_) -> _, _>(|(socket, buffer)| tokio_io::io::write_all(socket, buffer))
.and_then::<fn(_) -> _, _>(|(socket, _)| tokio_io::io::flush(socket))
.and_then::<fn(_) -> _, _>(|socket| tokio_io::io::shutdown(socket))
.map(|_| ())
}
}
impl<TSocket> OutboundUpgrade<TSocket> for Ping
where
TSocket: AsyncRead + AsyncWrite,
{
type Output = Duration;
type Error = io::Error;
type Future = PingDialer<Negotiated<TSocket>>;
#[inline]
fn upgrade_outbound(self, socket: Negotiated<TSocket>, _: Self::Info) -> Self::Future {
let payload: [u8; 32] = EntropyRng::default().sample(Standard);
debug!("Preparing for ping with payload {:?}", payload);
PingDialer {
inner: PingDialerInner::Write {
inner: tokio_io::io::write_all(socket, payload),
},
}
}
}
pub struct PingDialer<TSocket> {
inner: PingDialerInner<TSocket>,
}
enum PingDialerInner<TSocket> {
Write {
inner: tokio_io::io::WriteAll<TSocket, [u8; 32]>,
},
Flush {
inner: tokio_io::io::Flush<TSocket>,
ping_payload: [u8; 32],
},
Read {
inner: tokio_io::io::ReadExact<TSocket, [u8; 32]>,
ping_payload: [u8; 32],
started: Instant,
},
Shutdown {
inner: tokio_io::io::Shutdown<TSocket>,
ping_time: Duration,
},
}
impl<TSocket> Future for PingDialer<TSocket>
where TSocket: AsyncRead + AsyncWrite,
{
type Item = Duration;
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
let new_state = match self.inner {
PingDialerInner::Write { ref mut inner } => {
let (socket, ping_payload) = try_ready!(inner.poll());
PingDialerInner::Flush {
inner: tokio_io::io::flush(socket),
ping_payload,
}
},
PingDialerInner::Flush { ref mut inner, ping_payload } => {
let socket = try_ready!(inner.poll());
let started = Instant::now();
PingDialerInner::Read {
inner: tokio_io::io::read_exact(socket, [0; 32]),
ping_payload,
started,
}
},
PingDialerInner::Read { ref mut inner, ping_payload, started } => {
let (socket, obtained) = try_ready!(inner.poll());
let ping_time = started.elapsed();
if obtained != ping_payload {
return Err(io::Error::new(io::ErrorKind::InvalidData,
"Received ping payload doesn't match expected"));
}
PingDialerInner::Shutdown {
inner: tokio_io::io::shutdown(socket),
ping_time,
}
},
PingDialerInner::Shutdown { ref mut inner, ping_time } => {
let _ = try_ready!(inner.poll());
return Ok(Async::Ready(ping_time));
},
};
self.inner = new_state;
}
}
}
#[derive(Debug, Copy, Clone)]
pub enum PingOutput {
Pong,
Ping(Duration),
}
impl From<Duration> for PingOutput {
#[inline]
fn from(duration: Duration) -> PingOutput {
PingOutput::Ping(duration)
}
}
impl From<()> for PingOutput {
#[inline]
fn from(_: ()) -> PingOutput {
PingOutput::Pong
}
}
#[cfg(test)]
mod tests {
use tokio_tcp::{TcpListener, TcpStream};
use super::Ping;
use futures::{Future, Stream};
use libp2p_core::upgrade;
#[test]
fn ping_pong() {
let listener = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap();
let listener_addr = listener.local_addr().unwrap();
let server = listener
.incoming()
.into_future()
.map_err(|(e, _)| e)
.and_then(|(c, _)| {
upgrade::apply_inbound(c.unwrap(), Ping::default()).map_err(|_| panic!())
});
let client = TcpStream::connect(&listener_addr)
.and_then(|c| {
upgrade::apply_outbound(c, Ping::default()).map_err(|_| panic!())
})
.map(|_| ());
let mut runtime = tokio::runtime::Runtime::new().unwrap();
runtime.block_on(server.select(client).map_err(|_| panic!())).unwrap();
}
}