Skip to main content

revm_precompile/bls12_381/
g1_add.rs

1//! BLS12-381 G1 add precompile. More details in [`g1_add`]
2use super::utils::{pad_g1_point, remove_g1_padding};
3use crate::{
4    bls12_381_const::{G1_ADD_ADDRESS, G1_ADD_BASE_GAS_FEE, G1_ADD_INPUT_LENGTH, PADDED_G1_LENGTH},
5    crypto, eth_precompile_fn, EthPrecompileOutput, EthPrecompileResult, Precompile,
6    PrecompileHalt, PrecompileId,
7};
8
9eth_precompile_fn!(g1_add_precompile, g1_add);
10
11/// [EIP-2537](https://eips.ethereum.org/EIPS/eip-2537#specification) BLS12_G1ADD precompile.
12pub const PRECOMPILE: Precompile =
13    Precompile::new(PrecompileId::Bls12G1Add, G1_ADD_ADDRESS, g1_add_precompile);
14
15/// G1 addition call expects `256` bytes as an input that is interpreted as byte
16/// concatenation of two G1 points (`128` bytes each).
17/// Output is an encoding of addition operation result - single G1 point (`128`
18/// bytes).
19/// See also: <https://eips.ethereum.org/EIPS/eip-2537#abi-for-g1-addition>
20pub fn g1_add(input: &[u8], gas_limit: u64) -> EthPrecompileResult {
21    if G1_ADD_BASE_GAS_FEE > gas_limit {
22        return Err(PrecompileHalt::OutOfGas);
23    }
24
25    if input.len() != G1_ADD_INPUT_LENGTH {
26        return Err(PrecompileHalt::Bls12381G1AddInputLength);
27    }
28
29    // Extract coordinates from padded input
30    let [a_x, a_y] = remove_g1_padding(&input[..PADDED_G1_LENGTH])?;
31    let [b_x, b_y] = remove_g1_padding(&input[PADDED_G1_LENGTH..])?;
32
33    let a = (*a_x, *a_y);
34    let b = (*b_x, *b_y);
35
36    let unpadded_result = crypto().bls12_381_g1_add(a, b)?;
37
38    // Pad the result for EVM compatibility
39    let padded_result = pad_g1_point(&unpadded_result);
40
41    Ok(EthPrecompileOutput::new(
42        G1_ADD_BASE_GAS_FEE,
43        padded_result.into(),
44    ))
45}