revm_precompile/bls12_381/
map_fp2_to_g2.rs

1use super::{
2    g2::check_canonical_fp2,
3    g2::encode_g2_point,
4    utils::{remove_padding, PADDED_FP2_LENGTH, PADDED_FP_LENGTH},
5};
6use crate::{u64_to_address, PrecompileWithAddress};
7use blst::{blst_map_to_g2, blst_p2, blst_p2_affine, blst_p2_to_affine};
8use revm_primitives::{Bytes, Precompile, PrecompileError, PrecompileOutput, PrecompileResult};
9
10/// [EIP-2537](https://eips.ethereum.org/EIPS/eip-2537#specification) BLS12_MAP_FP2_TO_G2 precompile.
11pub const PRECOMPILE: PrecompileWithAddress =
12    PrecompileWithAddress(u64_to_address(ADDRESS), Precompile::Standard(map_fp2_to_g2));
13
14/// BLS12_MAP_FP2_TO_G2 precompile address.
15pub const ADDRESS: u64 = 0x13;
16
17/// Base gas fee for BLS12-381 map_fp2_to_g2 operation.
18const BASE_GAS_FEE: u64 = 75000;
19
20/// Field-to-curve call expects 128 bytes as an input that is interpreted as
21/// an element of Fp2. Output of this call is 256 bytes and is an encoded G2
22/// point.
23/// See also: <https://eips.ethereum.org/EIPS/eip-2537#abi-for-mapping-fp2-element-to-g2-point>
24pub(super) fn map_fp2_to_g2(input: &Bytes, gas_limit: u64) -> PrecompileResult {
25    if BASE_GAS_FEE > gas_limit {
26        return Err(PrecompileError::OutOfGas.into());
27    }
28
29    if input.len() != PADDED_FP2_LENGTH {
30        return Err(PrecompileError::Other(format!(
31            "MAP_FP2_TO_G2 input should be {PADDED_FP2_LENGTH} bytes, was {}",
32            input.len()
33        ))
34        .into());
35    }
36
37    let input_p0_x = remove_padding(&input[..PADDED_FP_LENGTH])?;
38    let input_p0_y = remove_padding(&input[PADDED_FP_LENGTH..PADDED_FP2_LENGTH])?;
39    let fp2 = check_canonical_fp2(input_p0_x, input_p0_y)?;
40
41    let mut p = blst_p2::default();
42    // SAFETY: p and fp2 are blst values.
43    // third argument is unused if null.
44    unsafe { blst_map_to_g2(&mut p, &fp2, core::ptr::null()) };
45
46    let mut p_aff = blst_p2_affine::default();
47    // SAFETY: p_aff and p are blst values.
48    unsafe { blst_p2_to_affine(&mut p_aff, &p) };
49
50    let out = encode_g2_point(&p_aff);
51    Ok(PrecompileOutput::new(BASE_GAS_FEE, out))
52}