fastcrypto 0.1.10

Common cryptographic library used at Mysten Labs
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
// Copyright (c) 2022, Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
#[macro_use]
extern crate criterion;

mod group_benches {
    use criterion::measurement::Measurement;
    use criterion::{measurement, BenchmarkGroup, BenchmarkId, Criterion};
    use fastcrypto::groups::bls12381::{
        G1Element, G1ElementUncompressed, G2Element, GTElement, Scalar as BlsScalar,
        G1_ELEMENT_BYTE_LENGTH, G2_ELEMENT_BYTE_LENGTH, GT_ELEMENT_BYTE_LENGTH, SCALAR_LENGTH,
    };
    use fastcrypto::groups::multiplier::windowed::WindowedScalarMultiplier;
    use fastcrypto::groups::multiplier::ScalarMultiplier;
    use fastcrypto::groups::ristretto255::RistrettoPoint;
    use fastcrypto::groups::{
        bls12381, secp256k1, secp256r1, FromTrustedByteArray, GroupElement, HashToGroupElement,
        MultiScalarMul, Pairing, Scalar,
    };
    use fastcrypto::serde_helpers::ToFromByteArray;
    use rand::thread_rng;

    fn add_single<G: GroupElement, M: measurement::Measurement>(
        name: &str,
        c: &mut BenchmarkGroup<M>,
    ) {
        let x = G::generator() * G::ScalarType::rand(&mut thread_rng());
        let y = G::generator() * G::ScalarType::rand(&mut thread_rng());
        c.bench_function(name.to_string(), move |b| b.iter(|| x + y));
    }

    fn add(c: &mut Criterion) {
        let mut group: BenchmarkGroup<_> = c.benchmark_group("Add");
        add_single::<G1Element, _>("BLS12381-G1", &mut group);
        add_single::<G2Element, _>("BLS12381-G2", &mut group);
        add_single::<GTElement, _>("BLS12381-GT", &mut group);
        add_single::<RistrettoPoint, _>("Ristretto255", &mut group);
    }

    fn scale_single<G: GroupElement, M: measurement::Measurement>(
        name: &str,
        c: &mut BenchmarkGroup<M>,
    ) {
        let x = G::generator() * G::ScalarType::rand(&mut thread_rng());
        let y = G::ScalarType::rand(&mut thread_rng());
        c.bench_function(name.to_string(), move |b| b.iter(|| x * y));
    }

    fn scale_single_precomputed<
        G: GroupElement,
        Mul: ScalarMultiplier<G, G::ScalarType>,
        M: Measurement,
    >(
        name: &str,
        c: &mut BenchmarkGroup<M>,
    ) {
        let x = G::generator() * G::ScalarType::rand(&mut thread_rng());
        let y = G::ScalarType::rand(&mut thread_rng());

        let multiplier = Mul::new(x, G::zero());
        c.bench_function(name.to_string(), move |b| b.iter(|| multiplier.mul(&y)));
    }

    fn scale(c: &mut Criterion) {
        let mut group: BenchmarkGroup<_> = c.benchmark_group("Scalar To Point Multiplication");
        scale_single::<G1Element, _>("BLS12381-G1", &mut group);
        scale_single::<G2Element, _>("BLS12381-G2", &mut group);
        scale_single::<GTElement, _>("BLS12381-GT", &mut group);
        scale_single::<RistrettoPoint, _>("Ristretto255", &mut group);
        scale_single::<secp256r1::ProjectivePoint, _>("Secp256r1", &mut group);

        scale_single_precomputed::<
            secp256r1::ProjectivePoint,
            WindowedScalarMultiplier<secp256r1::ProjectivePoint, secp256r1::Scalar, 16, 5>,
            _,
        >("Secp256r1 Fixed window (16)", &mut group);
        scale_single_precomputed::<
            secp256r1::ProjectivePoint,
            WindowedScalarMultiplier<secp256r1::ProjectivePoint, secp256r1::Scalar, 32, 5>,
            _,
        >("Secp256r1 Fixed window (32)", &mut group);
        scale_single_precomputed::<
            secp256r1::ProjectivePoint,
            WindowedScalarMultiplier<secp256r1::ProjectivePoint, secp256r1::Scalar, 64, 5>,
            _,
        >("Secp256r1 Fixed window (64)", &mut group);
        scale_single_precomputed::<
            secp256r1::ProjectivePoint,
            WindowedScalarMultiplier<secp256r1::ProjectivePoint, secp256r1::Scalar, 128, 5>,
            _,
        >("Secp256r1 Fixed window (128)", &mut group);
        scale_single_precomputed::<
            secp256r1::ProjectivePoint,
            WindowedScalarMultiplier<secp256r1::ProjectivePoint, secp256r1::Scalar, 256, 5>,
            _,
        >("Secp256r1 Fixed window (256)", &mut group);
    }

    fn msm_single<G: GroupElement + MultiScalarMul, M: Measurement>(
        name: &str,
        len: &usize,
        c: &mut BenchmarkGroup<M>,
    ) {
        let (scalars, points): (Vec<G::ScalarType>, Vec<G>) = (0..*len)
            .map(|_| {
                (
                    G::ScalarType::generator() * G::ScalarType::rand(&mut thread_rng()),
                    G::generator() * G::ScalarType::rand(&mut thread_rng()),
                )
            })
            .unzip();

        let scalars_copy = scalars.clone();
        let points_copy = points.clone();
        c.bench_function(BenchmarkId::new(name.to_string(), len), move |b| {
            b.iter(|| G::multi_scalar_mul(&scalars, &points).unwrap())
        });
        c.bench_function(BenchmarkId::new(format!("{} naive", name), len), move |b| {
            b.iter(|| msm_reference(&scalars_copy, &points_copy))
        });
    }

    /// A reference implementation of multi-scalar multiplication for benchmarking purposes.
    /// Computes the MSM using multiplication and addition in a straightforward manner.
    fn msm_reference<G: GroupElement + MultiScalarMul>(
        scalars: &[G::ScalarType],
        points: &[G],
    ) -> G {
        if scalars.len() != points.len() {
            panic!("Scalars and points must have the same length");
        }
        let mut result = G::zero();
        for (scalar, point) in scalars.iter().zip(points.iter()) {
            result += *point * scalar;
        }
        result
    }

    fn msm(c: &mut Criterion) {
        static INPUT_SIZES: [usize; 6] = [32, 64, 128, 256, 512, 1024];
        let mut group: BenchmarkGroup<_> = c.benchmark_group("MSM");
        for size in INPUT_SIZES.iter() {
            msm_single::<G1Element, _>("BLS12381-G1", size, &mut group);
        }
        for size in INPUT_SIZES.iter() {
            msm_single::<G2Element, _>("BLS12381-G2", size, &mut group);
        }
        for size in INPUT_SIZES.iter() {
            msm_single::<secp256k1::ProjectivePoint, _>("secp256k1", size, &mut group);
        }
    }

    fn double_scale_single<
        G: GroupElement,
        Mul: ScalarMultiplier<G, G::ScalarType>,
        M: Measurement,
    >(
        name: &str,
        c: &mut BenchmarkGroup<M>,
    ) {
        let g1 = G::generator() * G::ScalarType::rand(&mut thread_rng());
        let s1 = G::ScalarType::rand(&mut thread_rng());
        let g2 = G::generator() * G::ScalarType::rand(&mut thread_rng());
        let s2 = G::ScalarType::rand(&mut thread_rng());

        let multiplier = Mul::new(g1, G::zero());
        c.bench_function(name.to_string(), move |b| {
            b.iter(|| multiplier.two_scalar_mul(&s1, &g2, &s2))
        });
    }

    fn double_scale(c: &mut Criterion) {
        let mut group: BenchmarkGroup<_> = c.benchmark_group("Double Scalar Multiplication");

        double_scale_single::<
            secp256r1::ProjectivePoint,
            WindowedScalarMultiplier<secp256r1::ProjectivePoint, secp256r1::Scalar, 16, 5>,
            _,
        >("Secp256r1 Straus (16)", &mut group);
        double_scale_single::<
            secp256r1::ProjectivePoint,
            WindowedScalarMultiplier<secp256r1::ProjectivePoint, secp256r1::Scalar, 32, 5>,
            _,
        >("Secp256r1 Straus (32)", &mut group);
        double_scale_single::<
            secp256r1::ProjectivePoint,
            WindowedScalarMultiplier<secp256r1::ProjectivePoint, secp256r1::Scalar, 64, 5>,
            _,
        >("Secp256r1 Straus (64)", &mut group);
        double_scale_single::<
            secp256r1::ProjectivePoint,
            WindowedScalarMultiplier<secp256r1::ProjectivePoint, secp256r1::Scalar, 128, 5>,
            _,
        >("Secp256r1 Straus (128)", &mut group);
        double_scale_single::<
            secp256r1::ProjectivePoint,
            WindowedScalarMultiplier<secp256r1::ProjectivePoint, secp256r1::Scalar, 256, 5>,
            _,
        >("Secp256r1 Straus (256)", &mut group);
        double_scale_single::<
            secp256r1::ProjectivePoint,
            DefaultMultiplier<secp256r1::ProjectivePoint>,
            _,
        >("Secp256r1", &mut group);
    }

    fn hash_to_group_single<G: GroupElement + HashToGroupElement, M: measurement::Measurement>(
        name: &str,
        c: &mut BenchmarkGroup<M>,
    ) {
        let seed = b"Hello, World!";
        c.bench_function(name.to_string(), move |b| {
            b.iter(|| G::hash_to_group_element(seed))
        });
    }

    fn hash_to_group(c: &mut Criterion) {
        let mut group: BenchmarkGroup<_> = c.benchmark_group("Hash-to-group");
        hash_to_group_single::<G1Element, _>("BLS12381-G1", &mut group);
        hash_to_group_single::<G2Element, _>("BLS12381-G2", &mut group);
        hash_to_group_single::<RistrettoPoint, _>("Ristretto255", &mut group);
    }

    fn pairing_single<G: GroupElement + Pairing, M: measurement::Measurement>(
        name: &str,
        c: &mut BenchmarkGroup<M>,
    ) {
        let x = G::generator() * G::ScalarType::rand(&mut thread_rng());
        let y = G::Other::generator()
            * <<G as Pairing>::Other as GroupElement>::ScalarType::rand(&mut thread_rng());
        c.bench_function(name.to_string(), move |b| b.iter(|| G::pairing(&x, &y)));
    }

    fn pairing(c: &mut Criterion) {
        let mut group: BenchmarkGroup<_> = c.benchmark_group("Pairing");
        pairing_single::<G1Element, _>("BLS12381", &mut group);
    }

    fn multi_pairing_impl<G: GroupElement + Pairing, M: measurement::Measurement>(
        name: &str,
        len: usize,
        c: &mut BenchmarkGroup<M>,
    ) where
        <G as Pairing>::Output: GroupElement,
    {
        let (ps, qs): (Vec<G>, Vec<G::Other>) = (0..len)
            .map(|_| {
                (
                    G::generator() * G::ScalarType::rand(&mut thread_rng()),
                    G::Other::generator()
                        * <<G as Pairing>::Other as GroupElement>::ScalarType::rand(
                            &mut thread_rng(),
                        ),
                )
            })
            .unzip();
        c.bench_function(format!("{}/{}", name, len), move |b| {
            b.iter(|| G::multi_pairing(&ps, &qs))
        });
    }

    fn multi_pairing(c: &mut Criterion) {
        static NUMBER_OF_INPUTS: [usize; 3] = [2, 4, 8];
        let mut group: BenchmarkGroup<_> = c.benchmark_group("Multi-Pairing");

        for n in NUMBER_OF_INPUTS {
            multi_pairing_impl::<G1Element, _>("BLS12381", n, &mut group);
        }
    }

    fn sum(c: &mut Criterion) {
        static NUMBER_OF_TERMS: [usize; 4] = [10, 100, 500, 1000];

        for n in NUMBER_OF_TERMS {
            let terms: Vec<G1Element> = (0..n)
                .map(|_| G1Element::generator() * bls12381::Scalar::rand(&mut thread_rng()))
                .collect();

            let terms_uncompressed = terms
                .iter()
                .map(G1ElementUncompressed::from)
                .map(G1ElementUncompressed::into_byte_array)
                .collect::<Vec<_>>();

            let terms_compressed = terms
                .iter()
                .map(G1Element::to_byte_array)
                .collect::<Vec<_>>();

            c.bench_function(&format!("Sum/BLS12381-G1/{} uncompressed", n), move |b| {
                b.iter_batched(
                    || terms_uncompressed.clone(),
                    |t| {
                        let terms_deserialized = t
                            .into_iter()
                            .map(G1ElementUncompressed::from_trusted_byte_array)
                            .collect::<Vec<_>>();
                        G1ElementUncompressed::sum(terms_deserialized.as_slice())
                    },
                    criterion::BatchSize::SmallInput,
                )
            });

            c.bench_function(&format!("Sum/BLS12381-G1/{} compressed", n), move |b| {
                b.iter_batched(
                    || terms_compressed.clone(),
                    |t| {
                        t.iter()
                            .map(G1Element::from_trusted_byte_array)
                            .map(Result::unwrap)
                            .reduce(|a, b| a + b)
                    },
                    criterion::BatchSize::SmallInput,
                )
            });
        }
    }

    /// Implementation of a `Multiplier` where scalar multiplication is done without any pre-computation by
    /// simply calling the GroupElement implementation. Only used for benchmarking.
    struct DefaultMultiplier<G: GroupElement>(G);

    impl<G: GroupElement> ScalarMultiplier<G, G::ScalarType> for DefaultMultiplier<G> {
        fn new(base_element: G, _zero: G) -> Self {
            Self(base_element)
        }

        fn mul(&self, scalar: &G::ScalarType) -> G {
            self.0 * scalar
        }

        fn two_scalar_mul(
            &self,
            base_scalar: &G::ScalarType,
            other_element: &G,
            other_scalar: &G::ScalarType,
        ) -> G {
            self.0 * base_scalar + *other_element * other_scalar
        }
    }

    fn deser_single<
        G: GroupElement + ToFromByteArray<LENGTH> + FromTrustedByteArray<LENGTH>,
        M: Measurement,
        const LENGTH: usize,
    >(
        name: &str,
        trusted: bool,
        c: &mut BenchmarkGroup<M>,
    ) {
        let as_bytes = G::generator().to_byte_array();
        c.bench_function(name.to_string(), move |b| {
            b.iter(|| {
                if trusted {
                    G::from_trusted_byte_array(&as_bytes).unwrap()
                } else {
                    G::from_byte_array(&as_bytes).unwrap()
                }
            })
        });
    }

    fn deserialize(c: &mut Criterion) {
        let mut group: BenchmarkGroup<_> = c.benchmark_group("Deserialize");
        deser_single::<BlsScalar, _, { SCALAR_LENGTH }>(
            "BLS12381-Scalar-trusted",
            true,
            &mut group,
        );
        deser_single::<BlsScalar, _, { SCALAR_LENGTH }>("BLS12381-Scalar", false, &mut group);
        deser_single::<G1Element, _, { G1_ELEMENT_BYTE_LENGTH }>(
            "BLS12381-G1-trusted",
            true,
            &mut group,
        );
        deser_single::<G1Element, _, { G1_ELEMENT_BYTE_LENGTH }>("BLS12381-G1", false, &mut group);
        deser_single::<G2Element, _, { G2_ELEMENT_BYTE_LENGTH }>(
            "BLS12381-G2-trusted",
            true,
            &mut group,
        );
        deser_single::<G2Element, _, { G2_ELEMENT_BYTE_LENGTH }>("BLS12381-G2", false, &mut group);
        deser_single::<GTElement, _, { GT_ELEMENT_BYTE_LENGTH }>(
            "BLS12381-GT-trusted",
            true,
            &mut group,
        );
        deser_single::<GTElement, _, { GT_ELEMENT_BYTE_LENGTH }>("BLS12381-GT", false, &mut group);
    }

    criterion_group! {
        name = group_benches;
        config = Criterion::default().sample_size(100);
        targets =
            deserialize,
            add,
            scale,
            hash_to_group,
            pairing,
            multi_pairing,
            double_scale,
            msm,
            sum,
    }
}

criterion_main!(group_benches::group_benches,);