use std::{io, time::Duration};
use tokio::{
io::{AsyncRead, AsyncWrite, split},
net::TcpStream,
sync::{mpsc, oneshot},
time::timeout,
};
use tracing::*;
use crate::{
ConnectError,
Connection,
P2P,
protocols::{ProtocolHandler, ReturnableConnection},
};
#[async_trait::async_trait]
pub trait Handshake: P2P
where
Self: Clone + Send + Sync + 'static,
{
const TIMEOUT_MS: u64 = 5_000;
async fn enable_handshake(&self) {
let (from_node_sender, mut from_node_receiver) = mpsc::unbounded_channel::<ReturnableConnection>();
let (tx, rx) = oneshot::channel();
let self_clone = self.clone();
let handshake_task = tokio::spawn(async move {
trace!(parent: self_clone.tcp().span(), "spawned the Handshake handler task");
tx.send(()).unwrap();
while let Some((conn, result_sender)) = from_node_receiver.recv().await {
let addr = conn.addr();
let node = self_clone.clone();
tokio::spawn(async move {
debug!(parent: node.tcp().span(), "shaking hands with {} as the {:?}", addr, !conn.side());
let result = timeout(Duration::from_millis(Self::TIMEOUT_MS), node.perform_handshake(conn)).await;
let ret: io::Result<_> = match result {
Ok(Ok(conn)) => {
debug!(parent: node.tcp().span(), "successfully handshaken with {addr}");
Ok(conn)
}
Ok(Err(err)) => {
debug!(parent: node.tcp().span(), "handshake with {addr} failed: {err}");
Err(err.into())
}
Err(_) => {
debug!(parent: node.tcp().span(), "handshake with {addr} timed out");
Err(io::ErrorKind::TimedOut.into())
}
};
if result_sender.send(ret).is_err() {
unreachable!("couldn't return a Connection to the Tcp");
}
});
}
});
let _ = rx.await;
self.tcp().tasks.lock().push(handshake_task);
let hdl = Box::new(ProtocolHandler(from_node_sender));
assert!(self.tcp().protocols.handshake.set(hdl).is_ok(), "the Handshake protocol was enabled more than once!");
}
async fn perform_handshake(&self, conn: Connection) -> Result<Connection, ConnectError>;
fn borrow_stream<'a>(&self, conn: &'a mut Connection) -> &'a mut TcpStream {
conn.stream.as_mut().unwrap()
}
fn take_stream(&self, conn: &mut Connection) -> TcpStream {
conn.stream.take().unwrap()
}
fn return_stream<T: AsyncRead + AsyncWrite + Send + Sync + 'static>(&self, conn: &mut Connection, stream: T) {
let (reader, writer) = split(stream);
conn.reader = Some(Box::new(reader));
conn.writer = Some(Box::new(writer));
}
}