use std::{
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use futures::{
future::{select, Either, FutureExt, Select},
prelude::*,
};
use futures_timer::Delay;
use libp2p_identity::PeerId;
use quinn::rustls::pki_types::CertificateDer;
use quinn_proto::TransportError;
use crate::{Connection, ConnectionError, Error};
#[derive(Debug)]
pub struct Connecting {
connecting: Select<quinn::Connecting, Delay>,
}
impl Connecting {
pub(crate) fn new(connection: quinn::Connecting, timeout: Duration) -> Self {
Connecting {
connecting: select(connection, Delay::new(timeout)),
}
}
}
impl Connecting {
fn remote_peer_id(connection: &quinn::Connection) -> Result<PeerId, Error> {
fn transport_err(reason: &str) -> Error {
Error::Connection(ConnectionError(quinn::ConnectionError::TransportError(
TransportError {
code: quinn::TransportErrorCode::PROTOCOL_VIOLATION,
frame: None,
reason: reason.to_string(),
},
)))
}
let identity = connection
.peer_identity()
.ok_or_else(|| transport_err("No crypto identity in quinn's Connection"))?;
let certificates: Box<Vec<CertificateDer>> = identity
.downcast()
.map_err(|_| transport_err("Could not downcast identity"))?;
let end_entity = certificates
.first()
.ok_or_else(|| transport_err("No certificate found"))?;
let p2p_cert = libp2p_tls::certificate::parse(end_entity)
.map_err(|_| transport_err("Could not parse certificate"))?;
Ok(p2p_cert.peer_id())
}
}
impl Future for Connecting {
type Output = Result<(PeerId, Connection), Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let connection = match futures::ready!(self.connecting.poll_unpin(cx)) {
Either::Right(_) => return Poll::Ready(Err(Error::HandshakeTimedOut)),
Either::Left((connection, _)) => connection.map_err(ConnectionError)?,
};
let peer_id = Self::remote_peer_id(&connection)?;
let muxer = Connection::new(connection);
Poll::Ready(Ok((peer_id, muxer)))
}
}