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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
use crate::{
logging::NetworkSchema,
noise::{stream::NoiseStream, AntiReplayTimestamps, HandshakeAuthMode, NoiseUpgrader},
protocols::{
identity::exchange_handshake,
wire::handshake::v1::{HandshakeMsg, MessagingProtocolVersion, SupportedProtocols},
},
};
use diem_config::{
config::{PeerRole, HANDSHAKE_VERSION},
network_id::{NetworkContext, NetworkId},
};
use diem_crypto::x25519;
use diem_logger::prelude::*;
use diem_time_service::{timeout, TimeService, TimeServiceTrait};
use diem_types::{
chain_id::ChainId,
network_address::{parse_dns_tcp, parse_ip_tcp, parse_memory, NetworkAddress},
PeerId,
};
use futures::{
future::{Future, FutureExt},
io::{AsyncRead, AsyncWrite},
stream::{Stream, StreamExt, TryStreamExt},
};
use netcore::transport::{proxy_protocol, tcp, ConnectionOrigin, Transport};
use serde::Serialize;
use short_hex_str::AsShortHexStr;
use std::{
collections::BTreeMap,
convert::TryFrom,
fmt, io,
pin::Pin,
sync::{
atomic::{AtomicU32, Ordering},
Arc,
},
time::Duration,
};
#[cfg(test)]
mod test;
pub const TRANSPORT_TIMEOUT: Duration = Duration::from_secs(30);
pub const SUPPORTED_MESSAGING_PROTOCOL: MessagingProtocolVersion = MessagingProtocolVersion::V1;
static CONNECTION_ID_GENERATOR: ConnectionIdGenerator = ConnectionIdGenerator::new();
pub const DIEM_TCP_TRANSPORT: tcp::TcpTransport = tcp::TcpTransport {
ttl: None,
nodelay: Some(true),
};
pub trait TSocket: AsyncRead + AsyncWrite + Send + fmt::Debug + Unpin + 'static {}
impl<T> TSocket for T where T: AsyncRead + AsyncWrite + Send + fmt::Debug + Unpin + 'static {}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, Serialize)]
pub struct ConnectionId(u32);
impl From<u32> for ConnectionId {
fn from(i: u32) -> ConnectionId {
ConnectionId(i)
}
}
struct ConnectionIdGenerator {
ctr: AtomicU32,
}
impl ConnectionIdGenerator {
const fn new() -> ConnectionIdGenerator {
Self {
ctr: AtomicU32::new(0),
}
}
fn next(&self) -> ConnectionId {
let next = self.ctr.fetch_add(1, Ordering::Relaxed);
ConnectionId::from(next)
}
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct ConnectionMetadata {
pub remote_peer_id: PeerId,
pub connection_id: ConnectionId,
pub addr: NetworkAddress,
pub origin: ConnectionOrigin,
pub messaging_protocol: MessagingProtocolVersion,
pub application_protocols: SupportedProtocols,
pub role: PeerRole,
}
impl ConnectionMetadata {
pub fn new(
remote_peer_id: PeerId,
connection_id: ConnectionId,
addr: NetworkAddress,
origin: ConnectionOrigin,
messaging_protocol: MessagingProtocolVersion,
application_protocols: SupportedProtocols,
role: PeerRole,
) -> ConnectionMetadata {
ConnectionMetadata {
remote_peer_id,
connection_id,
addr,
origin,
messaging_protocol,
application_protocols,
role,
}
}
#[cfg(any(test, feature = "fuzzing"))]
pub fn mock(remote_peer_id: PeerId) -> ConnectionMetadata {
Self::mock_with_role_and_origin(
remote_peer_id,
PeerRole::Unknown,
ConnectionOrigin::Inbound,
)
}
#[cfg(any(test, feature = "fuzzing"))]
pub fn mock_with_role_and_origin(
remote_peer_id: PeerId,
role: PeerRole,
origin: ConnectionOrigin,
) -> ConnectionMetadata {
ConnectionMetadata {
remote_peer_id,
role,
origin,
connection_id: CONNECTION_ID_GENERATOR.next(),
addr: NetworkAddress::mock(),
messaging_protocol: MessagingProtocolVersion::V1,
application_protocols: [].iter().into(),
}
}
}
impl fmt::Debug for ConnectionMetadata {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self)
}
}
impl fmt::Display for ConnectionMetadata {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"[{},{},{},{},{:?},{:?}]",
self.remote_peer_id,
self.addr,
self.origin,
self.messaging_protocol,
self.application_protocols,
self.role
)
}
}
#[derive(Debug)]
pub struct Connection<TSocket> {
pub socket: TSocket,
pub metadata: ConnectionMetadata,
}
async fn timeout_io<F, T>(time_service: TimeService, duration: Duration, fut: F) -> io::Result<T>
where
F: Future<Output = io::Result<T>>,
{
let res = time_service.timeout(duration, fut).await;
match res {
Ok(out) => out,
Err(timeout::Elapsed) => Err(io::Error::new(io::ErrorKind::TimedOut, timeout::Elapsed)),
}
}
pub struct UpgradeContext {
noise: NoiseUpgrader,
handshake_version: u8,
supported_protocols: BTreeMap<MessagingProtocolVersion, SupportedProtocols>,
chain_id: ChainId,
network_id: NetworkId,
}
impl UpgradeContext {
pub fn new(
noise: NoiseUpgrader,
handshake_version: u8,
supported_protocols: BTreeMap<MessagingProtocolVersion, SupportedProtocols>,
chain_id: ChainId,
network_id: NetworkId,
) -> Self {
UpgradeContext {
noise,
handshake_version,
supported_protocols,
chain_id,
network_id,
}
}
}
fn add_pp_addr(proxy_protocol_enabled: bool, error: io::Error, addr: &NetworkAddress) -> io::Error {
if proxy_protocol_enabled {
io::Error::new(
error.kind(),
format!("proxied address: {}, error: {}", addr, error),
)
} else {
error
}
}
async fn upgrade_inbound<T: TSocket>(
ctxt: Arc<UpgradeContext>,
fut_socket: impl Future<Output = io::Result<T>>,
addr: NetworkAddress,
proxy_protocol_enabled: bool,
) -> io::Result<Connection<NoiseStream<T>>> {
let origin = ConnectionOrigin::Inbound;
let mut socket = fut_socket.await?;
let addr = if proxy_protocol_enabled {
proxy_protocol::read_header(&addr, &mut socket)
.await
.map_err(|err| {
debug!(
network_address = addr,
error = %err,
"ProxyProtocol: Failed to read header: {}",
err
);
err
})?
} else {
addr
};
let (mut socket, remote_peer_id, peer_role) =
ctxt.noise.upgrade_inbound(socket).await.map_err(|err| {
if err.should_security_log() {
sample!(
SampleRate::Duration(Duration::from_secs(15)),
error!(
SecurityEvent::NoiseHandshake,
NetworkSchema::new(&ctxt.noise.network_context)
.network_address(&addr)
.connection_origin(&origin),
error = %err,
)
);
}
let err = io::Error::new(io::ErrorKind::Other, err);
add_pp_addr(proxy_protocol_enabled, err, &addr)
})?;
let remote_pubkey = socket.get_remote_static();
let addr = addr.append_prod_protos(remote_pubkey, HANDSHAKE_VERSION);
let handshake_msg = HandshakeMsg {
supported_protocols: ctxt.supported_protocols.clone(),
chain_id: ctxt.chain_id,
network_id: ctxt.network_id.clone(),
};
let remote_handshake = exchange_handshake(&handshake_msg, &mut socket)
.await
.map_err(|err| add_pp_addr(proxy_protocol_enabled, err, &addr))?;
let (messaging_protocol, application_protocols) = handshake_msg
.perform_handshake(&remote_handshake)
.map_err(|err| {
let err = format!(
"handshake negotiation with peer {} failed: {}",
remote_peer_id.short_str(),
err
);
add_pp_addr(
proxy_protocol_enabled,
io::Error::new(io::ErrorKind::Other, err),
&addr,
)
})?;
Ok(Connection {
socket,
metadata: ConnectionMetadata::new(
remote_peer_id,
CONNECTION_ID_GENERATOR.next(),
addr,
origin,
messaging_protocol,
application_protocols,
peer_role,
),
})
}
pub async fn upgrade_outbound<T: TSocket>(
ctxt: Arc<UpgradeContext>,
fut_socket: impl Future<Output = io::Result<T>>,
addr: NetworkAddress,
remote_peer_id: PeerId,
remote_pubkey: x25519::PublicKey,
) -> io::Result<Connection<NoiseStream<T>>> {
let origin = ConnectionOrigin::Outbound;
let socket = fut_socket.await?;
let mut socket = ctxt
.noise
.upgrade_outbound(socket, remote_pubkey, AntiReplayTimestamps::now)
.await
.map_err(|err| {
if err.should_security_log() {
sample!(
SampleRate::Duration(Duration::from_secs(15)),
error!(
SecurityEvent::NoiseHandshake,
NetworkSchema::new(&ctxt.noise.network_context)
.network_address(&addr)
.connection_origin(&origin),
error = %err,
)
);
}
io::Error::new(io::ErrorKind::Other, err)
})?;
debug_assert_eq!(remote_pubkey, socket.get_remote_static());
let handshake_msg = HandshakeMsg {
supported_protocols: ctxt.supported_protocols.clone(),
chain_id: ctxt.chain_id,
network_id: ctxt.network_id.clone(),
};
let remote_handshake = exchange_handshake(&handshake_msg, &mut socket).await?;
let (messaging_protocol, application_protocols) = handshake_msg
.perform_handshake(&remote_handshake)
.map_err(|e| {
let e = format!(
"handshake negotiation with peer {} failed: {}",
remote_peer_id, e
);
io::Error::new(io::ErrorKind::Other, e)
})?;
Ok(Connection {
socket,
metadata: ConnectionMetadata::new(
remote_peer_id,
CONNECTION_ID_GENERATOR.next(),
addr,
origin,
messaging_protocol,
application_protocols,
PeerRole::Unknown,
),
})
}
pub struct DiemNetTransport<TTransport> {
base_transport: TTransport,
ctxt: Arc<UpgradeContext>,
time_service: TimeService,
identity_pubkey: x25519::PublicKey,
enable_proxy_protocol: bool,
}
impl<TTransport> DiemNetTransport<TTransport>
where
TTransport: Transport<Error = io::Error>,
TTransport::Output: TSocket,
TTransport::Outbound: Send + 'static,
TTransport::Inbound: Send + 'static,
TTransport::Listener: Send + 'static,
{
pub fn new(
base_transport: TTransport,
network_context: Arc<NetworkContext>,
time_service: TimeService,
identity_key: x25519::PrivateKey,
auth_mode: HandshakeAuthMode,
handshake_version: u8,
chain_id: ChainId,
application_protocols: SupportedProtocols,
enable_proxy_protocol: bool,
) -> Self {
let mut supported_protocols = BTreeMap::new();
supported_protocols.insert(SUPPORTED_MESSAGING_PROTOCOL, application_protocols);
let identity_pubkey = identity_key.public_key();
let network_id = network_context.network_id().clone();
let upgrade_context = UpgradeContext::new(
NoiseUpgrader::new(network_context, identity_key, auth_mode),
handshake_version,
supported_protocols,
chain_id,
network_id,
);
Self {
base_transport,
ctxt: Arc::new(upgrade_context),
time_service,
identity_pubkey,
enable_proxy_protocol,
}
}
fn parse_dial_addr(
addr: &NetworkAddress,
) -> io::Result<(NetworkAddress, x25519::PublicKey, u8)> {
use diem_types::network_address::Protocol::*;
let protos = addr.as_slice();
let (base_transport_protos, base_transport_suffix) = parse_ip_tcp(protos)
.map(|x| (&protos[..2], x.1))
.or_else(|| parse_dns_tcp(protos).map(|x| (&protos[..2], x.1)))
.or_else(|| parse_memory(protos).map(|x| (&protos[..1], x.1)))
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"Unexpected dialing network address: '{}', expected: \
memory, ip+tcp, or dns+tcp",
addr
),
)
})?;
match base_transport_suffix {
[NoiseIK(pubkey), Handshake(version)] => {
let base_addr = NetworkAddress::try_from(base_transport_protos.to_vec())
.expect("base_transport_protos is always non-empty");
Ok((base_addr, *pubkey, *version))
}
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"Unexpected dialing network address: '{}', expected: \
'/../ln-noise-ik/<pubkey>/ln-handshake/<version>'",
addr
),
)),
}
}
pub fn dial(
&self,
peer_id: PeerId,
addr: NetworkAddress,
) -> io::Result<
impl Future<Output = io::Result<Connection<NoiseStream<TTransport::Output>>>> + Send + 'static,
> {
let (base_addr, pubkey, handshake_version) = Self::parse_dial_addr(&addr)?;
if self.ctxt.handshake_version != handshake_version {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"Attempting to dial remote with unsupported handshake version: {}, expected: {}",
handshake_version, self.ctxt.handshake_version,
),
));
}
let fut_socket = self.base_transport.dial(peer_id, base_addr)?;
let upgrade_fut = upgrade_outbound(self.ctxt.clone(), fut_socket, addr, peer_id, pubkey);
let upgrade_fut = timeout_io(self.time_service.clone(), TRANSPORT_TIMEOUT, upgrade_fut);
Ok(upgrade_fut)
}
pub fn listen_on(
&self,
addr: NetworkAddress,
) -> io::Result<(
impl Stream<
Item = io::Result<(
impl Future<Output = io::Result<Connection<NoiseStream<TTransport::Output>>>>
+ Send
+ 'static,
NetworkAddress,
)>,
> + Send
+ 'static,
NetworkAddress,
)> {
let (listener, listen_addr) = self.base_transport.listen_on(addr)?;
let listen_addr =
listen_addr.append_prod_protos(self.identity_pubkey, self.ctxt.handshake_version);
let ctxt = self.ctxt.clone();
let time_service = self.time_service.clone();
let enable_proxy_protocol = self.enable_proxy_protocol;
let inbounds = listener.map_ok(move |(fut_socket, addr)| {
let fut_upgrade = upgrade_inbound(
ctxt.clone(),
fut_socket,
addr.clone(),
enable_proxy_protocol,
);
let fut_upgrade = timeout_io(time_service.clone(), TRANSPORT_TIMEOUT, fut_upgrade);
(fut_upgrade, addr)
});
Ok((inbounds, listen_addr))
}
}
impl<TTransport: Transport> Transport for DiemNetTransport<TTransport>
where
TTransport: Transport<Error = io::Error> + Send + 'static,
TTransport::Output: TSocket,
TTransport::Outbound: Send + 'static,
TTransport::Inbound: Send + 'static,
TTransport::Listener: Send + 'static,
{
type Output = Connection<NoiseStream<TTransport::Output>>;
type Error = io::Error;
type Inbound = Pin<Box<dyn Future<Output = io::Result<Self::Output>> + Send + 'static>>;
type Outbound = Pin<Box<dyn Future<Output = io::Result<Self::Output>> + Send + 'static>>;
type Listener =
Pin<Box<dyn Stream<Item = io::Result<(Self::Inbound, NetworkAddress)>> + Send + 'static>>;
fn dial(&self, peer_id: PeerId, addr: NetworkAddress) -> io::Result<Self::Outbound> {
self.dial(peer_id, addr)
.map(|upgrade_fut| upgrade_fut.boxed())
}
fn listen_on(&self, addr: NetworkAddress) -> io::Result<(Self::Listener, NetworkAddress)> {
let (listener, listen_addr) = self.listen_on(addr)?;
let listener = listener
.map_ok(|(upgrade_fut, addr)| (upgrade_fut.boxed(), addr))
.boxed();
Ok((listener, listen_addr))
}
}