#![allow(unused_imports)]
use super::*;
pub struct NoiseTransportSession {
pub send_cipher: NoiseCipherState,
pub recv_cipher: NoiseCipherState,
pub handshake_hash: [u8; 32],
pub local_identity: SovereignNodeIdentity,
pub remote_static_public: [u8; 32],
pub remote_did: String,
pub is_terminated: bool,
}
impl NoiseTransportSession {
pub fn new(
send_cipher: NoiseCipherState,
recv_cipher: NoiseCipherState,
handshake_hash: [u8; 32],
local_identity: SovereignNodeIdentity,
remote_static_public: [u8; 32],
remote_did: String,
) -> Self {
Self {
send_cipher,
recv_cipher,
handshake_hash,
local_identity,
remote_static_public,
remote_did,
is_terminated: false,
}
}
pub fn encrypt_frame(&mut self, plaintext: &[u8]) -> Result<Vec<u8>, String> {
if self.is_terminated {
return Err("Cannot operate on terminated Noise transport session".into());
}
let current_nonce = self.send_cipher.nonce;
let mut nonce_bytes = [0u8; NOISE_NONCELEN];
nonce_bytes[4..12].copy_from_slice(¤t_nonce.to_be_bytes());
let ciphertext_with_tag = self.send_cipher.encrypt_with_ad(&[], plaintext)?;
let payload_len = NOISE_NONCELEN + ciphertext_with_tag.len();
if payload_len > 0xffff {
return Err(format!("Frame payload exceeds 65535 bytes: {}", payload_len));
}
let mut frame = Vec::with_capacity(NOISE_FRAME_HEADER_LEN + payload_len);
frame.extend_from_slice(&(payload_len as u16).to_be_bytes());
frame.extend_from_slice(&nonce_bytes);
frame.extend_from_slice(&ciphertext_with_tag);
Ok(frame)
}
pub fn decrypt_frame(&mut self, frame: &[u8]) -> Result<Vec<u8>, String> {
if self.is_terminated {
return Err("Cannot operate on terminated Noise transport session".into());
}
if frame.len() < NOISE_FRAME_HEADER_LEN + NOISE_NONCELEN + NOISE_TAGLEN {
self.terminate_and_zeroize();
return Err(format!("Frame too short: {} < 30 (INV-257-01)", frame.len()));
}
let payload_len = u16::from_be_bytes([frame[0], frame[1]]) as usize;
if frame.len() < NOISE_FRAME_HEADER_LEN + payload_len {
self.terminate_and_zeroize();
return Err(format!("Truncated frame: expected {}, got {}", NOISE_FRAME_HEADER_LEN + payload_len, frame.len()));
}
let mut nonce_counter_bytes = [0u8; 8];
nonce_counter_bytes.copy_from_slice(&frame[NOISE_FRAME_HEADER_LEN + 4..NOISE_FRAME_HEADER_LEN + 12]);
let frame_nonce = u64::from_be_bytes(nonce_counter_bytes);
if frame_nonce != self.recv_cipher.nonce {
self.terminate_and_zeroize();
return Err(format!(
"Replay or out-of-order frame: expected nonce {}, got {} (INV-257-01)",
self.recv_cipher.nonce, frame_nonce
));
}
let ct_with_tag = &frame[NOISE_FRAME_HEADER_LEN + NOISE_NONCELEN..NOISE_FRAME_HEADER_LEN + payload_len];
match self.recv_cipher.decrypt_with_ad(&[], ct_with_tag) {
Ok(pt) => Ok(pt),
Err(e) => {
self.terminate_and_zeroize();
Err(e)
}
}
}
pub fn terminate_and_zeroize(&mut self) {
self.is_terminated = true;
self.send_cipher.zeroize();
self.recv_cipher.zeroize();
}
}