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
// Copyright 2021 Parity Technologies (UK) Ltd.
// Copyright 2022 Protocol Labs.
// 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.

//! QUIC transport.

use crate::{
    crypto::tls::make_client_config,
    error::{AddressError, Error},
    transport::{
        manager::TransportHandle,
        quic::{config::Config as QuicConfig, connection::QuicConnection, listener::QuicListener},
        Endpoint as Litep2pEndpoint, Transport, TransportBuilder, TransportEvent,
    },
    types::ConnectionId,
    PeerId,
};

use futures::{future::BoxFuture, stream::FuturesUnordered, Stream, StreamExt};
use multiaddr::{Multiaddr, Protocol};
use quinn::{ClientConfig, Connection, Endpoint, IdleTimeout};

use std::{
    collections::{HashMap, HashSet},
    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};

pub(crate) use substream::Substream;

mod connection;
mod listener;
mod substream;

pub mod config;

/// Logging target for the file.
const LOG_TARGET: &str = "litep2p::quic";

#[derive(Debug)]
struct NegotiatedConnection {
    /// Remote peer ID.
    peer: PeerId,

    /// QUIC connection.
    connection: Connection,
}

/// QUIC transport object.
pub(crate) struct QuicTransport {
    /// Transport handle.
    context: TransportHandle,

    /// Transport config.
    config: QuicConfig,

    /// QUIC listener.
    listener: QuicListener,

    /// Pending dials.
    pending_dials: HashMap<ConnectionId, Multiaddr>,

    /// Pending connections.
    pending_connections:
        FuturesUnordered<BoxFuture<'static, (ConnectionId, Result<NegotiatedConnection, Error>)>>,

    /// Negotiated connections waiting for validation.
    pending_open: HashMap<ConnectionId, (NegotiatedConnection, Litep2pEndpoint)>,

    /// Pending raw, unnegotiated connections.
    pending_raw_connections: FuturesUnordered<
        BoxFuture<'static, Result<(ConnectionId, Multiaddr, NegotiatedConnection), ConnectionId>>,
    >,

    /// Opened raw connection, waiting for approval/rejection from `TransportManager`.
    opened_raw: HashMap<ConnectionId, (NegotiatedConnection, Multiaddr)>,

    /// Canceled raw connections.
    canceled: HashSet<ConnectionId>,
}

impl QuicTransport {
    /// Attempt to extract `PeerId` from connection certificates.
    fn extract_peer_id(connection: &Connection) -> Option<PeerId> {
        let certificates: Box<Vec<rustls::Certificate>> =
            connection.peer_identity()?.downcast().ok()?;
        let p2p_cert = crate::crypto::tls::certificate::parse(certificates.first()?)
            .expect("the certificate was validated during TLS handshake; qed");

        Some(p2p_cert.peer_id())
    }

    /// Handle established connection.
    fn on_connection_established(
        &mut self,
        connection_id: ConnectionId,
        result: crate::Result<NegotiatedConnection>,
    ) -> Option<TransportEvent> {
        tracing::debug!(target: LOG_TARGET, ?connection_id, success = result.is_ok(), "connection established");

        // `on_connection_established()` is called for both inbound and outbound connections
        // but `pending_dials` will only contain entries for outbound connections.
        let maybe_address = self.pending_dials.remove(&connection_id);

        match result {
            Ok(connection) => {
                let peer = connection.peer;
                let endpoint = maybe_address.map_or(
                    {
                        let address = connection.connection.remote_address();
                        Litep2pEndpoint::listener(
                            Multiaddr::empty()
                                .with(Protocol::from(address.ip()))
                                .with(Protocol::Udp(address.port()))
                                .with(Protocol::QuicV1),
                            connection_id,
                        )
                    },
                    |address| Litep2pEndpoint::dialer(address, connection_id),
                );
                self.pending_open.insert(connection_id, (connection, endpoint.clone()));

                return Some(TransportEvent::ConnectionEstablished { peer, endpoint });
            }
            Err(error) => {
                tracing::debug!(target: LOG_TARGET, ?connection_id, ?error, "failed to establish connection");

                // since the address was found from `pending_dials`,
                // report the error to protocols and `TransportManager`
                if let Some(address) = maybe_address {
                    return Some(TransportEvent::DialFailure {
                        connection_id,
                        address,
                        error,
                    });
                }
            }
        }

        None
    }
}

impl TransportBuilder for QuicTransport {
    type Config = QuicConfig;
    type Transport = QuicTransport;

    /// Create new [`QuicTransport`] object.
    fn new(
        context: TransportHandle,
        mut config: Self::Config,
    ) -> crate::Result<(Self, Vec<Multiaddr>)>
    where
        Self: Sized,
    {
        tracing::info!(
            target: LOG_TARGET,
            ?config,
            "start quic transport",
        );

        let (listener, listen_addresses) = QuicListener::new(
            &context.keypair,
            std::mem::take(&mut config.listen_addresses),
        )?;

        Ok((
            Self {
                context,
                config,
                listener,
                canceled: HashSet::new(),
                opened_raw: HashMap::new(),
                pending_open: HashMap::new(),
                pending_dials: HashMap::new(),
                pending_raw_connections: FuturesUnordered::new(),
                pending_connections: FuturesUnordered::new(),
            },
            listen_addresses,
        ))
    }
}

impl Transport for QuicTransport {
    fn dial(&mut self, connection_id: ConnectionId, address: Multiaddr) -> crate::Result<()> {
        let Ok((socket_address, Some(peer))) = QuicListener::get_socket_address(&address) else {
            return Err(Error::AddressError(AddressError::PeerIdMissing));
        };

        let crypto_config =
            Arc::new(make_client_config(&self.context.keypair, Some(peer)).expect("to succeed"));
        let mut transport_config = quinn::TransportConfig::default();
        let timeout =
            IdleTimeout::try_from(self.config.connection_open_timeout).expect("to succeed");
        transport_config.max_idle_timeout(Some(timeout));
        let mut client_config = ClientConfig::new(crypto_config);
        client_config.transport_config(Arc::new(transport_config));

        let client_listen_address = match address.iter().next() {
            Some(Protocol::Ip6(_)) => SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0),
            Some(Protocol::Ip4(_)) => SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
            _ => return Err(Error::AddressError(AddressError::InvalidProtocol)),
        };

        let client = Endpoint::client(client_listen_address)
            .map_err(|error| Error::Other(error.to_string()))?;
        let connection = client
            .connect_with(client_config, socket_address, "l")
            .map_err(|error| Error::Other(error.to_string()))?;

        tracing::trace!(
            target: LOG_TARGET,
            ?address,
            ?peer,
            ?client_listen_address,
            "dial peer",
        );

        self.pending_dials.insert(connection_id, address);
        self.pending_connections.push(Box::pin(async move {
            let connection = match connection.await {
                Ok(connection) => connection,
                Err(error) => return (connection_id, Err(error.into())),
            };

            let Some(peer) = Self::extract_peer_id(&connection) else {
                return (connection_id, Err(Error::InvalidCertificate));
            };

            (connection_id, Ok(NegotiatedConnection { peer, connection }))
        }));

        Ok(())
    }

    fn accept(&mut self, connection_id: ConnectionId) -> crate::Result<()> {
        let (connection, endpoint) = self
            .pending_open
            .remove(&connection_id)
            .ok_or(Error::ConnectionDoesntExist(connection_id))?;
        let bandwidth_sink = self.context.bandwidth_sink.clone();
        let protocol_set = self.context.protocol_set(connection_id);
        let substream_open_timeout = self.config.substream_open_timeout;

        tracing::trace!(
            target: LOG_TARGET,
            ?connection_id,
            "start connection",
        );

        self.context.executor.run(Box::pin(async move {
            let _ = QuicConnection::new(
                connection.peer,
                endpoint,
                connection.connection,
                protocol_set,
                bandwidth_sink,
                substream_open_timeout,
            )
            .start()
            .await;
        }));

        Ok(())
    }

    fn reject(&mut self, connection_id: ConnectionId) -> crate::Result<()> {
        self.canceled.insert(connection_id);
        self.pending_open
            .remove(&connection_id)
            .map_or(Err(Error::ConnectionDoesntExist(connection_id)), |_| Ok(()))
    }

    fn open(
        &mut self,
        connection_id: ConnectionId,
        addresses: Vec<Multiaddr>,
    ) -> crate::Result<()> {
        let mut futures: FuturesUnordered<_> = addresses
            .into_iter()
            .map(|address| {
                let keypair = self.context.keypair.clone();
                let connection_open_timeout = self.config.connection_open_timeout;

                async move {
                    let Ok((socket_address, Some(peer))) =
                        QuicListener::get_socket_address(&address)
                    else {
                        return (
                            connection_id,
                            Err(Error::AddressError(AddressError::PeerIdMissing)),
                        );
                    };

                    let crypto_config =
                        Arc::new(make_client_config(&keypair, Some(peer)).expect("to succeed"));
                    let mut transport_config = quinn::TransportConfig::default();
                    let timeout =
                        IdleTimeout::try_from(connection_open_timeout).expect("to succeed");
                    transport_config.max_idle_timeout(Some(timeout));
                    let mut client_config = ClientConfig::new(crypto_config);
                    client_config.transport_config(Arc::new(transport_config));

                    let client_listen_address = match address.iter().next() {
                        Some(Protocol::Ip6(_)) =>
                            SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0),
                        Some(Protocol::Ip4(_)) =>
                            SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
                        _ =>
                            return (
                                connection_id,
                                Err(Error::AddressError(AddressError::InvalidProtocol)),
                            ),
                    };

                    let client = match Endpoint::client(client_listen_address) {
                        Ok(client) => client,
                        Err(error) => {
                            return (connection_id, Err(Error::Other(error.to_string())));
                        }
                    };
                    let connection = match client.connect_with(client_config, socket_address, "l") {
                        Ok(connection) => connection,
                        Err(error) => {
                            return (connection_id, Err(Error::Other(error.to_string())));
                        }
                    };

                    let connection = match connection.await {
                        Ok(connection) => connection,
                        Err(error) => return (connection_id, Err(error.into())),
                    };

                    let Some(peer) = Self::extract_peer_id(&connection) else {
                        return (connection_id, Err(Error::InvalidCertificate));
                    };

                    (
                        connection_id,
                        Ok((address, NegotiatedConnection { peer, connection })),
                    )
                }
            })
            .collect();

        self.pending_raw_connections.push(Box::pin(async move {
            while let Some(result) = futures.next().await {
                let (connection_id, result) = result;

                match result {
                    Ok((address, connection)) => return Ok((connection_id, address, connection)),
                    Err(error) => tracing::debug!(
                        target: LOG_TARGET,
                        ?connection_id,
                        ?error,
                        "failed to open connection",
                    ),
                }
            }

            Err(connection_id)
        }));

        Ok(())
    }

    fn negotiate(&mut self, connection_id: ConnectionId) -> crate::Result<()> {
        let (connection, _address) = self
            .opened_raw
            .remove(&connection_id)
            .ok_or(Error::ConnectionDoesntExist(connection_id))?;

        self.pending_connections
            .push(Box::pin(async move { (connection_id, Ok(connection)) }));

        Ok(())
    }

    /// Cancel opening connections.
    fn cancel(&mut self, connection_id: ConnectionId) {
        self.canceled.insert(connection_id);
    }
}

impl Stream for QuicTransport {
    type Item = TransportEvent;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        while let Poll::Ready(Some(connection)) = self.listener.poll_next_unpin(cx) {
            let connection_id = self.context.next_connection_id();

            tracing::trace!(
                target: LOG_TARGET,
                ?connection_id,
                "accept connection",
            );

            self.pending_connections.push(Box::pin(async move {
                let connection = match connection.await {
                    Ok(connection) => connection,
                    Err(error) => return (connection_id, Err(error.into())),
                };

                let Some(peer) = Self::extract_peer_id(&connection) else {
                    return (connection_id, Err(Error::InvalidCertificate));
                };

                (connection_id, Ok(NegotiatedConnection { peer, connection }))
            }));
        }

        while let Poll::Ready(Some(result)) = self.pending_raw_connections.poll_next_unpin(cx) {
            match result {
                Ok((connection_id, address, stream)) => {
                    tracing::trace!(
                        target: LOG_TARGET,
                        ?connection_id,
                        ?address,
                        canceled = self.canceled.contains(&connection_id),
                        "connection opened",
                    );

                    if !self.canceled.remove(&connection_id) {
                        self.opened_raw.insert(connection_id, (stream, address.clone()));

                        return Poll::Ready(Some(TransportEvent::ConnectionOpened {
                            connection_id,
                            address,
                        }));
                    }
                }
                Err(connection_id) =>
                    if !self.canceled.remove(&connection_id) {
                        return Poll::Ready(Some(TransportEvent::OpenFailure { connection_id }));
                    },
            }
        }

        while let Poll::Ready(Some(connection)) = self.pending_connections.poll_next_unpin(cx) {
            let (connection_id, result) = connection;

            match self.on_connection_established(connection_id, result) {
                Some(event) => return Poll::Ready(Some(event)),
                None => {}
            }
        }

        Poll::Pending
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        codec::ProtocolCodec,
        crypto::ed25519::Keypair,
        executor::DefaultExecutor,
        transport::manager::{ProtocolContext, TransportHandle},
        types::protocol::ProtocolName,
        BandwidthSink,
    };
    use multihash::Multihash;
    use tokio::sync::mpsc::channel;

    #[tokio::test]
    async fn test_quinn() {
        let _ = tracing_subscriber::fmt()
            .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
            .try_init();

        let keypair1 = Keypair::generate();
        let (tx1, _rx1) = channel(64);
        let (event_tx1, _event_rx1) = channel(64);

        let handle1 = TransportHandle {
            executor: Arc::new(DefaultExecutor {}),
            protocol_names: Vec::new(),
            next_substream_id: Default::default(),
            next_connection_id: Default::default(),
            keypair: keypair1.clone(),
            tx: event_tx1,
            bandwidth_sink: BandwidthSink::new(),

            protocols: HashMap::from_iter([(
                ProtocolName::from("/notif/1"),
                ProtocolContext {
                    tx: tx1,
                    codec: ProtocolCodec::Identity(32),
                    fallback_names: Vec::new(),
                },
            )]),
        };

        let (mut transport1, listen_addresses) =
            QuicTransport::new(handle1, Default::default()).unwrap();
        let listen_address = listen_addresses[0].clone();

        let keypair2 = Keypair::generate();
        let (tx2, _rx2) = channel(64);
        let (event_tx2, _event_rx2) = channel(64);

        let handle2 = TransportHandle {
            executor: Arc::new(DefaultExecutor {}),
            protocol_names: Vec::new(),
            next_substream_id: Default::default(),
            next_connection_id: Default::default(),
            keypair: keypair2.clone(),
            tx: event_tx2,
            bandwidth_sink: BandwidthSink::new(),

            protocols: HashMap::from_iter([(
                ProtocolName::from("/notif/1"),
                ProtocolContext {
                    tx: tx2,
                    codec: ProtocolCodec::Identity(32),
                    fallback_names: Vec::new(),
                },
            )]),
        };

        let (mut transport2, _) = QuicTransport::new(handle2, Default::default()).unwrap();
        let peer1: PeerId = PeerId::from_public_key(&keypair1.public().into());
        let _peer2: PeerId = PeerId::from_public_key(&keypair2.public().into());
        let listen_address = listen_address.with(Protocol::P2p(
            Multihash::from_bytes(&peer1.to_bytes()).unwrap(),
        ));

        transport2.dial(ConnectionId::new(), listen_address).unwrap();
        let (res1, res2) = tokio::join!(transport1.next(), transport2.next());

        assert!(std::matches!(
            res1,
            Some(TransportEvent::ConnectionEstablished { .. })
        ));
        assert!(std::matches!(
            res2,
            Some(TransportEvent::ConnectionEstablished { .. })
        ));
    }
}