w3f_bls/
single.rs

1//! ## Unaggreagated BLS signatures
2//!
3//! We simplify the code by using only the projective form as
4//! produced by algebraic operations, like aggregation, signing, and
5//! `SecretKey::into_public`, for both `Signature` and `Group`.
6//!
7//! In principle, one benifits from an affine form in serialization,
8//! and pairings meaning signature verification, but the conversion
9//! from affine to projective is always free and the converion from
10//! projective to affine is free if we do no algebraic operations.  
11//! We thus expect the conversion to and from projective to be free
12//! in the case of verifications where staying affine yields the
13//! largest benifits.
14//!
15//! We imagine this simplification helps focus on more important
16//! optimizations, like placing `batch_normalization` calls well.
17//! We could exploit `CurveGroup: += _mixed` function
18//! if we had seperate types for affine points, but if doing so
19//! improved performance enough then we instead suggest tweaking
20//! `CurveGroup::add_mixed` to test for normalized points.
21//!
22//! TODO: Add serde support for serialization throughout.  See
23//!  https://github.com/ebfull/pairing/pull/87#issuecomment-402397091
24//!  https://github.com/poanetwork/hbbft/blob/38178af1244ddeca27f9d23750ca755af6e886ee/src/crypto/serde_impl.rs#L95
25
26use alloc::{vec, vec::Vec};
27
28use ark_ff::field_hashers::{DefaultFieldHasher, HashToField};
29use ark_ff::{UniformRand, Zero};
30
31use ark_ec::{AffineRepr, CurveGroup};
32
33use ark_serialize::{
34    CanonicalDeserialize, CanonicalSerialize, Compress, Read, SerializationError, Valid, Validate,
35    Write,
36};
37#[cfg(feature = "std")]
38use rand::thread_rng;
39use rand::{rngs::StdRng, Rng, SeedableRng};
40use rand_chacha::ChaCha8Rng;
41use sha2::Sha256;
42use sha3::{
43    digest::{ExtendableOutput, Update, XofReader},
44    Shake128,
45};
46
47use digest::Digest;
48
49use core::iter::once;
50
51use crate::serialize::SerializableToBytes;
52use crate::{EngineBLS, Message, Signed};
53// //////////////// SECRETS //////////////// //
54
55/// Secret signing key lacking the side channel protections from
56/// key splitting.  Avoid using directly in production.
57#[derive(CanonicalSerialize, CanonicalDeserialize)]
58pub struct SecretKeyVT<E: EngineBLS>(pub E::Scalar);
59
60impl<E: EngineBLS> Clone for SecretKeyVT<E> {
61    fn clone(&self) -> Self {
62        SecretKeyVT(self.0)
63    }
64}
65
66impl<E: EngineBLS> SecretKeyVT<E> {
67    /// Generate a secret key without side channel protections.
68    pub fn generate<R: Rng>(mut rng: R) -> Self {
69        SecretKeyVT(E::generate(&mut rng))
70    }
71
72    pub fn from_seed(seed: &[u8]) -> Self {
73        let hasher = <DefaultFieldHasher<Sha256> as HashToField<E::Scalar>>::new(&[]);
74        return SecretKeyVT(hasher.hash_to_field(seed, 1)[0]);
75    }
76}
77
78impl<E: EngineBLS> SecretKeyVT<E> {
79    /// Sign without side channel protections from key mutation.
80    pub fn sign(&self, message: &Message) -> Signature<E> {
81        let mut s: E::SignatureGroup = message.hash_to_signature_curve::<E>();
82        s *= self.0;
83        // s.normalize();   // VRFs are faster if we only normalize once, but no normalize method exists.
84        // E::SignatureGroup::batch_normalization(&mut [&mut s]);
85        Signature(s)
86    }
87
88    /// Convert into a `SecretKey` that supports side channel protections,
89    /// but does not itself resplit the key.
90    pub fn into_split_dirty(&self) -> SecretKey<E> {
91        SecretKey {
92            key: [self.0.clone(), E::Scalar::zero()],
93            old_unsigned: E::SignatureGroup::zero(),
94            old_signed: E::SignatureGroup::zero(),
95        }
96    }
97
98    /// Convert into a `SecretKey` applying side channel protections.
99    pub fn into_split<R: Rng>(&self, mut rng: R) -> SecretKey<E> {
100        let mut s = self.into_split_dirty();
101        s.resplit(&mut rng);
102        s.init_point_mutation(rng);
103        s
104    }
105
106    /// Derive our public key from our secret key
107    pub fn into_public(&self) -> PublicKey<E> {
108        // TODO str4d never decided on projective vs affine here, so benchmark both versions.
109        PublicKey(<E::PublicKeyGroup as CurveGroup>::Affine::generator().into_group() * self.0)
110        // let mut g = <E::PublicKeyGroup as CurveGroup>::one();
111        // g *= self.0;
112        // PublicKey(p)
113    }
114}
115
116/// Secret signing key that is split to provide side channel protection.
117///
118/// A simple key splitting works because
119/// `self.key[0] * H(message) + self.key[1] * H(message) = (self.key[0] + self.key[1]) * H(message)`.
120/// In our case, we mutate the point being signed too by keeping
121/// an old point in both signed and unsigned forms, so our message
122/// point becomes `new_unsigned = H(message) - old_unsigned`,
123/// we compute `new_signed = self.key[0] * new_unsigned + self.key[1] * new_unsigned`,
124/// and our signature becomes `new_signed + old_signed`.
125/// We save the new signed and unsigned values as old ones, so that adversaries
126/// also cannot know the curves points being multiplied by scalars.
127/// In this, our `init_point_mutation` method signs some random point,
128/// so that even an adversary who tracks all signed messages cannot
129/// foresee the curve points being signed.
130///
131#[cfg_attr(
132    feature = "std",
133    doc = r##"
134/// We require mutable access to the secret key, but interior mutability
135/// can easily be employed, which might resemble:
136/// ```rust,no_run
137/// # extern crate bls_like as bls;
138/// # extern crate rand;
139/// # use bls::{SecretKey,ZBLS,Message};
140/// # #[cfg(feature=std)]
141/// # use rand::thread_rng;
142/// # let message = Message::new(b"ctx",b"test message");
143/// let mut secret = ::std::cell::RefCell::new(SecretKey::<ZBLS>::generate(thread_rng()));
144/// let signature = secret.borrow_mut().sign(message,thread_rng());
145/// ```
146/// If however `secret: Mutex<SecretKey>` or `secret: RwLock<SecretKey>`
147/// then one might avoid holding the write lock while signing, or even
148/// while sampling the random numbers by using other methods.
149"##
150)]
151///
152/// Right now, we serialize using `SecretKey::into_vartime` and
153/// `SecretKeyVT::write`, so `secret.into_vartime().write(writer)?`.
154/// We deserialize using the `read`, `from_repr`, and `into_split`
155/// methods of `SecretKeyVT`, so roughly
156/// `SecretKeyVT::from_repr(SecretKeyVT::read(reader) ?) ?.into_split(thread_rng())`.
157///
158/// TODO: Provide sensible `to_bytes` and `from_bytes` methods
159/// for `ZBLS` and `TinyBLS<..>`.
160///
161/// TODO: Is Pippenger’s algorithm, or another fast MSM algorithm,
162/// secure when used with key splitting?
163
164/// Secret signing key including the side channel protections from
165/// key splitting.
166pub struct SecretKey<E: EngineBLS> {
167    key: [E::Scalar; 2],
168    old_unsigned: E::SignatureGroup,
169    old_signed: E::SignatureGroup,
170}
171
172impl<E: EngineBLS> Clone for SecretKey<E> {
173    fn clone(&self) -> Self {
174        SecretKey {
175            key: self.key.clone(),
176            old_unsigned: self.old_unsigned.clone(),
177            old_signed: self.old_signed.clone(),
178        }
179    }
180}
181
182impl<E: EngineBLS> SecretKey<E>
183where
184    E: EngineBLS,
185{
186    /// Generate a secret key that is already split for side channel protection,
187    /// but does not apply signed point mutation.
188    pub fn generate_dirty<R: Rng>(mut rng: R) -> Self {
189        SecretKey {
190            key: [E::generate(&mut rng), E::generate(&mut rng)],
191            old_unsigned: E::SignatureGroup::zero(),
192            old_signed: E::SignatureGroup::zero(),
193        }
194    }
195
196    /// Generate a secret key that is already split for side channel protection.
197    pub fn generate<R: Rng>(mut rng: R) -> Self {
198        let mut s = Self::generate_dirty(&mut rng);
199        s.init_point_mutation(rng);
200        s
201    }
202
203    pub fn from_seed(seed: &[u8]) -> Self {
204        SecretKeyVT::from_seed(seed).into_split_dirty()
205    }
206}
207
208impl<E: EngineBLS> SecretKey<E> {
209    /// Initialize the signature curve signed point mutation.
210    ///
211    /// Amortized over many signings involing this once costs
212    /// nothing, but each individual invokation costs as much
213    /// as signing.
214    pub fn init_point_mutation<R: Rng>(&mut self, mut rng: R) {
215        let mut s = <E::SignatureGroup as UniformRand>::rand(&mut rng);
216        self.old_unsigned = s;
217        self.old_signed = s;
218        self.old_signed *= self.key[0];
219        s *= self.key[1];
220        self.old_signed += &s;
221    }
222
223    /// Create a representative usable for operations lacking
224    /// side channel protections.  
225    pub fn into_vartime(&self) -> SecretKeyVT<E> {
226        let mut secret = self.key[0].clone();
227        secret += &self.key[1];
228        SecretKeyVT(secret)
229    }
230
231    /// Randomly adjust how we split our secret signing key.
232    //
233    // An initial call to this function after deserialization or
234    // `into_split_dirty` incurs a miniscule risk from side channel
235    // attacks, but then protects the highly vulnerable signing
236    // operations.  `into_split` itself handles this.
237    #[inline(never)]
238    pub fn resplit<R: Rng>(&mut self, mut rng: R) {
239        // resplit_with(|| Ok(self), rng).unwrap();
240        let x = E::generate(&mut rng);
241        self.key[0] += &x;
242        self.key[1] -= &x;
243    }
244
245    /// Sign without doing the key resplit mutation that provides side channel protection.
246    ///
247    /// Avoid using directly without appropriate `replit` calls, but maybe
248    /// useful in proof-of-concenpt code, as it does not require a mutable
249    /// secret key.
250    pub fn sign_once(&mut self, message: &Message) -> Signature<E> {
251        let mut z = message.hash_to_signature_curve::<E>();
252        z -= &self.old_unsigned;
253        self.old_unsigned = z.clone();
254        let mut t = z.clone();
255        t *= self.key[0];
256        z *= self.key[1];
257        z += &t;
258        let old_signed = self.old_signed.clone();
259        self.old_signed = z.clone();
260        z += &old_signed;
261        // s.normalize();   // VRFs are faster if we only normalize once, but no normalize method exists.
262        // E::SignatureGroup::batch_normalization(&mut [&mut s]);
263        Signature(z)
264    }
265
266    /// Sign after respliting the secret key for side channel protections.
267    pub fn sign<R: Rng>(&mut self, message: &Message, rng: R) -> Signature<E> {
268        self.resplit(rng);
269        self.sign_once(message)
270    }
271
272    /// Derive our public key from our secret key
273    ///
274    /// We do not resplit for side channel protections here since
275    /// this call should be rare.
276    pub fn into_public(&self) -> PublicKey<E> {
277        let generator = <E::PublicKeyGroup as CurveGroup>::Affine::generator();
278        let mut publickey = generator * self.key[0];
279        publickey += generator.into_group() * self.key[1];
280        PublicKey(publickey)
281        // TODO str4d never decided on projective vs affine here, so benchmark this.
282        /*
283        let mut x = <E::PublicKeyGroup as CurveGroup>::one();
284        x *= self.0;
285        let y = <E::PublicKeyGroup as CurveGroup>::one();
286        y *= self.1;
287        x += &y;
288        PublicKey(x)
289        */
290    }
291}
292
293// ////////////// NON-SECRETS ////////////// //
294
295// /////// BEGIN MACROS /////// //
296
297/*
298TODO: Requires specilizatin
299macro_rules! borrow_wrapper {
300    ($wrapper:tt,$wrapped:tt,$var:tt) => {
301impl<E: EngineBLS> Borrow<E::$wrapped> for $wrapper<E> {
302    borrow(&self) -> &E::$wrapped { &self.$var }
303}
304impl<E: EngineBLS> BorrowMut<E::$wrapped> for $wrapper<E> {
305    borrow_mut(&self) -> &E::$wrapped { &self.$var }
306}
307    }
308} // macro_rules!
309*/
310
311#[macro_export]
312macro_rules! broken_derives {
313    ($wrapper:tt) => {
314        impl<E: EngineBLS> Clone for $wrapper<E> {
315            fn clone(&self) -> Self {
316                $wrapper(self.0)
317            }
318        }
319        impl<E: EngineBLS> Copy for $wrapper<E> {}
320
321        impl<E: EngineBLS> PartialEq<Self> for $wrapper<E> {
322            fn eq(&self, other: &Self) -> bool {
323                self.0.eq(&other.0)
324            }
325        }
326
327        impl<E: EngineBLS> Eq for $wrapper<E> {}
328    };
329} // macro_rules!
330
331// //////// END MACROS //////// //
332
333/// Implementing de/serialization for secret keypair
334/// Note that deriving serialization for secret is not sensible
335/// as you need to conver them to vartime form first
336impl<E> CanonicalSerialize for SecretKey<E>
337where
338    E: EngineBLS,
339{
340    #[inline]
341    fn serialize_with_mode<W: Write>(
342        &self,
343        writer: W,
344        compress: ark_serialize::Compress,
345    ) -> Result<(), SerializationError> {
346        self.into_vartime().serialize_with_mode(writer, compress)
347    }
348
349    #[inline]
350    fn serialize_compressed<W: Write>(&self, writer: W) -> Result<(), SerializationError> {
351        self.into_vartime().serialize_compressed(writer)?;
352        Ok(())
353    }
354
355    #[inline]
356    fn serialized_size(&self, compress: Compress) -> usize {
357        self.into_vartime().serialized_size(compress)
358    }
359
360    #[inline]
361    fn serialize_uncompressed<W: Write>(&self, mut writer: W) -> Result<(), SerializationError> {
362        self.into_vartime().serialize_uncompressed(&mut writer)?;
363        Ok(())
364    }
365
366    #[inline]
367    fn uncompressed_size(&self) -> usize {
368        self.into_vartime().uncompressed_size()
369    }
370
371    // #[inline]
372    // fn serialize_uncompressed_<W: Write>(&self, mut writer: W) -> Result<(), SerializationError> {
373    //     self.into_vartime().uncompressed_size().serialize_unchecked(&mut writer)?;
374    //     Ok(())
375    // }
376}
377
378impl<E> Valid for SecretKey<E>
379where
380    E: EngineBLS,
381{
382    fn check(&self) -> Result<(), SerializationError> {
383        //TODO probabaly turn into vartime and check that because vartime impl valid
384        match (self.key[1].check(), self.key[2].check()) {
385            (Ok(()), Ok(())) => Ok(()),
386            _ => Err(SerializationError::InvalidData),
387        }
388    }
389}
390
391impl<E> CanonicalDeserialize for SecretKey<E>
392where
393    E: EngineBLS,
394{
395    fn deserialize_with_mode<R: Read>(
396        reader: R,
397        compress: Compress,
398        validate: Validate,
399    ) -> Result<Self, SerializationError> {
400        let secret_key_vt = <SecretKeyVT<E> as CanonicalDeserialize>::deserialize_with_mode(
401            reader, compress, validate,
402        )?;
403        Ok(secret_key_vt.into_split_dirty())
404    }
405
406    #[inline]
407    fn deserialize_compressed<R: Read>(reader: R) -> Result<Self, SerializationError> {
408        let secret_key_vt =
409            <SecretKeyVT<E> as CanonicalDeserialize>::deserialize_compressed(reader)?;
410        Ok(secret_key_vt.into_split_dirty())
411    }
412
413    #[inline]
414    fn deserialize_uncompressed<R: Read>(mut reader: R) -> Result<Self, SerializationError> {
415        let secret_key_vt =
416            <SecretKeyVT<E> as CanonicalDeserialize>::deserialize_uncompressed(&mut reader)?;
417        Ok(secret_key_vt.into_split_dirty())
418    }
419
420    #[inline]
421    fn deserialize_uncompressed_unchecked<R: Read>(reader: R) -> Result<Self, SerializationError> {
422        let secret_key_vt =
423            <SecretKeyVT<E> as CanonicalDeserialize>::deserialize_uncompressed_unchecked(reader)?;
424        Ok(secret_key_vt.into_split_dirty())
425    }
426}
427
428//TODO: when const generic becomes stable we get the size from the trait and return
429//      constant size array so it can be implemented as follows
430// impl <E: EngineBLS> SerializableToBytes<{ E::SIGNATURE_SERIALIZED_SIZE }> for Signature<E> {}
431// impl <E: EngineBLS> SerializableToBytes<{ PublicKey::E::PUBLICKEY_SERIALIZED_SIZE }> for PublicKey<E>  {}
432impl<E: EngineBLS> SerializableToBytes for Signature<E> {
433    const SERIALIZED_BYTES_SIZE: usize = E::SIGNATURE_SERIALIZED_SIZE;
434}
435impl<E: EngineBLS> SerializableToBytes for PublicKey<E> {
436    const SERIALIZED_BYTES_SIZE: usize = E::PUBLICKEY_SERIALIZED_SIZE;
437}
438impl<E: EngineBLS> SerializableToBytes for SecretKeyVT<E> {
439    const SERIALIZED_BYTES_SIZE: usize = E::SECRET_KEY_SIZE;
440}
441
442impl<E: EngineBLS> SerializableToBytes for SecretKey<E> {
443    const SERIALIZED_BYTES_SIZE: usize = E::SECRET_KEY_SIZE;
444}
445
446/// because SecretKey is not canonically serializable and that we need to convert
447/// it to vartime first we need to manually re-implement this trait for secret keys
448//, CanonicalSerialize, CanonicalDeserialize)]
449/// Detached BLS Signature
450#[derive(Debug, CanonicalSerialize, CanonicalDeserialize)]
451pub struct Signature<E: EngineBLS>(pub E::SignatureGroup);
452// TODO: Serialization
453
454broken_derives!(Signature); // Actually the derive works for this one, not sure why.
455
456impl<E: EngineBLS> Signature<E> {
457    //const DESCRIPTION : &'static str = "A BLS signature";
458
459    /// Verify a single BLS signature
460    pub fn verify(&self, message: &Message, publickey: &PublicKey<E>) -> bool {
461        let publickey = E::prepare_public_key(publickey.0);
462        // TODO: Bentchmark these two variants
463        // Variant 1.  Do not batch any normalizations
464        let message = E::prepare_signature(message.hash_to_signature_curve::<E>());
465        let signature = E::prepare_signature(self.0);
466        // Variant 2.  Batch signature curve normalizations
467        //   let mut s = [E::hash_to_signature_curve(message), signature.0];
468        //   E::SignatureCurve::batch_normalization(&s);
469        //   let message = s[0].into_affine().prepare();
470        //   let signature = s[1].into_affine().prepare();
471        // TODO: Compare benchmarks on variants
472        E::verify_prepared(signature, &[(publickey, message)])
473    }
474}
475
476/// BLS Public Key
477#[derive(Debug, CanonicalSerialize, CanonicalDeserialize)]
478pub struct PublicKey<E: EngineBLS>(pub E::PublicKeyGroup);
479// TODO: Serialization
480
481// impl<E: EngineBLS> PublicKey<E> where E: DeserializePublicKey {
482//     pub fn i_have_checked_this_proof_of_possession(self) -> PublicKey<PoP<E>> {
483//         PublicKey(self.0)
484//     }
485// }
486
487broken_derives!(PublicKey);
488//serialization!(PublicKey,PublicKeyGroup,EngineBLS,EngineBLS);
489
490impl<E: EngineBLS> PublicKey<E> {
491    //const DESCRIPTION : &'static str = "A BLS signature";
492    pub fn verify(&self, message: &Message, signature: &Signature<E>) -> bool {
493        signature.verify(&message, self)
494    }
495}
496
497/// BLS Keypair
498///
499/// We create `Signed` messages with a `Keypair` to avoid recomputing
500/// the public key, which usually takes longer than signing when
501/// the public key group is `G2`.2
502///
503/// We provide constant-time signing using key splitting.
504pub struct KeypairVT<E: EngineBLS> {
505    pub secret: SecretKeyVT<E>,
506    pub public: PublicKey<E>,
507}
508
509impl<E: EngineBLS> Clone for KeypairVT<E> {
510    fn clone(&self) -> Self {
511        KeypairVT {
512            secret: self.secret.clone(),
513            public: self.public.clone(),
514        }
515    }
516}
517
518// TODO: Serialization
519impl<E: EngineBLS> KeypairVT<E> {
520    /// Generate a `Keypair`
521    pub fn generate<R: Rng>(rng: R) -> Self {
522        let secret = SecretKeyVT::generate(rng);
523        let public = secret.into_public();
524        KeypairVT { secret, public }
525    }
526}
527
528impl<E: EngineBLS> KeypairVT<E> {
529    /// Convert into a `SecretKey` applying side channel protections.
530    pub fn into_split<R: Rng>(&self, rng: R) -> Keypair<E> {
531        let secret = self.secret.into_split(rng);
532        let public = self.public;
533        Keypair { secret, public }
534    }
535
536    /// Sign a message creating a `SignedMessage` using a user supplied CSPRNG for the key splitting.
537    pub fn sign(&self, message: &Message) -> Signature<E> {
538        self.secret.sign(message)
539    }
540
541    /// Sign a message creating a `SignedMessage` using a user supplied CSPRNG for the key splitting.
542    pub fn signed_message(&self, message: &Message) -> SignedMessage<E> {
543        let signature = self.secret.sign(&message);
544        SignedMessage {
545            message: message.clone(),
546            publickey: self.public.clone(),
547            signature,
548        }
549    }
550}
551
552/// BLS Keypair
553///
554/// We create `Signed` messages with a `Keypair` to avoid recomputing
555/// the public key, which usually takes longer than signing when
556/// the public key group is `G2`.
557///
558/// We provide constant-time signing using key splitting.
559pub struct Keypair<E: EngineBLS> {
560    pub secret: SecretKey<E>,
561    pub public: PublicKey<E>,
562}
563
564impl<E: EngineBLS> Clone for Keypair<E> {
565    fn clone(&self) -> Self {
566        Keypair {
567            secret: self.secret.clone(),
568            public: self.public.clone(),
569        }
570    }
571}
572
573// TODO: Serialization
574impl<E: EngineBLS> Keypair<E> {
575    /// Generate a `Keypair`
576    pub fn generate<R: Rng>(rng: R) -> Self {
577        let secret = SecretKey::generate(rng);
578        let public = secret.into_public();
579        Keypair { secret, public }
580    }
581}
582
583impl<E: EngineBLS> Keypair<E> {
584    /// Create a representative usable for operations lacking
585    /// side channel protections.  
586    pub fn into_vartime(&self) -> KeypairVT<E> {
587        let secret = self.secret.into_vartime();
588        let public = self.public;
589        KeypairVT { secret, public }
590    }
591
592    /// Sign a message creating a `Signature` using a user supplied CSPRNG for the key splitting.
593    pub fn sign_with_rng<R: Rng>(&mut self, message: &Message, rng: R) -> Signature<E> {
594        self.secret.sign(&message, rng)
595    }
596
597    /// Sign a message using a Seedabale RNG created from user supplied seed
598    pub fn sign_with_random_seed(&mut self, message: &Message, seed: [u8; 32]) -> Signature<E> {
599        self.sign_with_rng::<StdRng>(message, SeedableRng::from_seed(seed))
600    }
601
602    /// Sign a message using a Seedabale RNG created from a seed derived from the message and key
603    pub fn sign(&mut self, message: &Message) -> Signature<E> {
604        let mut serialized_part1 = [0u8; 32];
605        let mut serialized_part2 = [0u8; 32];
606        self.secret.key[0]
607            .serialize_compressed(&mut serialized_part1[..])
608            .unwrap();
609        self.secret.key[1]
610            .serialize_compressed(&mut serialized_part2[..])
611            .unwrap();
612
613        let seed_digest = Sha256::new()
614            .chain_update(serialized_part1)
615            .chain_update(serialized_part2)
616            .chain_update(message.0);
617
618        let seed: [u8; 32] = seed_digest.finalize().into();
619
620        self.sign_with_rng::<StdRng>(message, SeedableRng::from_seed(seed))
621    }
622
623    #[cfg(feature = "std")]
624    /// Sign a message creating a `Signature` using the default `ThreadRng`.
625    pub fn sign_thread_rng(&mut self, message: &Message) -> Signature<E> {
626        self.sign_with_rng(message, thread_rng())
627    }
628
629    /// Create a `SignedMessage` using the default `ThreadRng`.
630    pub fn signed_message(&mut self, message: &Message) -> SignedMessage<E> {
631        let signature = self.sign(&message);
632        SignedMessage {
633            message: message.clone(),
634            publickey: self.public,
635            signature,
636        }
637    }
638}
639
640/// Message with attached BLS signature
641///
642///
643#[derive(Debug, Clone)]
644pub struct SignedMessage<E: EngineBLS> {
645    pub message: Message,
646    pub publickey: PublicKey<E>,
647    pub signature: Signature<E>,
648}
649// TODO: Serialization
650
651// borrow_wrapper!(Signature,SignatureGroup,signature);
652// borrow_wrapper!(PublicKey,PublicKeyGroup,publickey);
653
654impl<E: EngineBLS> PartialEq<Self> for SignedMessage<E> {
655    fn eq(&self, other: &Self) -> bool {
656        self.message.eq(&other.message)
657            && self.publickey.eq(&other.publickey)
658            && self.signature.eq(&other.signature)
659    }
660}
661
662impl<E: EngineBLS> Eq for SignedMessage<E> {}
663
664impl<'a, E: EngineBLS> Signed for &'a SignedMessage<E> {
665    type E = E;
666
667    type M = Message;
668    type PKG = PublicKey<E>;
669
670    type PKnM = ::core::iter::Once<(Message, PublicKey<E>)>;
671
672    fn messages_and_publickeys(self) -> Self::PKnM {
673        once((self.message.clone(), self.publickey)) // TODO:  Avoid clone
674    }
675
676    fn signature(&self) -> Signature<E> {
677        self.signature
678    }
679
680    fn verify(self) -> bool {
681        self.signature.verify(&self.message, &self.publickey)
682    }
683}
684
685impl<E: EngineBLS> SignedMessage<E> {
686    #[cfg(test)]
687    pub fn verify_slow(&self) -> bool {
688        let g1_one = <E::PublicKeyGroup as CurveGroup>::Affine::generator();
689        let message = self.message.hash_to_signature_curve::<E>().into_affine();
690        E::pairing(g1_one, self.signature.0.into_affine())
691            == E::pairing(self.publickey.0.into_affine(), message)
692    }
693
694    /// Hash output from a BLS signature regarded as a VRF.
695    ///
696    /// If you are not the signer then you must verify the VRF before calling this method.
697    ///
698    /// If called with distinct contexts then outputs should be independent.
699    ///
700    /// We incorporate both the input and output to provide the 2Hash-DH
701    /// construction from Theorem 2 on page 32 in appendex C of
702    /// ["Ouroboros Praos: An adaptively-secure, semi-synchronous proof-of-stake blockchain"](https://eprint.iacr.org/2017/573.pdf)
703    /// by Bernardo David, Peter Gazi, Aggelos Kiayias, and Alexander Russell.
704    pub fn vrf_hash<H: ExtendableOutput>(&self, h: &mut H) {
705        h.update(b"msg");
706        h.update(&self.message.0[..]);
707        h.update(b"out");
708        let affine_signature = self.signature.0.into_affine();
709        let mut serialized_signature = vec![0; affine_signature.uncompressed_size()];
710        affine_signature
711            .serialize_uncompressed(&mut serialized_signature[..])
712            .unwrap();
713
714        h.update(&serialized_signature);
715    }
716
717    /// Raw bytes output from a BLS signature regarded as a VRF.
718    ///
719    /// If you are not the signer then you must verify the VRF before calling this method.
720    ///
721    /// If called with distinct contexts then outputs should be independent.
722    pub fn make_bytes<Out: Default + AsMut<[u8]>>(&self, context: &[u8]) -> Out {
723        let mut t = Shake128::default();
724        t.update(context);
725        self.vrf_hash(&mut t);
726        let mut seed = Out::default();
727        XofReader::read(&mut t.finalize_xof(), seed.as_mut());
728        seed
729    }
730
731    /* TODO: Switch to this whenever pairing upgrades to rand 0.5 or later
732    /// VRF output converted into any `SeedableRng`.
733    ///
734    /// If you are not the signer then you must verify the VRF before calling this method.
735    ///
736    /// We expect most users would prefer the less generic `VRFInOut::make_chacharng` method.
737    pub fn make_rng<R: SeedableRng>(&self, context: &[u8]) -> R {
738        R::from_seed(self.make_bytes::<R::Seed>(context))
739    }
740    */
741
742    /// VRF output converted into a `ChaChaRng`.
743    ///
744    /// If you are not the signer then you must verify the VRF before calling this method.
745    ///
746    /// If called with distinct contexts then outputs should be independent.
747    /// Independent output streams are available via `ChaChaRng::set_stream` too.
748    ///
749    /// We incorporate both the input and output to provide the 2Hash-DH
750    /// construction from Theorem 2 on page 32 in appendex C of
751    /// ["Ouroboros Praos: An adaptively-secure, semi-synchronous proof-of-stake blockchain"](https://eprint.iacr.org/2017/573.pdf)
752    /// by Bernardo David, Peter Gazi, Aggelos Kiayias, and Alexander Russell.
753    pub fn make_chacharng(&self, context: &[u8]) -> ChaCha8Rng {
754        let bytes = self.make_bytes::<[u8; 32]>(context);
755        ChaCha8Rng::from_seed(bytes)
756    }
757}
758
759#[cfg(all(test, feature = "std"))]
760mod tests {
761    use ark_bls12_377::Bls12_377;
762    use ark_bls12_381::Bls12_381;
763    use ark_ec::bls12::Bls12Config;
764    use ark_ec::hashing::curve_maps::wb::{WBConfig, WBMap};
765    use ark_ec::hashing::map_to_curve_hasher::MapToCurve;
766    use ark_ec::pairing::Pairing as PairingEngine;
767
768    use super::*;
769    use crate::{CurveExtraConfig, TinyBLS, UsualBLS};
770
771    use core::convert::TryInto;
772    use hex_literal::hex;
773
774    fn bls_engine_serialization_test<
775        EB: EngineBLS<Engine = E>,
776        E: PairingEngine,
777        P: Bls12Config + CurveExtraConfig,
778    >(
779        x: SignedMessage<EB>,
780    ) -> SignedMessage<EB>
781    where
782        <P as Bls12Config>::G2Config: WBConfig,
783        WBMap<<P as Bls12Config>::G2Config>: MapToCurve<<E as PairingEngine>::G2>,
784    {
785        let SignedMessage {
786            message,
787            publickey,
788            signature,
789        } = x;
790
791        let publickey = PublicKey::<EB>::from_bytes(&publickey.to_bytes()).unwrap();
792        let signature = Signature::<EB>::from_bytes(&signature.to_bytes()).unwrap();
793
794        SignedMessage {
795            message,
796            publickey,
797            signature,
798        }
799    }
800
801    /// generates a random secret key sign a message and convert the
802    /// key to bytes then reconvert it to key and derive its public key
803    /// And check if the signature still verifies    
804    fn test_serialize_deserialize_production_secret_key<
805        E: PairingEngine,
806        P: Bls12Config + CurveExtraConfig,
807    >()
808    where
809        <P as Bls12Config>::G2Config: WBConfig,
810        WBMap<<P as Bls12Config>::G2Config>: MapToCurve<<E as PairingEngine>::G2>,
811    {
812        let mut keypair = Keypair::<UsualBLS<E, P>>::generate(thread_rng());
813        let serialized_secret_key = keypair.secret.to_bytes();
814        println!(
815            "secret key serialize size: {}, secret key first scaler serialize size {}",
816            keypair.secret.uncompressed_size(),
817            keypair.secret.key[0].uncompressed_size()
818        );
819
820        let good_message = Message::new(b"ctx", b"test message");
821
822        let sig = keypair.sign(&good_message);
823
824        let deserialized_secret_key =
825            SecretKey::<UsualBLS<E, P>>::from_bytes(&serialized_secret_key).unwrap();
826        let reconstructed_public_key = deserialized_secret_key.into_public();
827        assert!(sig.verify(&good_message, &reconstructed_public_key));
828    }
829
830    fn test_deserialize_random_value_as_secret_key_fails<
831        E: PairingEngine,
832        P: Bls12Config + CurveExtraConfig,
833    >(
834        random_seed: &[u8],
835    ) where
836        <P as Bls12Config>::G2Config: WBConfig,
837        WBMap<<P as Bls12Config>::G2Config>: MapToCurve<<E as PairingEngine>::G2>,
838    {
839        match SecretKey::<UsualBLS<E, P>>::from_bytes(
840            random_seed
841                .try_into()
842                .expect("the size of the seed be 32 Bytes."),
843        ) {
844            Ok(_) => assert!(
845                false,
846                "random seed should not be canonically deserializable to a secret key."
847            ),
848            Err(SerializationError::InvalidData) => (),
849            _ => assert!(false, "unexpected deserialization error."),
850        }
851    }
852
853    // fn test_public_key_and_message_serialization<E: PairingEngine, P: Bls12Config>(x: SignedMessage<EB>)-> SignedMessage<E> where <P as Bls12Config>::G2Config: WBConfig, WBMap<<P as Bls12Config>::G2Config>: MapToCurve<<E as PairingEngine>::G2> {
854    //     let SignedMessage { message, publickey, signature } = x;
855    //     let publickey = PublicKey::<E>::from_bytes(publickey.to_bytes()).unwrap();
856    //     let signature = Signature::<E>::from_bytes(signature.to_bytes()).unwrap();
857    //     assert!(SignedMessage { message, publickey, signature } == x);
858    // }
859
860    fn test_single_bls_message<E: PairingEngine, P: Bls12Config + CurveExtraConfig>()
861    where
862        <P as Bls12Config>::G2Config: WBConfig,
863        WBMap<<P as Bls12Config>::G2Config>: MapToCurve<<E as PairingEngine>::G2>,
864    {
865        let good = Message::new(b"ctx", b"test message");
866
867        let mut keypair = Keypair::<UsualBLS<E, P>>::generate(thread_rng());
868        let good_sig0 = keypair.signed_message(&good);
869        let good_sig = bls_engine_serialization_test::<UsualBLS<E, P>, E, P>(good_sig0);
870        assert!(good_sig.verify_slow());
871
872        let keypair_vt = keypair.into_vartime();
873        assert!(keypair_vt.secret.0 == keypair_vt.into_split(thread_rng()).into_vartime().secret.0);
874        assert!(good_sig == keypair.signed_message(&good));
875        assert!(good_sig == keypair_vt.signed_message(&good));
876
877        let bad = Message::new(b"ctx", b"wrong message");
878        let bad_sig0 = keypair.signed_message(&bad);
879        let bad_sig = bls_engine_serialization_test::<UsualBLS<E, P>, E, P>(bad_sig0);
880        assert!(bad_sig == keypair.into_vartime().signed_message(&bad));
881
882        assert!(bad_sig.verify());
883
884        let another = Message::new(b"ctx", b"another message");
885        let another_sig = keypair.signed_message(&another);
886        assert!(another_sig == keypair.into_vartime().signed_message(&another));
887        assert!(another_sig.verify());
888
889        assert!(
890            keypair.public.verify(&good, &good_sig.signature),
891            "Verification of a valid signature failed!"
892        );
893
894        assert!(good != bad, "good == bad");
895        assert!(
896            good_sig.signature != bad_sig.signature,
897            "good sig == bad sig"
898        );
899
900        assert!(
901            !keypair.public.verify(&good, &bad_sig.signature),
902            "Verification of a signature on a different message passed!"
903        );
904        assert!(
905            !keypair.public.verify(&bad, &good_sig.signature),
906            "Verification of a signature on a different message passed!"
907        );
908        assert!(
909            !keypair.public.verify(
910                &Message::new(b"other", b"test message"),
911                &good_sig.signature
912            ),
913            "Verification of a signature on a different message passed!"
914        );
915    }
916
917    #[test]
918    fn zbls_engine_bytes_test() {
919        let mut keypair =
920            Keypair::<UsualBLS<Bls12_381, ark_bls12_381::Config>>::generate(thread_rng());
921        let good_sig0 = keypair.signed_message(&Message::new(b"ctx", b"test message"));
922
923        bls_engine_serialization_test::<
924            UsualBLS<Bls12_381, ark_bls12_381::Config>,
925            Bls12_381,
926            ark_bls12_381::Config,
927        >(good_sig0);
928    }
929    #[test]
930    fn bls377_engine_bytes_test() {
931        let mut keypair =
932            Keypair::<UsualBLS<Bls12_377, ark_bls12_377::Config>>::generate(thread_rng());
933        let good_sig0 = keypair.signed_message(&Message::new(b"ctx", b"test message"));
934
935        bls_engine_serialization_test::<
936            UsualBLS<Bls12_377, ark_bls12_377::Config>,
937            Bls12_377,
938            ark_bls12_377::Config,
939        >(good_sig0);
940    }
941
942    #[test]
943    fn tiny_zbls_engine_bytes_test() {
944        let mut keypair =
945            Keypair::<TinyBLS<Bls12_381, ark_bls12_381::Config>>::generate(thread_rng());
946        let good_sig0 = keypair.signed_message(&Message::new(b"ctx", b"test message"));
947
948        bls_engine_serialization_test::<
949            TinyBLS<Bls12_381, ark_bls12_381::Config>,
950            Bls12_381,
951            ark_bls12_381::Config,
952        >(good_sig0);
953    }
954
955    #[test]
956    fn tiny_bls377_engine_bytes_test() {
957        let mut keypair =
958            Keypair::<TinyBLS<Bls12_377, ark_bls12_377::Config>>::generate(thread_rng());
959        let good_sig0 = keypair.signed_message(&Message::new(b"ctx", b"test message"));
960
961        bls_engine_serialization_test::<
962            TinyBLS<Bls12_377, ark_bls12_377::Config>,
963            Bls12_377,
964            ark_bls12_377::Config,
965        >(good_sig0);
966    }
967
968    #[test]
969    fn single_messages_zbls() {
970        test_single_bls_message::<Bls12_381, ark_bls12_381::Config>();
971    }
972
973    #[test]
974    fn single_messages_bls377() {
975        test_single_bls_message::<Bls12_377, ark_bls12_377::Config>();
976    }
977
978    #[test]
979    fn test_secret_key_serialization_for_zbls() {
980        test_serialize_deserialize_production_secret_key::<Bls12_381, ark_bls12_381::Config>();
981    }
982
983    #[test]
984    fn test_secret_key_serialization_for_bls377() {
985        test_serialize_deserialize_production_secret_key::<Bls12_377, ark_bls12_377::Config>();
986    }
987
988    #[test]
989    fn test_deserialize_random_value_as_secret_key_fails_for_bls377() {
990        let random_seed = hex!("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60");
991        test_deserialize_random_value_as_secret_key_fails::<Bls12_377, ark_bls12_377::Config>(
992            random_seed.as_slice(),
993        );
994    }
995}