iop_keyvault/ed25519/
pk.rs

1use super::*;
2
3/// The size of the public key in the compressed format used by [`to_bytes`]
4///
5/// [`to_bytes`]: #method.to_bytes
6pub const PUBLIC_KEY_SIZE: usize = ed::PUBLIC_KEY_LENGTH;
7
8/// Implementation of Ed25519::PublicKey
9#[derive(Clone, Eq, PartialEq)]
10pub struct EdPublicKey(ed::PublicKey);
11
12impl EdPublicKey {
13    /// The public key serialized in a format that can be fed to [`from_bytes`]
14    ///
15    /// [`from_bytes`]: #method.from_bytes
16    pub fn to_bytes(&self) -> Vec<u8> {
17        let mut res = Vec::with_capacity(PUBLIC_KEY_SIZE);
18        res.extend_from_slice(self.0.as_bytes());
19        res
20    }
21
22    /// Creates a public key from a byte slice possibly returned by the [`to_bytes`] method.
23    ///
24    /// # Error
25    /// If `bytes` is rejected by `ed25519_dalek::PublicKey::from_bytes`
26    ///
27    /// [`to_bytes`]: #method.to_bytes
28    pub fn from_bytes<D: AsRef<[u8]>>(bytes: D) -> Result<Self> {
29        let pk = ed::PublicKey::from_bytes(bytes.as_ref())?;
30        Ok(Self(pk))
31    }
32}
33
34impl From<ed::PublicKey> for EdPublicKey {
35    fn from(pk: ed::PublicKey) -> Self {
36        Self(pk)
37    }
38}
39
40impl<'a> From<&'a EdPublicKey> for &'a ed::PublicKey {
41    fn from(pk: &'a EdPublicKey) -> &'a ed::PublicKey {
42        &pk.0
43    }
44}
45
46impl PublicKey<Ed25519> for EdPublicKey {
47    fn key_id(&self) -> EdKeyId {
48        EdKeyId::from(self)
49    }
50    fn validate_id(&self, key_id: &EdKeyId) -> bool {
51        &self.key_id() == key_id
52    }
53    /// We should never assume that there is only 1 public key that can verify a given
54    /// signature. Actually, there are 8 public keys.
55    fn verify<D: AsRef<[u8]>>(&self, data: D, sig: &EdSignature) -> bool {
56        let res = self.0.verify(data.as_ref(), sig.into());
57        res.is_ok()
58    }
59}
60
61#[allow(clippy::derive_hash_xor_eq)] // If the 2 pks are equal. their hashes will be equal, too
62impl Hash for EdPublicKey {
63    fn hash<H: Hasher>(&self, hasher: &mut H) {
64        self.to_bytes().hash(hasher);
65    }
66}
67
68impl PartialOrd<Self> for EdPublicKey {
69    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
70        Some(self.cmp(rhs))
71    }
72}
73
74impl Ord for EdPublicKey {
75    fn cmp(&self, rhs: &Self) -> Ordering {
76        self.to_bytes().cmp(&rhs.to_bytes())
77    }
78}
79
80impl ExtendedPublicKey<Ed25519> for EdPublicKey {
81    fn derive_normal_child(&self, _idx: i32) -> Result<EdPublicKey> {
82        bail!("Normal derivation of Ed25519 is invalid based on SLIP-0010.")
83    }
84    fn public_key(&self) -> EdPublicKey {
85        self.clone()
86    }
87}