Skip to main content

frost_core/
signature.rs

1//! Schnorr signatures over prime order groups (or subgroups)
2
3use alloc::{string::ToString, vec::Vec};
4use derive_getters::Getters;
5
6use crate::{Ciphersuite, Element, Error, Field, Group, Scalar};
7
8/// A Schnorr signature over some prime order group (or subgroup).
9#[derive(Copy, Clone, Eq, PartialEq, Getters)]
10pub struct Signature<C: Ciphersuite> {
11    /// The commitment `R` to the signature nonce.
12    pub(crate) R: Element<C>,
13    /// The response `z` to the challenge computed from the commitment `R`, the verifying key, and
14    /// the message.
15    pub(crate) z: Scalar<C>,
16}
17
18impl<C> Signature<C>
19where
20    C: Ciphersuite,
21    C::Group: Group,
22    <C::Group as Group>::Field: Field,
23{
24    /// Create a new Signature.
25    #[cfg(feature = "internals")]
26    pub fn new(
27        R: <C::Group as Group>::Element,
28        z: <<C::Group as Group>::Field as Field>::Scalar,
29    ) -> Self {
30        Self { R, z }
31    }
32
33    /// Converts default-encoded bytes as
34    /// [`Ciphersuite::SignatureSerialization`] into a `Signature<C>`.
35    #[cfg_attr(feature = "internals", visibility::make(pub))]
36    pub(crate) fn default_deserialize(bytes: &[u8]) -> Result<Self, Error<C>> {
37        // To compute the expected length of the encoded point, encode the generator
38        // and get its length. Note that we can't use the identity because it can be encoded
39        // shorter in some cases (e.g. P-256, which uses SEC1 encoding).
40        let generator = <C::Group>::generator();
41        let mut R_serialization = <C::Group>::serialize(&generator)?;
42        let R_bytes_len = R_serialization.as_ref().len();
43
44        let zero = <<C::Group as Group>::Field as Field>::zero();
45        let mut z_serialization = <<C::Group as Group>::Field as Field>::serialize(&zero);
46        let z_bytes_len = z_serialization.as_ref().len();
47
48        if bytes.len() != R_bytes_len + z_bytes_len {
49            return Err(Error::MalformedSignature);
50        }
51
52        R_serialization
53            .as_mut()
54            .copy_from_slice(bytes.get(0..R_bytes_len).ok_or(Error::MalformedSignature)?);
55
56        // We extract the exact length of bytes we expect, not just the remaining bytes with `bytes[R_bytes_len..]`
57        z_serialization.as_mut().copy_from_slice(
58            bytes
59                .get(R_bytes_len..R_bytes_len + z_bytes_len)
60                .ok_or(Error::MalformedSignature)?,
61        );
62
63        Ok(Self {
64            R: <C::Group>::deserialize(&R_serialization)?,
65            z: <<C::Group as Group>::Field>::deserialize(&z_serialization)?,
66        })
67    }
68
69    /// Converts bytes as [`Ciphersuite::SignatureSerialization`] into a `Signature<C>`.
70    pub fn deserialize(bytes: &[u8]) -> Result<Self, Error<C>> {
71        C::deserialize_signature(bytes)
72    }
73
74    /// Converts this signature to its default byte serialization.
75    #[cfg_attr(feature = "internals", visibility::make(pub))]
76    pub(crate) fn default_serialize(&self) -> Result<Vec<u8>, Error<C>> {
77        let R_serialization = <C::Group>::serialize(&self.R)?;
78        let z_serialization = <<C::Group as Group>::Field>::serialize(&self.z);
79
80        let R_bytes = R_serialization.as_ref();
81        let z_bytes = z_serialization.as_ref();
82
83        let mut bytes = Vec::with_capacity(R_bytes.len() + z_bytes.len());
84
85        bytes.extend(R_bytes);
86        bytes.extend(z_bytes);
87
88        Ok(bytes)
89    }
90
91    /// Converts this signature to its byte serialization.
92    pub fn serialize(&self) -> Result<Vec<u8>, Error<C>> {
93        <C>::serialize_signature(self)
94    }
95}
96
97#[cfg(feature = "serde")]
98impl<C> serde::Serialize for Signature<C>
99where
100    C: Ciphersuite,
101    C::Group: Group,
102    <C::Group as Group>::Field: Field,
103{
104    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
105    where
106        S: serde::Serializer,
107    {
108        serdect::slice::serialize_hex_lower_or_bin(
109            &self.serialize().map_err(serde::ser::Error::custom)?,
110            serializer,
111        )
112    }
113}
114
115#[cfg(feature = "serde")]
116impl<'de, C> serde::Deserialize<'de> for Signature<C>
117where
118    C: Ciphersuite,
119    C::Group: Group,
120    <C::Group as Group>::Field: Field,
121{
122    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
123    where
124        D: serde::Deserializer<'de>,
125    {
126        let bytes = serdect::slice::deserialize_hex_or_bin_vec(deserializer)?;
127        let signature = Signature::deserialize(&bytes)
128            .map_err(|err| serde::de::Error::custom(format!("{err}")))?;
129        Ok(signature)
130    }
131}
132
133impl<C: Ciphersuite> core::fmt::Debug for Signature<C> {
134    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
135        f.debug_struct("Signature")
136            .field(
137                "R",
138                &<C::Group>::serialize(&self.R)
139                    .map(|s| hex::encode(s.as_ref()))
140                    .unwrap_or("<invalid>".to_string()),
141            )
142            .field(
143                "z",
144                &hex::encode(<<C::Group as Group>::Field>::serialize(&self.z).as_ref()),
145            )
146            .finish()
147    }
148}