mithril_stm/bls_multi_signature/
signature.rs

1use std::{cmp::Ordering, iter::Sum};
2
3use blake2::{Blake2b, Blake2b512, Digest};
4use blst::{
5    blst_p1, blst_p2,
6    min_sig::{AggregateSignature, PublicKey as BlstVk, Signature as BlstSig},
7    p1_affines, p2_affines,
8};
9use digest::consts::U16;
10
11use crate::bls_multi_signature::{
12    BlsVerificationKey,
13    helper::unsafe_helpers::{p1_affine_to_sig, p2_affine_to_vk, sig_to_p1, vk_from_p2_affine},
14};
15use crate::{
16    Index,
17    error::{MultiSignatureError, blst_err_to_mithril},
18};
19
20/// MultiSig signature, which is a wrapper over the `BlstSig` type.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct BlsSignature(pub BlstSig);
23
24impl BlsSignature {
25    /// Verify a signature against a verification key.
26    pub fn verify(&self, msg: &[u8], mvk: &BlsVerificationKey) -> Result<(), MultiSignatureError> {
27        blst_err_to_mithril(
28            self.0.validate(true).map_or_else(
29                |e| e,
30                |_| self.0.verify(false, msg, &[], &[], &mvk.to_blst_vk(), false),
31            ),
32            Some(*self),
33            None,
34        )
35    }
36
37    /// Dense mapping function indexed by the index to be evaluated.
38    /// We hash the signature to produce a 64 bytes integer.
39    /// The return value of this function refers to
40    /// `ev = H("map" || msg || index || σ) <- MSP.Eval(msg,index,σ)` given in paper.
41    pub fn eval(&self, msg: &[u8], index: Index) -> [u8; 64] {
42        let hasher = Blake2b512::new()
43            .chain_update(b"map")
44            .chain_update(msg)
45            .chain_update(index.to_le_bytes())
46            .chain_update(self.to_bytes())
47            .finalize();
48
49        let mut output = [0u8; 64];
50        output.copy_from_slice(hasher.as_slice());
51
52        output
53    }
54
55    /// Convert an `Signature` to its compressed byte representation.
56    pub fn to_bytes(self) -> [u8; 48] {
57        self.0.to_bytes()
58    }
59
60    /// Convert a string of bytes into a `MspSig`.
61    ///
62    /// # Error
63    /// Returns an error if the byte string does not represent a point in the curve.
64    pub fn from_bytes(bytes: &[u8]) -> Result<Self, MultiSignatureError> {
65        let bytes = bytes.get(..48).ok_or(MultiSignatureError::SerializationError)?;
66        match BlstSig::sig_validate(bytes, true) {
67            Ok(sig) => Ok(Self(sig)),
68            Err(e) => Err(blst_err_to_mithril(e, None, None)
69                .expect_err("If deserialization is not successful, blst returns and error different to SUCCESS."))
70        }
71    }
72
73    /// Compare two signatures. Used for PartialOrd impl, used to rank signatures. The comparison
74    /// function can be anything, as long as it is consistent across different nodes.
75    fn cmp_msp_sig(&self, other: &Self) -> Ordering {
76        let self_bytes = self.to_bytes();
77        let other_bytes = other.to_bytes();
78        let mut result = Ordering::Equal;
79
80        for (i, j) in self_bytes.iter().zip(other_bytes.iter()) {
81            result = i.cmp(j);
82            if result != Ordering::Equal {
83                return result;
84            }
85        }
86        result
87    }
88
89    /// Aggregate a slice of verification keys and Signatures by first hashing the
90    /// signatures into random scalars, and multiplying the signature and verification
91    /// key with the resulting value. This follows the steps defined in Figure 6,
92    /// `Aggregate` step.
93    pub fn aggregate(
94        vks: &[BlsVerificationKey],
95        sigs: &[BlsSignature],
96    ) -> Result<(BlsVerificationKey, BlsSignature), MultiSignatureError> {
97        if vks.len() != sigs.len() || vks.is_empty() {
98            return Err(MultiSignatureError::AggregateSignatureInvalid);
99        }
100
101        if vks.len() < 2 {
102            return Ok((vks[0], sigs[0]));
103        }
104
105        let mut hashed_sigs = Blake2b::<U16>::new();
106        for sig in sigs {
107            hashed_sigs.update(sig.to_bytes());
108        }
109
110        // First we generate the scalars
111        let mut scalars = Vec::with_capacity(vks.len() * 128);
112        let mut signatures = Vec::with_capacity(vks.len());
113        for (index, sig) in sigs.iter().enumerate() {
114            let mut hasher = hashed_sigs.clone();
115            hasher.update(index.to_be_bytes());
116            signatures.push(sig.0);
117            scalars.extend_from_slice(hasher.finalize().as_slice());
118        }
119
120        let transmuted_vks: Vec<blst_p2> = vks.iter().map(vk_from_p2_affine).collect();
121        let transmuted_sigs: Vec<blst_p1> = signatures.iter().map(sig_to_p1).collect();
122
123        let grouped_vks = p2_affines::from(transmuted_vks.as_slice());
124        let grouped_sigs = p1_affines::from(transmuted_sigs.as_slice());
125
126        let aggr_vk: BlstVk = p2_affine_to_vk(&grouped_vks.mult(&scalars, 128));
127        let aggr_sig: BlstSig = p1_affine_to_sig(&grouped_sigs.mult(&scalars, 128));
128
129        Ok((BlsVerificationKey(aggr_vk), BlsSignature(aggr_sig)))
130    }
131
132    /// Verify a set of signatures with their corresponding verification keys using the
133    /// aggregation mechanism of Figure 6.
134    pub fn verify_aggregate(
135        msg: &[u8],
136        vks: &[BlsVerificationKey],
137        sigs: &[BlsSignature],
138    ) -> Result<(), MultiSignatureError> {
139        let (aggr_vk, aggr_sig) = Self::aggregate(vks, sigs)?;
140
141        blst_err_to_mithril(
142            aggr_sig.0.verify(false, msg, &[], &[], &aggr_vk.to_blst_vk(), false),
143            Some(aggr_sig),
144            None,
145        )
146    }
147
148    /// Batch verify several sets of signatures with their corresponding verification keys.
149    pub fn batch_verify_aggregates(
150        msgs: &[Vec<u8>],
151        vks: &[BlsVerificationKey],
152        sigs: &[BlsSignature],
153    ) -> Result<(), MultiSignatureError> {
154        let batched_sig: BlstSig = match AggregateSignature::aggregate(
155            &(sigs.iter().map(|sig| &sig.0).collect::<Vec<&BlstSig>>()),
156            false,
157        ) {
158            Ok(sig) => BlstSig::from_aggregate(&sig),
159            Err(e) => return blst_err_to_mithril(e, None, None),
160        };
161
162        let p2_vks: Vec<BlstVk> = vks.iter().map(|vk| vk.to_blst_vk()).collect();
163        let p2_vks_ref: Vec<&BlstVk> = p2_vks.iter().collect();
164        let slice_msgs = msgs.iter().map(|msg| msg.as_slice()).collect::<Vec<&[u8]>>();
165
166        blst_err_to_mithril(
167            batched_sig.aggregate_verify(false, &slice_msgs, &[], &p2_vks_ref, false),
168            None,
169            None,
170        )
171        .map_err(|_| MultiSignatureError::BatchInvalid)
172    }
173}
174
175impl<'a> Sum<&'a Self> for BlsSignature {
176    fn sum<I>(iter: I) -> Self
177    where
178        I: Iterator<Item = &'a Self>,
179    {
180        let signatures: Vec<&BlstSig> = iter.map(|x| &x.0).collect();
181        assert!(!signatures.is_empty(), "One cannot add an empty vector");
182        let aggregate = AggregateSignature::aggregate(&signatures, false)
183            .expect("An MspSig is always a valid signature. This function only fails if signatures is empty or if the signatures are invalid, none of which can happen.")
184            .to_signature();
185
186        Self(aggregate)
187    }
188}
189
190impl PartialOrd for BlsSignature {
191    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
192        Some(std::cmp::Ord::cmp(self, other))
193    }
194}
195
196impl Ord for BlsSignature {
197    fn cmp(&self, other: &Self) -> Ordering {
198        self.cmp_msp_sig(other)
199    }
200}