revm_precompile/bls12_381/
g1_msm.rs1use super::crypto_backend::{encode_g1_point, p1_msm, read_g1, read_scalar};
2use crate::bls12_381::utils::remove_g1_padding;
3use crate::bls12_381_const::{
4 DISCOUNT_TABLE_G1_MSM, G1_MSM_ADDRESS, G1_MSM_BASE_GAS_FEE, G1_MSM_INPUT_LENGTH,
5 PADDED_G1_LENGTH, SCALAR_LENGTH,
6};
7use crate::bls12_381_utils::msm_required_gas;
8use crate::{PrecompileError, PrecompileOutput, PrecompileResult, PrecompileWithAddress};
9use primitives::Bytes;
10use std::vec::Vec;
11
12pub const PRECOMPILE: PrecompileWithAddress = PrecompileWithAddress(G1_MSM_ADDRESS, g1_msm);
14
15pub(super) fn g1_msm(input: &Bytes, gas_limit: u64) -> PrecompileResult {
24 let input_len = input.len();
25 if input_len == 0 || input_len % G1_MSM_INPUT_LENGTH != 0 {
26 return Err(PrecompileError::Other(format!(
27 "G1MSM input length should be multiple of {}, was {}",
28 G1_MSM_INPUT_LENGTH, input_len
29 )));
30 }
31
32 let k = input_len / G1_MSM_INPUT_LENGTH;
33 let required_gas = msm_required_gas(k, &DISCOUNT_TABLE_G1_MSM, G1_MSM_BASE_GAS_FEE);
34 if required_gas > gas_limit {
35 return Err(PrecompileError::OutOfGas);
36 }
37
38 let mut g1_points: Vec<_> = Vec::with_capacity(k);
39 let mut scalars = Vec::with_capacity(k);
40 for i in 0..k {
41 let encoded_g1_element =
42 &input[i * G1_MSM_INPUT_LENGTH..i * G1_MSM_INPUT_LENGTH + PADDED_G1_LENGTH];
43 let encoded_scalar = &input[i * G1_MSM_INPUT_LENGTH + PADDED_G1_LENGTH
44 ..i * G1_MSM_INPUT_LENGTH + PADDED_G1_LENGTH + SCALAR_LENGTH];
45
46 if encoded_g1_element.iter().all(|i| *i == 0) {
51 continue;
52 }
53
54 let [a_x, a_y] = remove_g1_padding(encoded_g1_element)?;
55
56 let p0_aff = read_g1(a_x, a_y)?;
58
59 if encoded_scalar.iter().all(|i| *i == 0) {
65 continue;
66 }
67
68 g1_points.push(p0_aff);
69 scalars.push(read_scalar(encoded_scalar)?);
70 }
71
72 const ENCODED_POINT_AT_INFINITY: [u8; PADDED_G1_LENGTH] = [0; PADDED_G1_LENGTH];
75 if g1_points.is_empty() {
76 return Ok(PrecompileOutput::new(
77 required_gas,
78 ENCODED_POINT_AT_INFINITY.into(),
79 ));
80 }
81
82 let multiexp_aff = p1_msm(g1_points, scalars);
83
84 let out = encode_g1_point(&multiexp_aff);
85 Ok(PrecompileOutput::new(required_gas, out.into()))
86}
87
88#[cfg(test)]
89mod test {
90 use super::*;
91 use primitives::hex;
92
93 #[test]
94 fn bls_g1multiexp_g1_not_on_curve_but_in_subgroup() {
95 let input = Bytes::from(hex!("000000000000000000000000000000000a2833e497b38ee3ca5c62828bf4887a9f940c9e426c7890a759c20f248c23a7210d2432f4c98a514e524b5184a0ddac00000000000000000000000000000000150772d56bf9509469f9ebcd6e47570429fd31b0e262b66d512e245c38ec37255529f2271fd70066473e393a8bead0c30000000000000000000000000000000000000000000000000000000000000000"));
96 let fail = g1_msm(&input, G1_MSM_BASE_GAS_FEE);
97 assert_eq!(
98 fail,
99 Err(PrecompileError::Other(
100 "Element not on G1 curve".to_string()
101 ))
102 );
103 }
104}