use bincode::{Decode, Encode};
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
#[cfg(feature = "json")]
use hex::serde as hex_serde;
#[cfg(feature = "json")]
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "json", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct Ed25519 {
#[cfg_attr(feature = "json", serde(with = "hex_serde"))]
pub public_key: [u8; 32],
#[cfg_attr(feature = "json", serde(with = "hex_serde"))]
pub signature: Vec<u8>,
#[cfg_attr(feature = "json", serde(with = "hex_serde"))]
pub message: Vec<u8>,
}
impl Ed25519 {
pub fn verify(&self) -> Result<(), Error> {
let pk = VerifyingKey::from_bytes(&self.public_key)
.map_err(|e| Error::InvalidPublicKey(e.to_string()))?;
let sig = Signature::from_slice(&self.signature).map_err(Error::InvalidSignature)?;
pk.verify(&self.message, &sig)
.map_err(|_| Error::VerificationFailed)
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("public key decoding error: {0}")]
InvalidPublicKey(String),
#[error("signature decoding error: {0}")]
InvalidSignature(#[from] ed25519_dalek::SignatureError),
#[error("signature verification failed")]
VerificationFailed,
}