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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
use crate::structs_proto;
use futures::prelude::*;
use libp2p_core::{
Multiaddr,
PublicKey,
upgrade::{self, InboundUpgrade, OutboundUpgrade, UpgradeInfo}
};
use log::{debug, trace};
use prost::Message;
use std::convert::TryFrom;
use std::{fmt, io, iter, pin::Pin};
#[derive(Debug, Clone)]
pub struct IdentifyProtocol;
#[derive(Debug, Clone)]
pub struct IdentifyPushProtocol<T>(T);
pub struct InboundPush();
pub struct OutboundPush(IdentifyInfo);
impl IdentifyPushProtocol<InboundPush> {
pub fn inbound() -> Self {
IdentifyPushProtocol(InboundPush())
}
}
impl IdentifyPushProtocol<OutboundPush> {
pub fn outbound(info: IdentifyInfo) -> Self {
IdentifyPushProtocol(OutboundPush(info))
}
}
#[derive(Debug, Clone)]
pub struct IdentifyInfo {
pub public_key: PublicKey,
pub protocol_version: String,
pub agent_version: String,
pub listen_addrs: Vec<Multiaddr>,
pub protocols: Vec<String>,
pub observed_addr: Multiaddr,
}
pub struct ReplySubstream<T> {
inner: T,
}
impl<T> fmt::Debug for ReplySubstream<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("ReplySubstream").finish()
}
}
impl<T> ReplySubstream<T>
where
T: AsyncWrite + Unpin
{
pub async fn send(self, info: IdentifyInfo) -> io::Result<()> {
send(self.inner, info).await
}
}
impl UpgradeInfo for IdentifyProtocol {
type Info = &'static [u8];
type InfoIter = iter::Once<Self::Info>;
fn protocol_info(&self) -> Self::InfoIter {
iter::once(b"/ipfs/id/1.0.0")
}
}
impl<C> InboundUpgrade<C> for IdentifyProtocol {
type Output = ReplySubstream<C>;
type Error = io::Error;
type Future = future::Ready<Result<Self::Output, io::Error>>;
fn upgrade_inbound(self, socket: C, _: Self::Info) -> Self::Future {
future::ok(ReplySubstream { inner: socket })
}
}
impl<C> OutboundUpgrade<C> for IdentifyProtocol
where
C: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
type Output = IdentifyInfo;
type Error = io::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
fn upgrade_outbound(self, socket: C, _: Self::Info) -> Self::Future {
recv(socket).boxed()
}
}
impl<T> UpgradeInfo for IdentifyPushProtocol<T> {
type Info = &'static [u8];
type InfoIter = iter::Once<Self::Info>;
fn protocol_info(&self) -> Self::InfoIter {
iter::once(b"/ipfs/id/push/1.0.0")
}
}
impl<C> InboundUpgrade<C> for IdentifyPushProtocol<InboundPush>
where
C: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
type Output = IdentifyInfo;
type Error = io::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
fn upgrade_inbound(self, socket: C, _: Self::Info) -> Self::Future {
recv(socket).boxed()
}
}
impl<C> OutboundUpgrade<C> for IdentifyPushProtocol<OutboundPush>
where
C: AsyncWrite + Unpin + Send + 'static,
{
type Output = ();
type Error = io::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
fn upgrade_outbound(self, socket: C, _: Self::Info) -> Self::Future {
send(socket, self.0.0).boxed()
}
}
async fn send<T>(mut io: T, info: IdentifyInfo) -> io::Result<()>
where
T: AsyncWrite + Unpin
{
trace!("Sending: {:?}", info);
let listen_addrs = info.listen_addrs
.into_iter()
.map(|addr| addr.to_vec())
.collect();
let pubkey_bytes = info.public_key.into_protobuf_encoding();
let message = structs_proto::Identify {
agent_version: Some(info.agent_version),
protocol_version: Some(info.protocol_version),
public_key: Some(pubkey_bytes),
listen_addrs,
observed_addr: Some(info.observed_addr.to_vec()),
protocols: info.protocols
};
let mut bytes = Vec::with_capacity(message.encoded_len());
message.encode(&mut bytes).expect("Vec<u8> provides capacity as needed");
upgrade::write_length_prefixed(&mut io, bytes).await?;
io.close().await?;
Ok(())
}
async fn recv<T>(mut socket: T) -> io::Result<IdentifyInfo>
where
T: AsyncRead + AsyncWrite + Unpin
{
socket.close().await?;
let msg = upgrade::read_length_prefixed(&mut socket, 4096)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
.await?;
let info = match parse_proto_msg(msg) {
Ok(v) => v,
Err(err) => {
debug!("Invalid message: {:?}", err);
return Err(err.into())
}
};
trace!("Received: {:?}", info);
Ok(info)
}
fn parse_proto_msg(msg: impl AsRef<[u8]>) -> Result<IdentifyInfo, io::Error> {
match structs_proto::Identify::decode(msg.as_ref()) {
Ok(msg) => {
fn parse_multiaddr(bytes: Vec<u8>) -> Result<Multiaddr, io::Error> {
Multiaddr::try_from(bytes)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
}
let listen_addrs = {
let mut addrs = Vec::new();
for addr in msg.listen_addrs.into_iter() {
addrs.push(parse_multiaddr(addr)?);
}
addrs
};
let public_key = PublicKey::from_protobuf_encoding(&msg.public_key.unwrap_or_default())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let observed_addr = parse_multiaddr(msg.observed_addr.unwrap_or_default())?;
let info = IdentifyInfo {
public_key,
protocol_version: msg.protocol_version.unwrap_or_default(),
agent_version: msg.agent_version.unwrap_or_default(),
listen_addrs,
protocols: msg.protocols,
observed_addr,
};
Ok(info)
}
Err(err) => Err(io::Error::new(io::ErrorKind::InvalidData, err)),
}
}
#[cfg(test)]
mod tests {
use libp2p_tcp::TcpConfig;
use futures::{prelude::*, channel::oneshot};
use libp2p_core::{
identity,
Transport,
upgrade::{self, apply_outbound, apply_inbound}
};
use super::*;
#[test]
fn correct_transfer() {
let send_pubkey = identity::Keypair::generate_ed25519().public();
let recv_pubkey = send_pubkey.clone();
let (tx, rx) = oneshot::channel();
let bg_task = async_std::task::spawn(async move {
let transport = TcpConfig::new();
let mut listener = transport
.listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap())
.unwrap();
let addr = listener.next().await
.expect("some event")
.expect("no error")
.into_new_address()
.expect("listen address");
tx.send(addr).unwrap();
let socket = listener
.next().await.unwrap().unwrap()
.into_upgrade().unwrap()
.0.await.unwrap();
let sender = apply_inbound(socket, IdentifyProtocol).await.unwrap();
sender.send(
IdentifyInfo {
public_key: send_pubkey,
protocol_version: "proto_version".to_owned(),
agent_version: "agent_version".to_owned(),
listen_addrs: vec![
"/ip4/80.81.82.83/tcp/500".parse().unwrap(),
"/ip6/::1/udp/1000".parse().unwrap(),
],
protocols: vec!["proto1".to_string(), "proto2".to_string()],
observed_addr: "/ip4/100.101.102.103/tcp/5000".parse().unwrap(),
},
).await.unwrap();
});
async_std::task::block_on(async move {
let transport = TcpConfig::new();
let socket = transport.dial(rx.await.unwrap()).unwrap().await.unwrap();
let info = apply_outbound(
socket,
IdentifyProtocol,
upgrade::Version::V1
).await.unwrap();
assert_eq!(info.observed_addr, "/ip4/100.101.102.103/tcp/5000".parse().unwrap());
assert_eq!(info.public_key, recv_pubkey);
assert_eq!(info.protocol_version, "proto_version");
assert_eq!(info.agent_version, "agent_version");
assert_eq!(info.listen_addrs,
&["/ip4/80.81.82.83/tcp/500".parse().unwrap(),
"/ip6/::1/udp/1000".parse().unwrap()]);
assert_eq!(info.protocols, &["proto1".to_string(), "proto2".to_string()]);
bg_task.await;
});
}
}