use std::time::Duration;
use async_trait::async_trait;
use calimero_crypto::{Nonce, SharedKey};
use eyre::Result;
use super::wire::StreamMessage;
#[async_trait]
pub trait SyncTransport: Send {
async fn send(&mut self, message: &StreamMessage<'_>) -> Result<()>;
async fn recv(&mut self) -> Result<Option<StreamMessage<'static>>>;
async fn recv_timeout(&mut self, timeout: Duration) -> Result<Option<StreamMessage<'static>>>;
fn set_encryption(&mut self, encryption: Option<(SharedKey, Nonce)>);
fn encryption(&self) -> Option<(SharedKey, Nonce)>;
async fn close(&mut self) -> Result<()>;
}
#[derive(Debug, Clone, Default)]
pub struct EncryptionState {
pub key_nonce: Option<(SharedKey, Nonce)>,
}
impl EncryptionState {
#[must_use]
pub fn new() -> Self {
Self { key_nonce: None }
}
pub fn set(&mut self, encryption: Option<(SharedKey, Nonce)>) {
self.key_nonce = encryption;
}
#[must_use]
pub fn get(&self) -> Option<(SharedKey, Nonce)> {
self.key_nonce.clone()
}
pub fn encrypt(&self, data: Vec<u8>) -> Result<Vec<u8>> {
match &self.key_nonce {
Some((key, nonce)) => key
.encrypt(data, *nonce)
.ok_or_else(|| eyre::eyre!("encryption failed")),
None => Ok(data),
}
}
pub fn decrypt(&self, data: Vec<u8>) -> Result<Vec<u8>> {
match &self.key_nonce {
Some((key, nonce)) => key
.decrypt(data, *nonce)
.ok_or_else(|| eyre::eyre!("decryption failed")),
None => Ok(data),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encryption_state_default() {
let state = EncryptionState::new();
assert!(state.get().is_none());
}
#[test]
fn test_encryption_state_passthrough() {
let state = EncryptionState::new();
let data = b"hello world".to_vec();
let encrypted = state.encrypt(data.clone()).unwrap();
assert_eq!(encrypted, data); let decrypted = state.decrypt(encrypted).unwrap();
assert_eq!(decrypted, data);
}
}