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
//! Different variants of the BLS signature scheme.
use super::{
group::{
Point, DST, G1, G1_MESSAGE, G1_PROOF_OF_POSSESSION, G2, G2_MESSAGE, G2_PROOF_OF_POSSESSION,
GT,
},
Error,
};
use crate::bls12381::primitives::group::{Element, Scalar};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use blst::{
blst_final_exp, blst_fp12, blst_miller_loop, Pairing as blst_pairing, BLS12_381_NEG_G1,
BLS12_381_NEG_G2,
};
use commonware_codec::FixedSize;
use core::{
fmt::{Debug, Formatter},
hash::Hash,
};
use rand_core::CryptoRngCore;
/// A specific instance of a signature scheme.
pub trait Variant: Clone + Send + Sync + Hash + Eq + Debug + 'static {
/// The public key type.
type Public: Point + FixedSize + Debug + Hash + Copy + AsRef<Self::Public>;
/// The signature type.
type Signature: Point + FixedSize + Debug + Hash + Copy + AsRef<Self::Signature>;
/// The domain separator tag (DST) for a proof of possession.
const PROOF_OF_POSSESSION: DST;
/// The domain separator tag (DST) for a message.
const MESSAGE: DST;
/// Verify the signature from the provided public key and pre-hashed message.
fn verify(
public: &Self::Public,
hm: &Self::Signature,
signature: &Self::Signature,
) -> Result<(), Error>;
/// Verify a batch of signatures from the provided public keys and pre-hashed messages.
fn batch_verify<R: CryptoRngCore>(
rng: &mut R,
publics: &[Self::Public],
hms: &[Self::Signature],
signatures: &[Self::Signature],
) -> Result<(), Error>;
/// Compute the pairing `e(G1, G2) -> GT`.
fn pairing(public: &Self::Public, signature: &Self::Signature) -> GT;
}
/// A [Variant] with a public key of type [G1] and a signature of type [G2].
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct MinPk {}
impl Variant for MinPk {
type Public = G1;
type Signature = G2;
const PROOF_OF_POSSESSION: DST = G2_PROOF_OF_POSSESSION;
const MESSAGE: DST = G2_MESSAGE;
/// Verifies that `e(hm,pk)` is equal to `e(sig,G1::one())` using a single product check with
/// a negated G1 generator (`e(hm,pk) * e(sig,-G1::one()) == 1`).
fn verify(
public: &Self::Public,
hm: &Self::Signature,
signature: &Self::Signature,
) -> Result<(), Error> {
// Create a pairing context
//
// We only handle pre-hashed messages, so we leave the domain separator tag (`DST`) empty.
let mut pairing = blst_pairing::new(false, &[]);
// Convert `sig` into affine and aggregate `e(sig,-G1::one())`
let q = signature.as_blst_p2_affine();
unsafe {
pairing.raw_aggregate(&q, &BLS12_381_NEG_G1);
}
// Convert `pk` and `hm` into affine
let p = public.as_blst_p1_affine();
let q = hm.as_blst_p2_affine();
// Aggregate `e(hm,pk)`
pairing.raw_aggregate(&q, &p);
// Finalize the pairing accumulation and verify the result
//
// If `finalverify()` returns `true`, it means `e(hm,pk) * e(sig,-G1::one()) == 1`. This
// is equivalent to `e(hm,pk) == e(sig,G1::one())`.
pairing.commit();
if !pairing.finalverify(None) {
return Err(Error::InvalidSignature);
}
Ok(())
}
/// Verifies a set of signatures against their respective public keys and pre-hashed messages.
///
/// This method is outperforms individual signature verification (`2` pairings per signature) by
/// verifying a random linear combination of the public keys and signatures (`n+1` pairings and
/// `2n` multiplications for `n` signatures).
///
/// The verification equation for each signature `i` is:
/// `e(hm_i,pk_i) == e(sig_i,G1::one())`,
/// which is equivalent to checking if `e(hm_i,pk_i) * e(sig_i,-G1::one()) == 1`.
///
/// To batch verify `n` such equations, we introduce random non-zero scalars `r_i` (for `i=1..n`).
/// The batch verification checks if the product of these individual equations, each raised to the power
/// of its respective `r_i`, equals one:
/// `prod_i((e(hm_i,pk_i) * e(sig_i,-G1::one()))^{r_i}) == 1`
///
/// Using the bilinearity of pairings, this can be rewritten (by moving `r_i` inside the pairings):
/// `prod_i(e(hm_i,r_i * pk_i) * e(r_i * sig_i,-G1::one())) == 1`
///
/// The second term `e(r_i * sig_i,-G1::one())` can be computed efficiently with Multi-Scalar Multiplication:
/// `e(sum_i(r_i * sig_i),-G1::one())`
///
/// Finally, we aggregate all pairings `e(hm_i,r_i * pk_i)` (`n`) and `e(sum_i(r_i * sig_i),-G1::one())` (`1`)
/// into a single product in the target group `G_T`. If the result is the identity element in `G_T`,
/// the batch verification succeeds.
///
/// Source: <https://ethresear.ch/t/security-of-bls-batch-verification/10748>
fn batch_verify<R: CryptoRngCore>(
rng: &mut R,
publics: &[Self::Public],
hms: &[Self::Signature],
signatures: &[Self::Signature],
) -> Result<(), Error> {
// Ensure there is an equal number of public keys, messages, and signatures.
assert_eq!(publics.len(), hms.len());
assert_eq!(publics.len(), signatures.len());
if publics.is_empty() {
return Ok(());
}
// Generate random non-zero scalars.
let scalars: Vec<Scalar> = (0..publics.len())
.map(|_| loop {
let scalar = Scalar::from_rand(rng);
if scalar != Scalar::zero() {
return scalar;
}
})
.collect();
// Compute S_agg = sum(r_i * sig_i) using Multi-Scalar Multiplication (MSM).
let s_agg = G2::msm(signatures, &scalars);
// Initialize pairing context. DST is empty as we use pre-hashed messages.
let mut pairing = blst_pairing::new(false, &[]);
// Aggregate the single term corresponding to signatures: e(-G1::one(),S_agg)
let s_agg_affine = s_agg.as_blst_p2_affine();
unsafe {
pairing.raw_aggregate(&s_agg_affine, &BLS12_381_NEG_G1);
}
// Aggregate the `n` terms corresponding to public keys and messages: e(r_i * pk_i,hm_i)
for i in 0..publics.len() {
let mut scaled_pk = publics[i];
scaled_pk.mul(&scalars[i]);
let pk_affine = scaled_pk.as_blst_p1_affine();
let hm_affine = hms[i].as_blst_p2_affine();
pairing.raw_aggregate(&hm_affine, &pk_affine);
}
// Perform the final verification on the product of (n+1) pairing terms.
pairing.commit();
if !pairing.finalverify(None) {
return Err(Error::InvalidSignature);
}
Ok(())
}
/// Compute the pairing `e(public, signature) -> GT`.
fn pairing(public: &Self::Public, signature: &Self::Signature) -> GT {
let p1_affine = public.as_blst_p1_affine();
let p2_affine = signature.as_blst_p2_affine();
let mut result = blst_fp12::default();
unsafe {
blst_miller_loop(&mut result, &p2_affine, &p1_affine);
blst_final_exp(&mut result, &result);
}
GT::from_blst_fp12(result)
}
}
impl Debug for MinPk {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
f.debug_struct("MinPk").finish()
}
}
/// A [Variant] with a public key of type [G2] and a signature of type [G1].
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct MinSig {}
impl Variant for MinSig {
type Public = G2;
type Signature = G1;
const PROOF_OF_POSSESSION: DST = G1_PROOF_OF_POSSESSION;
const MESSAGE: DST = G1_MESSAGE;
/// Verifies that `e(pk,hm)` is equal to `e(G2::one(),sig)` using a single product check with
/// a negated G2 generator (`e(pk,hm) * e(-G2::one(),sig) == 1`).
fn verify(
public: &Self::Public,
hm: &Self::Signature,
signature: &Self::Signature,
) -> Result<(), Error> {
// Create a pairing context
//
// We only handle pre-hashed messages, so we leave the domain separator tag (`DST`) empty.
let mut pairing = blst_pairing::new(false, &[]);
// Convert `sig` into affine and aggregate `e(-G2::one(), sig)`
let q = signature.as_blst_p1_affine();
unsafe {
pairing.raw_aggregate(&BLS12_381_NEG_G2, &q);
}
// Convert `pk` and `hm` into affine
let p = public.as_blst_p2_affine();
let q = hm.as_blst_p1_affine();
// Aggregate `e(pk,hm)`
pairing.raw_aggregate(&p, &q);
// Finalize the pairing accumulation and verify the result
//
// If `finalverify()` returns `true`, it means `e(pk,hm) * e(-G2::one(),sig) == 1`. This
// is equivalent to `e(pk,hm) == e(G2::one(),sig)`.
pairing.commit();
if !pairing.finalverify(None) {
return Err(Error::InvalidSignature);
}
Ok(())
}
/// Verifies a set of signatures against their respective public keys and pre-hashed messages.
///
/// This method outperforms individual signature verification (`2` pairings per signature) by
/// verifying a random linear combination of the public keys and signatures (`n+1` pairings and
/// `2n` multiplications for `n` signatures).
///
/// The verification equation for each signature `i` is:
/// `e(pk_i,hm_i) == e(G2::one(),sig_i)`,
/// which is equivalent to checking if `e(pk_i,hm_i) * e(-G2::one(),sig_i) == 1`.
///
/// To batch verify `n` such equations, we introduce random non-zero scalars `r_i` (for `i=1..n`).
/// The batch verification checks if the product of these individual equations, each effectively
/// raised to the power of its respective `r_i`, equals one:
/// `prod_i((e(pk_i,hm_i) * e(-G2::one(),sig_i))^{r_i}) == 1`
///
/// Using the bilinearity of pairings, this can be rewritten (by moving `r_i` inside the pairings):
/// `prod_i(e(r_i * pk_i,hm_i) * e(-G2::one(),r_i * sig_i)) == 1`
///
/// The second term `e(-G2::one(),r_i * sig_i)` can be computed efficiently with Multi-Scalar Multiplication:
/// `e(-G2::one(),sum_i(r_i * sig_i))`
///
/// Finally, we aggregate all pairings `e(r_i * pk_i,hm_i)` (`n`) and `e(-G2::one(),sum_i(r_i * sig_i))` (`1`)
/// into a single product in the target group `G_T`. If the result is the identity element in `G_T`,
/// the batch verification succeeds.
///
/// Source: <https://ethresear.ch/t/security-of-bls-batch-verification/10748>
fn batch_verify<R: CryptoRngCore>(
rng: &mut R,
publics: &[Self::Public],
hms: &[Self::Signature],
signatures: &[Self::Signature],
) -> Result<(), Error> {
// Ensure there is an equal number of public keys, messages, and signatures.
assert_eq!(publics.len(), hms.len());
assert_eq!(publics.len(), signatures.len());
if publics.is_empty() {
return Ok(());
}
// Generate random non-zero scalars.
let scalars: Vec<Scalar> = (0..publics.len())
.map(|_| loop {
let scalar = Scalar::from_rand(rng);
if scalar != Scalar::zero() {
return scalar;
}
})
.collect();
// Compute S_agg = sum(r_i * sig_i) using Multi-Scalar Multiplication (MSM).
let s_agg = G1::msm(signatures, &scalars);
// Initialize pairing context. DST is empty as we use pre-hashed messages.
let mut pairing = blst_pairing::new(false, &[]);
// Aggregate the single term corresponding to signatures: e(S_agg,-G2::one())
let s_agg_affine = s_agg.as_blst_p1_affine();
unsafe {
pairing.raw_aggregate(&BLS12_381_NEG_G2, &s_agg_affine);
}
// Aggregate the `n` terms corresponding to public keys and messages: e(hm_i, r_i * pk_i)
for i in 0..publics.len() {
let mut scaled_pk = publics[i];
scaled_pk.mul(&scalars[i]);
let pk_affine = scaled_pk.as_blst_p2_affine();
let hm_affine = hms[i].as_blst_p1_affine();
pairing.raw_aggregate(&pk_affine, &hm_affine);
}
// Perform the final verification on the product of (n+1) pairing terms.
pairing.commit();
if !pairing.finalverify(None) {
return Err(Error::InvalidSignature);
}
Ok(())
}
/// Compute the pairing `e(signature, public) -> GT`.
fn pairing(public: &Self::Public, signature: &Self::Signature) -> GT {
let p1_affine = signature.as_blst_p1_affine();
let p2_affine = public.as_blst_p2_affine();
let mut result = blst_fp12::default();
unsafe {
blst_miller_loop(&mut result, &p2_affine, &p1_affine);
blst_final_exp(&mut result, &result);
}
GT::from_blst_fp12(result)
}
}
impl Debug for MinSig {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
f.debug_struct("MinSig").finish()
}
}