use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::Debug;
use std::sync::Arc;
pub use runar_keys::mobile::EnvelopeEncryptedData;
pub use runar_keys::EnvelopeCrypto;
pub type KeyStore = dyn EnvelopeCrypto;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LabelKeyInfo {
pub profile_public_keys: Vec<Vec<u8>>,
pub network_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct KeyMappingConfig {
pub label_mappings: HashMap<String, LabelKeyInfo>,
}
pub trait LabelResolver: Send + Sync {
fn resolve_label_info(&self, label: &str) -> Result<Option<LabelKeyInfo>>;
fn available_labels(&self) -> Vec<String>;
fn can_resolve(&self, label: &str) -> bool;
fn clone_box(&self) -> Box<dyn LabelResolver>;
}
impl LabelResolver for Box<dyn LabelResolver> {
fn resolve_label_info(&self, label: &str) -> Result<Option<LabelKeyInfo>> {
self.as_ref().resolve_label_info(label)
}
fn available_labels(&self) -> Vec<String> {
self.as_ref().available_labels()
}
fn can_resolve(&self, label: &str) -> bool {
self.as_ref().can_resolve(label)
}
fn clone_box(&self) -> Box<dyn LabelResolver> {
self.as_ref().clone_box()
}
}
pub struct ConfigurableLabelResolver {
config: KeyMappingConfig,
}
impl ConfigurableLabelResolver {
pub fn new(config: KeyMappingConfig) -> Self {
Self { config }
}
}
impl LabelResolver for ConfigurableLabelResolver {
fn resolve_label_info(&self, label: &str) -> Result<Option<LabelKeyInfo>> {
Ok(self.config.label_mappings.get(label).cloned())
}
fn available_labels(&self) -> Vec<String> {
self.config.label_mappings.keys().cloned().collect()
}
fn can_resolve(&self, label: &str) -> bool {
self.config.label_mappings.contains_key(label)
}
fn clone_box(&self) -> Box<dyn LabelResolver> {
Box::new(ConfigurableLabelResolver {
config: self.config.clone(),
})
}
}
pub trait RunarEncryptable {}
pub trait RunarEncrypt: RunarEncryptable {
type Encrypted: RunarDecrypt<Decrypted = Self> + Serialize;
fn encrypt_with_keystore(
&self,
keystore: &Arc<KeyStore>,
resolver: &dyn LabelResolver,
) -> Result<Self::Encrypted>;
}
pub trait RunarDecrypt {
type Decrypted: RunarEncrypt<Encrypted = Self>;
fn decrypt_with_keystore(&self, keystore: &Arc<KeyStore>) -> Result<Self::Decrypted>;
}
#[derive(Clone)]
pub struct SerializationContext {
pub keystore: Arc<KeyStore>,
pub resolver: Arc<dyn LabelResolver>,
pub network_id: String,
pub profile_public_key: Option<Vec<u8>>,
}