Skip to content

Commit

Permalink
Increase modexp gas cost when mod is even (polkadot-evm#1017)
Browse files Browse the repository at this point in the history
* Increase modexp gas cost when mod is even

* Fix tests
  • Loading branch information
sorpaas authored and Dinonard committed Mar 22, 2023
1 parent be1857a commit 997ee15
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
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

0 comments on commit 997ee15

Please sign in to comment.