Skip to content

Commit dfd0762

Browse files
authored
Merge pull request ethereum#14718 from holiman/gascalc_fix
core/vm: fix overflow in gas calculation formula
2 parents 6dc32e8 + e430156 commit dfd0762

File tree

2 files changed

+17
-17
lines changed

2 files changed

+17
-17
lines changed

core/vm/gas_table.go

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
package vm
1818

1919
import (
20-
gmath "math"
2120
"math/big"
2221

2322
"github.com/ethereum/go-ethereum/common"
@@ -28,15 +27,20 @@ import (
2827
// memoryGasCosts calculates the quadratic gas for memory expansion. It does so
2928
// only for the memory region that is expanded, not the total memory.
3029
func memoryGasCost(mem *Memory, newMemSize uint64) (uint64, error) {
31-
// The maximum that will fit in a uint64 is max_word_count - 1
32-
// anything above that will result in an overflow.
33-
if newMemSize > gmath.MaxUint64-32 {
34-
return 0, errGasUintOverflow
35-
}
3630

3731
if newMemSize == 0 {
3832
return 0, nil
3933
}
34+
// The maximum that will fit in a uint64 is max_word_count - 1
35+
// anything above that will result in an overflow.
36+
// Additionally, a newMemSize which results in a
37+
// newMemSizeWords larger than 0x7ffffffff will cause the square operation
38+
// to overflow.
39+
// The constant 0xffffffffe0 is the highest number that can be used without
40+
// overflowing the gas calculation
41+
if newMemSize > 0xffffffffe0 {
42+
return 0, errGasUintOverflow
43+
}
4044

4145
newMemSizeWords := toWordSize(newMemSize)
4246
newMemSize = newMemSizeWords * 32

core/vm/gas_table_test.go

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,24 +16,20 @@
1616

1717
package vm
1818

19-
import (
20-
"math"
21-
"testing"
22-
)
19+
import "testing"
2320

2421
func TestMemoryGasCost(t *testing.T) {
25-
size := uint64(math.MaxUint64 - 64)
26-
_, err := memoryGasCost(&Memory{}, size)
22+
//size := uint64(math.MaxUint64 - 64)
23+
size := uint64(0xffffffffe0)
24+
v, err := memoryGasCost(&Memory{}, size)
2725
if err != nil {
2826
t.Error("didn't expect error:", err)
2927
}
30-
31-
_, err = memoryGasCost(&Memory{}, size+32)
32-
if err != nil {
33-
t.Error("didn't expect error:", err)
28+
if v != 36028899963961341 {
29+
t.Errorf("Expected: 36028899963961341, got %d", v)
3430
}
3531

36-
_, err = memoryGasCost(&Memory{}, size+33)
32+
_, err = memoryGasCost(&Memory{}, size+1)
3733
if err == nil {
3834
t.Error("expected error")
3935
}

0 commit comments

Comments
 (0)