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, 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
19pub const PRECOMPILE: Precompile = Precompile::new(
21 PrecompileId::Bls12Pairing,
22 PAIRING_ADDRESS,
23 pairing_precompile,
24);
25
26pub 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 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}