revm_precompile/bls12_381/
pairing.rs1use 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, Precompile, PrecompileError, PrecompileId, PrecompileOutput, PrecompileResult,
12};
13use primitives::B256;
14use std::vec::Vec;
15
16pub const PRECOMPILE: Precompile =
18 Precompile::new(PrecompileId::Bls12Pairing, PAIRING_ADDRESS, pairing);
19
20pub fn pairing(input: &[u8], gas_limit: u64) -> PrecompileResult {
33 let input_len = input.len();
34 if input_len == 0 || !input_len.is_multiple_of(PAIRING_INPUT_LENGTH) {
35 return Err(PrecompileError::Bls12381PairingInputLength);
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 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}