revm_precompile/bls12_381/
pairing.rs1use 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::{crypto, PrecompileError, PrecompileOutput, PrecompileResult, PrecompileWithAddress};
9use primitives::B256;
10use std::vec::Vec;
11
12pub const PRECOMPILE: PrecompileWithAddress = PrecompileWithAddress(PAIRING_ADDRESS, pairing);
14
15pub fn pairing(input: &[u8], gas_limit: u64) -> PrecompileResult {
28 let input_len = input.len();
29 if input_len == 0 || !input_len.is_multiple_of(PAIRING_INPUT_LENGTH) {
30 return Err(PrecompileError::Other(format!(
31 "Pairing input length should be multiple of {PAIRING_INPUT_LENGTH}, was {input_len}"
32 )));
33 }
34
35 let k = input_len / PAIRING_INPUT_LENGTH;
36 let required_gas: u64 = PAIRING_MULTIPLIER_BASE * k as u64 + PAIRING_OFFSET_BASE;
37 if required_gas > gas_limit {
38 return Err(PrecompileError::OutOfGas);
39 }
40
41 let mut pairs: Vec<PairingPair> = Vec::with_capacity(k);
43 for i in 0..k {
44 let encoded_g1_element =
45 &input[i * PAIRING_INPUT_LENGTH..i * PAIRING_INPUT_LENGTH + PADDED_G1_LENGTH];
46 let encoded_g2_element = &input[i * PAIRING_INPUT_LENGTH + PADDED_G1_LENGTH
47 ..i * PAIRING_INPUT_LENGTH + PADDED_G1_LENGTH + PADDED_G2_LENGTH];
48
49 let [a_x, a_y] = remove_g1_padding(encoded_g1_element)?;
50 let [b_x_0, b_x_1, b_y_0, b_y_1] = remove_g2_padding(encoded_g2_element)?;
51
52 pairs.push(((*a_x, *a_y), (*b_x_0, *b_x_1, *b_y_0, *b_y_1)));
53 }
54
55 let result = crypto().bls12_381_pairing_check(&pairs)?;
56 let result = if result { 1 } else { 0 };
57
58 Ok(PrecompileOutput::new(
59 required_gas,
60 B256::with_last_byte(result).into(),
61 ))
62}