Skip to content

Commit 7504dbd

Browse files
holimankaralabe
authored andcommitted
core/vm: 64 bit memory and gas calculations (#19210)
* core/vm: remove function call for stack validation from evm runloop * core/vm: separate gas calc into static + dynamic * core/vm: optimize push1 * core/vm: reuse pooled bigints for ADDRESS, ORIGIN and CALLER * core/vm: use generic error message for jump/jumpi, to avoid string interpolation * testdata: fix tests for new error message * core/vm: use 64-bit memory calculations * core/vm: fix error in memory calculation * core/vm: address review concerns * core/vm: avoid unnecessary use of big.Int:BitLen()
1 parent da5de01 commit 7504dbd

13 files changed

Lines changed: 914 additions & 744 deletions

‎common/types.go‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -202,9 +202,6 @@ func IsHexAddress(s string) bool {
202202
// Bytes gets the string representation of the underlying address.
203203
func (a Address) Bytes() []byte { return a[:] }
204204

205-
// Big converts an address to a big integer.
206-
func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) }
207-
208205
// Hash converts an address to a hash by left-padding it with zeros.
209206
func (a Address) Hash() Hash { return BytesToHash(a[:]) }
210207

‎common/types_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,8 @@ func TestAddressUnmarshalJSON(t *testing.T) {
114114
if test.ShouldErr {
115115
t.Errorf("test #%d: expected error, got none", i)
116116
}
117-
if v.Big().Cmp(test.Output) != 0 {
118-
t.Errorf("test #%d: address mismatch: have %v, want %v", i, v.Big(), test.Output)
117+
if got := new(big.Int).SetBytes(v.Bytes()); got.Cmp(test.Output) != 0 {
118+
t.Errorf("test #%d: address mismatch: have %v, want %v", i, got, test.Output)
119119
}
120120
}
121121
}

‎core/mkalloc.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ func makelist(g *core.Genesis) allocList {
5252
if len(account.Storage) > 0 || len(account.Code) > 0 || account.Nonce != 0 {
5353
panic(fmt.Sprintf("can't encode account %x", addr))
5454
}
55-
a = append(a, allocItem{addr.Big(), account.Balance})
55+
bigAddr := new(big.Int).SetBytes(addr.Bytes())
56+
a = append(a, allocItem{bigAddr, account.Balance})
5657
}
5758
sort.Sort(a)
5859
return a

‎core/vm/common.go‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,31 @@ import (
2323
"github.com/ethereum/go-ethereum/common/math"
2424
)
2525

26-
// calculates the memory size required for a step
27-
func calcMemSize(off, l *big.Int) *big.Int {
28-
if l.Sign() == 0 {
29-
return common.Big0
26+
// calcMemSize64 calculates the required memory size, and returns
27+
// the size and whether the result overflowed uint64
28+
func calcMemSize64(off, l *big.Int) (uint64, bool) {
29+
if !l.IsUint64() {
30+
return 0, true
3031
}
32+
return calcMemSize64WithUint(off, l.Uint64())
33+
}
3134

32-
return new(big.Int).Add(off, l)
35+
// calcMemSize64WithUint calculates the required memory size, and returns
36+
// the size and whether the result overflowed uint64
37+
// Identical to calcMemSize64, but length is a uint64
38+
func calcMemSize64WithUint(off *big.Int, length64 uint64) (uint64, bool) {
39+
// if length is zero, memsize is always zero, regardless of offset
40+
if length64 == 0 {
41+
return 0, false
42+
}
43+
// Check that offset doesn't overflow
44+
if !off.IsUint64() {
45+
return 0, true
46+
}
47+
offset64 := off.Uint64()
48+
val := offset64 + length64
49+
// if value < either of it's parts, then it overflowed
50+
return val, val < offset64
3351
}
3452

3553
// getData returns a slice from the data based on the start and size and pads
@@ -59,7 +77,7 @@ func getDataBig(data []byte, start *big.Int, size *big.Int) []byte {
5977
// bigUint64 returns the integer casted to a uint64 and returns whether it
6078
// overflowed in the process.
6179
func bigUint64(v *big.Int) (uint64, bool) {
62-
return v.Uint64(), v.BitLen() > 64
80+
return v.Uint64(), !v.IsUint64()
6381
}
6482

6583
// toWordSize returns the ceiled word size required for memory expansion.

‎core/vm/gas.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,11 @@ func callGas(gasTable params.GasTable, availableGas, base uint64, callCost *big.
4343
// If the bit length exceeds 64 bit we know that the newly calculated "gas" for EIP150
4444
// is smaller than the requested amount. Therefor we return the new gas instead
4545
// of returning an error.
46-
if callCost.BitLen() > 64 || gas < callCost.Uint64() {
46+
if !callCost.IsUint64() || gas < callCost.Uint64() {
4747
return gas, nil
4848
}
4949
}
50-
if callCost.BitLen() > 64 {
50+
if !callCost.IsUint64() {
5151
return 0, errGasUintOverflow
5252
}
5353

‎core/vm/gas_table.go‎

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,6 @@ func memoryGasCost(mem *Memory, newMemSize uint64) (uint64, error) {
5757
return 0, nil
5858
}
5959

60-
func constGasFunc(gas uint64) gasFunc {
61-
return func(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
62-
return gas, nil
63-
}
64-
}
65-
6660
func gasCallDataCopy(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
6761
gas, err := memoryGasCost(mem, memorySize)
6862
if err != nil {
@@ -521,15 +515,3 @@ func gasStaticCall(gt params.GasTable, evm *EVM, contract *Contract, stack *Stac
521515
}
522516
return gas, nil
523517
}
524-
525-
func gasPush(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
526-
return GasFastestStep, nil
527-
}
528-
529-
func gasSwap(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
530-
return GasFastestStep, nil
531-
}
532-
533-
func gasDup(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
534-
return GasFastestStep, nil
535-
}

‎core/vm/instructions.go‎

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ package vm
1818

1919
import (
2020
"errors"
21-
"fmt"
2221
"math/big"
2322

2423
"github.com/ethereum/go-ethereum/common"
@@ -35,6 +34,7 @@ var (
3534
errReturnDataOutOfBounds = errors.New("evm: return data out of bounds")
3635
errExecutionReverted = errors.New("evm: execution reverted")
3736
errMaxCodeSizeExceeded = errors.New("evm: max code size exceeded")
37+
errInvalidJump = errors.New("evm: invalid jump destination")
3838
)
3939

4040
func opAdd(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
@@ -405,7 +405,7 @@ func opSha3(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory
405405
}
406406

407407
func opAddress(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
408-
stack.push(contract.Address().Big())
408+
stack.push(interpreter.intPool.get().SetBytes(contract.Address().Bytes()))
409409
return nil, nil
410410
}
411411

@@ -416,12 +416,12 @@ func opBalance(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memo
416416
}
417417

418418
func opOrigin(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
419-
stack.push(interpreter.evm.Origin.Big())
419+
stack.push(interpreter.intPool.get().SetBytes(interpreter.evm.Origin.Bytes()))
420420
return nil, nil
421421
}
422422

423423
func opCaller(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
424-
stack.push(contract.Caller().Big())
424+
stack.push(interpreter.intPool.get().SetBytes(contract.Caller().Bytes()))
425425
return nil, nil
426426
}
427427

@@ -467,7 +467,7 @@ func opReturnDataCopy(pc *uint64, interpreter *EVMInterpreter, contract *Contrac
467467
)
468468
defer interpreter.intPool.put(memOffset, dataOffset, length, end)
469469

470-
if end.BitLen() > 64 || uint64(len(interpreter.returnData)) < end.Uint64() {
470+
if !end.IsUint64() || uint64(len(interpreter.returnData)) < end.Uint64() {
471471
return nil, errReturnDataOutOfBounds
472472
}
473473
memory.Set(memOffset.Uint64(), length.Uint64(), interpreter.returnData[dataOffset.Uint64():end.Uint64()])
@@ -572,7 +572,7 @@ func opBlockhash(pc *uint64, interpreter *EVMInterpreter, contract *Contract, me
572572
}
573573

574574
func opCoinbase(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
575-
stack.push(interpreter.evm.Coinbase.Big())
575+
stack.push(interpreter.intPool.get().SetBytes(interpreter.evm.Coinbase.Bytes()))
576576
return nil, nil
577577
}
578578

@@ -645,8 +645,7 @@ func opSstore(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memor
645645
func opJump(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
646646
pos := stack.pop()
647647
if !contract.validJumpdest(pos) {
648-
nop := contract.GetOp(pos.Uint64())
649-
return nil, fmt.Errorf("invalid jump destination (%v) %v", nop, pos)
648+
return nil, errInvalidJump
650649
}
651650
*pc = pos.Uint64()
652651

@@ -658,8 +657,7 @@ func opJumpi(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory
658657
pos, cond := stack.pop(), stack.pop()
659658
if cond.Sign() != 0 {
660659
if !contract.validJumpdest(pos) {
661-
nop := contract.GetOp(pos.Uint64())
662-
return nil, fmt.Errorf("invalid jump destination (%v) %v", nop, pos)
660+
return nil, errInvalidJump
663661
}
664662
*pc = pos.Uint64()
665663
} else {
@@ -711,7 +709,7 @@ func opCreate(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memor
711709
} else if suberr != nil && suberr != ErrCodeStoreOutOfGas {
712710
stack.push(interpreter.intPool.getZero())
713711
} else {
714-
stack.push(addr.Big())
712+
stack.push(interpreter.intPool.get().SetBytes(addr.Bytes()))
715713
}
716714
contract.Gas += returnGas
717715
interpreter.intPool.put(value, offset, size)
@@ -739,7 +737,7 @@ func opCreate2(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memo
739737
if suberr != nil {
740738
stack.push(interpreter.intPool.getZero())
741739
} else {
742-
stack.push(addr.Big())
740+
stack.push(interpreter.intPool.get().SetBytes(addr.Bytes()))
743741
}
744742
contract.Gas += returnGas
745743
interpreter.intPool.put(endowment, offset, size, salt)
@@ -912,6 +910,21 @@ func makeLog(size int) executionFunc {
912910
}
913911
}
914912

913+
// opPush1 is a specialized version of pushN
914+
func opPush1(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
915+
var (
916+
codeLen = uint64(len(contract.Code))
917+
integer = interpreter.intPool.get()
918+
)
919+
*pc += 1
920+
if *pc < codeLen {
921+
stack.push(integer.SetUint64(uint64(contract.Code[*pc])))
922+
} else {
923+
stack.push(integer.SetUint64(0))
924+
}
925+
return nil, nil
926+
}
927+
915928
// make push instruction function
916929
func makePush(size uint64, pushByteSize int) executionFunc {
917930
return func(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {

‎core/vm/interpreter.go‎

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -118,22 +118,6 @@ func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
118118
}
119119
}
120120

121-
func (in *EVMInterpreter) enforceRestrictions(op OpCode, operation operation, stack *Stack) error {
122-
if in.evm.chainRules.IsByzantium {
123-
if in.readOnly {
124-
// If the interpreter is operating in readonly mode, make sure no
125-
// state-modifying operation is performed. The 3rd stack item
126-
// for a call operation is the value. Transferring value from one
127-
// account to the others means the state is modified and should also
128-
// return with an error.
129-
if operation.writes || (op == CALL && stack.Back(2).BitLen() > 0) {
130-
return errWriteProtection
131-
}
132-
}
133-
}
134-
return nil
135-
}
136-
137121
// Run loops and evaluates the contract's code with the given input data and returns
138122
// the return byte-slice and an error if one occurred.
139123
//
@@ -217,19 +201,35 @@ func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (
217201
if !operation.valid {
218202
return nil, fmt.Errorf("invalid opcode 0x%x", int(op))
219203
}
220-
if err = operation.validateStack(stack); err != nil {
221-
return nil, err
204+
// Validate stack
205+
if sLen := stack.len(); sLen < operation.minStack {
206+
return nil, fmt.Errorf("stack underflow (%d <=> %d)", sLen, operation.minStack)
207+
} else if sLen > operation.maxStack {
208+
return nil, fmt.Errorf("stack limit reached %d (%d)", sLen, operation.maxStack)
222209
}
223210
// If the operation is valid, enforce and write restrictions
224-
if err = in.enforceRestrictions(op, operation, stack); err != nil {
225-
return nil, err
211+
if in.readOnly && in.evm.chainRules.IsByzantium {
212+
// If the interpreter is operating in readonly mode, make sure no
213+
// state-modifying operation is performed. The 3rd stack item
214+
// for a call operation is the value. Transferring value from one
215+
// account to the others means the state is modified and should also
216+
// return with an error.
217+
if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) {
218+
return nil, errWriteProtection
219+
}
220+
}
221+
// Static portion of gas
222+
if !contract.UseGas(operation.constantGas) {
223+
return nil, ErrOutOfGas
226224
}
227225

228226
var memorySize uint64
229227
// calculate the new memory size and expand the memory to fit
230228
// the operation
229+
// Memory check needs to be done prior to evaluating the dynamic gas portion,
230+
// to detect calculation overflows
231231
if operation.memorySize != nil {
232-
memSize, overflow := bigUint64(operation.memorySize(stack))
232+
memSize, overflow := operation.memorySize(stack)
233233
if overflow {
234234
return nil, errGasUintOverflow
235235
}
@@ -239,11 +239,14 @@ func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (
239239
return nil, errGasUintOverflow
240240
}
241241
}
242+
// Dynamic portion of gas
242243
// consume the gas and return an error if not enough gas is available.
243244
// cost is explicitly set so that the capture state defer method can get the proper cost
244-
cost, err = operation.gasCost(in.gasTable, in.evm, contract, stack, mem, memorySize)
245-
if err != nil || !contract.UseGas(cost) {
246-
return nil, ErrOutOfGas
245+
if operation.dynamicGas != nil {
246+
cost, err = operation.dynamicGas(in.gasTable, in.evm, contract, stack, mem, memorySize)
247+
if err != nil || !contract.UseGas(cost) {
248+
return nil, ErrOutOfGas
249+
}
247250
}
248251
if memorySize > 0 {
249252
mem.Resize(memorySize)

0 commit comments

Comments
 (0)