ark_algebra_test_templates/
groups.rs

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
#[macro_export]
#[doc(hidden)]
macro_rules! __test_group {
    ($group: ty) => {
        type ScalarField = <$group as PrimeGroup>::ScalarField;
        #[test]
        fn test_add_properties() {
            let mut rng = &mut ark_std::test_rng();
            let zero = <$group>::zero();
            for _ in 0..ITERATIONS {
                let a = <$group>::rand(rng);
                let b = <$group>::rand(rng);
                let c = <$group>::rand(rng);

                // Associativity
                assert_eq!((a + b) + c, a + (b + c));

                // Commutativity
                assert_eq!(a + b, b + a);

                // Identity
                assert_eq!(zero + a, a);
                assert_eq!(zero + b, b);
                assert_eq!(zero + c, c);
                assert_eq!(a + zero, a);
                assert_eq!(b + zero, b);
                assert_eq!(c + zero, c);

                // Negation
                assert_eq!(-a + a, zero);
                assert_eq!(-b + b, zero);
                assert_eq!(-c + c, zero);
                assert_eq!(-zero, zero);

                // Associativity and commutativity simultaneously
                let t0 = (a + &b) + &c; // (a + b) + c
                let t1 = (a + &c) + &b; // (a + c) + b
                let t2 = (b + &c) + &a; // (b + c) + a

                assert_eq!(t0, t1);
                assert_eq!(t1, t2);

                // Doubling
                assert_eq!(a.double(), a + a);
                assert_eq!(b.double(), b + b);
                assert_eq!(c.double(), c + c);
                assert_eq!(zero.double(), zero);
                assert_eq!((-zero).double(), zero);
            }
        }

        #[test]
        fn test_sub_properties() {
            use ark_std::UniformRand;
            let mut rng = test_rng();
            let zero = <$group>::zero();

            for _ in 0..ITERATIONS{
                // Anti-commutativity
                let a = <$group>::rand(&mut rng);
                let b = <$group>::rand(&mut rng);
                assert!(((a - b) + (b - a)).is_zero());

                // Identity
                assert_eq!(zero - a, -a);
                assert_eq!(zero - b, -b);

                assert_eq!(a - zero, a);
                assert_eq!(b - zero, b);

                // Affine - Projective
                assert_eq!(a.into_affine() - b, a - b);
            }
        }

        #[test]
        fn test_mul_properties() {
            use ark_std::UniformRand;
            let mut rng = test_rng();
            let zero = ScalarField::zero();
            let one = ScalarField::one();
            assert_eq!(one.inverse().unwrap(), one);
            assert!(one.is_one());

            for _ in 0..ITERATIONS {
                // Associativity
                let a = <$group>::rand(&mut rng);
                let b = ScalarField::rand(&mut rng);
                let c = ScalarField::rand(&mut rng);
                assert_eq!((a * b) * c, a * (b * c));

                // Identity
                assert_eq!(a * one, a);

                assert_eq!(a * zero, <$group>::zero());

                // Inverses
                assert_eq!((a * b.inverse().unwrap()) * b, a);

                // Distributivity
                assert_eq!(a * (b + c), a * b + a * c);

                // s ( a + b) using wNAF for several window values in [2,5]
                for w in 2..=5 {
                    let context = WnafContext::new(w);
                    assert_eq!(a * b, context.mul(a, &b));

                    let table = context.table(a);
                    assert_eq!(a * b, context.mul_with_table(&table, &b).unwrap());

                    if w > 2 {
                        let bad_context = WnafContext::new(w - 1);
                        let bad_table = bad_context.table(a);
                        assert_eq!(context.mul_with_table(&bad_table, &b), None);
                    }
                }

                // num_scalars != scalars.len()
                let mut scalars = vec![ScalarField::rand(&mut rng); 100];
                scalars[0] = ScalarField::zero();
                let table = BatchMulPreprocessing::new(a, scalars.len() - 1);
                let result = table.batch_mul(&scalars);
                let naive_result = scalars
                    .iter()
                    .enumerate()
                    .map(|(i, s)| a * s)
                    .collect::<Vec<_>>();
                assert_eq!(result, naive_result);
            }
        }

        #[test]
        fn test_serialization() {
            for compress in [Compress::Yes, Compress::No] {
                for validate in [Validate::Yes, Validate::No] {
                    let buf_size = <$group>::zero().serialized_size(compress);

                    let mut rng = ark_std::test_rng();

                    // Test that serializing and deserializing random elements
                    // works.
                    for _ in 0..ITERATIONS {
                        let a = <$group>::rand(&mut rng);
                        {
                            let mut serialized = vec![0; buf_size];
                            let mut cursor = Cursor::new(&mut serialized[..]);
                            a.serialize_with_mode(&mut cursor, compress).unwrap();

                            let mut cursor = Cursor::new(&serialized[..]);
                            let b = <$group>::deserialize_with_mode(&mut cursor, compress, validate).unwrap();
                            assert_eq!(a, b);
                        }
                    }

                    // Test that serializing and deserializing the identity element
                    // works.
                    {
                        let a = <$group>::zero();
                        let mut serialized = vec![0; buf_size];
                        let mut cursor = Cursor::new(&mut serialized[..]);
                        a.serialize_with_mode(&mut cursor, compress).unwrap();
                        let mut cursor = Cursor::new(&serialized[..]);
                        let b = <$group>::deserialize_with_mode(&mut cursor, compress, validate).unwrap();
                        assert_eq!(a, b);
                    }

                    // Test that serializing the identity point into a buffer that
                    // is not big enough will yield an error.
                    {
                        let a = <$group>::zero();
                        let mut serialized = vec![0; buf_size - 1];
                        let mut cursor = Cursor::new(&mut serialized[..]);
                        a.serialize_with_mode(&mut cursor, compress).unwrap_err();
                    }

                    // Test that deserializing from a buffer that is not big enough
                    // will yield and error.
                    // This test does not explicitly check that the error is due to
                    // a buffer that is not big enough.
                    {
                        let serialized = vec![0; buf_size - 1];
                        let mut cursor = Cursor::new(&serialized[..]);
                        <$group>::deserialize_with_mode(&mut cursor, compress, validate).unwrap_err();
                    }
                }
            }
        }
    };
    ($group:ty; msm) => {
        #[test]
        fn test_var_base_msm() {
            $crate::msm::test_var_base_msm::<$group>();
        }

        #[test]
        fn test_chunked_pippenger() {
            $crate::msm::test_chunked_pippenger::<$group>();
        }

        #[test]
        fn test_hashmap_pippenger() {
            $crate::msm::test_hashmap_pippenger::<$group>();
        }
    };
    ($group:ty; curve) => {
        $crate::__test_group!($group);
        $crate::__test_group!($group; msm);
        type Affine = <$group as CurveGroup>::Affine;
        type Config = <$group as CurveGroup>::Config;
        type BaseField = <$group as CurveGroup>::BaseField;

        #[test]
        fn test_affine_conversion() {
            let mut rng = &mut ark_std::test_rng();

            for _ in 0..ITERATIONS {
                let g = <$group>::rand(&mut rng);
                let g_affine = g.into_affine();
                let g_projective = g_affine.into_group();
                assert_eq!(g, g_projective);
            }

            // Batch normalization
            for _ in 0..10 {
                let mut v = (0..ITERATIONS)
                    .map(|_| <$group>::rand(&mut rng).double())
                    .collect::<Vec<_>>();

                use ark_std::rand::distributions::{Distribution, Uniform};
                let between = Uniform::from(0..ITERATIONS);
                // Sprinkle in some normalized points
                for _ in 0..5 {
                    v[between.sample(&mut rng)] = <$group>::zero();
                }
                for _ in 0..5 {
                    let s = between.sample(&mut rng);
                    v[s] = v[s].into_affine().into_group();
                }

                let expected_v = v.iter().map(|v| v.into_affine()).collect::<Vec<_>>();
                let actual_v = <$group>::normalize_batch(&v);

                assert_eq!(actual_v, expected_v);
            }
        }

        #[test]
        fn test_cofactor_ops() {
            let rng = &mut ark_std::test_rng();
            for _ in 0..ITERATIONS {
                let a = Affine::rand(rng);
                assert_eq!(a.mul_by_cofactor_to_group(), a.mul_bigint(&Config::COFACTOR));
                assert_eq!(a.mul_by_cofactor(), a.mul_bigint(&Config::COFACTOR));
                assert_eq!(a.mul_by_cofactor().mul_by_cofactor_inv(), a);
                assert_eq!(a.mul_by_cofactor_inv().mul_by_cofactor(), a);
                assert_eq!(a.mul_by_cofactor_inv(), a * Config::COFACTOR_INV);

                assert!(a.clear_cofactor().is_in_correct_subgroup_assuming_on_curve());
            }
        }

        #[test]
        fn test_mixed_addition() {
            let rng = &mut ark_std::test_rng();
            for _ in 0..ITERATIONS {
                let a = Affine::rand(rng);
                let a_group = a.into_group();
                let b = <$group>::rand(rng);
                assert!(a.is_on_curve());
                assert!(b.into_affine().is_on_curve());
                assert_eq!(b + a, b + a_group, "b + a failed on input {a}, {b}");
                assert_eq!(a + b, a_group + b, "a + b failed on input {a}, {b}");
            }
        }
    };
    ($group:ty; sw) => {
        $crate::__test_group!($group; curve);

        #[test]
        fn test_sw_properties() {
            let mut rng = &mut ark_std::test_rng();

            let generator = <$group>::generator().into_affine();
            assert!(generator.is_on_curve());
            assert!(generator.is_in_correct_subgroup_assuming_on_curve());

            for i in 0.. {
                let x = BaseField::from(i);
                // y^2 = x^3 + a * x + b
                let rhs = x * x.square() + x * <Config as SWCurveConfig>::COEFF_A + <Config as SWCurveConfig>::COEFF_B;

                if let Some(y) = rhs.sqrt() {
                    let p = Affine::new_unchecked(x, if y < -y { y } else { -y });
                    if !<<$group as CurveGroup>::Config as CurveConfig>::cofactor_is_one() {
                        if p.is_in_correct_subgroup_assuming_on_curve() {
                            continue;
                        }
                    }

                    let g1 = p.mul_by_cofactor_to_group();
                    if !g1.is_zero() {
                        let g1 = Affine::from(g1);
                        assert!(g1.is_in_correct_subgroup_assuming_on_curve());
                        break;
                    }
                }
            }

            for _ in 0..ITERATIONS {
                let f = BaseField::rand(rng);
                assert_eq!(<Config as SWCurveConfig>::mul_by_a(f), f * <Config as SWCurveConfig>::COEFF_A);
                assert_eq!(<Config as SWCurveConfig>::add_b(f), f + <Config as SWCurveConfig>::COEFF_B);
            }
            {
                use ark_ec::models::short_weierstrass::SWFlags;
                for compress in [Compress::Yes, Compress::No] {
                    for flag in [SWFlags::PointAtInfinity, SWFlags::YIsNegative, SWFlags::YIsPositive] {
                        let a = BaseField::rand(&mut rng);
                        let buf_size = a.serialized_size(compress);
                        let mut serialized = vec![0u8; buf_size + 1];
                        let mut cursor = Cursor::new(&mut serialized[..]);
                        a.serialize_with_flags(&mut cursor, flag)
                        .unwrap();
                        let mut cursor = Cursor::new(&serialized[..]);
                        let (b, flags) = BaseField::deserialize_with_flags::<_, SWFlags>(&mut cursor).unwrap();
                        assert_eq!(flags, flag);
                        assert_eq!(a, b);
                    }

                }
            }
        }
    };
    ($group:ty; te) => {
        $crate::__test_group!($group; curve);

        #[test]
        fn test_te_properties() {
            let mut rng = &mut ark_std::test_rng();

            let generator = <$group>::generator().into_affine();
            assert!(generator.is_on_curve());
            assert!(generator.is_in_correct_subgroup_assuming_on_curve());
            let mut y = BaseField::zero();
            let one = BaseField::one();
            for _ in 0..ITERATIONS {
                let f = BaseField::rand(rng);
                assert_eq!(<Config as TECurveConfig>::mul_by_a(f), f * <Config as TECurveConfig>::COEFF_A);
            }
            {
                use ark_ec::models::twisted_edwards::TEFlags;
                for compress in [Compress::Yes, Compress::No] {
                    for flag in [TEFlags::XIsPositive, TEFlags::XIsNegative] {
                        let a = BaseField::rand(&mut rng);
                        let buf_size = a.serialized_size(compress);
                        let mut serialized = vec![0u8; buf_size + 1];
                        let mut cursor = Cursor::new(&mut serialized[..]);
                        a.serialize_with_flags(&mut cursor, flag)
                        .unwrap();
                        let mut cursor = Cursor::new(&serialized[..]);
                        let (b, flags) = BaseField::deserialize_with_flags::<_, TEFlags>(&mut cursor).unwrap();
                        assert_eq!(flags, flag);
                        assert_eq!(a, b);
                    }

                }
            }
        }

        #[test]
        fn test_montgomery_conversion_test()
        {
            use ark_ec::twisted_edwards::MontCurveConfig;
            // A = 2 * (a + d) / (a - d)
            let a = <Config as CurveConfig>::BaseField::one().double()
                * &(<Config as TECurveConfig>::COEFF_A + &<Config as TECurveConfig>::COEFF_D)
                * &(<Config as TECurveConfig>::COEFF_A - &<Config as TECurveConfig>::COEFF_D).inverse().unwrap();
            // B = 4 / (a - d)
            let b = <Config as CurveConfig>::BaseField::one().double().double() *
                &(<Config as TECurveConfig>::COEFF_A - &<Config as TECurveConfig>::COEFF_D).inverse().unwrap();

            assert_eq!(a, <Config as MontCurveConfig>::COEFF_A);
            assert_eq!(b, <Config as MontCurveConfig>::COEFF_B);
        }
    };
    ($group:ty; glv) => {
        type Config = <$group as CurveGroup>::Config;

        #[test]
        fn test_scalar_decomposition()
        {
            $crate::glv::glv_scalar_decomposition::<Config>();
        }


        #[test]
        fn test_endomorphism_eigenvalue() {
            $crate::glv::glv_endomorphism_eigenvalue::<Config>();
        }

        #[test]
        fn test_glv_mul() {
            $crate::glv::glv_projective::<Config>();
            $crate::glv::glv_affine::<Config>();
        }
    }
}

#[macro_export]
macro_rules! test_group {
    ($mod_name:ident; $group:ty $(; $tail:tt)* ) => {
        mod $mod_name {
            use super::*;
            use ark_ff::*;
            use ark_ec::{PrimeGroup, CurveGroup, ScalarMul, AffineRepr, CurveConfig, short_weierstrass::SWCurveConfig, twisted_edwards::TECurveConfig, scalar_mul::{*, wnaf::*}};
            use ark_serialize::*;
            use ark_std::{io::Cursor, rand::Rng, vec::*, test_rng, vec, Zero, One, UniformRand};
            const ITERATIONS: usize = 500;

            $crate::__test_group!($group $(; $tail)*);
        }
    };

    ($iters:expr; $mod_name:ident; $group:ty $(; $tail:tt)* ) => {
        mod $mod_name {
            use super::*;
            use ark_ff::*;
            use ark_ec::{PrimeGroup, CurveGroup, ScalarMul, AffineRepr, CurveConfig, short_weierstrass::SWCurveConfig, twisted_edwards::TECurveConfig, scalar_mul::{*, wnaf::*}};
            use ark_serialize::*;
            use ark_std::{io::Cursor, rand::Rng, vec::*, test_rng, vec, Zero, One, UniformRand};
            const ITERATIONS: usize = $iters;

            $crate::__test_group!($group $(; $tail)*);
        }
    };
}