use std::sync::Arc;
use anyhow::Result;
use bincode::{ Decode, Encode };
use futures::future::BoxFuture;
use serde::{ Deserialize, Serialize };
use crate::{
context::Context,
protocols::{
client_type::{ ClientType, send_bytes },
codec::Codec,
command::{ Action, Command, Entity },
frame::Frame,
},
};
#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode)]
pub struct OnlineAckCommand {
pub session_id: [u8; 16], pub address: String, pub ephemeral_public_key: [u8; 32], }
impl Codec for OnlineAckCommand {}
pub async fn send_online_ack(
context: Arc<Context>,
client_type: &ClientType,
ack: OnlineAckCommand ) -> Result<()> {
let command = Command::new(Entity::Node as u8, Action::OnLineAck as u8, Some(ack.to_bytes()));
let frame = Frame::build(context, command, 1).await.unwrap();
let bytes = Frame::to_bytes(&frame);
send_bytes(client_type, &bytes).await;
Ok(())
}
pub fn on_online_ack(
cmd: Command,
frame: Frame,
context: Arc<Context>,
client_type: Arc<ClientType>
) -> BoxFuture<'static, ()>
{
Box::pin(async move {
println!(
"✅ Node OnlineAck received from {} nonce={}",
frame.body.address,
frame.body.nonce
);
println!("received ack: {:?}", cmd.data.as_ref().unwrap());
let ack = match OnlineAckCommand::from_bytes(&cmd.data.as_ref().unwrap()) {
Ok(cmd) => cmd,
Err(e) => {
eprintln!("❌ decode OnlineAckCommand failed: {e}");
return;
}
};
println!("session:id: {:?}", ack.session_id);
let session = {
let mut temp_sessions = context.temp_sessions.lock().await;
let mut session = match temp_sessions.remove(&ack.session_id) {
Some(s) => s,
None => {
eprintln!("❌ temp session not found for session_id={:?}", ack.session_id);
return;
}
};
let peer_pub = x25519_dalek::PublicKey::from(ack.ephemeral_public_key);
if let Err(e) = session.establish(&peer_pub) {
eprintln!("❌ session establish failed: {e}");
return;
}
session.touch();
session
};
{
let mut sessions = context.session_keys.lock().await;
sessions.insert(ack.address.clone(), session);
}
println!("🔐 Session established with {} (session_id={:?})", ack.address, ack.session_id);
})
}