use super::{
ed25519_dalek::{self as ed25519, Signer as _, Verifier as _},
EnrKey, EnrKeyUnambiguous, EnrPublicKey, SigningError,
};
use crate::Key;
use alloy_rlp::{Decodable, Error as DecoderError};
use bytes::Bytes;
use std::collections::BTreeMap;
pub const ENR_KEY: &str = "ed25519";
impl EnrKey for ed25519::SigningKey {
type PublicKey = ed25519::VerifyingKey;
fn sign_v4(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError> {
Ok(self.sign(msg).to_bytes().to_vec())
}
fn public(&self) -> Self::PublicKey {
self.verifying_key()
}
fn enr_to_public(content: &BTreeMap<Key, Bytes>) -> Result<Self::PublicKey, DecoderError> {
let pubkey_bytes = content
.get(ENR_KEY.as_bytes())
.ok_or(DecoderError::Custom("Unknown signature"))?;
let pubkey_bytes = Bytes::decode(&mut pubkey_bytes.as_ref())?;
Self::decode_public(&pubkey_bytes)
}
}
impl EnrKeyUnambiguous for ed25519::SigningKey {
fn decode_public(bytes: &[u8]) -> Result<Self::PublicKey, DecoderError> {
ed25519::VerifyingKey::try_from(bytes)
.map_err(|_| DecoderError::Custom("Invalid ed25519 Signature"))
}
}
impl EnrPublicKey for ed25519::VerifyingKey {
type Raw = [u8; ed25519::PUBLIC_KEY_LENGTH];
type RawUncompressed = [u8; ed25519::PUBLIC_KEY_LENGTH];
fn verify_v4(&self, msg: &[u8], sig: &[u8]) -> bool {
ed25519::Signature::try_from(sig)
.and_then(|s| self.verify(msg, &s))
.is_ok()
}
fn encode(&self) -> Self::Raw {
self.to_bytes()
}
fn encode_uncompressed(&self) -> Self::RawUncompressed {
self.encode()
}
fn enr_key(&self) -> Key {
ENR_KEY.into()
}
}