w3f-bls 0.3.1

Aggregate BLS-like signatures
Documentation
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use alloc::vec;
use alloc::vec::Vec;

use ark_ec::{CurveGroup, PrimeGroup, VariableBaseMSM};
use ark_ff::field_hashers::{DefaultFieldHasher, HashToField};

use digest::FixedOutputReset;

#[cfg(feature = "benchmark")]
use std::time::Instant;

use crate::dual_scalar_mul::DualScalarMultiplication;
use crate::engine::EngineBLS;
use crate::nugget::{NuggetBLS, NuggetPublicKey, NuggetSignature};
use crate::serialize::SerializableToBytes;
use crate::{Message, SecretKey, SecretKeyVT};

pub type DLEQProof<E> = (<E as EngineBLS>::Scalar, <E as EngineBLS>::Scalar);
pub type ChaumPedersenSignature<E> = NuggetSignature<E>;

/// Chaum-Pedersen signer trait, implemented by secret-key types: produces a
/// BLS signature paired with a DLEQ proof that the same secret discrete log
/// links the public key (in the sister group) and the signature (in the
/// signature group).
///
/// `ChaumPedersenDleqProver` supertrait is the private part of the trait
/// that is not exposed to API
#[allow(private_bounds)]
pub trait ChaumPedersenSigner<E: EngineBLS, S: CurveGroup, H: FixedOutputReset + Default + Clone>:
    ChaumPedersenDleqProver<E, S, H>
where
    S: PrimeGroup<ScalarField = E::Scalar>,
{
    /// The proof of possession generator is supposed to
    /// to produce a schnoor signature of the message using
    /// the secret key which it claim to possess.
    fn generate_cp_signature(&mut self, message: &Message) -> ChaumPedersenSignature<E>;
}

/// Internal helpers backing `generate_cp_signature`shouldn't be called directly
trait ChaumPedersenDleqProver<E: EngineBLS, S: CurveGroup, H: FixedOutputReset + Default + Clone>
where
    S: PrimeGroup<ScalarField = E::Scalar>,
{
    fn generate_witness_scaler(
        &self,
        message_point_as_bytes: &Vec<u8>,
        signature_point_as_bytes: &Vec<u8>,
        public_key_in_signature_group_as_bytes: &Vec<u8>,
    ) -> <<E as EngineBLS>::PublicKeyGroup as PrimeGroup>::ScalarField;

    fn generate_dleq_proof(
        &mut self,
        message: &Message,
        bls_signature: E::SignatureGroup,
    ) -> DLEQProof<E>;
}

/// This should be implemented by public key
pub trait ChaumPedersenVerifier<
    E: EngineBLS,
    S: CurveGroup + DualScalarMultiplication + SerializableToBytes,
    H: FixedOutputReset + Default + Clone,
>: NuggetPublicKey<E, S> where
    S: PrimeGroup<ScalarField = E::Scalar>,
    E::SignatureGroup: DualScalarMultiplication,
{
    #[allow(non_snake_case)]
    fn verify_cp_signature_naive(
        &self,
        message: &Message,
        signature_proof: &ChaumPedersenSignature<E>,
    ) -> bool {
        #[cfg(feature = "benchmark")]
        let total_start = Instant::now();

        let signature_as_scalars_of_sister_group: (S::ScalarField, S::ScalarField) =
            (signature_proof.1.0, signature_proof.1.1);
        let message_as_point_on_signature_curve = message.hash_to_signature_curve::<E>();

        #[cfg(feature = "benchmark")]
        let start = Instant::now();
        let A_check_point = <S as PrimeGroup>::generator() * signature_as_scalars_of_sister_group.1
            + self.to_public_key_in_sister_group().0 * signature_as_scalars_of_sister_group.0;
        #[cfg(feature = "benchmark")]
        println!(
            "[Naive] A_check_point (2 scalar muls + add): {:?}",
            start.elapsed()
        );

        #[cfg(feature = "benchmark")]
        let start = Instant::now();
        let B_check_point = message_as_point_on_signature_curve * signature_proof.1.1
            + signature_proof.0 * signature_proof.1.0;
        #[cfg(feature = "benchmark")]
        println!(
            "[Naive] B_check_point (2 scalar muls + add): {:?}",
            start.elapsed()
        );

        let A_point_as_bytes = A_check_point.to_bytes();
        let B_point_as_bytes = E::signature_point_to_byte(&B_check_point);

        let signature_point_as_bytes = E::signature_point_to_byte(&signature_proof.0);
        let message_point_as_bytes =
            E::signature_point_to_byte(&message_as_point_on_signature_curve);
        let public_key_in_signature_group_as_bytes =
            E::signature_point_to_byte(&self.to_public_key_in_signature_group().0);

        let resulting_proof_basis = [
            message_point_as_bytes,
            public_key_in_signature_group_as_bytes,
            signature_point_as_bytes,
            A_point_as_bytes,
            B_point_as_bytes,
        ]
        .concat();

        let hasher = <DefaultFieldHasher<H> as HashToField<
            <<E as EngineBLS>::PublicKeyGroup as PrimeGroup>::ScalarField,
        >>::new(&[]);
        let c_check: <<E as EngineBLS>::PublicKeyGroup as PrimeGroup>::ScalarField =
            hasher.hash_to_field::<1>(resulting_proof_basis.as_slice())[0];

        #[cfg(feature = "benchmark")]
        println!("[Naive] TOTAL: {:?}", total_start.elapsed());

        c_check == signature_proof.1.0
    }

    #[allow(non_snake_case)]
    fn verify_cp_signature(
        &self,
        message: &Message,
        signature_proof: &ChaumPedersenSignature<E>,
    ) -> bool {
        #[cfg(feature = "benchmark")]
        let total_start = Instant::now();

        let signature_as_scalars_of_sister_group: (S::ScalarField, S::ScalarField) =
            (signature_proof.1.0, signature_proof.1.1);
        let generator = <S as PrimeGroup>::generator();
        let pubkey = self.to_public_key_in_sister_group().0;

        let message_as_point_on_signature_curve = message.hash_to_signature_curve::<E>();
        let message_point_as_bytes =
            E::signature_point_to_byte(&message_as_point_on_signature_curve);

        #[cfg(feature = "benchmark")]
        let start = Instant::now();
        let A_check_point = S::dual_scalar_mul(
            &signature_as_scalars_of_sister_group.1,
            &signature_as_scalars_of_sister_group.0,
            &generator,
            &pubkey,
            Some(self.straus_sister_group_precomputed_points()),
        );
        #[cfg(feature = "benchmark")]
        println!(
            "[CP] A_check_point (dual_scalar_mul): {:?}",
            start.elapsed()
        );

        #[cfg(feature = "benchmark")]
        let start = Instant::now();
        let B_check_point = E::SignatureGroup::dual_scalar_mul(
            &signature_proof.1.0,
            &signature_proof.1.1,
            &signature_proof.0,
            &message_as_point_on_signature_curve,
            None, //not precomputed //Some(&[signature_proof.0 + message.hash_to_signature_curve::<E>()]),
        );
        #[cfg(feature = "benchmark")]
        println!(
            "[CP] B_check_point (dual_scalar_mul): {:?}",
            start.elapsed()
        );

        let A_point_as_bytes = A_check_point.to_bytes();
        let B_point_as_bytes = E::signature_point_to_byte(&B_check_point);

        let signature_point_as_bytes = E::signature_point_to_byte(&signature_proof.0);
        let public_key_in_signature_group_as_bytes =
            E::signature_point_to_byte(&self.to_public_key_in_signature_group().0);

        let resulting_proof_basis = [
            message_point_as_bytes,
            public_key_in_signature_group_as_bytes,
            signature_point_as_bytes,
            A_point_as_bytes,
            B_point_as_bytes,
        ]
        .concat();

        let hasher = <DefaultFieldHasher<H> as HashToField<
            <<E as EngineBLS>::PublicKeyGroup as PrimeGroup>::ScalarField,
        >>::new(&[]);
        let c_check: <<E as EngineBLS>::PublicKeyGroup as PrimeGroup>::ScalarField =
            hasher.hash_to_field::<1>(resulting_proof_basis.as_slice())[0];

        #[cfg(feature = "benchmark")]
        println!("[CP] TOTAL: {:?}", total_start.elapsed());

        c_check == signature_proof.1.0
    }

    #[allow(non_snake_case)]
    fn verify_cp_signature_with_msm_optimization(
        &self,
        message: &Message,
        signature_proof: &ChaumPedersenSignature<E>,
    ) -> bool {
        let signature_as_scalars_of_sister_group: (S::ScalarField, S::ScalarField) =
            (signature_proof.1.0, signature_proof.1.1);

        let message_as_point_on_signature_curve = message.hash_to_signature_curve::<E>();

        let A_check_point = S::msm(
            (vec![
                <S as PrimeGroup>::generator().into_affine(),
                self.to_public_key_in_sister_group().0.into_affine(),
            ])
            .as_slice(),
            (vec![
                signature_as_scalars_of_sister_group.1,
                signature_as_scalars_of_sister_group.0,
            ])
            .as_slice(),
        )
        .unwrap();

        let B_check_point = E::SignatureGroup::msm(
            (vec![
                signature_proof.0.into_affine(),
                message_as_point_on_signature_curve.into_affine(),
            ])
            .as_slice(),
            (vec![signature_proof.1.0, signature_proof.1.1]).as_slice(),
        )
        .unwrap();

        let A_point_as_bytes = A_check_point.to_bytes();
        let B_point_as_bytes = E::signature_point_to_byte(&B_check_point);

        let signature_point_as_bytes = E::signature_point_to_byte(&signature_proof.0);
        let message_point_as_bytes =
            E::signature_point_to_byte(&message_as_point_on_signature_curve);
        let public_key_in_signature_group_as_bytes =
            E::signature_point_to_byte(&self.to_public_key_in_signature_group().0);

        let resulting_proof_basis = [
            message_point_as_bytes,
            public_key_in_signature_group_as_bytes,
            signature_point_as_bytes,
            A_point_as_bytes,
            B_point_as_bytes,
        ]
        .concat();

        let hasher = <DefaultFieldHasher<H> as HashToField<
            <<E as EngineBLS>::PublicKeyGroup as PrimeGroup>::ScalarField,
        >>::new(&[]);
        let c_check: <<E as EngineBLS>::PublicKeyGroup as PrimeGroup>::ScalarField =
            hasher.hash_to_field::<1>(resulting_proof_basis.as_slice())[0];

        c_check == signature_proof.1.0
    }
}

impl<E: EngineBLS, S: CurveGroup, H: FixedOutputReset + Default + Clone>
    ChaumPedersenSigner<E, S, H> for SecretKeyVT<E>
where
    S: PrimeGroup<ScalarField = E::Scalar> + SerializableToBytes,
{
    fn generate_cp_signature(&mut self, message: &Message) -> ChaumPedersenSignature<E> {
        //First we generate a vanila BLS Signature;
        let bls_signature = SecretKeyVT::sign(self, message);
        NuggetSignature(
            bls_signature.0,
            <SecretKeyVT<E> as ChaumPedersenDleqProver<E, S, H>>::generate_dleq_proof(
                self,
                message,
                bls_signature.0,
            ),
        )
    }
}

impl<E: EngineBLS, S: CurveGroup, H: FixedOutputReset + Default + Clone>
    ChaumPedersenDleqProver<E, S, H> for SecretKeyVT<E>
where
    S: PrimeGroup<ScalarField = E::Scalar> + SerializableToBytes,
{
    #[allow(non_snake_case)]
    fn generate_dleq_proof(
        &mut self,
        message: &Message,
        bls_signature: E::SignatureGroup,
    ) -> DLEQProof<E> {
        let signature_point = bls_signature;
        let message_point = message.hash_to_signature_curve::<E>();

        let signature_point_as_bytes = E::signature_point_to_byte(&signature_point);
        let message_point_as_bytes = E::signature_point_to_byte(&message_point);
        let public_key_in_signature_group_as_bytes = E::signature_point_to_byte(
            &NuggetBLS::<E, S>::to_public_key_in_signature_group(self).0,
        );

        // As a defense meauser everyting that is hashed in c and doesn't dependens on k is
        // also hashed in k.
        let mut k = <SecretKeyVT<E> as ChaumPedersenDleqProver<E, S, H>>::generate_witness_scaler(
            self,
            &message_point_as_bytes,
            &signature_point_as_bytes,
            &public_key_in_signature_group_as_bytes,
        );

        let A_point = <S as PrimeGroup>::generator() * k;
        let B_point = message_point * k;

        let A_point_as_bytes = A_point.to_bytes();
        let B_point_as_bytes = E::signature_point_to_byte(&B_point);

        let proof_basis = [
            message_point_as_bytes,
            public_key_in_signature_group_as_bytes,
            signature_point_as_bytes,
            A_point_as_bytes,
            B_point_as_bytes,
        ]
        .concat();

        let hasher = <DefaultFieldHasher<H> as HashToField<
            <<E as EngineBLS>::PublicKeyGroup as PrimeGroup>::ScalarField,
        >>::new(&[]);

        let c = hasher.hash_to_field::<1>(proof_basis.as_slice())[0];

        let s = k - c * self.0;

        ::zeroize::Zeroize::zeroize(&mut k); //clear secret witness from memory

        (c, s)
    }

    fn generate_witness_scaler(
        &self,
        message_point_as_bytes: &Vec<u8>,
        signature_point_as_bytes: &Vec<u8>,
        public_key_in_signature_group_as_bytes: &Vec<u8>,
    ) -> <<E as EngineBLS>::PublicKeyGroup as PrimeGroup>::ScalarField {
        let mut secret_key_hasher = H::default();

        let mut secret_key_as_bytes = self.to_bytes();
        secret_key_hasher.update(secret_key_as_bytes.as_slice());
        ::zeroize::Zeroize::zeroize(secret_key_as_bytes.as_mut_slice());

        let hashed_secret_key = secret_key_hasher.finalize_fixed_reset().to_vec();

        let hasher = <DefaultFieldHasher<H> as HashToField<
            <<E as EngineBLS>::PublicKeyGroup as PrimeGroup>::ScalarField,
        >>::new(&[]);
        let scalar_seed = [
            hashed_secret_key,
            message_point_as_bytes.clone(),
            public_key_in_signature_group_as_bytes.clone(),
            signature_point_as_bytes.clone(),
        ]
        .concat();
        hasher.hash_to_field::<1>(scalar_seed.as_slice())[0]
    }
}

/// Side-channel-protected variant: BLS signing goes through
/// `SecretKey::seeded_sign` (resplits the key with deterministic
/// randomness), while DLEQ proof generation and witness derivation
/// delegate to the vartime form, which is acceptable because they
/// operate over auxiliary scalars rather than the long-term key.
impl<E: EngineBLS, S: CurveGroup, H: FixedOutputReset + Default + Clone>
    ChaumPedersenDleqProver<E, S, H> for SecretKey<E>
where
    S: PrimeGroup<ScalarField = E::Scalar> + SerializableToBytes,
{
    fn generate_dleq_proof(
        &mut self,
        message: &Message,
        bls_signature: E::SignatureGroup,
    ) -> DLEQProof<E> {
        <SecretKeyVT<E> as ChaumPedersenDleqProver<E, S, H>>::generate_dleq_proof(
            &mut self.to_vartime(),
            message,
            bls_signature,
        )
    }

    fn generate_witness_scaler(
        &self,
        message_point_as_bytes: &Vec<u8>,
        signature_point_as_bytes: &Vec<u8>,
        public_key_in_signature_group_as_bytes: &Vec<u8>,
    ) -> <<E as EngineBLS>::PublicKeyGroup as PrimeGroup>::ScalarField {
        <SecretKeyVT<E> as ChaumPedersenDleqProver<E, S, H>>::generate_witness_scaler(
            &self.to_vartime(),
            message_point_as_bytes,
            signature_point_as_bytes,
            public_key_in_signature_group_as_bytes,
        )
    }
}

impl<E: EngineBLS, S: CurveGroup, H: FixedOutputReset + Default + Clone>
    ChaumPedersenSigner<E, S, H> for SecretKey<E>
where
    S: PrimeGroup<ScalarField = E::Scalar> + SerializableToBytes,
{
    fn generate_cp_signature(&mut self, message: &Message) -> ChaumPedersenSignature<E> {
        let bls_signature = self.seeded_sign(message);
        let dleq = <Self as ChaumPedersenDleqProver<E, S, H>>::generate_dleq_proof(
            self,
            message,
            bls_signature.0,
        );
        NuggetSignature(bls_signature.0, dleq)
    }
}

#[cfg(all(test, feature = "std"))]
mod tests {
    use rand::thread_rng;

    use super::*;

    use crate::double_nugget_glv::{DoubleNuggetBLSGLV, NuggetDoublePublicKeyGLV};
    use crate::{DoubleNuggetBLS, Keypair, NuggetDoublePublicKey, TinyBLS381};
    use sha2::Sha256;

    #[test]
    fn test_chaum_pedersen_verification() {
        type EB = TinyBLS381;

        let message = Message::new(b"ctx", b"test message");

        let mut keypair = Keypair::<EB>::generate(thread_rng());
        let good_sig = <Keypair<EB> as NuggetBLS<EB, <EB as EngineBLS>::SignatureGroup>>::sign(
            &mut keypair,
            &message,
        );

        let publickey: NuggetDoublePublicKey<EB> =
            DoubleNuggetBLS::<EB>::to_nugget_double_public_key(&keypair);

        assert!(ChaumPedersenVerifier::<
            EB,
            <EB as EngineBLS>::SignatureGroup,
            Sha256,
        >::verify_cp_signature_naive(
            &publickey, &message, &good_sig,
        ));

        assert!(ChaumPedersenVerifier::<
            EB,
            <EB as EngineBLS>::SignatureGroup,
            Sha256,
        >::verify_cp_signature(
            &publickey, &message, &good_sig,
        ));

        assert!(ChaumPedersenVerifier::<
            EB,
            <EB as EngineBLS>::SignatureGroup,
            Sha256,
        >::verify_cp_signature_with_msm_optimization(
            &publickey, &message, &good_sig,
        ));

        let publickey_glv: NuggetDoublePublicKeyGLV<EB> =
            DoubleNuggetBLSGLV::<EB>::to_nugget_double_public_key(&keypair);

        assert!(ChaumPedersenVerifier::<
            EB,
            <EB as EngineBLS>::SignatureGroup,
            Sha256,
        >::verify_cp_signature(
            &publickey_glv, &message, &good_sig,
        ));
    }

    #[test]
    #[cfg(feature = "experimental")]
    fn test_chaum_pedersen_verification_weierstrass_sister_curve() {
        #[cfg(feature = "benchmark")]
        use std::time::Instant;

        use crate::experimental::triple_nugget::{NuggetTriplePublicKey, TripleNuggetBLS};
        use ark_sw_by_bls12_381::SWProjective;

        type EB = TinyBLS381;
        type S = SWProjective;

        let message = Message::new(b"ctx", b"test message");

        let mut keypair = Keypair::<EB>::generate(thread_rng());
        let good_sig = <Keypair<EB> as NuggetBLS<EB, S>>::sign(&mut keypair, &message);

        let publickey: NuggetTriplePublicKey<EB, S> =
            TripleNuggetBLS::<EB, S>::to_nugget_triple_public_key(&keypair);

        #[cfg(feature = "benchmark")]
        let start = Instant::now();
        assert!(
            ChaumPedersenVerifier::<EB, S, Sha256>::verify_cp_signature_naive(
                &publickey, &message, &good_sig,
            )
        );
        #[cfg(feature = "benchmark")]
        println!("[SW Test] verify_cp_signature_naive: {:?}", start.elapsed());

        #[cfg(feature = "benchmark")]
        let start = Instant::now();
        assert!(ChaumPedersenVerifier::<EB, S, Sha256>::verify_cp_signature(
            &publickey, &message, &good_sig,
        ));
        #[cfg(feature = "benchmark")]
        println!(
            "[SW Test] verify_cp_signature (Strauss-Shamir): {:?}",
            start.elapsed()
        );

        #[cfg(feature = "benchmark")]
        let start = Instant::now();
        assert!(
            ChaumPedersenVerifier::<EB, S, Sha256>::verify_cp_signature_with_msm_optimization(
                &publickey, &message, &good_sig,
            )
        );
        #[cfg(feature = "benchmark")]
        println!(
            "[SW Test] verify_cp_signature_with_msm_optimization: {:?}",
            start.elapsed()
        );

        // Also test with G1 as the sister group (GLV path)
        let good_sig_g1_as_sister = <Keypair<EB> as NuggetBLS<
            EB,
            <EB as EngineBLS>::SignatureGroup,
        >>::sign(&mut keypair, &message);

        let publickey_glv: NuggetDoublePublicKeyGLV<EB> =
            DoubleNuggetBLSGLV::<EB>::to_nugget_double_public_key(&keypair);

        #[cfg(feature = "benchmark")]
        let start = Instant::now();
        assert!(ChaumPedersenVerifier::<
            EB,
            <EB as EngineBLS>::SignatureGroup,
            Sha256,
        >::verify_cp_signature(
            &publickey_glv,
            &message,
            &good_sig_g1_as_sister,
        ));
        #[cfg(feature = "benchmark")]
        println!(
            "[G1 Test] verify_cp_signature (Straus+GLV G1 as Sister): {:?}",
            start.elapsed()
        );
    }
}