revm_precompile/bls12_381/
g2_add.rs

1//! BLS12-381 G2 add precompile. More details in [`g2_add`]
2use super::utils::{pad_g2_point, remove_g2_padding};
3use crate::{
4    bls12_381_const::{G2_ADD_ADDRESS, G2_ADD_BASE_GAS_FEE, G2_ADD_INPUT_LENGTH, PADDED_G2_LENGTH},
5    crypto, Precompile, PrecompileError, PrecompileId, PrecompileOutput, PrecompileResult,
6};
7
8/// [EIP-2537](https://eips.ethereum.org/EIPS/eip-2537#specification) BLS12_G2ADD precompile.
9pub const PRECOMPILE: Precompile =
10    Precompile::new(PrecompileId::Bls12G2Add, G2_ADD_ADDRESS, g2_add);
11
12/// G2 addition call expects `512` bytes as an input that is interpreted as byte
13/// concatenation of two G2 points (`256` bytes each).
14///
15/// Output is an encoding of addition operation result - single G2 point (`256`
16/// bytes).
17/// See also <https://eips.ethereum.org/EIPS/eip-2537#abi-for-g2-addition>
18pub fn g2_add(input: &[u8], gas_limit: u64) -> PrecompileResult {
19    if G2_ADD_BASE_GAS_FEE > gas_limit {
20        return Err(PrecompileError::OutOfGas);
21    }
22
23    if input.len() != G2_ADD_INPUT_LENGTH {
24        return Err(PrecompileError::Bls12381G2AddInputLength);
25    }
26
27    // Extract coordinates from padded input
28    let [a_x_0, a_x_1, a_y_0, a_y_1] = remove_g2_padding(&input[..PADDED_G2_LENGTH])?;
29    let [b_x_0, b_x_1, b_y_0, b_y_1] = remove_g2_padding(&input[PADDED_G2_LENGTH..])?;
30
31    let a = (*a_x_0, *a_x_1, *a_y_0, *a_y_1);
32    let b = (*b_x_0, *b_x_1, *b_y_0, *b_y_1);
33
34    let unpadded_result = crypto().bls12_381_g2_add(a, b)?;
35
36    // Pad the result for EVM compatibility
37    let padded_result = pad_g2_point(&unpadded_result);
38
39    Ok(PrecompileOutput::new(
40        G2_ADD_BASE_GAS_FEE,
41        padded_result.into(),
42    ))
43}