/ algorithms / src / msm / tests.rs
tests.rs
 1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
 2  // This file is part of the deltavm library.
 3  
 4  // Licensed under the Apache License, Version 2.0 (the "License");
 5  // you may not use this file except in compliance with the License.
 6  // You may obtain a copy of the License at:
 7  
 8  // http://www.apache.org/licenses/LICENSE-2.0
 9  
10  // Unless required by applicable law or agreed to in writing, software
11  // distributed under the License is distributed on an "AS IS" BASIS,
12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  // See the License for the specific language governing permissions and
14  // limitations under the License.
15  
16  use crate::msm::*;
17  use deltavm_curves::{
18      bls12_377::{Fr, G1Projective},
19      traits::{AffineCurve, ProjectiveCurve},
20  };
21  use deltavm_fields::{PrimeField, Zero};
22  use deltavm_utilities::{
23      BitIteratorBE,
24      rand::{TestRng, Uniform},
25  };
26  
27  fn naive_variable_base_msm<G: AffineCurve>(
28      bases: &[G],
29      scalars: &[<G::ScalarField as PrimeField>::BigInteger],
30  ) -> G::Projective {
31      let mut acc = G::Projective::zero();
32  
33      for (base, scalar) in bases.iter().zip(scalars.iter()) {
34          acc += base.mul_bits(BitIteratorBE::new(*scalar));
35      }
36      acc
37  }
38  
39  #[test]
40  fn variable_base_test_with_bls12() {
41      const SAMPLES: usize = 1 << 10;
42  
43      let mut rng = TestRng::default();
44  
45      let v = (0..SAMPLES).map(|_| Fr::rand(&mut rng).to_bigint()).collect::<Vec<_>>();
46      let g = (0..SAMPLES).map(|_| G1Projective::rand(&mut rng).to_affine()).collect::<Vec<_>>();
47  
48      let naive = naive_variable_base_msm(g.as_slice(), v.as_slice());
49      let fast = VariableBase::msm(g.as_slice(), v.as_slice());
50  
51      assert_eq!(naive.to_affine(), fast.to_affine());
52  }
53  
54  #[test]
55  fn variable_base_test_with_bls12_unequal_numbers() {
56      const SAMPLES: usize = 1 << 10;
57  
58      let mut rng = TestRng::default();
59  
60      let v = (0..SAMPLES - 100).map(|_| Fr::rand(&mut rng).to_bigint()).collect::<Vec<_>>();
61      let g = (0..SAMPLES).map(|_| G1Projective::rand(&mut rng).to_affine()).collect::<Vec<_>>();
62  
63      let naive = naive_variable_base_msm(g.as_slice(), v.as_slice());
64      let fast = VariableBase::msm(g.as_slice(), v.as_slice());
65  
66      assert_eq!(naive.to_affine(), fast.to_affine());
67  }