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
use anyhow::bail;
use bc_crypto::SCHNORR_SIGNATURE_SIZE;

use crate::ECKeyBase;


/// A Schnorr (x-only) elliptic curve public key.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SchnorrPublicKey([u8; Self::KEY_SIZE]);

impl SchnorrPublicKey {
    /// Restores a Schnorr public key from a vector of bytes.
    pub const fn from_data(data: [u8; Self::KEY_SIZE]) -> Self {
        Self(data)
    }

    /// Returns the Schnorr public key as a vector of bytes.
    pub fn data(&self) -> &[u8; Self::KEY_SIZE] {
        &self.0
    }
}

impl SchnorrPublicKey {
    /// Verifies the given Schnorr signature for the given message and tag.
    pub fn schnorr_verify<D1, D2>(&self, signature: &[u8; SCHNORR_SIGNATURE_SIZE],  message: D1, tag: D2) -> bool
    where
        D1: AsRef<[u8]>,
        D2: AsRef<[u8]>
    {
        bc_crypto::schnorr_verify(self.into(), signature, message, tag)
    }
}

impl<'a> From<&'a SchnorrPublicKey> for &'a [u8; SchnorrPublicKey::KEY_SIZE] {
    fn from(value: &'a SchnorrPublicKey) -> Self {
        &value.0
    }
}

impl From<[u8; Self::KEY_SIZE]> for SchnorrPublicKey {
    fn from(value: [u8; Self::KEY_SIZE]) -> Self {
        Self::from_data(value)
    }
}

impl AsRef<[u8]> for SchnorrPublicKey {
    fn as_ref(&self) -> &[u8] {
        self.data()
    }
}

impl std::fmt::Display for SchnorrPublicKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.hex())
    }
}

impl std::fmt::Debug for SchnorrPublicKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SchnorrPublicKey({})", self.hex())
    }
}

impl ECKeyBase for SchnorrPublicKey {
    const KEY_SIZE: usize = bc_crypto::SCHNORR_PUBLIC_KEY_SIZE;

    fn from_data_ref(data: impl AsRef<[u8]>) -> anyhow::Result<Self> where Self: Sized {
        let data = data.as_ref();
        if data.len() != Self::KEY_SIZE {
            bail!("invalid Schnorr public key size");
        }
        let mut key = [0u8; Self::KEY_SIZE];
        key.copy_from_slice(data);
        Ok(Self(key))
    }

    fn data(&self) -> &[u8] {
        &self.0
    }
}