1use std::str::FromStr;
4
5use base64::decode_config;
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7
8use crate::{
9 basic::Basic, derivation::DerivationCode, errors::KrError, key_manage::Publickey,
10 self_signing_pre::SelfSigningPrefix, Prefix,
11};
12
13#[derive(Debug, Clone)]
14pub struct BasicPrefix {
15 pub derivation: Basic,
16 pub public_key: Publickey,
17}
18
19impl BasicPrefix {
20 pub fn new(code: Basic, public_key: Publickey) -> Self {
21 Self {
22 derivation: code,
23 public_key,
24 }
25 }
26
27 pub fn verify(&self, data: &[u8], signature: &SelfSigningPrefix) -> Result<bool, KrError> {
28 verify(data, self, signature)
29 }
30}
31
32impl PartialEq for BasicPrefix {
33 fn eq(&self, other: &Self) -> bool {
34 self.derivation == other.derivation && self.public_key == other.public_key
35 }
36}
37
38impl FromStr for BasicPrefix {
39 type Err = KrError;
40
41 fn from_str(s: &str) -> Result<Self, Self::Err> {
42 let code = Basic::from_str(s)?;
43
44 if s.len() == code.prefix_b64_len() {
45 let k_vec =
46 decode_config(&s[code.code_len()..code.prefix_b64_len()], base64::URL_SAFE)?;
47 Ok(Self::new(code, Publickey::from(k_vec)))
48 } else {
49 Err(KrError::SemanticError(format!(
50 "Incorrect Prefix Length: {}",
51 s
52 )))
53 }
54 }
55}
56
57impl Prefix for BasicPrefix {
58 fn derivative(&self) -> Vec<u8> {
59 self.public_key.key().to_vec()
60 }
61 fn derivation_code(&self) -> String {
62 self.derivation.to_str()
63 }
64}
65
66impl Serialize for BasicPrefix {
68 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
69 where
70 S: Serializer,
71 {
72 serializer.serialize_str(&self.to_str())
73 }
74}
75
76impl<'de> Deserialize<'de> for BasicPrefix {
78 fn deserialize<D>(deserializer: D) -> Result<BasicPrefix, D::Error>
79 where
80 D: Deserializer<'de>,
81 {
82 let s = String::deserialize(deserializer)?;
83
84 BasicPrefix::from_str(&s).map_err(serde::de::Error::custom)
85 }
86}
87
88pub fn verify(
93 _data: &[u8],
94 _key: &BasicPrefix,
95 _signature: &SelfSigningPrefix,
96) -> Result<bool, KrError> {
97 Ok(true)
113}