Skip to main content

revm_precompile/bls12_381/
pairing.rs

1//! BLS12-381 pairing precompile. More details in [`pairing`]
2use super::{
3    utils::{remove_g1_padding, remove_g2_padding},
4    PairingPair,
5};
6use crate::{
7    bls12_381_const::{
8        PADDED_G1_LENGTH, PADDED_G2_LENGTH, PAIRING_ADDRESS, PAIRING_INPUT_LENGTH,
9        PAIRING_MULTIPLIER_BASE, PAIRING_OFFSET_BASE,
10    },
11    crypto, eth_precompile_fn, EthPrecompileOutput, EthPrecompileResult, Precompile,
12    PrecompileHalt, PrecompileId,
13};
14use primitives::B256;
15use std::vec::Vec;
16
17eth_precompile_fn!(pairing_precompile, pairing);
18
19/// [EIP-2537](https://eips.ethereum.org/EIPS/eip-2537#specification) BLS12_PAIRING precompile.
20pub const PRECOMPILE: Precompile = Precompile::new(
21    PrecompileId::Bls12Pairing,
22    PAIRING_ADDRESS,
23    pairing_precompile,
24);
25
26/// Pairing call expects 384*k (k being a positive integer) bytes as an inputs
27/// that is interpreted as byte concatenation of k slices. Each slice has the
28/// following structure:
29///    * 128 bytes of G1 point encoding
30///    * 256 bytes of G2 point encoding
31///
32/// Each point is expected to be in the subgroup of order q.
33/// Output is 32 bytes where first 31 bytes are equal to 0x00 and the last byte
34/// is 0x01 if pairing result is equal to the multiplicative identity in a pairing
35/// target field and 0x00 otherwise.
36///
37/// See also: <https://eips.ethereum.org/EIPS/eip-2537#abi-for-pairing>
38pub fn pairing(input: &[u8], gas_limit: u64) -> EthPrecompileResult {
39    let input_len = input.len();
40    if input_len == 0 || !input_len.is_multiple_of(PAIRING_INPUT_LENGTH) {
41        return Err(PrecompileHalt::Bls12381PairingInputLength);
42    }
43
44    let k = input_len / PAIRING_INPUT_LENGTH;
45    let required_gas: u64 = PAIRING_MULTIPLIER_BASE * k as u64 + PAIRING_OFFSET_BASE;
46    if required_gas > gas_limit {
47        return Err(PrecompileHalt::OutOfGas);
48    }
49
50    // Collect pairs of points for the pairing check
51    let mut pairs: Vec<PairingPair> = Vec::with_capacity(k);
52    for i in 0..k {
53        let encoded_g1_element =
54            &input[i * PAIRING_INPUT_LENGTH..i * PAIRING_INPUT_LENGTH + PADDED_G1_LENGTH];
55        let encoded_g2_element = &input[i * PAIRING_INPUT_LENGTH + PADDED_G1_LENGTH
56            ..i * PAIRING_INPUT_LENGTH + PADDED_G1_LENGTH + PADDED_G2_LENGTH];
57
58        let [a_x, a_y] = remove_g1_padding(encoded_g1_element)?;
59        let [b_x_0, b_x_1, b_y_0, b_y_1] = remove_g2_padding(encoded_g2_element)?;
60
61        pairs.push(((*a_x, *a_y), (*b_x_0, *b_x_1, *b_y_0, *b_y_1)));
62    }
63
64    let result = crypto().bls12_381_pairing_check(&pairs)?;
65    let result = if result { 1 } else { 0 };
66
67    Ok(EthPrecompileOutput::new(
68        required_gas,
69        B256::with_last_byte(result).into(),
70    ))
71}