use core::fmt;
use std::{convert::TryFrom, path::PathBuf};
use entropy_protocol::PartyId;
use serde::{Deserialize, Serialize};
use synedrion::{KeyShare, ProductionParams};
use tracing::{info, span, Level, Span};
use zeroize::Zeroize;
use super::{
error::{InnerKvError, KvResult},
helpers::{deserialize, serialize},
kv::Kv,
};
#[derive(Zeroize, Debug, Clone, Serialize, Deserialize)]
#[zeroize(drop)]
pub struct Entropy(pub Vec<u8>);
#[derive(Clone, Serialize, Deserialize)]
pub struct PartyInfo {
pub party_ids: Vec<PartyId>,
pub share: KeyShare<ProductionParams, PartyId>,
}
impl fmt::Debug for PartyInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Point")
.field("party_ids", &self.party_ids)
.field("share", &self.share.verifying_key())
.finish()
}
}
#[derive(Clone)]
pub struct KvManager {
kv: Kv<KvValue>,
storage_path: PathBuf,
}
impl KvManager {
pub fn new(storage_path: PathBuf, encryption_key: [u8; 32]) -> KvResult<Self> {
Ok(KvManager {
kv: Kv::<KvValue>::new(storage_path.clone(), encryption_key)?,
storage_path,
})
}
pub fn kv(&self) -> &Kv<KvValue> {
&self.kv
}
pub fn storage_path(&self) -> &PathBuf {
&self.storage_path
}
}
pub type KvValue = Vec<u8>;
impl TryFrom<KvValue> for PartyInfo {
type Error = InnerKvError;
fn try_from(v: KvValue) -> Result<Self, Self::Error> {
deserialize(&v).ok_or(InnerKvError::DeserializationErr)
}
}
impl TryFrom<PartyInfo> for KvValue {
type Error = InnerKvError;
fn try_from(v: PartyInfo) -> Result<Self, Self::Error> {
serialize(&v).map_err(|_| InnerKvError::SerializationErr)
}
}
impl TryFrom<KvValue> for Entropy {
type Error = InnerKvError;
fn try_from(v: KvValue) -> Result<Self, Self::Error> {
deserialize(&v).ok_or(InnerKvError::DeserializationErr)
}
}
impl TryFrom<Entropy> for KvValue {
type Error = InnerKvError;
fn try_from(v: Entropy) -> Result<Self, Self::Error> {
serialize(&v).map_err(|_| InnerKvError::SerializationErr)
}
}
impl PartyInfo {
pub fn log_info(&self, session_id: &str, sign_span: Span) {
let init_span = span!(parent: &sign_span, Level::INFO, "init");
let _enter = init_span.enter();
info!("[uid:{:?}] starting Sign with [session ID: {}]", self.share.owner(), session_id,);
}
}