use std::str::FromStr;
use base64::decode_config;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::{
basic::Basic, derivation::DerivationCode, errors::KrError, key_manage::Publickey,
self_signing_pre::SelfSigningPrefix, Prefix,
};
#[derive(Debug, Clone)]
pub struct BasicPrefix {
pub derivation: Basic,
pub public_key: Publickey,
}
impl BasicPrefix {
pub fn new(code: Basic, public_key: Publickey) -> Self {
Self {
derivation: code,
public_key,
}
}
pub fn verify(&self, data: &[u8], signature: &SelfSigningPrefix) -> Result<bool, KrError> {
verify(data, self, signature)
}
}
impl PartialEq for BasicPrefix {
fn eq(&self, other: &Self) -> bool {
self.derivation == other.derivation && self.public_key == other.public_key
}
}
impl FromStr for BasicPrefix {
type Err = KrError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let code = Basic::from_str(s)?;
if s.len() == code.prefix_b64_len() {
let k_vec =
decode_config(&s[code.code_len()..code.prefix_b64_len()], base64::URL_SAFE)?;
Ok(Self::new(code, Publickey::from(k_vec)))
} else {
Err(KrError::SemanticError(format!(
"Incorrect Prefix Length: {}",
s
)))
}
}
}
impl Prefix for BasicPrefix {
fn derivative(&self) -> Vec<u8> {
self.public_key.key().to_vec()
}
fn derivation_code(&self) -> String {
self.derivation.to_str()
}
}
impl Serialize for BasicPrefix {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_str())
}
}
impl<'de> Deserialize<'de> for BasicPrefix {
fn deserialize<D>(deserializer: D) -> Result<BasicPrefix, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
BasicPrefix::from_str(&s).map_err(serde::de::Error::custom)
}
}
pub fn verify(
_data: &[u8],
_key: &BasicPrefix,
_signature: &SelfSigningPrefix,
) -> Result<bool, KrError> {
Ok(true)
}