zaun_community_protocol/crypto/voice/
identity.rs1use std::fmt;
4
5use hpke::kem::XWing;
6use hpke::{Deserializable, Kem, Serializable};
7use zeroize::Zeroizing;
8
9use super::{KEM_PUBLIC_LEN, VoiceError};
10use crate::ids::fill_random;
11
12pub(super) type XWingSecret = <XWing as Kem>::PrivateKey;
13pub(super) type XWingPublic = <XWing as Kem>::PublicKey;
14
15#[derive(Clone, PartialEq, Eq)]
17pub struct VoicePublicKey {
18 bytes: [u8; KEM_PUBLIC_LEN],
19 key: XWingPublic,
20}
21
22impl VoicePublicKey {
23 pub fn from_bytes(bytes: &[u8]) -> Result<Self, VoiceError> {
28 let arr: [u8; KEM_PUBLIC_LEN] = bytes
29 .try_into()
30 .map_err(|_| VoiceError::Length("voice public key"))?;
31 let key = XWingPublic::from_bytes(&arr).map_err(|_| VoiceError::PublicKey)?;
32 Ok(Self { bytes: arr, key })
33 }
34
35 #[must_use]
37 pub const fn as_bytes(&self) -> &[u8; KEM_PUBLIC_LEN] {
38 &self.bytes
39 }
40
41 pub(super) const fn key(&self) -> &XWingPublic {
42 &self.key
43 }
44}
45
46impl fmt::Debug for VoicePublicKey {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 let h = crate::crypto::content_hash(&self.bytes);
49 write!(f, "VoicePublicKey(sha3:{})", crate::b64::encode(&h[..8]))
50 }
51}
52
53pub struct VoiceIdentity {
56 secret: XWingSecret,
57 public: VoicePublicKey,
58}
59
60impl VoiceIdentity {
61 pub fn generate() -> Result<Self, VoiceError> {
66 let mut seed = Zeroizing::new([0u8; 32]);
67 fill_random(seed.as_mut())?;
68 Self::from_seed(&seed)
69 }
70
71 pub fn from_seed(seed: &[u8; 32]) -> Result<Self, VoiceError> {
77 let secret = XWingSecret::from_bytes(seed).map_err(|_| VoiceError::PublicKey)?;
78 let public = XWing::sk_to_pk(&secret);
79 let public = VoicePublicKey::from_bytes(&public.to_bytes())?;
80 Ok(Self { secret, public })
81 }
82
83 #[must_use]
85 pub const fn public_key(&self) -> &VoicePublicKey {
86 &self.public
87 }
88
89 pub(super) const fn secret(&self) -> &XWingSecret {
90 &self.secret
91 }
92}
93
94impl fmt::Debug for VoiceIdentity {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 f.debug_struct("VoiceIdentity")
97 .field("public", &self.public)
98 .finish_non_exhaustive()
99 }
100}