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
10fn 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
28pub fn msm(points: &[G1Projective], scalars: &[Scalar]) -> Result<G1Projective, Error> {
31 if points.len() != scalars.len() {
33 return Err(Error::InvalidLength);
34 }
35
36 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 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 let result = blst_points.mult(scalar_bytes, 255);
52
53 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 Ok(G1Projective::from(
63 G1Affine::from_compressed(&out_compressed).unwrap(),
64 ))
65}