use std::time::Duration;
use crate::identity::PublicId;
use crate::peer::Peer;
use crate::{error::AetherError, util::gen_nonce};
use log::info;
use rand::{thread_rng, Rng};
use crate::{config::Config, link::Link};
pub const NONCE_SIZE: usize = 32;
pub fn authenticate(
link: Link,
peer_uid: String,
identity_number: u32,
config: Config,
) -> Result<Peer, AetherError> {
let delta = thread_rng().gen_range(0..config.aether.delta_time);
let recv_timeout = Duration::from_millis(config.aether.handshake_retry_delay + delta);
let other_id = PublicId::from_base64(&peer_uid)?;
let nonce = gen_nonce(NONCE_SIZE);
link.send(other_id.public_encrypt(&nonce)?).unwrap();
let nonce_enc = match link.recv_timeout(recv_timeout) {
Ok(data) => data,
Err(err) => match err {
AetherError::RecvTimeout(_) => return Err(AetherError::AuthenticationFailed(peer_uid)),
other => return Err(other),
},
};
let nonce_dec = link.private_id.private_decrypt(&nonce_enc)?;
link.send(nonce_dec).unwrap();
let nonce_recv = match link.recv_timeout(recv_timeout) {
Ok(data) => data,
Err(err) => match err {
AetherError::RecvTimeout(_) => return Err(AetherError::AuthenticationFailed(peer_uid)),
other => return Err(other),
},
};
if nonce == nonce_recv {
info!("Authenticated: {}", peer_uid);
let peer = Peer {
uid: peer_uid,
identity_number,
link,
};
Ok(peer)
} else {
Err(AetherError::AuthenticationInvalid(peer_uid))
}
}