radix_common/crypto/ed25519/
public_key.rs

1use crate::internal_prelude::*;
2
3/// Represents an ED25519 public key.
4#[cfg_attr(feature = "fuzzing", derive(::arbitrary::Arbitrary))]
5#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
6#[derive(
7    Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Categorize, Encode, Decode, BasicDescribe,
8)]
9#[sbor(transparent)]
10pub struct Ed25519PublicKey(
11    #[cfg_attr(feature = "serde", serde(with = "hex::serde"))] pub [u8; Self::LENGTH],
12);
13
14impl Describe<ScryptoCustomTypeKind> for Ed25519PublicKey {
15    const TYPE_ID: RustTypeId =
16        RustTypeId::WellKnown(well_known_scrypto_custom_types::ED25519_PUBLIC_KEY_TYPE);
17
18    fn type_data() -> ScryptoTypeData<RustTypeId> {
19        well_known_scrypto_custom_types::ed25519_public_key_type_data()
20    }
21}
22
23impl Ed25519PublicKey {
24    pub const LENGTH: usize = 32;
25
26    pub fn to_vec(&self) -> Vec<u8> {
27        self.0.to_vec()
28    }
29
30    pub fn to_hash(&self) -> Ed25519PublicKeyHash {
31        Ed25519PublicKeyHash::new_from_public_key(self)
32    }
33}
34
35impl TryFrom<&[u8]> for Ed25519PublicKey {
36    type Error = ParseEd25519PublicKeyError;
37
38    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
39        if slice.len() != Ed25519PublicKey::LENGTH {
40            return Err(ParseEd25519PublicKeyError::InvalidLength(slice.len()));
41        }
42
43        Ok(Ed25519PublicKey(copy_u8_array(slice)))
44    }
45}
46
47impl AsRef<Self> for Ed25519PublicKey {
48    fn as_ref(&self) -> &Self {
49        self
50    }
51}
52
53impl AsRef<[u8]> for Ed25519PublicKey {
54    fn as_ref(&self) -> &[u8] {
55        &self.0
56    }
57}
58
59//======
60// hash
61//======
62
63#[cfg_attr(feature = "fuzzing", derive(::arbitrary::Arbitrary))]
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Categorize, Encode, Decode, BasicDescribe)]
65#[sbor(transparent)]
66pub struct Ed25519PublicKeyHash(pub [u8; Self::LENGTH]);
67
68impl Describe<ScryptoCustomTypeKind> for Ed25519PublicKeyHash {
69    const TYPE_ID: RustTypeId =
70        RustTypeId::WellKnown(well_known_scrypto_custom_types::ED25519_PUBLIC_KEY_HASH_TYPE);
71
72    fn type_data() -> ScryptoTypeData<RustTypeId> {
73        well_known_scrypto_custom_types::ed25519_public_key_hash_type_data()
74    }
75}
76
77impl Ed25519PublicKeyHash {
78    pub const LENGTH: usize = NodeId::RID_LENGTH;
79
80    pub fn new_from_public_key(public_key: &Ed25519PublicKey) -> Self {
81        Self(hash_public_key_bytes(public_key.0))
82    }
83}
84
85impl HasPublicKeyHash for Ed25519PublicKey {
86    type TypedPublicKeyHash = Ed25519PublicKeyHash;
87
88    fn get_hash(&self) -> Self::TypedPublicKeyHash {
89        Self::TypedPublicKeyHash::new_from_public_key(self)
90    }
91}
92
93impl IsPublicKeyHash for Ed25519PublicKeyHash {
94    fn get_hash_bytes(&self) -> &[u8; Self::LENGTH] {
95        &self.0
96    }
97
98    fn into_enum(self) -> PublicKeyHash {
99        PublicKeyHash::Ed25519(self)
100    }
101}
102
103impl HasPublicKeyHash for Ed25519PublicKeyHash {
104    type TypedPublicKeyHash = Self;
105
106    fn get_hash(&self) -> Self::TypedPublicKeyHash {
107        *self
108    }
109}
110
111//======
112// error
113//======
114
115/// Represents an error when parsing ED25519 public key from hex.
116#[derive(Debug, Clone, PartialEq, Eq, ScryptoSbor)]
117pub enum ParseEd25519PublicKeyError {
118    InvalidHex(String),
119    InvalidLength(usize),
120}
121
122#[cfg(not(feature = "alloc"))]
123impl std::error::Error for ParseEd25519PublicKeyError {}
124
125#[cfg(not(feature = "alloc"))]
126impl fmt::Display for ParseEd25519PublicKeyError {
127    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
128        write!(f, "{:?}", self)
129    }
130}
131
132//======
133// text
134//======
135
136impl FromStr for Ed25519PublicKey {
137    type Err = ParseEd25519PublicKeyError;
138
139    fn from_str(s: &str) -> Result<Self, Self::Err> {
140        let bytes =
141            hex::decode(s).map_err(|_| ParseEd25519PublicKeyError::InvalidHex(s.to_owned()))?;
142        Self::try_from(bytes.as_slice())
143    }
144}
145
146impl fmt::Display for Ed25519PublicKey {
147    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
148        write!(f, "{}", hex::encode(self.to_vec()))
149    }
150}
151
152impl fmt::Debug for Ed25519PublicKey {
153    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
154        write!(f, "{}", self)
155    }
156}