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

Fix gas cost overflow for opCall opcode #2026

Merged
merged 5 commits into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 3 additions & 1 deletion chain/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,10 @@ func (f *Forks) SetFork(name string, value Fork) {
(*f)[name] = value
}

func (f *Forks) RemoveFork(name string) {
func (f *Forks) RemoveFork(name string) *Forks {
delete(*f, name)

return f
}

// At returns ForksInTime instance that shows which supported forks are enabled for the block
Expand Down
10 changes: 10 additions & 0 deletions helper/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,16 @@ func BigIntDivCeil(a, b *big.Int) *big.Int {
Div(result, b)
}

// SafeAddUint64 sums two unsigned int64 numbers if there are no overflow.
Stefan-Ethernal marked this conversation as resolved.
Show resolved Hide resolved
// In case there is an overflow, it would return 0 and true, otherwise sum and false.
func SafeAddUint64(a, b uint64) (uint64, bool) {
Stefan-Ethernal marked this conversation as resolved.
Show resolved Hide resolved
if a > math.MaxUint64-b {
return 0, true
}

return a + b, false
}

// EncodeUint64ToBytes encodes provided uint64 to big endian byte slice
func EncodeUint64ToBytes(value uint64) []byte {
result := make([]byte, 8)
Expand Down
31 changes: 31 additions & 0 deletions helper/common/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"math/big"
"testing"
"time"
Expand Down Expand Up @@ -124,3 +126,32 @@ func TestRetryForever_CancelContext_ShouldEnd(t *testing.T) {
})
require.True(t, errors.Is(ctx.Err(), context.Canceled))
}

func Test_SafeAddUint64(t *testing.T) {
cases := []struct {
a uint64
b uint64
result uint64
overflow bool
}{
{
a: 10,
b: 4,
result: 14,
},
{
a: math.MaxUint64,
b: 3,
result: 0,
overflow: true,
},
}

for i, c := range cases {
t.Run(fmt.Sprintf("%d case", i+1), func(t *testing.T) {
actualResult, actualOverflow := SafeAddUint64(c.a, c.b)
require.Equal(t, c.result, actualResult)
require.Equal(t, c.overflow, actualOverflow)
})
}
}
18 changes: 12 additions & 6 deletions state/runtime/evm/instructions.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ package evm

import (
"errors"
"fmt"
"math/big"
"math/bits"
"sync"

"github.com/0xPolygon/polygon-edge/crypto"
"github.com/0xPolygon/polygon-edge/helper/common"
"github.com/0xPolygon/polygon-edge/helper/keccak"
"github.com/0xPolygon/polygon-edge/state/runtime"
"github.com/0xPolygon/polygon-edge/types"
Expand Down Expand Up @@ -1232,11 +1232,10 @@ func (c *state) buildCallContract(op OpCode) (*runtime.Contract, uint64, uint64,
gasCost = 40
}

eip158 := c.config.EIP158
transfersValue := (op == CALL || op == CALLCODE) && value != nil && value.Sign() != 0

if op == CALL {
if eip158 {
if c.config.EIP158 {
if transfersValue && c.host.Empty(addr) {
gasCost += 25000
}
Expand Down Expand Up @@ -1271,7 +1270,14 @@ func (c *state) buildCallContract(op OpCode) (*runtime.Contract, uint64, uint64,
gas = initialGas.Uint64()
}

gasCost = gasCost + gas
gasCostTmp, isOverflow := common.SafeAddUint64(gasCost, gas)
if isOverflow {
c.exit(errGasUintOverflow)

return nil, 0, 0, nil
}

gasCost = gasCostTmp

// Consume gas cost
if !c.consumeGas(gasCost) {
Expand Down Expand Up @@ -1309,7 +1315,7 @@ func (c *state) buildCallContract(op OpCode) (*runtime.Contract, uint64, uint64,

if transfersValue {
if c.host.GetBalance(c.msg.Address).Cmp(value) < 0 {
return contract, 0, 0, fmt.Errorf("bad")
return contract, 0, 0, types.ErrInsufficientFunds
}
}

Expand Down Expand Up @@ -1352,7 +1358,7 @@ func (c *state) buildCreateContract(op OpCode) (*runtime.Contract, error) {

if hasTransfer {
if c.host.GetBalance(c.msg.Address).Cmp(value) < 0 {
return nil, fmt.Errorf("bad")
vcastellm marked this conversation as resolved.
Show resolved Hide resolved
return nil, types.ErrInsufficientFunds
}
}

Expand Down
81 changes: 75 additions & 6 deletions state/runtime/evm/instructions_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package evm

import (
"math"
"math/big"
"testing"

Expand Down Expand Up @@ -666,7 +667,7 @@ func Test_opCall(t *testing.T) {
name string
op OpCode
contract *runtime.Contract
config *chain.ForksInTime
config chain.ForksInTime
initState *state
resultState *state
mockHost *mockHostForInstructions
Expand All @@ -678,7 +679,7 @@ func Test_opCall(t *testing.T) {
contract: &runtime.Contract{
Static: true,
},
config: &allEnabledForks,
config: allEnabledForks,
initState: &state{
gas: 1000,
sp: 6,
Expand All @@ -696,6 +697,73 @@ func Test_opCall(t *testing.T) {
memory: []byte{0x01},
stop: false,
err: nil,
gas: 300,
},
mockHost: &mockHostForInstructions{
callxResult: &runtime.ExecutionResult{
ReturnValue: []byte{0x03},
},
},
},
{
name: "call cost overflow (EIP150 fork disabled)",
op: CALLCODE,
contract: &runtime.Contract{
Static: false,
},
config: chain.AllForksEnabled.RemoveFork(chain.EIP150).At(0),
initState: &state{
gas: 6640,
sp: 7,
stack: []*big.Int{
big.NewInt(0x00), // outSize
big.NewInt(0x00), // outOffset
big.NewInt(0x00), // inSize
big.NewInt(0x00), // inOffset
big.NewInt(0x01), // value
big.NewInt(0x03), // address
big.NewInt(0).SetUint64(math.MaxUint64), // initialGas
},
memory: []byte{0x01},
},
resultState: &state{
memory: []byte{0x01},
stop: true,
err: errGasUintOverflow,
gas: 6640,
},
mockHost: &mockHostForInstructions{
callxResult: &runtime.ExecutionResult{
ReturnValue: []byte{0x03},
},
},
},
{
name: "available gas underflow",
op: CALLCODE,
contract: &runtime.Contract{
Static: false,
},
config: allEnabledForks,
initState: &state{
gas: 6640,
sp: 7,
stack: []*big.Int{
big.NewInt(0x00), // outSize
big.NewInt(0x00), // outOffset
big.NewInt(0x00), // inSize
big.NewInt(0x00), // inOffset
big.NewInt(0x01), // value
big.NewInt(0x03), // address
big.NewInt(0).SetUint64(math.MaxUint64), // initialGas
},
memory: []byte{0x01},
},
resultState: &state{
memory: []byte{0x01},
stop: true,
err: errOutOfGas,
gas: 6640,
},
mockHost: &mockHostForInstructions{
callxResult: &runtime.ExecutionResult{
Expand All @@ -717,14 +785,15 @@ func Test_opCall(t *testing.T) {
state.sp = test.initState.sp
state.stack = test.initState.stack
state.memory = test.initState.memory
state.config = test.config
state.config = &test.config
state.host = test.mockHost

opCall(test.op)(state)

assert.Equal(t, test.resultState.memory, state.memory, "memory in state after execution is not correct")
assert.Equal(t, test.resultState.stop, state.stop, "stop in state after execution is not correct")
assert.Equal(t, test.resultState.err, state.err, "err in state after execution is not correct")
assert.Equal(t, test.resultState.memory, state.memory, "memory in state after execution is incorrect")
assert.Equal(t, test.resultState.stop, state.stop, "stop in state after execution is incorrect")
assert.Equal(t, test.resultState.err, state.err, "err in state after execution is incorrect")
assert.Equal(t, test.resultState.gas, state.gas, "gas in state after execution is incorrect")
})
}
}
3 changes: 3 additions & 0 deletions types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ var (

// ErrTxTypeNotSupported denotes that transaction is not supported
ErrTxTypeNotSupported = errors.New("transaction type not supported")

// ErrInsufficientFunds denotes that account has insufficient funds for transaction execution
ErrInsufficientFunds = errors.New("insufficient funds for execution")
)

type Hash [HashLength]byte
Expand Down
Loading