Skip to main content

polynomials_ecc/
utils.rs

1use bls12_381::{G1Affine, G1Projective, Scalar};
2use bytemuck::cast_slice;
3
4use crate::Error;
5use blst::{
6    blst_p1, blst_p1_affine, blst_p1_affine_compress, blst_p1_deserialize, blst_p1_from_affine,
7    blst_p1_to_affine, p1_affines,
8};
9
10// Converts a G1Projective to a blst_p1
11fn g1proj_to_blst_p1(point: &G1Projective) -> blst_p1 {
12    let mut blst_affine = blst_p1_affine::default();
13    unsafe {
14        blst_p1_deserialize(
15            &mut blst_affine,
16            G1Affine::from(point).to_compressed().as_ptr(),
17        );
18    }
19
20    let mut blst_projective = blst_p1::default();
21    unsafe {
22        blst_p1_from_affine(&mut blst_projective, &blst_affine);
23    }
24
25    blst_projective
26}
27
28/// Performs efficient multi scalar multiplication using the Pippenger's algorithm over
29/// a given set of scalars and points.
30pub fn msm(points: &[G1Projective], scalars: &[Scalar]) -> Result<G1Projective, Error> {
31    // Both sets need to have the same length
32    if points.len() != scalars.len() {
33        return Err(Error::InvalidLength);
34    }
35
36    // Convert scalars to bytes
37    let mut scalar_bytes = vec![];
38    for scalar in scalars {
39        scalar_bytes.push(scalar.to_bytes());
40    }
41    let scalar_bytes = cast_slice(scalar_bytes.as_slice());
42
43    // Convert points to p1_affines
44    let mut blst_points = vec![];
45    for point in points {
46        blst_points.push(g1proj_to_blst_p1(point));
47    }
48    let blst_points = p1_affines::from(&blst_points);
49
50    // Perform the MSM
51    let result = blst_points.mult(scalar_bytes, 255);
52
53    // Convert the result to bytes
54    let mut out = blst_p1_affine::default();
55    unsafe {
56        blst_p1_to_affine(&mut out, &result);
57    }
58    let mut out_compressed = [0u8; 48];
59    unsafe { blst_p1_affine_compress(out_compressed.as_mut_ptr(), &out) }
60
61    // Return the result as G1Projective
62    Ok(G1Projective::from(
63        G1Affine::from_compressed(&out_compressed).unwrap(),
64    ))
65}