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
658
// Copyright 2023 litep2p developers
//
// 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.

use crate::{
    addresses::PublicAddresses,
    crypto::ed25519::Keypair,
    error::ImmediateDialError,
    executor::Executor,
    protocol::ProtocolSet,
    transport::manager::{
        address::{AddressRecord, AddressStore},
        types::{PeerContext, PeerState, SupportedTransport},
        ProtocolContext, TransportManagerEvent, LOG_TARGET,
    },
    types::{protocol::ProtocolName, ConnectionId},
    BandwidthSink, PeerId,
};

use multiaddr::{Multiaddr, Protocol};
use parking_lot::RwLock;
use tokio::sync::mpsc::{error::TrySendError, Sender};

use std::{
    collections::{HashMap, HashSet},
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
};

/// Inner commands sent from [`TransportManagerHandle`] to
/// [`crate::transport::manager::TransportManager`].
pub enum InnerTransportManagerCommand {
    /// Dial peer.
    DialPeer {
        /// Remote peer ID.
        peer: PeerId,
    },

    /// Dial address.
    DialAddress {
        /// Remote address.
        address: Multiaddr,
    },
}

/// Handle for communicating with [`crate::transport::manager::TransportManager`].
#[derive(Debug, Clone)]
pub struct TransportManagerHandle {
    /// Local peer ID.
    local_peer_id: PeerId,

    /// Peers.
    peers: Arc<RwLock<HashMap<PeerId, PeerContext>>>,

    /// TX channel for sending commands to [`crate::transport::manager::TransportManager`].
    cmd_tx: Sender<InnerTransportManagerCommand>,

    /// Supported transports.
    supported_transport: HashSet<SupportedTransport>,

    /// Local listen addresess.
    listen_addresses: Arc<RwLock<HashSet<Multiaddr>>>,

    /// Public addresses.
    public_addresses: PublicAddresses,
}

impl TransportManagerHandle {
    /// Create new [`TransportManagerHandle`].
    pub fn new(
        local_peer_id: PeerId,
        peers: Arc<RwLock<HashMap<PeerId, PeerContext>>>,
        cmd_tx: Sender<InnerTransportManagerCommand>,
        supported_transport: HashSet<SupportedTransport>,
        listen_addresses: Arc<RwLock<HashSet<Multiaddr>>>,
        public_addresses: PublicAddresses,
    ) -> Self {
        Self {
            peers,
            cmd_tx,
            local_peer_id,
            supported_transport,
            listen_addresses,
            public_addresses,
        }
    }

    /// Register new transport to [`TransportManagerHandle`].
    pub(crate) fn register_transport(&mut self, transport: SupportedTransport) {
        self.supported_transport.insert(transport);
    }

    /// Get the list of public addresses of the node.
    pub(crate) fn public_addresses(&self) -> PublicAddresses {
        self.public_addresses.clone()
    }

    /// Get the list of listen addresses of the node.
    pub(crate) fn listen_addresses(&self) -> HashSet<Multiaddr> {
        self.listen_addresses.read().clone()
    }

    /// Check if `address` is supported by one of the enabled transports.
    pub fn supported_transport(&self, address: &Multiaddr) -> bool {
        let mut iter = address.iter();

        match iter.next() {
            Some(Protocol::Ip4(address)) =>
                if address.is_unspecified() {
                    return false;
                },
            Some(Protocol::Ip6(address)) =>
                if address.is_unspecified() {
                    return false;
                },
            Some(Protocol::Dns(_)) | Some(Protocol::Dns4(_)) | Some(Protocol::Dns6(_)) => {}
            _ => return false,
        }

        match iter.next() {
            None => false,
            Some(Protocol::Tcp(_)) => match iter.next() {
                Some(Protocol::P2p(_)) =>
                    self.supported_transport.contains(&SupportedTransport::Tcp),
                #[cfg(feature = "websocket")]
                Some(Protocol::Ws(_)) =>
                    self.supported_transport.contains(&SupportedTransport::WebSocket),
                #[cfg(feature = "websocket")]
                Some(Protocol::Wss(_)) =>
                    self.supported_transport.contains(&SupportedTransport::WebSocket),
                _ => false,
            },
            #[cfg(feature = "quic")]
            Some(Protocol::Udp(_)) => match (
                iter.next(),
                self.supported_transport.contains(&SupportedTransport::Quic),
            ) {
                (Some(Protocol::QuicV1), true) => true,
                _ => false,
            },
            _ => false,
        }
    }

    /// Check if the address is a local listen address and if so, discard it.
    fn is_local_address(&self, address: &Multiaddr) -> bool {
        let address: Multiaddr = address
            .iter()
            .take_while(|protocol| !std::matches!(protocol, Protocol::P2p(_)))
            .collect();

        self.listen_addresses.read().contains(&address)
    }

    /// Add one or more known addresses for peer.
    ///
    /// If peer doesn't exist, it will be added to known peers.
    ///
    /// Returns the number of added addresses after non-supported transports were filtered out.
    pub fn add_known_address(
        &mut self,
        peer: &PeerId,
        addresses: impl Iterator<Item = Multiaddr>,
    ) -> usize {
        let mut peers = self.peers.write();
        let addresses = addresses
            .filter_map(|address| {
                (self.supported_transport(&address) && !self.is_local_address(&address))
                    .then_some(AddressRecord::from_multiaddr(address)?)
            })
            .collect::<HashSet<_>>();

        // if all of the added addresses belonged to unsupported transports, exit early
        let num_added = addresses.len();
        if num_added == 0 {
            tracing::debug!(
                target: LOG_TARGET,
                ?peer,
                "didn't add any addresses for peer because transport is not supported",
            );

            return 0usize;
        }

        tracing::trace!(
            target: LOG_TARGET,
            ?peer,
            ?addresses,
            "add known addresses",
        );

        match peers.get_mut(peer) {
            Some(context) =>
                for record in addresses {
                    if !context.addresses.contains(record.address()) {
                        context.addresses.insert(record);
                    }
                },
            None => {
                peers.insert(
                    *peer,
                    PeerContext {
                        state: PeerState::Disconnected { dial_record: None },
                        addresses: AddressStore::from_iter(addresses),
                        secondary_connection: None,
                    },
                );
            }
        }

        num_added
    }

    /// Dial peer using `PeerId`.
    ///
    /// Returns an error if the peer is unknown or the peer is already connected.
    pub fn dial(&self, peer: &PeerId) -> Result<(), ImmediateDialError> {
        if peer == &self.local_peer_id {
            return Err(ImmediateDialError::TriedToDialSelf);
        }

        {
            match self.peers.read().get(peer) {
                Some(PeerContext {
                    state: PeerState::Connected { .. },
                    ..
                }) => return Err(ImmediateDialError::AlreadyConnected),
                Some(PeerContext {
                    state: PeerState::Disconnected { dial_record },
                    addresses,
                    ..
                }) => {
                    if addresses.is_empty() {
                        return Err(ImmediateDialError::NoAddressAvailable);
                    }

                    // peer is already being dialed, don't dial again until the first dial concluded
                    if dial_record.is_some() {
                        tracing::debug!(
                            target: LOG_TARGET,
                            ?peer,
                            ?dial_record,
                            "peer is aready being dialed",
                        );
                        return Ok(());
                    }
                }
                Some(PeerContext {
                    state: PeerState::Dialing { .. } | PeerState::Opening { .. },
                    ..
                }) => return Ok(()),
                None => return Err(ImmediateDialError::NoAddressAvailable),
            }
        }

        self.cmd_tx
            .try_send(InnerTransportManagerCommand::DialPeer { peer: *peer })
            .map_err(|error| match error {
                TrySendError::Full(_) => ImmediateDialError::ChannelClogged,
                TrySendError::Closed(_) => ImmediateDialError::TaskClosed,
            })
    }

    /// Dial peer using `Multiaddr`.
    ///
    /// Returns an error if address it not valid.
    pub fn dial_address(&self, address: Multiaddr) -> Result<(), ImmediateDialError> {
        if !address.iter().any(|protocol| std::matches!(protocol, Protocol::P2p(_))) {
            return Err(ImmediateDialError::PeerIdMissing);
        }

        self.cmd_tx
            .try_send(InnerTransportManagerCommand::DialAddress { address })
            .map_err(|error| match error {
                TrySendError::Full(_) => ImmediateDialError::ChannelClogged,
                TrySendError::Closed(_) => ImmediateDialError::TaskClosed,
            })
    }
}

// TODO: add getters for these
pub struct TransportHandle {
    pub keypair: Keypair,
    pub tx: Sender<TransportManagerEvent>,
    pub protocols: HashMap<ProtocolName, ProtocolContext>,
    pub next_connection_id: Arc<AtomicUsize>,
    pub next_substream_id: Arc<AtomicUsize>,
    pub bandwidth_sink: BandwidthSink,
    pub executor: Arc<dyn Executor>,
}

impl TransportHandle {
    pub fn protocol_set(&self, connection_id: ConnectionId) -> ProtocolSet {
        ProtocolSet::new(
            connection_id,
            self.tx.clone(),
            self.next_substream_id.clone(),
            self.protocols.clone(),
        )
    }

    /// Get next connection ID.
    pub fn next_connection_id(&mut self) -> ConnectionId {
        let connection_id = self.next_connection_id.fetch_add(1usize, Ordering::Relaxed);

        ConnectionId::from(connection_id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use multihash::Multihash;
    use parking_lot::lock_api::RwLock;
    use tokio::sync::mpsc::{channel, Receiver};

    fn make_transport_manager_handle() -> (
        TransportManagerHandle,
        Receiver<InnerTransportManagerCommand>,
    ) {
        let (cmd_tx, cmd_rx) = channel(64);

        let local_peer_id = PeerId::random();
        (
            TransportManagerHandle {
                local_peer_id,
                cmd_tx,
                peers: Default::default(),
                supported_transport: HashSet::new(),
                listen_addresses: Default::default(),
                public_addresses: PublicAddresses::new(local_peer_id),
            },
            cmd_rx,
        )
    }

    #[tokio::test]
    async fn tcp_supported() {
        let (mut handle, _rx) = make_transport_manager_handle();
        handle.supported_transport.insert(SupportedTransport::Tcp);

        let address =
            "/dns4/google.com/tcp/24928/p2p/12D3KooWKrUnV42yDR7G6DewmgHtFaVCJWLjQRi2G9t5eJD3BvTy"
                .parse()
                .unwrap();
        assert!(handle.supported_transport(&address));
    }

    #[cfg(feature = "websocket")]
    #[tokio::test]
    async fn websocket_supported() {
        let (mut handle, _rx) = make_transport_manager_handle();
        handle.supported_transport.insert(SupportedTransport::WebSocket);

        let address =
            "/dns4/google.com/tcp/24928/ws/p2p/12D3KooWKrUnV42yDR7G6DewmgHtFaVCJWLjQRi2G9t5eJD3BvTy"
                .parse()
                .unwrap();
        assert!(handle.supported_transport(&address));
    }

    #[test]
    fn transport_not_supported() {
        let (handle, _rx) = make_transport_manager_handle();

        // only peer id (used by Polkadot sometimes)
        assert!(!handle.supported_transport(
            &Multiaddr::empty().with(Protocol::P2p(Multihash::from(PeerId::random())))
        ));

        // only one transport
        assert!(!handle.supported_transport(
            &Multiaddr::empty().with(Protocol::Ip4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
        ));

        // any udp-based protocol other than quic
        assert!(!handle.supported_transport(
            &Multiaddr::empty()
                .with(Protocol::Ip4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
                .with(Protocol::Udp(8888))
                .with(Protocol::Utp)
        ));

        // any other protocol other than tcp
        assert!(!handle.supported_transport(
            &Multiaddr::empty()
                .with(Protocol::Ip4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
                .with(Protocol::Sctp(8888))
        ));
    }

    #[test]
    fn zero_addresses_added() {
        let (mut handle, _rx) = make_transport_manager_handle();
        handle.supported_transport.insert(SupportedTransport::Tcp);

        assert!(
            handle.add_known_address(
                &PeerId::random(),
                vec![
                    Multiaddr::empty()
                        .with(Protocol::Ip4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
                        .with(Protocol::Udp(8888))
                        .with(Protocol::Utp),
                    Multiaddr::empty()
                        .with(Protocol::Ip4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
                        .with(Protocol::Tcp(8888))
                        .with(Protocol::Wss(std::borrow::Cow::Owned("/".to_string()))),
                ]
                .into_iter()
            ) == 0usize
        );
    }

    #[tokio::test]
    async fn dial_already_connected_peer() {
        let (mut handle, _rx) = make_transport_manager_handle();
        handle.supported_transport.insert(SupportedTransport::Tcp);

        let peer = {
            let peer = PeerId::random();
            let mut peers = handle.peers.write();

            peers.insert(
                peer,
                PeerContext {
                    state: PeerState::Connected {
                        record: AddressRecord::from_multiaddr(
                            Multiaddr::empty()
                                .with(Protocol::Ip4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
                                .with(Protocol::Tcp(8888))
                                .with(Protocol::P2p(Multihash::from(peer))),
                        )
                        .unwrap(),
                        dial_record: None,
                    },
                    secondary_connection: None,
                    addresses: AddressStore::from_iter(
                        vec![Multiaddr::empty()
                            .with(Protocol::Ip4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
                            .with(Protocol::Tcp(8888))
                            .with(Protocol::P2p(Multihash::from(peer)))]
                        .into_iter(),
                    ),
                },
            );
            drop(peers);

            peer
        };

        match handle.dial(&peer) {
            Err(ImmediateDialError::AlreadyConnected) => {}
            _ => panic!("invalid return value"),
        }
    }

    #[tokio::test]
    async fn peer_already_being_dialed() {
        let (mut handle, _rx) = make_transport_manager_handle();
        handle.supported_transport.insert(SupportedTransport::Tcp);

        let peer = {
            let peer = PeerId::random();
            let mut peers = handle.peers.write();

            peers.insert(
                peer,
                PeerContext {
                    state: PeerState::Dialing {
                        record: AddressRecord::from_multiaddr(
                            Multiaddr::empty()
                                .with(Protocol::Ip4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
                                .with(Protocol::Tcp(8888))
                                .with(Protocol::P2p(Multihash::from(peer))),
                        )
                        .unwrap(),
                    },
                    secondary_connection: None,
                    addresses: AddressStore::from_iter(
                        vec![Multiaddr::empty()
                            .with(Protocol::Ip4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
                            .with(Protocol::Tcp(8888))
                            .with(Protocol::P2p(Multihash::from(peer)))]
                        .into_iter(),
                    ),
                },
            );
            drop(peers);

            peer
        };

        match handle.dial(&peer) {
            Ok(()) => {}
            _ => panic!("invalid return value"),
        }
    }

    #[tokio::test]
    async fn no_address_available_for_peer() {
        let (mut handle, _rx) = make_transport_manager_handle();
        handle.supported_transport.insert(SupportedTransport::Tcp);

        let peer = {
            let peer = PeerId::random();
            let mut peers = handle.peers.write();

            peers.insert(
                peer,
                PeerContext {
                    state: PeerState::Disconnected { dial_record: None },
                    secondary_connection: None,
                    addresses: AddressStore::new(),
                },
            );
            drop(peers);

            peer
        };

        let err = handle.dial(&peer).unwrap_err();
        assert!(matches!(err, ImmediateDialError::NoAddressAvailable));
    }

    #[tokio::test]
    async fn pending_connection_for_disconnected_peer() {
        let (mut handle, mut rx) = make_transport_manager_handle();
        handle.supported_transport.insert(SupportedTransport::Tcp);

        let peer = {
            let peer = PeerId::random();
            let mut peers = handle.peers.write();

            peers.insert(
                peer,
                PeerContext {
                    state: PeerState::Disconnected {
                        dial_record: Some(
                            AddressRecord::from_multiaddr(
                                Multiaddr::empty()
                                    .with(Protocol::Ip4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
                                    .with(Protocol::Tcp(8888))
                                    .with(Protocol::P2p(Multihash::from(peer))),
                            )
                            .unwrap(),
                        ),
                    },
                    secondary_connection: None,
                    addresses: AddressStore::from_iter(
                        vec![Multiaddr::empty()
                            .with(Protocol::Ip4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
                            .with(Protocol::Tcp(8888))
                            .with(Protocol::P2p(Multihash::from(peer)))]
                        .into_iter(),
                    ),
                },
            );
            drop(peers);

            peer
        };

        match handle.dial(&peer) {
            Ok(()) => {}
            _ => panic!("invalid return value"),
        }
        assert!(rx.try_recv().is_err());
    }

    #[tokio::test]
    async fn try_to_dial_self() {
        let (mut handle, mut rx) = make_transport_manager_handle();
        handle.supported_transport.insert(SupportedTransport::Tcp);

        let err = handle.dial(&handle.local_peer_id).unwrap_err();
        assert_eq!(err, ImmediateDialError::TriedToDialSelf);

        assert!(rx.try_recv().is_err());
    }

    #[test]
    fn is_local_address() {
        let (cmd_tx, _cmd_rx) = channel(64);

        let local_peer_id = PeerId::random();
        let first_addr: Multiaddr = "/ip6/::1/tcp/8888".parse().expect("valid multiaddress");
        let second_addr: Multiaddr = "/ip4/127.0.0.1/tcp/8888".parse().expect("valid multiaddress");

        let listen_addresses = Arc::new(RwLock::new(
            [first_addr.clone(), second_addr.clone()].iter().cloned().collect(),
        ));
        println!("{:?}", listen_addresses);

        let handle = TransportManagerHandle {
            local_peer_id,
            cmd_tx,
            peers: Default::default(),
            supported_transport: HashSet::new(),
            listen_addresses,
            public_addresses: PublicAddresses::new(local_peer_id),
        };

        // local addresses
        assert!(handle.is_local_address(
            &"/ip6/::1/tcp/8888".parse::<Multiaddr>().expect("valid multiaddress")
        ));
        assert!(handle
            .is_local_address(&"/ip4/127.0.0.1/tcp/8888".parse().expect("valid multiaddress")));
        assert!(handle.is_local_address(
            &"/ip6/::1/tcp/8888/p2p/12D3KooWT2ouvz5uMmCvHJGzAGRHiqDts5hzXR7NdoQ27pGdzp9Q"
                .parse()
                .expect("valid multiaddress")
        ));
        assert!(handle.is_local_address(
            &"/ip4/127.0.0.1/tcp/8888/p2p/12D3KooWT2ouvz5uMmCvHJGzAGRHiqDts5hzXR7NdoQ27pGdzp9Q"
                .parse()
                .expect("valid multiaddress")
        ));

        // same address but different peer id
        assert!(handle.is_local_address(
            &"/ip6/::1/tcp/8888/p2p/12D3KooWPGxxxQiBEBZ52RY31Z2chn4xsDrGCMouZ88izJrak2T1"
                .parse::<Multiaddr>()
                .expect("valid multiaddress")
        ));
        assert!(handle.is_local_address(
            &"/ip4/127.0.0.1/tcp/8888/p2p/12D3KooWPGxxxQiBEBZ52RY31Z2chn4xsDrGCMouZ88izJrak2T1"
                .parse()
                .expect("valid multiaddress")
        ));

        // different address
        assert!(!handle
            .is_local_address(&"/ip4/127.0.0.1/tcp/9999".parse().expect("valid multiaddress")));
        // different address
        assert!(!handle
            .is_local_address(&"/ip4/127.0.0.1/tcp/7777".parse().expect("valid multiaddress")));
    }
}