Skip to content

Commit

Permalink
fix: expmod precompile if modulus is 1 (#1294)
Browse files Browse the repository at this point in the history
  • Loading branch information
ivokub authored Oct 16, 2024
1 parent 09571fe commit f7b61b7
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
11 changes: 8 additions & 3 deletions std/evmprecompiles/05-expmod.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,21 @@ import (
//
// [MODEXP]: https://ethereum.github.io/execution-specs/autoapi/ethereum/paris/vm/precompiled_contracts/expmod/index.html
func Expmod[P emulated.FieldParams](api frontend.API, base, exp, modulus *emulated.Element[P]) *emulated.Element[P] {
// x^0 = 1
// x^0 = 1 (unless mod 0 or mod 1)
// x mod 0 = 0
// x mod 1 = 0
// 0^0 = 1 (unless mod 0 or mod 1)

f, err := emulated.NewField[P](api)
if err != nil {
panic(fmt.Sprintf("new field: %v", err))
}
// in case modulus is zero, then need to compute with dummy values and return zero as a result
// in case modulus is zero or one, then need to compute with dummy values and return zero as a result
isZeroMod := f.IsZero(modulus)
isOneMod := f.IsZero(f.Sub(modulus, f.One()))
isOneOrZeroMod := api.Or(isZeroMod, isOneMod)
modulus = f.Select(isZeroMod, f.One(), modulus)
res := f.ModExp(base, exp, modulus)
res = f.Select(isZeroMod, f.Zero(), res)
res = f.Select(isOneOrZeroMod, f.Zero(), res)
return res
}
2 changes: 1 addition & 1 deletion std/evmprecompiles/05-expmod_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func TestEdgeCases(t *testing.T) {
base, exp, modulus, result *big.Int
}{
{big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0)}, // 0^0 = 0 mod 0
{big.NewInt(0), big.NewInt(0), big.NewInt(1), big.NewInt(1)}, // 0^0 = 1 mod 1
{big.NewInt(0), big.NewInt(0), big.NewInt(1), big.NewInt(0)}, // 0^0 = 0 mod 1
{big.NewInt(0), big.NewInt(0), big.NewInt(123), big.NewInt(1)}, // 0^0 = 1 mod 123
{big.NewInt(123), big.NewInt(123), big.NewInt(0), big.NewInt(0)}, // 123^123 = 0 mod 0
{big.NewInt(123), big.NewInt(123), big.NewInt(0), big.NewInt(0)}, // 123^123 = 0 mod 1
Expand Down

0 comments on commit f7b61b7

Please sign in to comment.