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

Increase modexp gas cost when mod is even #1017

Merged
merged 2 commits into from
Mar 15, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
14 changes: 11 additions & 3 deletions frame/evm/precompile/modexp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ extern crate alloc;
use alloc::{vec, vec::Vec};
use core::cmp::max;

use num::{BigUint, FromPrimitive, One, ToPrimitive, Zero};
use num::{BigUint, FromPrimitive, Integer, One, ToPrimitive, Zero};

use fp_evm::{
ExitError, ExitSucceed, Precompile, PrecompileFailure, PrecompileHandle, PrecompileOutput,
Expand All @@ -41,6 +41,7 @@ fn calculate_gas_cost(
mod_length: u64,
exponent: &BigUint,
exponent_bytes: &[u8],
mod_is_even: bool,
) -> u64 {
fn calculate_multiplication_complexity(base_length: u64, mod_length: u64) -> u64 {
let max_length = max(base_length, mod_length);
Expand Down Expand Up @@ -91,6 +92,7 @@ fn calculate_gas_cost(
MIN_GAS_COST,
multiplication_complexity * iteration_count / 3,
)
.saturating_mul(if mod_is_even { 20 } else { 1 })
}

/// Copy bytes from input to target.
Expand Down Expand Up @@ -196,7 +198,13 @@ impl Precompile for Modexp {
let modulus = BigUint::from_bytes_be(&mod_buf);

// do our gas accounting
let gas_cost = calculate_gas_cost(base_len as u64, mod_len as u64, &exponent, &exp_buf);
let gas_cost = calculate_gas_cost(
base_len as u64,
mod_len as u64,
&exponent,
&exp_buf,
modulus.is_even(),
);

handle.record_cost(gas_cost)?;

Expand Down Expand Up @@ -510,6 +518,6 @@ mod tests {

let _ = Modexp::execute(&mut handle).expect("Modexp::execute() returned error");

assert_eq!(handle.gas_used, 7104); // gas used when ran in geth
assert_eq!(handle.gas_used, 7104 * 20); // gas used when ran in geth (x20)
}
}
2 changes: 1 addition & 1 deletion shell.nix
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ let
mozillaOverlay =
import (builtins.fetchGit {
url = "https://github.com/mozilla/nixpkgs-mozilla.git";
rev = "4a07484cf0e49047f82d83fd119acffbad3b235f";
rev = "78e723925daf5c9e8d0a1837ec27059e61649cb6";
});
nixpkgs = import <nixpkgs> { overlays = [ mozillaOverlay ]; };
rust-nightly = with nixpkgs; ((rustChannelOf { date = "2022-11-16"; channel = "nightly"; }).rust.override {
Expand Down