bc_components/ed25519/
ed25519_public_key.rs1use anyhow::{Result, bail};
2
3pub const ED25519_PUBLIC_KEY_SIZE: usize = bc_crypto::ED25519_PUBLIC_KEY_SIZE;
4
5#[derive(Clone, PartialEq, Eq, Hash)]
19pub struct Ed25519PublicKey([u8; ED25519_PUBLIC_KEY_SIZE]);
20
21impl Ed25519PublicKey {
22 pub const fn from_data(data: [u8; ED25519_PUBLIC_KEY_SIZE]) -> Self {
24 Self(data)
25 }
26
27 pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
28 let data = data.as_ref();
29 if data.len() != ED25519_PUBLIC_KEY_SIZE {
30 bail!("Invalid Ed25519 public key size");
31 }
32 let mut key = [0u8; ED25519_PUBLIC_KEY_SIZE];
33 key.copy_from_slice(data);
34 Ok(Self(key))
35 }
36
37 pub fn data(&self) -> &[u8; ED25519_PUBLIC_KEY_SIZE] { &self.0 }
39
40 pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
42
43 fn hex(&self) -> String { hex::encode(self.data()) }
44
45 pub fn from_hex(hex: impl AsRef<str>) -> Result<Self> {
46 let data = hex::decode(hex.as_ref())?;
47 Self::from_data_ref(data)
48 }
49}
50
51impl Ed25519PublicKey {
52 pub fn verify(
55 &self,
56 signature: &[u8; bc_crypto::ED25519_SIGNATURE_SIZE],
57 message: impl AsRef<[u8]>,
58 ) -> bool {
59 bc_crypto::ed25519_verify(&self.0, message.as_ref(), signature)
60 }
61}
62
63impl AsRef<[u8]> for Ed25519PublicKey {
64 fn as_ref(&self) -> &[u8] { &self.0 }
65}
66
67impl std::fmt::Display for Ed25519PublicKey {
69 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70 write!(f, "{}", self.hex())
71 }
72}
73
74impl std::fmt::Debug for Ed25519PublicKey {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 write!(f, "Ed25519PublicKey({})", self.hex())
78 }
79}
80
81impl<'a> From<&'a Ed25519PublicKey> for &'a [u8; ED25519_PUBLIC_KEY_SIZE] {
84 fn from(value: &'a Ed25519PublicKey) -> Self { &value.0 }
85}
86
87impl From<[u8; ED25519_PUBLIC_KEY_SIZE]> for Ed25519PublicKey {
89 fn from(value: [u8; ED25519_PUBLIC_KEY_SIZE]) -> Self {
90 Self::from_data(value)
91 }
92}
93
94impl<'a> From<&'a Ed25519PublicKey> for &'a [u8] {
96 fn from(value: &'a Ed25519PublicKey) -> Self { &value.0 }
97}