Skip to content

Commit bed3b10

Browse files
authored
common/math: optimized modexp (+ fuzzer) (#25525)
This adds a * core/vm, tests: optimized modexp + fuzzer * common/math: modexp optimizations * core/vm: special case base 1 in big modexp * core/vm: disable fastexp
1 parent a007ab7 commit bed3b10

File tree

4 files changed

+181
-2
lines changed

4 files changed

+181
-2
lines changed

common/math/modexp.go

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Copyright 2020 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package math
6+
7+
import (
8+
"math/big"
9+
"math/bits"
10+
11+
"github.com/ethereum/go-ethereum/common"
12+
)
13+
14+
// FastExp is semantically equivalent to x.Exp(x,y, m), but is faster for even
15+
// modulus.
16+
func FastExp(x, y, m *big.Int) *big.Int {
17+
// Split m = m1 × m2 where m1 = 2ⁿ
18+
n := m.TrailingZeroBits()
19+
m1 := new(big.Int).Lsh(common.Big1, n)
20+
mask := new(big.Int).Sub(m1, common.Big1)
21+
m2 := new(big.Int).Rsh(m, n)
22+
23+
// We want z = x**y mod m.
24+
// z1 = x**y mod m1 = (x**y mod m) mod m1 = z mod m1
25+
// z2 = x**y mod m2 = (x**y mod m) mod m2 = z mod m2
26+
z1 := fastExpPow2(x, y, mask)
27+
z2 := new(big.Int).Exp(x, y, m2)
28+
29+
// Reconstruct z from z1, z2 using CRT, using algorithm from paper,
30+
// which uses only a single modInverse.
31+
// p = (z1 - z2) * m2⁻¹ (mod m1)
32+
// z = z2 + p * m2
33+
z := new(big.Int).Set(z2)
34+
35+
// Compute (z1 - z2) mod m1 [m1 == 2**n] into z1.
36+
z1 = z1.And(z1, mask)
37+
z2 = z2.And(z2, mask)
38+
z1 = z1.Sub(z1, z2)
39+
if z1.Sign() < 0 {
40+
z1 = z1.Add(z1, m1)
41+
}
42+
43+
// Reuse z2 for p = z1 * m2inv.
44+
m2inv := new(big.Int).ModInverse(m2, m1)
45+
z2 = z2.Mul(z1, m2inv)
46+
z2 = z2.And(z2, mask)
47+
48+
// Reuse z1 for m2 * p.
49+
z = z.Add(z, z1.Mul(z2, m2))
50+
z = z.Rem(z, m)
51+
52+
return z
53+
}
54+
55+
func fastExpPow2(x, y *big.Int, mask *big.Int) *big.Int {
56+
z := big.NewInt(1)
57+
if y.Sign() == 0 {
58+
return z
59+
}
60+
p := new(big.Int).Set(x)
61+
p = p.And(p, mask)
62+
if p.Cmp(z) <= 0 { // p <= 1
63+
return p
64+
}
65+
if y.Cmp(mask) > 0 {
66+
y = new(big.Int).And(y, mask)
67+
}
68+
t := new(big.Int)
69+
70+
for _, b := range y.Bits() {
71+
for i := 0; i < bits.UintSize; i++ {
72+
if b&1 != 0 {
73+
z, t = t.Mul(z, p), z
74+
z = z.And(z, mask)
75+
}
76+
p, t = t.Mul(p, p), p
77+
p = p.And(p, mask)
78+
b >>= 1
79+
}
80+
}
81+
return z
82+
}

core/vm/contracts.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -380,12 +380,23 @@ func (c *bigModExp) Run(input []byte) ([]byte, error) {
380380
base = new(big.Int).SetBytes(getData(input, 0, baseLen))
381381
exp = new(big.Int).SetBytes(getData(input, baseLen, expLen))
382382
mod = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen))
383+
v []byte
383384
)
384-
if mod.BitLen() == 0 {
385+
switch {
386+
case mod.BitLen() == 0:
385387
// Modulo 0 is undefined, return zero
386388
return common.LeftPadBytes([]byte{}, int(modLen)), nil
389+
case base.Cmp(common.Big1) == 0:
390+
//If base == 1, then we can just return base % mod (if mod >= 1, which it is)
391+
v = base.Mod(base, mod).Bytes()
392+
//case mod.Bit(0) == 0:
393+
// // Modulo is even
394+
// v = math.FastExp(base, exp, mod).Bytes()
395+
default:
396+
// Modulo is odd
397+
v = base.Exp(base, exp, mod).Bytes()
387398
}
388-
return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil
399+
return common.LeftPadBytes(v, int(modLen)), nil
389400
}
390401

391402
// newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point,

oss-fuzz.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,5 +125,7 @@ compile_fuzzer tests/fuzzers/snap FuzzSRange fuzz_storage_range
125125
compile_fuzzer tests/fuzzers/snap FuzzByteCodes fuzz_byte_codes
126126
compile_fuzzer tests/fuzzers/snap FuzzTrieNodes fuzz_trie_nodes
127127

128+
compile_fuzzer tests/fuzzers/modexp Fuzz fuzzModexp
129+
128130
#TODO: move this to tests/fuzzers, if possible
129131
compile_fuzzer crypto/blake2b Fuzz fuzzBlake2b
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// Copyright 2022 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package modexp
18+
19+
import (
20+
"fmt"
21+
"math/big"
22+
23+
"github.com/ethereum/go-ethereum/common"
24+
"github.com/ethereum/go-ethereum/common/math"
25+
"github.com/ethereum/go-ethereum/core/vm"
26+
)
27+
28+
// The function must return
29+
// 1 if the fuzzer should increase priority of the
30+
// given input during subsequent fuzzing (for example, the input is lexically
31+
// correct and was parsed successfully);
32+
// -1 if the input must not be added to corpus even if gives new coverage; and
33+
// 0 otherwise
34+
// other values are reserved for future use.
35+
func Fuzz(input []byte) int {
36+
if len(input) <= 96 {
37+
return -1
38+
}
39+
// Abort on too expensive inputs
40+
precomp := vm.PrecompiledContractsBerlin[common.BytesToAddress([]byte{5})]
41+
if gas := precomp.RequiredGas(input); gas > 40_000_000 {
42+
return 0
43+
}
44+
var (
45+
baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64()
46+
expLen = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64()
47+
modLen = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64()
48+
)
49+
// Handle a special case when both the base and mod length is zero
50+
if baseLen == 0 && modLen == 0 {
51+
return -1
52+
}
53+
input = input[96:]
54+
// Retrieve the operands and execute the exponentiation
55+
var (
56+
base = new(big.Int).SetBytes(getData(input, 0, baseLen))
57+
exp = new(big.Int).SetBytes(getData(input, baseLen, expLen))
58+
mod = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen))
59+
)
60+
if mod.BitLen() == 0 {
61+
// Modulo 0 is undefined, return zero
62+
return -1
63+
}
64+
var a = math.FastExp(new(big.Int).Set(base), new(big.Int).Set(exp), new(big.Int).Set(mod))
65+
var b = base.Exp(base, exp, mod)
66+
if a.Cmp(b) != 0 {
67+
panic(fmt.Sprintf("Inequality %x != %x", a, b))
68+
}
69+
return 1
70+
}
71+
72+
// getData returns a slice from the data based on the start and size and pads
73+
// up to size with zero's. This function is overflow safe.
74+
func getData(data []byte, start uint64, size uint64) []byte {
75+
length := uint64(len(data))
76+
if start > length {
77+
start = length
78+
}
79+
end := start + size
80+
if end > length {
81+
end = length
82+
}
83+
return common.RightPadBytes(data[start:end], int(size))
84+
}

0 commit comments

Comments
 (0)