revm_precompile/bls12_381/
pairing.rs

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