revm_precompile/bls12_381/
map_fp_to_g1.rs

1//! BLS12-381 map fp to g1 precompile. More details in [`map_fp_to_g1`]
2use super::utils::{pad_g1_point, remove_fp_padding};
3use crate::bls12_381_const::{MAP_FP_TO_G1_ADDRESS, MAP_FP_TO_G1_BASE_GAS_FEE, PADDED_FP_LENGTH};
4use crate::{
5    crypto, Precompile, PrecompileError, PrecompileId, PrecompileOutput, PrecompileResult,
6};
7
8/// [EIP-2537](https://eips.ethereum.org/EIPS/eip-2537#specification) BLS12_MAP_FP_TO_G1 precompile.
9pub const PRECOMPILE: Precompile = Precompile::new(
10    PrecompileId::Bls12MapFpToGp1,
11    MAP_FP_TO_G1_ADDRESS,
12    map_fp_to_g1,
13);
14
15/// Field-to-curve call expects 64 bytes as an input that is interpreted as an
16/// element of Fp. Output of this call is 128 bytes and is an encoded G1 point.
17/// See also: <https://eips.ethereum.org/EIPS/eip-2537#abi-for-mapping-fp-element-to-g1-point>
18pub fn map_fp_to_g1(input: &[u8], gas_limit: u64) -> PrecompileResult {
19    if MAP_FP_TO_G1_BASE_GAS_FEE > gas_limit {
20        return Err(PrecompileError::OutOfGas);
21    }
22
23    if input.len() != PADDED_FP_LENGTH {
24        return Err(PrecompileError::Other(format!(
25            "MAP_FP_TO_G1 input should be {PADDED_FP_LENGTH} bytes, was {}",
26            input.len()
27        )));
28    }
29
30    let input_p0 = remove_fp_padding(input)?;
31
32    let unpadded_result = crypto().bls12_381_fp_to_g1(input_p0)?;
33
34    // Pad the result for EVM compatibility
35    let padded_result = pad_g1_point(&unpadded_result);
36
37    Ok(PrecompileOutput::new(
38        MAP_FP_TO_G1_BASE_GAS_FEE,
39        padded_result.into(),
40    ))
41}
42
43#[cfg(test)]
44mod test {
45    use super::*;
46    use primitives::{hex, Bytes};
47
48    #[test]
49    fn sanity_test() {
50        let input = Bytes::from(hex!("000000000000000000000000000000006900000000000000636f6e7472616374595a603f343061cd305a03f40239f5ffff31818185c136bc2595f2aa18e08f17"));
51        let fail = map_fp_to_g1(&input, MAP_FP_TO_G1_BASE_GAS_FEE);
52        assert_eq!(
53            fail,
54            Err(PrecompileError::Other("non-canonical fp value".to_string()))
55        );
56    }
57}