radix_common/crypto/bls12381/
signature.rs

1use crate::internal_prelude::*;
2use blst::{
3    min_pk::{AggregateSignature, Signature},
4    BLST_ERROR,
5};
6use radix_rust::copy_u8_array;
7use sbor::rust::borrow::ToOwned;
8use sbor::rust::fmt;
9use sbor::rust::str::FromStr;
10use sbor::rust::string::String;
11use sbor::rust::vec::Vec;
12use sbor::*;
13
14/// BLS12-381 ciphersuite v1
15/// It has following parameters
16///  - hash-to-curve: BLS12381G2_XMD:SHA-256_SSWU_RO
17///    - pairing-friendly elliptic curve: BLS12-381
18///    - hash function: SHA-256
19///    - signature variant: G2 minimal pubkey size
20///  - scheme:
21///    - proof-of-possession
22///
23/// More details: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-04
24pub const BLS12381_CIPHERSITE_V1: &[u8] = b"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_";
25
26/// Represents a BLS12-381 G2 signature (variant with 96-byte signature and 48-byte public key)
27#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
28#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Sbor)]
29#[sbor(transparent)]
30pub struct Bls12381G2Signature(
31    #[cfg_attr(feature = "serde", serde(with = "hex::serde"))] pub [u8; Self::LENGTH],
32);
33
34impl Bls12381G2Signature {
35    pub const LENGTH: usize = 96;
36
37    pub fn to_vec(&self) -> Vec<u8> {
38        self.0.to_vec()
39    }
40
41    fn to_native_signature(self) -> Result<Signature, ParseBlsSignatureError> {
42        Signature::from_bytes(&self.0).map_err(|err| err.into())
43    }
44
45    /// Aggregate multiple signatures into a single one.
46    /// This method validates provided input signatures if `should_validate` flag is set.
47    pub fn aggregate(
48        signatures: &[Self],
49        should_validate: bool,
50    ) -> Result<Self, ParseBlsSignatureError> {
51        if signatures.is_empty() {
52            return Err(ParseBlsSignatureError::NoSignatureGiven);
53        }
54        let serialized_sigs = signatures
55            .iter()
56            .map(|sig| sig.as_ref())
57            .collect::<Vec<_>>();
58
59        let sig = AggregateSignature::aggregate_serialized(&serialized_sigs, should_validate)?
60            .to_signature();
61
62        Ok(Self(sig.to_bytes()))
63    }
64
65    /// Aggregate multiple signatures into a single one.
66    /// This method does not validate provided input signatures, it is left
67    /// here for backward compatibility.
68    /// It is recommended to use `aggregate()` method instead.
69    pub fn aggregate_anemone(signatures: &[Self]) -> Result<Self, ParseBlsSignatureError> {
70        if !signatures.is_empty() {
71            let sig_first = signatures[0].to_native_signature()?;
72
73            let mut agg_sig = AggregateSignature::from_signature(&sig_first);
74
75            for sig in signatures.iter().skip(1) {
76                agg_sig.add_signature(&sig.to_native_signature()?, true)?;
77            }
78            Ok(Self(agg_sig.to_signature().to_bytes()))
79        } else {
80            Err(ParseBlsSignatureError::NoSignatureGiven)
81        }
82    }
83}
84
85impl TryFrom<&[u8]> for Bls12381G2Signature {
86    type Error = ParseBlsSignatureError;
87
88    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
89        if slice.len() != Self::LENGTH {
90            return Err(ParseBlsSignatureError::InvalidLength(slice.len()));
91        }
92
93        Ok(Self(copy_u8_array(slice)))
94    }
95}
96
97impl AsRef<Self> for Bls12381G2Signature {
98    fn as_ref(&self) -> &Self {
99        self
100    }
101}
102
103impl AsRef<[u8]> for Bls12381G2Signature {
104    fn as_ref(&self) -> &[u8] {
105        &self.0
106    }
107}
108
109//======
110// error
111//======
112
113impl From<BLST_ERROR> for ParseBlsSignatureError {
114    fn from(error: BLST_ERROR) -> Self {
115        let err_msg = format!("{:?}", error);
116        Self::BlsError(err_msg)
117    }
118}
119
120/// Represents an error when retrieving BLS signature from hex or when aggregating.
121#[derive(Debug, Clone, PartialEq, Eq, ScryptoSbor)]
122pub enum ParseBlsSignatureError {
123    InvalidHex(String),
124    InvalidLength(usize),
125    NoSignatureGiven,
126    // Error returned by underlying BLS library
127    BlsError(String),
128}
129
130#[cfg(not(feature = "alloc"))]
131impl std::error::Error for ParseBlsSignatureError {}
132
133impl fmt::Display for ParseBlsSignatureError {
134    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
135        write!(f, "{:?}", self)
136    }
137}
138
139//======
140// text
141//======
142
143impl FromStr for Bls12381G2Signature {
144    type Err = ParseBlsSignatureError;
145
146    fn from_str(s: &str) -> Result<Self, Self::Err> {
147        let bytes = hex::decode(s).map_err(|_| ParseBlsSignatureError::InvalidHex(s.to_owned()))?;
148        Self::try_from(bytes.as_slice())
149    }
150}
151
152impl fmt::Display for Bls12381G2Signature {
153    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
154        write!(f, "{}", hex::encode(self.to_vec()))
155    }
156}
157
158impl fmt::Debug for Bls12381G2Signature {
159    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
160        write!(f, "{}", self)
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use sbor::rust::str::FromStr;
168
169    macro_rules! signature_validate {
170        ($sig: expr) => {
171            blst::min_pk::Signature::from_bytes(&$sig.0)
172                .unwrap()
173                .validate(true)
174        };
175    }
176
177    #[test]
178    fn signature_not_in_group() {
179        let signature_not_in_group = "8b84ff5a1d4f8095ab8a80518ac99230ed24a7d1ec90c4105f9c719aa7137ed5d7ce1454d4a953f5f55f3959ab416f3014f4cd2c361e4d32c6b4704a70b0e2e652a908f501acb54ec4e79540be010e3fdc1fbf8e7af61625705e185a71c884f0";
180        let signature_not_in_group = Bls12381G2Signature::from_str(signature_not_in_group).unwrap();
181        let signature_valid = "82131f69b6699755f830e29d6ed41cbf759591a2ab598aa4e9686113341118d1db900d190436048601791121b5757c341045d4d0c94a95ec31a9ba6205f9b7504de85dadff52874375c58eec6cec28397279de87d5595101e398d31646d345bb";
182        let signature_valid = Bls12381G2Signature::from_str(signature_valid).unwrap();
183
184        assert_eq!(
185            signature_validate!(signature_not_in_group),
186            Err(blst::BLST_ERROR::BLST_POINT_NOT_IN_GROUP)
187        );
188
189        let sigs = vec![signature_not_in_group, signature_valid];
190
191        let agg_sig = Bls12381G2Signature::aggregate(&sigs, true);
192
193        assert_eq!(
194            agg_sig,
195            Err(ParseBlsSignatureError::BlsError(
196                "BLST_POINT_NOT_IN_GROUP".to_string()
197            ))
198        );
199
200        let sigs = vec![signature_valid, signature_not_in_group];
201
202        let agg_sig = Bls12381G2Signature::aggregate(&sigs, true);
203
204        assert_eq!(
205            agg_sig,
206            Err(ParseBlsSignatureError::BlsError(
207                "BLST_POINT_NOT_IN_GROUP".to_string()
208            ))
209        );
210    }
211}