use crate::{Digest, Error, Reference, ReferenceProvider, Result};
pub const ED25519_PUBLIC_KEY_SIZE: usize = bc_crypto::ED25519_PUBLIC_KEY_SIZE;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Ed25519PublicKey([u8; ED25519_PUBLIC_KEY_SIZE]);
impl Ed25519PublicKey {
pub const fn from_data(data: [u8; ED25519_PUBLIC_KEY_SIZE]) -> Self {
Self(data)
}
pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
let data = data.as_ref();
if data.len() != ED25519_PUBLIC_KEY_SIZE {
return Err(Error::invalid_size(
"Ed25519 public key",
ED25519_PUBLIC_KEY_SIZE,
data.len(),
));
}
let mut key = [0u8; ED25519_PUBLIC_KEY_SIZE];
key.copy_from_slice(data);
Ok(Self(key))
}
pub fn data(&self) -> &[u8; ED25519_PUBLIC_KEY_SIZE] { &self.0 }
pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
fn hex(&self) -> String { hex::encode(self.data()) }
pub fn from_hex(hex: impl AsRef<str>) -> Result<Self> {
let data = hex::decode(hex.as_ref())?;
Self::from_data_ref(data)
}
}
impl Ed25519PublicKey {
pub fn verify(
&self,
signature: &[u8; bc_crypto::ED25519_SIGNATURE_SIZE],
message: impl AsRef<[u8]>,
) -> bool {
bc_crypto::ed25519_verify(&self.0, message.as_ref(), signature)
}
}
impl AsRef<[u8]> for Ed25519PublicKey {
fn as_ref(&self) -> &[u8] { &self.0 }
}
impl std::fmt::Debug for Ed25519PublicKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Ed25519PublicKey({})", self.hex())
}
}
impl<'a> From<&'a Ed25519PublicKey> for &'a [u8; ED25519_PUBLIC_KEY_SIZE] {
fn from(value: &'a Ed25519PublicKey) -> Self { &value.0 }
}
impl From<[u8; ED25519_PUBLIC_KEY_SIZE]> for Ed25519PublicKey {
fn from(value: [u8; ED25519_PUBLIC_KEY_SIZE]) -> Self {
Self::from_data(value)
}
}
impl<'a> From<&'a Ed25519PublicKey> for &'a [u8] {
fn from(value: &'a Ed25519PublicKey) -> Self { &value.0 }
}
impl ReferenceProvider for Ed25519PublicKey {
fn reference(&self) -> Reference {
Reference::from_digest(Digest::from_image(self.data()))
}
}
impl std::fmt::Display for Ed25519PublicKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Ed25519PublicKey({})", self.ref_hex_short())
}
}