xand_api_proto/proto_models/
public_key.rs

1use core::convert::TryFrom;
2use core::fmt::{self, Display, Formatter};
3use core::str::FromStr;
4use serde::{Deserialize, Serialize};
5
6// TODO cratify this for public use
7#[derive(Copy, Clone, Debug, Default, Hash, PartialEq, Eq, Serialize, Deserialize)]
8pub struct PublicKey {
9    key_as_bytes: [u8; 32],
10}
11impl PublicKey {
12    pub fn as_bytes(&self) -> &[u8; 32] {
13        &self.key_as_bytes
14    }
15}
16
17impl From<[u8; 32]> for PublicKey {
18    fn from(bytes: [u8; 32]) -> Self {
19        PublicKey {
20            key_as_bytes: bytes,
21        }
22    }
23}
24
25impl From<&[u8; 32]> for PublicKey {
26    fn from(bytes: &[u8; 32]) -> Self {
27        PublicKey {
28            key_as_bytes: *bytes,
29        }
30    }
31}
32
33impl TryFrom<&[u8]> for PublicKey {
34    type Error = PublicKeyParseError;
35
36    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
37        Ok(<&[u8; 32]>::try_from(bytes)
38            .map_err(|_| PublicKeyParseError {})?
39            .into())
40    }
41}
42
43impl TryFrom<Vec<u8>> for PublicKey {
44    type Error = PublicKeyParseError;
45
46    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
47        if value.len() != 32 {
48            return Err(PublicKeyParseError {});
49        }
50        PublicKey::try_from(&value[..])
51    }
52}
53
54#[derive(Debug, Eq, PartialEq)]
55pub struct PublicKeyParseError;
56
57impl FromStr for PublicKey {
58    type Err = PublicKeyParseError;
59
60    fn from_str(s: &str) -> Result<Self, Self::Err> {
61        let point_bytes = bs58::decode(s)
62            .into_vec()
63            .map_err(|_| PublicKeyParseError)?;
64        PublicKey::try_from(point_bytes.as_slice()).map_err(|_| PublicKeyParseError)
65    }
66}
67
68impl Display for PublicKey {
69    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
70        let serialized_b58 = bs58::encode(self.key_as_bytes).into_string();
71        write!(f, "{}", serialized_b58)
72    }
73}
74
75impl Display for PublicKeyParseError {
76    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
77        write!(f, "{:?}", self)
78    }
79}