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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
//! Schnorr signatures over prime order groups (or subgroups)

use debugless_unwrap::DebuglessUnwrap;

use crate::{Ciphersuite, Element, Error, Field, Group, Scalar};

/// A Schnorr signature over some prime order group (or subgroup).
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Signature<C: Ciphersuite> {
    /// The commitment `R` to the signature nonce.
    pub(crate) R: Element<C>,
    /// The response `z` to the challenge computed from the commitment `R`, the verifying key, and
    /// the message.
    pub(crate) z: Scalar<C>,
}

impl<C> Signature<C>
where
    C: Ciphersuite,
    C::Group: Group,
    <C::Group as Group>::Field: Field,
{
    /// Create a new Signature.
    #[cfg(feature = "internals")]
    pub fn new(
        R: <C::Group as Group>::Element,
        z: <<C::Group as Group>::Field as Field>::Scalar,
    ) -> Self {
        Self { R, z }
    }

    /// Converts bytes as [`Ciphersuite::SignatureSerialization`] into a `Signature<C>`.
    pub fn deserialize(bytes: C::SignatureSerialization) -> Result<Self, Error<C>> {
        // To compute the expected length of the encoded point, encode the generator
        // and get its length. Note that we can't use the identity because it can be encoded
        // shorter in some cases (e.g. P-256, which uses SEC1 encoding).
        let generator = <C::Group>::generator();
        let mut R_bytes = Vec::from(<C::Group>::serialize(&generator).as_ref());

        let R_bytes_len = R_bytes.len();

        R_bytes[..].copy_from_slice(
            bytes
                .as_ref()
                .get(0..R_bytes_len)
                .ok_or(Error::MalformedSignature)?,
        );

        let R_serialization = &R_bytes.try_into().map_err(|_| Error::MalformedSignature)?;

        let one = <<C::Group as Group>::Field as Field>::zero();
        let mut z_bytes =
            Vec::from(<<C::Group as Group>::Field as Field>::serialize(&one).as_ref());

        let z_bytes_len = z_bytes.len();

        // We extract the exact length of bytes we expect, not just the remaining bytes with `bytes[R_bytes_len..]`
        z_bytes[..].copy_from_slice(
            bytes
                .as_ref()
                .get(R_bytes_len..R_bytes_len + z_bytes_len)
                .ok_or(Error::MalformedSignature)?,
        );

        let z_serialization = &z_bytes.try_into().map_err(|_| Error::MalformedSignature)?;

        Ok(Self {
            R: <C::Group>::deserialize(R_serialization)?,
            z: <<C::Group as Group>::Field>::deserialize(z_serialization)?,
        })
    }

    /// Converts this signature to its [`Ciphersuite::SignatureSerialization`] in bytes.
    pub fn serialize(&self) -> C::SignatureSerialization {
        let mut bytes = vec![];

        bytes.extend(<C::Group>::serialize(&self.R).as_ref());
        bytes.extend(<<C::Group as Group>::Field>::serialize(&self.z).as_ref());

        bytes.try_into().debugless_unwrap()
    }
}

#[cfg(feature = "serde")]
impl<C> serde::Serialize for Signature<C>
where
    C: Ciphersuite,
    C::Group: Group,
    <C::Group as Group>::Field: Field,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serdect::slice::serialize_hex_lower_or_bin(&self.serialize().as_ref(), serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de, C> serde::Deserialize<'de> for Signature<C>
where
    C: Ciphersuite,
    C::Group: Group,
    <C::Group as Group>::Field: Field,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let bytes = serdect::slice::deserialize_hex_or_bin_vec(deserializer)?;
        let array = bytes
            .try_into()
            .map_err(|_| serde::de::Error::custom("invalid byte length"))?;
        let identifier = Signature::deserialize(array)
            .map_err(|err| serde::de::Error::custom(format!("{err}")))?;
        Ok(identifier)
    }
}

impl<C: Ciphersuite> std::fmt::Debug for Signature<C> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_struct("Signature")
            .field("R", &hex::encode(<C::Group>::serialize(&self.R).as_ref()))
            .field(
                "z",
                &hex::encode(<<C::Group as Group>::Field>::serialize(&self.z).as_ref()),
            )
            .finish()
    }
}