libp2p_quic/connection/
connecting.rs1use std::{
24 pin::Pin,
25 task::{Context, Poll},
26 time::Duration,
27};
28
29use futures::{
30 future::{Either, FutureExt, Select, select},
31 prelude::*,
32};
33use futures_timer::Delay;
34use libp2p_identity::PeerId;
35use quinn::rustls::pki_types::CertificateDer;
36use quinn_proto::TransportError;
37
38use crate::{Connection, ConnectionError, Error};
39
40#[derive(Debug)]
42pub struct Connecting {
43 connecting: Select<quinn::Connecting, Delay>,
44}
45
46impl Connecting {
47 pub(crate) fn new(connection: quinn::Connecting, timeout: Duration) -> Self {
48 Connecting {
49 connecting: select(connection, Delay::new(timeout)),
50 }
51 }
52}
53
54impl Connecting {
55 fn remote_peer_id(connection: &quinn::Connection) -> Result<PeerId, Error> {
56 fn transport_err(reason: &str) -> Error {
57 Error::Connection(ConnectionError(quinn::ConnectionError::TransportError(
58 TransportError {
59 code: quinn::TransportErrorCode::PROTOCOL_VIOLATION,
60 frame: None,
61 reason: reason.to_string(),
62 },
63 )))
64 }
65
66 let identity = connection
67 .peer_identity()
68 .ok_or_else(|| transport_err("No crypto identity in quinn's Connection"))?;
69 let certificates: Box<Vec<CertificateDer>> = identity
70 .downcast()
71 .map_err(|_| transport_err("Could not downcast identity"))?;
72 let end_entity = certificates
73 .first()
74 .ok_or_else(|| transport_err("No certificate found"))?;
75 let p2p_cert = libp2p_tls::certificate::parse(end_entity)
76 .map_err(|_| transport_err("Could not parse certificate"))?;
77 Ok(p2p_cert.peer_id())
78 }
79}
80
81impl Future for Connecting {
82 type Output = Result<(PeerId, Connection), Error>;
83
84 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
85 let connection = match futures::ready!(self.connecting.poll_unpin(cx)) {
86 Either::Right(_) => return Poll::Ready(Err(Error::HandshakeTimedOut)),
87 Either::Left((connection, _)) => connection.map_err(ConnectionError)?,
88 };
89
90 let peer_id = Self::remote_peer_id(&connection)?;
91 let muxer = Connection::new(connection);
92 Poll::Ready(Ok((peer_id, muxer)))
93 }
94}