Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(precompile): BLS G2 MSM #1428

Merged
merged 9 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions crates/precompile/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ blst = { version = "0.3.11", optional = true }
[dev-dependencies]
criterion = { version = "0.5" }
rand = { version = "0.8", features = ["std"] }
eyre = "0.6.12"
rstest = "0.19.0"
serde = "1.0"
serde_json = "1.0"
serde_derive = "1.0"

[features]
default = ["std", "c-kzg", "secp256k1", "portable", "blst"]
Expand Down
134 changes: 134 additions & 0 deletions crates/precompile/src/bls12_381.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
use crate::PrecompileWithAddress;

mod g1;
pub mod g1_add;
pub mod g1_msm;
pub mod g1_mul;
mod g2;
pub mod g2_add;
pub mod g2_msm;
pub mod g2_mul;
pub mod map_fp2_to_g2;
pub mod map_fp_to_g1;
mod msm;
pub mod pairing;
mod utils;

/// Returns the BLS12-381 precompiles with their addresses.
pub fn precompiles() -> impl Iterator<Item = PrecompileWithAddress> {
[
g1_add::PRECOMPILE,
g1_mul::PRECOMPILE,
g1_msm::PRECOMPILE,
g2_add::PRECOMPILE,
g2_mul::PRECOMPILE,
g2_msm::PRECOMPILE,
pairing::PRECOMPILE,
map_fp_to_g1::PRECOMPILE,
map_fp2_to_g2::PRECOMPILE,
]
.into_iter()
}

#[cfg(test)]
mod test {
use super::g1_add;
use super::g1_msm;
use super::g1_mul;
use super::g2_add;
use super::g2_msm;
use super::g2_mul;
use super::map_fp2_to_g2;
use super::map_fp_to_g1;
use super::msm::msm_required_gas;
use super::pairing;
use eyre::Result;
use revm_primitives::{hex::FromHex, Bytes, PrecompileResult};
use rstest::rstest;
use serde_derive::{Deserialize, Serialize};
use std::{fs, path::Path};

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct TestVector {
input: String,
expected: String,
name: String,
gas: u64,
error: Option<bool>,
}

#[derive(Serialize, Deserialize, Debug)]
struct TestVectors(Vec<TestVector>);

fn load_test_vectors<P: AsRef<Path>>(path: P) -> Result<TestVectors> {
let file_contents = fs::read_to_string(path)?;
Ok(serde_json::from_str(&file_contents)?)
}

#[rstest]
#[case::g1_add(g1_add::g1_add, "add_G1_bls.json")]
#[case::g1_mul(g1_mul::g1_mul, "mul_G1_bls.json")]
#[case::g1_msm(g1_msm::g1_msm, "multiexp_G1_bls.json")]
#[case::g2_add(g2_add::g2_add, "add_G2_bls.json")]
#[case::g2_mul(g2_mul::g2_mul, "mul_G2_bls.json")]
#[case::g2_msm(g2_msm::g2_msm, "multiexp_G2_bls.json")]
#[case::pairing(pairing::pairing, "pairing_check_bls.json")]
#[case::map_fp_to_g1(map_fp_to_g1::map_fp_to_g1, "map_fp_to_G1_bls.json")]
#[case::map_fp2_to_g2(map_fp2_to_g2::map_fp2_to_g2, "map_fp2_to_G2_bls.json")]
fn test_bls(
#[case] precompile: fn(input: &Bytes, gas_limit: u64) -> PrecompileResult,
#[case] file_name: &str,
) {
let test_vectors = load_test_vectors(format!("test-vectors/{file_name}"))
.unwrap_or_else(|e| panic!("Failed to load test vectors from {file_name}: {e}"));

for vector in test_vectors.0 {
let test_name = format!("{file_name}/{}", vector.name);
let input = Bytes::from_hex(vector.input.clone()).unwrap_or_else(|e| {
panic!(
"could not deserialize input {} as hex in {test_name}: {e}",
&vector.input
)
});
let target_gas: u64 = 30_000_000;
let res = precompile(&input, target_gas);
if vector.error.unwrap_or_default() {
assert!(res.is_err(), "expected error didn't happen in {test_name}");
} else {
let (actual_gas, actual_output) =
res.unwrap_or_else(|e| panic!("precompile call failed for {test_name}: {e}"));
assert_eq!(
vector.gas, actual_gas,
"expected gas: {}, actual gas: {} in {test_name}",
vector.gas, actual_gas
);
let expected_output = Bytes::from_hex(vector.expected).unwrap();
assert_eq!(
expected_output, actual_output,
"expected output: {expected_output}, actual output: {actual_output} in {test_name}");
}
}
}

#[rstest]
#[case::g1_empty(0, g1_mul::BASE_GAS_FEE, 0)]
#[case::g1_one_item(160, g1_mul::BASE_GAS_FEE, 14400)]
#[case::g1_two_items(320, g1_mul::BASE_GAS_FEE, 21312)]
#[case::g1_ten_items(1600, g1_mul::BASE_GAS_FEE, 50760)]
#[case::g1_sixty_four_items(10240, g1_mul::BASE_GAS_FEE, 170496)]
#[case::g1_one_hundred_twenty_eight_items(20480, g1_mul::BASE_GAS_FEE, 267264)]
#[case::g1_one_hundred_twenty_nine_items(20640, g1_mul::BASE_GAS_FEE, 269352)]
#[case::g1_two_hundred_fifty_six_items(40960, g1_mul::BASE_GAS_FEE, 534528)]
fn test_g1_msm_required_gas(
#[case] input_len: usize,
#[case] multiplication_cost: u64,
#[case] expected_output: u64,
) {
let k = input_len / g1_mul::INPUT_LENGTH;

let actual_output = msm_required_gas(k, multiplication_cost);

assert_eq!(expected_output, actual_output);
}
}
47 changes: 42 additions & 5 deletions crates/precompile/src/bls12_381/g1.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::utils::{fp_to_bytes, remove_padding, PADDED_FP_LENGTH};
use blst::{blst_fp_from_bendian, blst_p1_affine, blst_p1_affine_in_g1};
use blst::{blst_fp_from_bendian, blst_p1_affine, blst_p1_affine_in_g1, blst_p1_affine_on_curve};
use revm_primitives::{Bytes, PrecompileError};

/// Length of each of the elements in a g1 operation input.
Expand All @@ -19,7 +19,12 @@ pub(super) fn encode_g1_point(input: *const blst_p1_affine) -> Bytes {
}

/// Extracts a G1 point in Affine format from a 128 byte slice representation.
pub(super) fn extract_g1_input(input: &[u8]) -> Result<blst_p1_affine, PrecompileError> {
///
/// NOTE: This function will perform a G1 subgroup check if `subgroup_check` is set to `true`.
pub(super) fn extract_g1_input(
input: &[u8],
subgroup_check: bool,
) -> Result<blst_p1_affine, PrecompileError> {
if input.len() != G1_INPUT_ITEM_LENGTH {
return Err(PrecompileError::Other(format!(
"Input should be {G1_INPUT_ITEM_LENGTH} bytes, was {}",
Expand All @@ -37,9 +42,41 @@ pub(super) fn extract_g1_input(input: &[u8]) -> Result<blst_p1_affine, Precompil
blst_fp_from_bendian(&mut out.y, input_p0_y.as_ptr());
}

// SAFETY: out is a blst value.
if unsafe { !blst_p1_affine_in_g1(&out) } {
return Err(PrecompileError::Other("Element not in G1".to_string()));
if subgroup_check {
// NB: Subgroup checks
//
// Scalar multiplications, MSMs and pairings MUST perform a subgroup check.
//
// Implementations SHOULD use the optimized subgroup check method:
//
// https://eips.ethereum.org/assets/eip-2537/fast_subgroup_checks
//
// On any input that fail the subgroup check, the precompile MUST return an error.
//
// As endomorphism acceleration requires input on the correct subgroup, implementers MAY
// use endomorphism acceleration.
if unsafe { !blst_p1_affine_in_g1(&out) } {
return Err(PrecompileError::Other("Element not in G2".to_string()));
}
} else {
// From EIP-2537:
//
// Error cases:
//
// * An input is neither a point on the G1 elliptic curve nor the infinity point
//
// NB: There is no subgroup check for the G1 addition precompile.
//
// We use blst_p1_affine_on_curve instead of blst_p1_affine_in_g2 because the latter performs
// the subgroup check.
//
// SAFETY: out is a blst value.
if unsafe { !blst_p1_affine_on_curve(&out) } {
return Err(PrecompileError::Other(
"Element not on G2 curve".to_string(),
));
}
}

Ok(out)
}
9 changes: 6 additions & 3 deletions crates/precompile/src/bls12_381/g1_add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const INPUT_LENGTH: usize = 256;
/// Output is an encoding of addition operation result - single G1 point (`128`
/// bytes).
/// See also: <https://eips.ethereum.org/EIPS/eip-2537#abi-for-g1-addition>
fn g1_add(input: &Bytes, gas_limit: u64) -> PrecompileResult {
pub(super) fn g1_add(input: &Bytes, gas_limit: u64) -> PrecompileResult {
if BASE_GAS_FEE > gas_limit {
return Err(PrecompileError::OutOfGas);
}
Expand All @@ -33,8 +33,11 @@ fn g1_add(input: &Bytes, gas_limit: u64) -> PrecompileResult {
)));
}

let a_aff = &extract_g1_input(&input[..G1_INPUT_ITEM_LENGTH])?;
let b_aff = &extract_g1_input(&input[G1_INPUT_ITEM_LENGTH..])?;
// NB: There is no subgroup check for the G2 addition precompile.
rakita marked this conversation as resolved.
Show resolved Hide resolved
rakita marked this conversation as resolved.
Show resolved Hide resolved
//
// So we set the subgroup checks here to `false`
let a_aff = &extract_g1_input(&input[..G1_INPUT_ITEM_LENGTH], false)?;
let b_aff = &extract_g1_input(&input[G1_INPUT_ITEM_LENGTH..], false)?;

let mut b = blst_p1::default();
// SAFETY: b and b_aff are blst values.
Expand Down
6 changes: 5 additions & 1 deletion crates/precompile/src/bls12_381/g1_msm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub const ADDRESS: u64 = 0x0d;
/// Output is an encoding of multi-scalar-multiplication operation result - single G1
/// point (`128` bytes).
/// See also: <https://eips.ethereum.org/EIPS/eip-2537#abi-for-g1-multiexponentiation>
fn g1_msm(input: &Bytes, gas_limit: u64) -> PrecompileResult {
pub(super) fn g1_msm(input: &Bytes, gas_limit: u64) -> PrecompileResult {
let input_len = input.len();
if input_len == 0 || input_len % g1_mul::INPUT_LENGTH != 0 {
return Err(PrecompileError::Other(format!(
Expand All @@ -41,8 +41,12 @@ fn g1_msm(input: &Bytes, gas_limit: u64) -> PrecompileResult {
let mut g1_points: Vec<blst_p1> = Vec::with_capacity(k);
let mut scalars: Vec<u8> = Vec::with_capacity(k * SCALAR_LENGTH);
for i in 0..k {
// NB: Scalar multiplications, MSMs and pairings MUST perform a subgroup check.
//
// So we set the subgroup_check flag to `true`
let p0_aff = &extract_g1_input(
&input[i * g1_mul::INPUT_LENGTH..i * g1_mul::INPUT_LENGTH + G1_INPUT_ITEM_LENGTH],
true,
)?;
let mut p0 = blst_p1::default();
// SAFETY: p0 and p0_aff are blst values.
Expand Down
7 changes: 5 additions & 2 deletions crates/precompile/src/bls12_381/g1_mul.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub(super) const INPUT_LENGTH: usize = 160;
/// Output is an encoding of multiplication operation result - single G1 point
/// (`128` bytes).
/// See also: <https://eips.ethereum.org/EIPS/eip-2537#abi-for-g1-multiplication>
pub fn g1_mul(input: &Bytes, gas_limit: u64) -> PrecompileResult {
pub(super) fn g1_mul(input: &Bytes, gas_limit: u64) -> PrecompileResult {
if BASE_GAS_FEE > gas_limit {
return Err(PrecompileError::OutOfGas);
}
Expand All @@ -34,7 +34,10 @@ pub fn g1_mul(input: &Bytes, gas_limit: u64) -> PrecompileResult {
)));
}

let p0_aff = &extract_g1_input(&input[..G1_INPUT_ITEM_LENGTH])?;
// NB: Scalar multiplications, MSMs and pairings MUST perform a subgroup check.
//
// So we set the subgroup_check flag to `true`
let p0_aff = &extract_g1_input(&input[..G1_INPUT_ITEM_LENGTH], true)?;
let mut p0 = blst_p1::default();
// SAFETY: p0 and p0_aff are blst values.
unsafe { blst_p1_from_affine(&mut p0, p0_aff) };
Expand Down
Loading
Loading