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