1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use ed25519_dalek::{self as ed, Verifier};

use super::{Ed25519, EdKeyId, EdSignature};
use crate::*;

/// The size of the public key in the compressed format used by [`to_bytes`]
///
/// [`to_bytes`]: #method.to_bytes
pub const PUBLIC_KEY_SIZE: usize = ed::PUBLIC_KEY_LENGTH;

/// Implementation of Ed25519::PublicKey
#[derive(Clone, Eq, PartialEq)]
pub struct EdPublicKey(ed::PublicKey);

impl EdPublicKey {
    /// The public key serialized in a format that can be fed to [`from_bytes`]
    ///
    /// [`from_bytes`]: #method.from_bytes
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut res = Vec::with_capacity(PUBLIC_KEY_SIZE);
        res.extend_from_slice(self.0.as_bytes());
        res
    }

    /// Creates a public key from a byte slice possibly returned by the [`to_bytes`] method.
    ///
    /// # Error
    /// If `bytes` is rejected by `ed25519_dalek::PublicKey::from_bytes`
    ///
    /// [`to_bytes`]: #method.to_bytes
    pub fn from_bytes<D: AsRef<[u8]>>(bytes: D) -> Result<Self> {
        let pk = ed::PublicKey::from_bytes(bytes.as_ref())?;
        Ok(Self(pk))
    }
}

impl From<ed::PublicKey> for EdPublicKey {
    fn from(pk: ed::PublicKey) -> Self {
        Self(pk)
    }
}

impl PublicKey<Ed25519> for EdPublicKey {
    fn key_id(&self) -> EdKeyId {
        EdKeyId::from(self)
    }
    fn validate_id(&self, key_id: &EdKeyId) -> bool {
        &self.key_id() == key_id
    }
    /// We should never assume that there is only 1 public key that can verify a given
    /// signature. Actually, there are 8 public keys.
    fn verify<D: AsRef<[u8]>>(&self, data: D, sig: &EdSignature) -> bool {
        let res = self.0.verify(data.as_ref(), sig.into());
        res.is_ok()
    }
}

#[allow(clippy::derive_hash_xor_eq)] // If the 2 pks are equal. their hashes will be equal, too
impl Hash for EdPublicKey {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.to_bytes().hash(hasher);
    }
}

impl PartialOrd<Self> for EdPublicKey {
    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
        Some(self.cmp(rhs))
    }
}

impl Ord for EdPublicKey {
    fn cmp(&self, rhs: &Self) -> Ordering {
        self.to_bytes().cmp(&rhs.to_bytes())
    }
}

impl ExtendedPublicKey<Ed25519> for EdPublicKey {
    fn derive_normal_child(&self, _idx: i32) -> Result<EdPublicKey> {
        bail!("Normal derivation of Ed25519 is invalid based on SLIP-0010.")
    }
    fn public_key(&self) -> EdPublicKey {
        self.clone()
    }
}