Skip to content

Commit

Permalink
feat: use batch bn256 pair operation (bluealloy#1643)
Browse files Browse the repository at this point in the history
* feat: use batch bn256 pair operation

We are currently not taking advantage of the batch pair operation from
the `bn` library for the pairing check precompile.

This yields a ~27% speedup on the existing bench:
```
Crypto Precompile benchmarks/precompile bench | ecpairing precompile
                        time:   [2.2389 ms 2.2441 ms 2.2495 ms]
                        change: [-27.689% -27.469% -27.227%] (p = 0.00 < 0.05)
                        Performance has improved.
```

* use with_capacity

* import vec
  • Loading branch information
Rjected committed Jul 19, 2024
1 parent a605d05 commit 8eaff99
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions crates/precompile/src/bn128.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{
};
use bn::{AffineG1, AffineG2, Fq, Fq2, Group, Gt, G1, G2};
use revm_primitives::PrecompileOutput;
use std::vec::Vec;

pub mod add {
use super::*;
Expand Down Expand Up @@ -179,7 +180,9 @@ pub fn run_pair(
} else {
let elements = input.len() / PAIR_ELEMENT_LEN;

let mut mul = Gt::one();
let mut points = Vec::with_capacity(elements);

// read points
for idx in 0..elements {
let read_fq_at = |n: usize| {
debug_assert!(n < PAIR_ELEMENT_LEN / 32);
Expand All @@ -200,16 +203,19 @@ pub fn run_pair(
let b = {
let ba = Fq2::new(bax, bay);
let bb = Fq2::new(bbx, bby);
// TODO: check whether or not we need these zero checks
if ba.is_zero() && bb.is_zero() {
G2::zero()
} else {
G2::from(AffineG2::new(ba, bb).map_err(|_| Error::Bn128AffineGFailedToCreate)?)
}
};

mul = mul * bn::pairing(a, b);
points.push((a, b));
}

let mul = bn::pairing_batch(&points);

mul == Gt::one()
};
Ok(PrecompileOutput::new(gas_used, bool_to_bytes32(success)))
Expand Down

0 comments on commit 8eaff99

Please sign in to comment.