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

update modexp #114

Merged
merged 1 commit into from
Aug 9, 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
2 changes: 1 addition & 1 deletion arithmetic/arithmetic/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "besu-native-arithmetic"
version = "0.11.0"
description = """Native arithemetic for EVM.
Derived from aurora - https://github.com/aurora-is-near/aurora-engine/tree/4ecee7ded1e6c78b69416e5b22388357316f7551/engine-modexp - originally CC0-1.0 license."""
Derived from aurora - https://github.com/aurora-is-near/aurora-engine/tree/0cfda4686dbdb7a57b2dc18dddc5106ec8e24a38/engine-modexp - originally CC0-1.0 license."""
license = "Apache-2.0"
authors = ["Aurora Labs <hello@aurora.dev>", "Danno Ferrin <danno.ferrin@shemnon.com>"]
repository = "https://github.com/hyperledger/besu-native"
Expand Down
2 changes: 1 addition & 1 deletion arithmetic/arithmetic/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Besu native `modexp`

Originally from Aurora `modexp` [implementation](https://github.com/aurora-is-near/aurora-engine/tree/4ecee7ded1e6c78b69416e5b22388357316f7551/engine-modexp)
Originally from Aurora `modexp` [implementation](https://github.com/aurora-is-near/aurora-engine/tree/0cfda4686dbdb7a57b2dc18dddc5106ec8e24a38/engine-modexp)

## What this crate is

Expand Down
17 changes: 13 additions & 4 deletions arithmetic/arithmetic/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ macro_rules! read_u64_with_overflow {

/// from revm - https://github.com/bluealloy/revm/blob/main/crates/revm_precompiles/src/modexp.rs
fn modexp_precompiled_impl(input: &[u8]) -> Rc<Vec<u8>> {
let len = input.len();
let (base_len, base_overflow) = read_u64_with_overflow!(input, 0, 32, u32::MAX as usize);
let (exp_len, exp_overflow) = read_u64_with_overflow!(input, 32, 64, u32::MAX as usize);
let (mod_len, mod_overflow) = read_u64_with_overflow!(input, 64, 96, u32::MAX as usize);
Expand All @@ -83,10 +84,18 @@ fn modexp_precompiled_impl(input: &[u8]) -> Rc<Vec<u8>> {
let exp_end = base_end + exp_len;
let mod_end = exp_end + mod_len;

let base = &input[base_start..base_end];
let exponent = &input[base_end..exp_end];
let modulus = &input[exp_end..mod_end];
let bytes = modexp(base, exponent, modulus);
let read_big = |from: usize, to: usize| {
let mut out = vec![0; to - from];
let from = min(from, len);
let to = min(to, len);
out[..to - from].copy_from_slice(&input[from..to]);
out
};

let base = read_big(base_start, base_end);
let exponent = read_big(base_end, exp_end);
let modulus = read_big(exp_end, mod_end);
let bytes = modexp(base.as_slice(), exponent.as_slice(), modulus.as_slice());

// write output to given memory, left padded and same length as the modulus.
// always true except in the case of zero-length modulus, which leads to
Expand Down
45 changes: 43 additions & 2 deletions arithmetic/arithmetic/src/mpnat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@ pub struct MPNat {
}

impl MPNat {
fn strip_leading_zeroes(a: &[u8]) -> (&[u8], bool) {
let len = a.len();
let end = a.iter().position(|&x| x != 0).unwrap_or(len);

if end == len {
(&[], true)
} else {
(&a[end..], false)
}
}

// Koç's algorithm for inversion mod 2^k
// https://eprint.iacr.org/2017/411.pdf
fn koc_2017_inverse(aa: &Self, k: usize) -> Self {
Expand Down Expand Up @@ -143,8 +154,24 @@ impl MPNat {

/// Computes `self ^ exp mod modulus`. `exp` must be given as big-endian bytes.
pub fn modpow(&mut self, exp: &[u8], modulus: &Self) -> Self {
if exp.iter().all(|x| x == &0) {
return Self { digits: vec![1] };
// exp must be stripped because it is iterated over in
// big_wrapping_pow and modpow_montgomery, and a large
// zero-padded exp leads to performance issues.
let (exp, exp_is_zero) = Self::strip_leading_zeroes(exp);

// base^0 is always 1, regardless of base.
// Hence the result is 0 for (base^0) % 1, and 1
// for every modulus larger than 1.
//
// The case of modulus being 0 should have already been
// handled in modexp().
debug_assert!(!(modulus.digits.len() == 1 && modulus.digits[0] == 0));
if exp_is_zero {
if modulus.digits.len() == 1 && modulus.digits[0] == 1 {
return Self { digits: vec![0] };
} else {
return Self { digits: vec![1] };
}
}

if exp.len() <= core::mem::size_of::<usize>() {
Expand Down Expand Up @@ -604,6 +631,20 @@ fn test_modpow_even() {
"023f4f762936eb0973d46b6eadb59d68d06101"
);

// Test empty exp
let base = hex::decode("00").unwrap();
let exponent = hex::decode("").unwrap();
let modulus = hex::decode("02").unwrap();
let result = crate::modexp(&base, &exponent, &modulus);
assert_eq!(hex::encode(result), "01");

// Test zero exp
let base = hex::decode("00").unwrap();
let exponent = hex::decode("00").unwrap();
let modulus = hex::decode("02").unwrap();
let result = crate::modexp(&base, &exponent, &modulus);
assert_eq!(hex::encode(result), "01");

fn check_modpow_even(base: u128, exp: u128, modulus: u128, expected: u128) {
let mut x = MPNat::from_big_endian(&base.to_be_bytes());
let m = MPNat::from_big_endian(&modulus.to_be_bytes());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ public class TestLibArithmetic {

public static Object[][] modExpParameters() {
return new Object[][] {
{
"000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
"0000000000000000000000000000000000000000000000000000000000000000"
},
{
"000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
"0000000000000000000000000000000000000000000000000000000000000000"
},
{
"000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
"0000000000000000000000000000000000000000000000000000000000000000"
},
{
"00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002003fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2efffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
"0000000000000000000000000000000000000000000000000000000000000001"
Expand Down Expand Up @@ -100,5 +112,4 @@ void testModExp(String inputString, String outputString) {

assertThat(result).isEqualTo(output);
}

}
Loading