core/vm: removed arbitrary precision VM + multithreaded JIT status

Removed the arbitrary precision VM in favour of the optimised JIT VM.
This enables the new VM for all calls and creates and removed the need
for the --jitvm and --forcejit flags.

This fixes a minor issue when the jit is used in a multithreaded
environment it would ignore the complitation status of the JIT and
default to the byte-code VM. Instead it now waits for the compilation to
finish and run the JIT if the execution was successful.
This commit is contained in:
Jeffrey Wilcke 2016-06-15 11:28:33 +02:00 committed by Jeffrey Wilcke
parent f770d3643b
commit 422b26b515
17 changed files with 432 additions and 893 deletions

View file

@ -155,9 +155,7 @@ participating.
utils.WhisperEnabledFlag,
utils.DevModeFlag,
utils.TestNetFlag,
utils.VMForceJitFlag,
utils.VMJitCacheFlag,
utils.VMEnableJitFlag,
utils.VMCacheFlag,
utils.NetworkIdFlag,
utils.RPCCORSDomainFlag,
utils.MetricsEnabledFlag,

View file

@ -149,9 +149,7 @@ var AppHelpFlagGroups = []flagGroup{
{
Name: "VIRTUAL MACHINE",
Flags: []cli.Flag{
utils.VMEnableJitFlag,
utils.VMForceJitFlag,
utils.VMJitCacheFlag,
utils.VMCacheFlag,
},
},
{

View file

@ -22,13 +22,11 @@ import (
"io/ioutil"
"math"
"math/big"
"math/rand"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/ethereum/ethash"
"github.com/ethereum/go-ethereum/accounts"
@ -214,18 +212,10 @@ var (
Value: "",
}
VMForceJitFlag = cli.BoolFlag{
Name: "forcejit",
Usage: "Force the JIT VM to take precedence",
}
VMJitCacheFlag = cli.IntFlag{
Name: "jitcache",
Usage: "Amount of cached JIT VM programs",
Value: 64,
}
VMEnableJitFlag = cli.BoolFlag{
Name: "jitvm",
Usage: "Enable the JIT VM",
VMCacheFlag = cli.IntFlag{
Name: "vmcache",
Usage: "Amount of cached VM programs",
Value: 1024,
}
// logging and debug settings
@ -455,9 +445,6 @@ func makeNodeUserIdent(ctx *cli.Context) string {
if identity := ctx.GlobalString(IdentityFlag.Name); len(identity) > 0 {
comps = append(comps, identity)
}
if ctx.GlobalBool(VMEnableJitFlag.Name) {
comps = append(comps, "JIT")
}
return strings.Join(comps, "/")
}
@ -666,16 +653,6 @@ func RegisterEthService(ctx *cli.Context, stack *node.Node, extra []byte) {
Fatalf("The %v flags are mutually exclusive", netFlags)
}
// initialise new random number generator
rand := rand.New(rand.NewSource(time.Now().UnixNano()))
// get enabled jit flag
jitEnabled := ctx.GlobalBool(VMEnableJitFlag.Name)
// if the jit is not enabled enable it for 10 pct of the people
if !jitEnabled && rand.Float64() < 0.1 {
jitEnabled = true
glog.V(logger.Info).Infoln("You're one of the lucky few that will try out the JIT VM (random). If you get a consensus failure please be so kind to report this incident with the block hash that failed. You can switch to the regular VM by setting --jitvm=false")
}
ethConf := &eth.Config{
Etherbase: MakeEtherbase(stack.AccountManager(), ctx),
ChainConfig: MakeChainConfig(ctx, stack),
@ -687,8 +664,6 @@ func RegisterEthService(ctx *cli.Context, stack *node.Node, extra []byte) {
ExtraData: MakeMinerExtra(extra, ctx),
NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
DocRoot: ctx.GlobalString(DocRootFlag.Name),
EnableJit: jitEnabled,
ForceJit: ctx.GlobalBool(VMForceJitFlag.Name),
GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
GpoMinGasPrice: common.String2Big(ctx.GlobalString(GpoMinGasPriceFlag.Name)),
GpoMaxGasPrice: common.String2Big(ctx.GlobalString(GpoMaxGasPriceFlag.Name)),

View file

@ -40,6 +40,18 @@ func (self PrecompiledAccount) Call(in []byte) []byte {
// Precompiled contains the default set of ethereum contracts
var Precompiled = PrecompiledContracts()
// RunPrecompile runs and evaluate the output of a precompiled contract defined in contracts.go
func RunPrecompiled(p *PrecompiledAccount, input []byte, contract *Contract) (ret []byte, err error) {
gas := p.Gas(len(input))
if contract.UseGas(gas.Uint64()) {
ret = p.Call(input)
return ret, nil
} else {
return nil, OutOfGasError
}
}
// PrecompiledContracts returns the default set of precompiled ethereum
// contracts defined by the ethereum yellow paper.
func PrecompiledContracts() map[string]*PrecompiledAccount {

View file

@ -17,16 +17,10 @@
/*
Package vm implements the Ethereum Virtual Machine.
The vm package implements two EVMs, a byte code VM and a JIT VM. The BC
(Byte Code) VM loops over a set of bytes and executes them according to the set
of rules defined in the Ethereum yellow paper. When the BC VM is invoked it
invokes the JIT VM in a separate goroutine and compiles the byte code in JIT
instructions.
The JIT VM, when invoked, loops around a set of pre-defined instructions until
The VM, when invoked, loops around a set of pre-defined instructions until
it either runs of gas, causes an internal error, returns or stops.
The JIT optimiser attempts to pre-compile instructions in to chunks or segments
The optimiser attempts to pre-compile instructions in to chunks or segments
such as multiple PUSH operations and static JUMPs. It does this by analysing the
opcodes and attempts to match certain regions to known sets. Whenever the
optimiser finds said segments it creates a new instruction and replaces the

View file

@ -1,23 +1,8 @@
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package vm
import (
"fmt"
gmath "math"
"math/big"
"github.com/ethereum/go-ethereum/common"
@ -25,19 +10,36 @@ import (
)
var (
GasQuickStep = big.NewInt(2)
GasFastestStep = big.NewInt(3)
GasFastStep = big.NewInt(5)
GasMidStep = big.NewInt(8)
GasSlowStep = big.NewInt(10)
GasExtStep = big.NewInt(20)
maxInt63 = new(big.Int).Exp(big.NewInt(2), big.NewInt(63), big.NewInt(0))
maxIntCap = new(big.Int).Sub(maxInt63, big.NewInt(1))
)
GasReturn = big.NewInt(0)
GasStop = big.NewInt(0)
var (
StackLimit64 = params.StackLimit.Uint64()
GasQuickStep64 uint64 = 2
GasFastestStep64 uint64 = 3
GasFastStep64 uint64 = 5
GasMidStep64 uint64 = 8
GasSlowStep64 uint64 = 10
GasExtStep64 uint64 = 20
GasContractByte = big.NewInt(200)
GasReturn64 uint64 = 0
GasStop64 uint64 = 0
n64 = big.NewInt(64)
GasContractByte64 uint64 = 200
LogGas64 = params.LogGas.Uint64()
LogTopicGas64 = params.LogTopicGas.Uint64()
LogDataGas64 = params.LogDataGas.Uint64()
ExpByteGas64 = params.ExpByteGas.Uint64()
SstoreSetGas64 = params.SstoreSetGas.Uint64()
SstoreClearGas64 = params.SstoreClearGas.Uint64()
SstoreResetGas64 = params.SstoreResetGas.Uint64()
KeccakWordGas64 = params.Sha3WordGas.Uint64()
CopyGas64 = params.CopyGas.Uint64()
CallNewAccountGas64 = params.CallNewAccountGas.Uint64()
CallValueTransferGas64 = params.CallValueTransferGas.Uint64()
MemoryGas64 = params.MemoryGas.Uint64()
QuadCoeffDiv64 = params.QuadCoeffDiv.Uint64()
)
// calcGas returns the actual gas cost of the call.
@ -45,7 +47,7 @@ var (
// The cost of gas was changed during the homestead price change HF. To allow for EIP150
// to be implemented. The returned gas is gas - base * 63 / 64.
func callGas(gasTable params.GasTable, availableGas, base, callCost uint64) uint64 {
if gasTable.CreateBySuicide != nil {
if gasTable.CreateBySuicide > 0 {
gas := availableGas - (availableGas-base)/64
if gas < callCost {
return gas
@ -54,164 +56,134 @@ func callGas(gasTable params.GasTable, availableGas, base, callCost uint64) uint
return callCost
}
/*
// calcGas returns the actual gas cost of the call.
//
// The cost of gas was changed during the homestead price change HF. To allow for EIP150
// to be implemented. The returned gas is gas - base * 63 / 64.
func callGas(gasTable params.GasTable, availableGas, base, callCost *big.Int) *big.Int {
if gasTable.CreateBySuicide != nil {
availableGas = new(big.Int).Sub(availableGas, base)
g := new(big.Int).Div(availableGas, n64)
g.Sub(availableGas, g)
if g.Cmp(callCost) < 0 {
return g
}
}
return callCost
}
*/
// baseCheck checks for any stack error underflows
func baseCheck(op OpCode, stack *Stack, gas *big.Int) error {
// PUSH and DUP are a bit special. They all cost the same but we do want to have checking on stack push limit
// PUSH is also allowed to calculate the same price for all PUSHes
// DUP requirements are handled elsewhere (except for the stack limit check)
if op >= PUSH1 && op <= PUSH32 {
op = PUSH1
}
if op >= DUP1 && op <= DUP16 {
op = DUP1
}
if r, ok := _baseCheck[op]; ok {
err := stack.require(r.stackPop)
if err != nil {
return err
}
if r.stackPush > 0 && stack.len()-r.stackPop+r.stackPush > int(params.StackLimit.Int64()) {
return fmt.Errorf("stack limit reached %d (%d)", stack.len(), params.StackLimit.Int64())
}
gas.Add(gas, r.gas)
}
return nil
}
// casts a arbitrary number to the amount of words (sets of 32 bytes)
func toWordSize(size *big.Int) *big.Int {
tmp := new(big.Int)
tmp.Add(size, u256(31))
tmp.Div(tmp, u256(32))
return tmp
func toWordSize(size uint64) uint64 {
return (size + 31) / 32
}
// calculates the memory size required for a step
func calcMemSize(off, l *big.Int) *big.Int {
func calcMemSize(off, l *big.Int) (uint64, bool) {
if l.Cmp(common.Big0) == 0 {
return common.Big0
return 0, false
}
return new(big.Int).Add(off, l)
size := new(big.Int).Add(off, l)
if size.Cmp(maxIntCap) > 0 {
return 0, true
}
return size.Uint64(), false
}
// calculates the quadratic gas
func quadMemGas(mem *Memory, newMemSize, gas *big.Int) {
if newMemSize.Cmp(common.Big0) > 0 {
// TODO this function requires guarding of overflows
func calcQuadMemGas(mem *Memory, newMemSize uint64) (uint64, bool) {
oldTotalFee := mem.cost
if newMemSize > 0 {
newMemSizeWords := toWordSize(newMemSize)
newMemSize.Mul(newMemSizeWords, u256(32))
newMemSize = newMemSizeWords * 32
if newMemSize.Cmp(u256(int64(mem.Len()))) > 0 {
// be careful reusing variables here when changing.
// The order has been optimised to reduce allocation
oldSize := toWordSize(big.NewInt(int64(mem.Len())))
pow := new(big.Int).Exp(oldSize, common.Big2, Zero)
linCoef := oldSize.Mul(oldSize, params.MemoryGas)
quadCoef := new(big.Int).Div(pow, params.QuadCoeffDiv)
oldTotalFee := new(big.Int).Add(linCoef, quadCoef)
if newMemSize > uint64(mem.Len()) {
pow := uint64(gmath.Pow(float64(newMemSizeWords), 2))
linCoef := newMemSizeWords * MemoryGas64
quadCoef := pow / QuadCoeffDiv64
newTotalFee := linCoef + quadCoef
pow.Exp(newMemSizeWords, common.Big2, Zero)
linCoef = linCoef.Mul(newMemSizeWords, params.MemoryGas)
quadCoef = quadCoef.Div(pow, params.QuadCoeffDiv)
newTotalFee := linCoef.Add(linCoef, quadCoef)
fee := newTotalFee - oldTotalFee
mem.cost = newTotalFee
fee := newTotalFee.Sub(newTotalFee, oldTotalFee)
gas.Add(gas, fee)
return fee, false
}
}
return 0, false
}
// jitBaseCalc is the same as baseCheck except it doesn't do the look up in the
// gas table. This is done during compilation instead.
func jitBaseCalc(instr instruction, stack *Stack) (uint64, error) {
err := stack.require(instr.spop)
if err != nil {
return 0, err
}
if instr.spush > 0 && stack.len()-instr.spop+instr.spush > int(StackLimit64) {
return 0, fmt.Errorf("stack limit reached %d (%d)", stack.len(), StackLimit64)
}
// 0 on gas means no base calculation
if instr.gas == 0 {
return 0, nil
}
return instr.gas, nil
}
type req struct {
stackPop int
gas *big.Int
gas uint64
stackPush int
}
var _baseCheck = map[OpCode]req{
// opcode | stack pop | gas price | stack push
ADD: {2, GasFastestStep, 1},
LT: {2, GasFastestStep, 1},
GT: {2, GasFastestStep, 1},
SLT: {2, GasFastestStep, 1},
SGT: {2, GasFastestStep, 1},
EQ: {2, GasFastestStep, 1},
ISZERO: {1, GasFastestStep, 1},
SUB: {2, GasFastestStep, 1},
AND: {2, GasFastestStep, 1},
OR: {2, GasFastestStep, 1},
XOR: {2, GasFastestStep, 1},
NOT: {1, GasFastestStep, 1},
BYTE: {2, GasFastestStep, 1},
CALLDATALOAD: {1, GasFastestStep, 1},
CALLDATACOPY: {3, GasFastestStep, 1},
MLOAD: {1, GasFastestStep, 1},
MSTORE: {2, GasFastestStep, 0},
MSTORE8: {2, GasFastestStep, 0},
CODECOPY: {3, GasFastestStep, 0},
MUL: {2, GasFastStep, 1},
DIV: {2, GasFastStep, 1},
SDIV: {2, GasFastStep, 1},
MOD: {2, GasFastStep, 1},
SMOD: {2, GasFastStep, 1},
SIGNEXTEND: {2, GasFastStep, 1},
ADDMOD: {3, GasMidStep, 1},
MULMOD: {3, GasMidStep, 1},
JUMP: {1, GasMidStep, 0},
JUMPI: {2, GasSlowStep, 0},
EXP: {2, GasSlowStep, 1},
ADDRESS: {0, GasQuickStep, 1},
ORIGIN: {0, GasQuickStep, 1},
CALLER: {0, GasQuickStep, 1},
CALLVALUE: {0, GasQuickStep, 1},
CODESIZE: {0, GasQuickStep, 1},
GASPRICE: {0, GasQuickStep, 1},
COINBASE: {0, GasQuickStep, 1},
TIMESTAMP: {0, GasQuickStep, 1},
NUMBER: {0, GasQuickStep, 1},
CALLDATASIZE: {0, GasQuickStep, 1},
DIFFICULTY: {0, GasQuickStep, 1},
GASLIMIT: {0, GasQuickStep, 1},
POP: {1, GasQuickStep, 0},
PC: {0, GasQuickStep, 1},
MSIZE: {0, GasQuickStep, 1},
GAS: {0, GasQuickStep, 1},
BLOCKHASH: {1, GasExtStep, 1},
BALANCE: {1, Zero, 1},
EXTCODESIZE: {1, Zero, 1},
EXTCODECOPY: {4, Zero, 0},
SLOAD: {1, params.SloadGas, 1},
SSTORE: {2, Zero, 0},
SHA3: {2, params.Sha3Gas, 1},
CREATE: {3, params.CreateGas, 1},
// Zero is calculated in the gasSwitch
CALL: {7, Zero, 1},
CALLCODE: {7, Zero, 1},
DELEGATECALL: {6, Zero, 1},
SUICIDE: {1, Zero, 0},
JUMPDEST: {0, params.JumpdestGas, 0},
RETURN: {2, Zero, 0},
PUSH1: {0, GasFastestStep, 1},
DUP1: {0, Zero, 1},
ADD: {2, GasFastestStep64, 1},
LT: {2, GasFastestStep64, 1},
GT: {2, GasFastestStep64, 1},
SLT: {2, GasFastestStep64, 1},
SGT: {2, GasFastestStep64, 1},
EQ: {2, GasFastestStep64, 1},
ISZERO: {1, GasFastestStep64, 1},
SUB: {2, GasFastestStep64, 1},
AND: {2, GasFastestStep64, 1},
OR: {2, GasFastestStep64, 1},
XOR: {2, GasFastestStep64, 1},
NOT: {1, GasFastestStep64, 1},
BYTE: {2, GasFastestStep64, 1},
CALLDATALOAD: {1, GasFastestStep64, 1},
CALLDATACOPY: {3, GasFastestStep64, 1},
MLOAD: {1, GasFastestStep64, 1},
MSTORE: {2, GasFastestStep64, 0},
MSTORE8: {2, GasFastestStep64, 0},
CODECOPY: {3, GasFastestStep64, 0},
MUL: {2, GasFastStep64, 1},
DIV: {2, GasFastStep64, 1},
SDIV: {2, GasFastStep64, 1},
MOD: {2, GasFastStep64, 1},
SMOD: {2, GasFastStep64, 1},
SIGNEXTEND: {2, GasFastStep64, 1},
ADDMOD: {3, GasMidStep64, 1},
MULMOD: {3, GasMidStep64, 1},
JUMP: {1, GasMidStep64, 0},
JUMPI: {2, GasSlowStep64, 0},
EXP: {2, GasSlowStep64, 1},
ADDRESS: {0, GasQuickStep64, 1},
ORIGIN: {0, GasQuickStep64, 1},
CALLER: {0, GasQuickStep64, 1},
CALLVALUE: {0, GasQuickStep64, 1},
CODESIZE: {0, GasQuickStep64, 1},
GASPRICE: {0, GasQuickStep64, 1},
COINBASE: {0, GasQuickStep64, 1},
TIMESTAMP: {0, GasQuickStep64, 1},
NUMBER: {0, GasQuickStep64, 1},
CALLDATASIZE: {0, GasQuickStep64, 1},
DIFFICULTY: {0, GasQuickStep64, 1},
GASLIMIT: {0, GasQuickStep64, 1},
POP: {1, GasQuickStep64, 0},
PC: {0, GasQuickStep64, 1},
MSIZE: {0, GasQuickStep64, 1},
GAS: {0, GasQuickStep64, 1},
BLOCKHASH: {1, GasExtStep64, 1},
BALANCE: {1, 0, 1},
EXTCODESIZE: {1, 0, 1},
EXTCODECOPY: {4, 0, 0},
SLOAD: {1, 0, 1},
SSTORE: {2, 0, 0},
SHA3: {2, params.Sha3Gas.Uint64(), 1},
CREATE: {3, params.CreateGas.Uint64(), 1},
CALL: {7, 0, 1},
CALLCODE: {7, 0, 1},
DELEGATECALL: {6, 0, 1},
JUMPDEST: {0, params.JumpdestGas.Uint64(), 0},
SUICIDE: {1, 0, 0},
RETURN: {2, 0, 0},
PUSH1: {0, GasFastestStep64, 1},
DUP1: {0, 0, 1},
}

View file

@ -27,7 +27,7 @@ import (
type programInstruction interface {
// executes the program instruction and allows the instruction to modify the state of the program
do(program *Program, pc *uint64, env Environment, contract *Contract, memory *Memory, stack *Stack) ([]byte, error)
do(vm *EVM, program *Program, pc *uint64, env Environment, contract *Contract, memory *Memory, stack *Stack) ([]byte, error)
// returns whether the program instruction halts the execution of the JIT
halts() bool
// Returns the current op code (debugging purposes)
@ -58,9 +58,9 @@ func jump(mapping map[uint64]uint64, destinations map[uint64]struct{}, contract
return mapping[to.Uint64()], nil
}
func (instr instruction) do(program *Program, pc *uint64, env Environment, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
func (instr instruction) do(vm *EVM, program *Program, pc *uint64, env Environment, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
// calculate the new memory size and gas price for the current executing opcode
newMemSize, cost, err := jitCalculateGasAndSize(env, contract, instr, env.Db(), memory, stack)
newMemSize, cost, err := jitCalculateGasAndSize(vm.gasTable, env, contract, instr, env.Db(), memory, stack)
if err != nil {
return nil, err
}

View file

@ -17,7 +17,6 @@
package vm
import (
"fmt"
gmath "math"
"math/big"
"sync/atomic"
@ -41,7 +40,7 @@ const (
progReady // ready for use status
progError // error status (usually caused during compilation)
defaultJitMaxCache int = 64 // maximum amount of jit cached programs
defaultJitMaxCache int = 1024 // maximum amount of jit cached programs
)
var MaxProgSize int // Max cache size for JIT programs
@ -116,7 +115,7 @@ func (p *Program) addInstr(op OpCode, pc uint64, fn instrFn, data *big.Int) {
if op >= DUP1 && op <= DUP16 {
baseOp = DUP1
}
base := _baseCheck64[baseOp]
base := _baseCheck[baseOp]
returns := op == RETURN || op == SUICIDE || op == STOP
instr := instruction{op, pc, fn, data, base.gas, base.stackPop, base.stackPush, returns}
@ -126,17 +125,13 @@ func (p *Program) addInstr(op OpCode, pc uint64, fn instrFn, data *big.Int) {
}
// CompileProgram compiles the given program and return an error when it fails
func CompileProgram(program *Program) (err error) {
func CompileProgram(program *Program) {
if progStatus(atomic.LoadInt32(&program.status)) == progCompile {
return nil
return
}
atomic.StoreInt32(&program.status, int32(progCompile))
defer func() {
if err != nil {
atomic.StoreInt32(&program.status, int32(progError))
} else {
atomic.StoreInt32(&program.status, int32(progReady))
}
atomic.StoreInt32(&program.status, int32(progReady))
}()
if glog.V(logger.Debug) {
glog.Infof("compiling %x\n", program.Id[:4])
@ -295,54 +290,10 @@ func CompileProgram(program *Program) (err error) {
}
optimiseProgram(program)
return nil
}
// RunProgram runs the program given the environment and contract and returns an
// error if the execution failed (non-consensus)
func RunProgram(program *Program, env Environment, contract *Contract, input []byte) ([]byte, error) {
return runProgram(program, 0, NewMemory(), newstack(), env, contract, input)
}
func runProgram(program *Program, pcstart uint64, mem *Memory, stack *Stack, env Environment, contract *Contract, input []byte) ([]byte, error) {
contract.Input = input
var (
pc uint64 = program.mapping[pcstart]
instrCount = 0
)
if glog.V(logger.Debug) {
glog.Infof("running JIT program %x\n", program.Id[:4])
tstart := time.Now()
defer func() {
glog.Infof("JIT program %x done. time: %v instrc: %v\n", program.Id[:4], time.Since(tstart), instrCount)
}()
}
homestead := env.ChainConfig().IsHomestead(env.BlockNumber())
for pc < uint64(len(program.instructions)) {
instrCount++
instr := program.instructions[pc]
if instr.Op() == DELEGATECALL && !homestead {
return nil, fmt.Errorf("Invalid opcode 0x%x", instr.Op())
}
ret, err := instr.do(program, &pc, env, contract, mem, stack)
if err != nil {
return nil, err
}
if instr.halts() {
return ret, nil
}
}
contract.Input = nil
return nil, nil
return New(env, Config{}).Run(contract, input)
}
// validDest checks if the given destination is a valid one given the
@ -359,10 +310,10 @@ func validDest(dests map[uint64]struct{}, dest *big.Int) bool {
// jitCalculateGasAndSize calculates the required given the opcode and stack items calculates the new memorysize for
// the operation. This does not reduce gas or resizes the memory.
func jitCalculateGasAndSize(env Environment, contract *Contract, instr instruction, statedb Database, mem *Memory, stack *Stack) (uint64, uint64, error) {
func jitCalculateGasAndSize(gasTable params.GasTable, env Environment, contract *Contract, instr instruction, statedb Database, mem *Memory, stack *Stack) (uint64, uint64, error) {
var (
newMemSize uint64
sizeFault bool
newMemSize, memGas uint64
sizeFault bool
)
gas, err := jitBaseCalc(instr, stack)
@ -372,6 +323,41 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi
// stack Check, memory resize & gas phase
switch op := instr.op; op {
case SUICIDE:
// if suicide is not nil: homestead gas fork
if gasTable.CreateBySuicide > 0 {
gas += gasTable.Suicide
var (
address = common.BigToAddress(stack.data[len(stack.data)-1])
eip158 = env.ChainConfig().IsEIP158(env.BlockNumber())
)
switch {
case eip158:
var (
empty = env.Db().Empty(address) // checking exist avoids going through the trie on nonexistent
transfersValue = statedb.GetBalance(contract.Address()).BitLen() > 0
)
if empty && transfersValue {
gas += gasTable.CreateBySuicide
}
default:
exist := env.Db().Exist(address)
if !exist {
gas += gasTable.CreateBySuicide
}
}
}
if !statedb.HasSuicided(contract.Address()) {
statedb.AddRefund(params.SuicideRefundGas)
}
case EXTCODESIZE:
gas = gasTable.ExtcodeSize
case BALANCE:
gas = gasTable.Balance
case SLOAD:
gas = gasTable.SLoad
case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
n := int(op - SWAP1 + 2)
err := stack.require(n)
@ -410,7 +396,12 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi
}
gas += gasLogData
newMemSize, sizeFault = calcMemSize64(mStart, mSize)
newMemSize, sizeFault = calcMemSize(mStart, mSize)
memGas, _ := calcQuadMemGas(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
gas += memGas
case EXP:
x := uint64(len(stack.data[stack.len()-2].Bytes()))
if !math.IsMulSafe(x, ExpByteGas64) {
@ -443,20 +434,36 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi
} else {
gas = SstoreResetGas64
}
case SUICIDE:
if !statedb.HasSuicided(contract.Address()) {
statedb.AddRefund(params.SuicideRefundGas)
}
case MLOAD:
newMemSize, sizeFault = calcMemSize64(stack.peek(), u256(32))
newMemSize, sizeFault = calcMemSize(stack.peek(), u256(32))
memGas, _ := calcQuadMemGas(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
gas += memGas
case MSTORE8:
newMemSize, sizeFault = calcMemSize64(stack.peek(), u256(1))
newMemSize, sizeFault = calcMemSize(stack.peek(), u256(1))
memGas, _ := calcQuadMemGas(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
gas += memGas
case MSTORE:
newMemSize, sizeFault = calcMemSize64(stack.peek(), u256(32))
newMemSize, sizeFault = calcMemSize(stack.peek(), u256(32))
memGas, _ := calcQuadMemGas(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
gas += memGas
case RETURN:
newMemSize, sizeFault = calcMemSize64(stack.peek(), stack.data[stack.len()-2])
newMemSize, sizeFault = calcMemSize(stack.peek(), stack.data[stack.len()-2])
memGas, _ := calcQuadMemGas(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
gas += memGas
case SHA3:
newMemSize, sizeFault = calcMemSize64(stack.peek(), stack.data[stack.len()-2])
newMemSize, sizeFault = calcMemSize(stack.peek(), stack.data[stack.len()-2])
if sizeFault {
return 0, 0, OutOfGasError
}
@ -464,7 +471,7 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi
if stack.data[stack.len()-2].BitLen() > 64 {
return 0, 0, OutOfGasError
}
words := toWordSize64(stack.data[stack.len()-2].Uint64())
words := toWordSize(stack.data[stack.len()-2].Uint64())
if !math.IsMulSafe(words, KeccakWordGas64) {
return 0, 0, OutOfGasError
}
@ -473,13 +480,18 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi
return 0, 0, OutOfGasError
}
gas += wordsGas
memGas, _ := calcQuadMemGas(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
gas += memGas
case CALLDATACOPY:
newMemSize, sizeFault = calcMemSize64(stack.peek(), stack.data[stack.len()-3])
newMemSize, sizeFault = calcMemSize(stack.peek(), stack.data[stack.len()-3])
if sizeFault {
return 0, 0, OutOfGasError
}
words := toWordSize64(stack.data[stack.len()-3].Uint64())
words := toWordSize(stack.data[stack.len()-3].Uint64())
if !math.IsMulSafe(words, CopyGas64) {
return 0, 0, OutOfGasError
}
@ -488,13 +500,18 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi
return 0, 0, OutOfGasError
}
gas += wordsGas
memGas, _ := calcQuadMemGas(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
gas += memGas
case CODECOPY:
newMemSize, sizeFault = calcMemSize64(stack.peek(), stack.data[stack.len()-3])
newMemSize, sizeFault = calcMemSize(stack.peek(), stack.data[stack.len()-3])
if sizeFault {
return 0, 0, OutOfGasError
}
words := toWordSize64(stack.data[stack.len()-3].Uint64())
words := toWordSize(stack.data[stack.len()-3].Uint64())
if !math.IsMulSafe(words, CopyGas64) {
return 0, 0, OutOfGasError
}
@ -503,13 +520,18 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi
return 0, 0, OutOfGasError
}
gas += wordsGas
memGas, _ := calcQuadMemGas(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
gas += memGas
case EXTCODECOPY:
newMemSize, sizeFault = calcMemSize64(stack.data[stack.len()-2], stack.data[stack.len()-4])
newMemSize, sizeFault = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-4])
if sizeFault {
return 0, 0, OutOfGasError
}
words := toWordSize64(stack.data[stack.len()-4].Uint64())
words := toWordSize(stack.data[stack.len()-4].Uint64())
if !math.IsMulSafe(words, CopyGas64) {
return 0, 0, OutOfGasError
}
@ -518,36 +540,59 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi
return 0, 0, OutOfGasError
}
gas += wordsGas
case CREATE:
newMemSize, sizeFault = calcMemSize64(stack.data[stack.len()-2], stack.data[stack.len()-3])
case CALL, CALLCODE:
callGas := stack.data[stack.len()-1]
if callGas.BitLen() > 64 {
memGas, _ = calcQuadMemGas(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
gas += callGas.Uint64()
case CREATE:
newMemSize, sizeFault = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-3])
memGas, _ := calcQuadMemGas(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
gas += memGas
case CALL, CALLCODE:
gas = gasTable.Calls
transfersValue := stack.data[len(stack.data)-3].BitLen() > 0
if op == CALL {
if !env.Db().Exist(common.BigToAddress(stack.data[stack.len()-2])) {
if !math.IsAddSafe(gas, CallNewAccountGas64) {
return 0, 0, OutOfGasError
var (
address = common.BigToAddress(stack.data[len(stack.data)-2])
eip158 = env.ChainConfig().IsEIP158(env.BlockNumber())
)
switch {
case eip158:
empty := env.Db().Empty(address)
if empty && transfersValue {
if !math.IsAddSafe(gas, CallNewAccountGas64) {
return 0, 0, OutOfGasError
}
gas += CallNewAccountGas64
}
default:
exist := env.Db().Exist(address)
if !exist {
if !math.IsAddSafe(gas, CallNewAccountGas64) {
return 0, 0, OutOfGasError
}
gas += CallNewAccountGas64
}
gas += CallNewAccountGas64
}
}
if len(stack.data[stack.len()-3].Bytes()) > 0 {
if transfersValue {
if !math.IsAddSafe(gas, CallValueTransferGas64) {
return 0, 0, OutOfGasError
}
gas += CallValueTransferGas64
}
x, xSizeFault := calcMemSize64(stack.data[stack.len()-6], stack.data[stack.len()-7])
x, xSizeFault := calcMemSize(stack.data[stack.len()-6], stack.data[stack.len()-7])
if xSizeFault {
return 0, 0, OutOfGasError
}
y, ySizeFault := calcMemSize64(stack.data[stack.len()-4], stack.data[stack.len()-5])
y, ySizeFault := calcMemSize(stack.data[stack.len()-4], stack.data[stack.len()-5])
if ySizeFault {
return 0, 0, OutOfGasError
}
@ -556,31 +601,72 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi
if y > newMemSize {
newMemSize = y
}
case DELEGATECALL:
callGas := stack.data[stack.len()-1]
if callGas.BitLen() > 64 {
memGas, _ := calcQuadMemGas(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
gas += callGas.Uint64()
gas += memGas
x, xSizeFault := calcMemSize64(stack.data[stack.len()-5], stack.data[stack.len()-6])
cg := callGas(gasTable, contract.gas64, gas, stack.data[stack.len()-1].Uint64())
// Replace the stack item with the new gas calculation. This means that
// either the original item is left on the stack or the item is replaced by:
// (availableGas - gas) * 63 / 64
// We replace the stack item so that it's available when the opCall instruction is
// called. This information is otherwise lost due to the dependency on *current*
// available gas.
stack.data[stack.len()-1] = new(big.Int).SetUint64(cg)
if !math.IsAddSafe(gas, cg) {
return 0, 0, OutOfGasError
}
gas += cg
case DELEGATECALL:
gas = gasTable.Calls
x, xSizeFault := calcMemSize(stack.data[stack.len()-5], stack.data[stack.len()-6])
if xSizeFault {
return 0, 0, OutOfGasError
}
y, ySizeFault := calcMemSize64(stack.data[stack.len()-3], stack.data[stack.len()-4])
y, ySizeFault := calcMemSize(stack.data[stack.len()-3], stack.data[stack.len()-4])
if ySizeFault {
return 0, 0, OutOfGasError
}
newMemSize = uint64(gmath.Max(float64(x), float64(y)))
memGas, _ := calcQuadMemGas(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
gas += memGas
cg := callGas(gasTable, contract.gas64, gas, stack.data[stack.len()-1].Uint64())
// Replace the stack item with the new gas calculation. This means that
// either the original item is left on the stack or the item is replaced by:
// (availableGas - gas) * 63 / 64
// We replace the stack item so that it's available when the opCall instruction is
// called. This information is otherwise lost due to the dependency on *current*
// available gas.
stack.data[stack.len()-1] = new(big.Int).SetUint64(cg)
if !math.IsAddSafe(gas, cg) {
return 0, 0, OutOfGasError
}
gas += cg
}
if sizeFault {
return 0, 0, OutOfGasError
}
memGas, _ := calcQuadMemGas64(mem, newMemSize)
if !math.IsAddSafe(gas, memGas) {
return 0, 0, OutOfGasError
}
return toWordSize64(newMemSize) * 32, gas + memGas, nil
return toWordSize(newMemSize) * 32, gas, nil
}
// waitCompile returns a new channel to broadcast the new result after
// a compilation has started.
func WaitCompile(id common.Hash) chan progStatus {
ch := make(chan progStatus)
go func() {
defer close(ch)
for GetProgramStatus(id) == progCompile {
time.Sleep(time.Microsecond * 10)
}
ch <- GetProgramStatus(id)
}()
return ch
}

View file

@ -115,7 +115,7 @@ func makePushSeg(instrs []instruction) (pushSeg, int) {
// makeStaticJumpSeg creates a new static jump segment from a predefined
// destination (PUSH, JUMP).
func makeStaticJumpSeg(to *big.Int, program *Program) jumpSeg {
gas := _baseCheck64[PUSH1].gas + _baseCheck64[JUMP].gas
gas := _baseCheck[PUSH1].gas + _baseCheck[JUMP].gas
contract := &Contract{Code: program.code}
pos, err := jump(program.mapping, program.destinations, contract, to)

View file

@ -24,7 +24,7 @@ type jumpSeg struct {
gas uint64
}
func (j jumpSeg) do(program *Program, pc *uint64, env Environment, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
func (j jumpSeg) do(vm *EVM, program *Program, pc *uint64, env Environment, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
if !contract.UseGas(j.gas) {
return nil, OutOfGasError
}
@ -42,7 +42,7 @@ type pushSeg struct {
gas uint64
}
func (s pushSeg) do(program *Program, pc *uint64, env Environment, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
func (s pushSeg) do(vm *EVM, program *Program, pc *uint64, env Environment, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
// Use the calculated gas. When insufficient gas is present, use all gas and return an
// Out Of Gas error
if !contract.UseGas(s.gas) {

View file

@ -1,175 +0,0 @@
package vm
import (
"fmt"
gmath "math"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/params"
)
var (
maxInt63 = new(big.Int).Exp(big.NewInt(2), big.NewInt(63), big.NewInt(0))
maxIntCap = new(big.Int).Sub(maxInt63, big.NewInt(1))
)
var (
StackLimit64 = params.StackLimit.Uint64()
GasQuickStep64 uint64 = 2
GasFastestStep64 uint64 = 3
GasFastStep64 uint64 = 5
GasMidStep64 uint64 = 8
GasSlowStep64 uint64 = 10
GasExtStep64 uint64 = 20
GasReturn64 uint64 = 0
GasStop64 uint64 = 0
GasContractByte64 uint64 = 200
LogGas64 = params.LogGas.Uint64()
LogTopicGas64 = params.LogTopicGas.Uint64()
LogDataGas64 = params.LogDataGas.Uint64()
ExpByteGas64 = params.ExpByteGas.Uint64()
SstoreSetGas64 = params.SstoreSetGas.Uint64()
SstoreClearGas64 = params.SstoreClearGas.Uint64()
SstoreResetGas64 = params.SstoreResetGas.Uint64()
KeccakWordGas64 = params.Sha3WordGas.Uint64()
CopyGas64 = params.CopyGas.Uint64()
CallNewAccountGas64 = params.CallNewAccountGas.Uint64()
CallValueTransferGas64 = params.CallValueTransferGas.Uint64()
MemoryGas64 = params.MemoryGas.Uint64()
QuadCoeffDiv64 = params.QuadCoeffDiv.Uint64()
)
// casts a arbitrary number to the amount of words (sets of 32 bytes)
func toWordSize64(size uint64) uint64 {
return (size + 31) / 32
}
// calculates the memory size required for a step
func calcMemSize64(off, l *big.Int) (uint64, bool) {
if l.Cmp(common.Big0) == 0 {
return 0, false
}
size := new(big.Int).Add(off, l)
if size.Cmp(maxIntCap) > 0 {
return 0, true
}
return size.Uint64(), false
}
// calculates the quadratic gas
// TODO this function requires guarding of overflows
func calcQuadMemGas64(mem *Memory, newMemSize uint64) (uint64, bool) {
oldTotalFee := mem.cost
if newMemSize > 0 {
newMemSizeWords := toWordSize64(newMemSize)
newMemSize = newMemSizeWords * 32
if newMemSize > uint64(mem.Len()) {
pow := uint64(gmath.Pow(float64(newMemSizeWords), 2))
linCoef := newMemSizeWords * MemoryGas64
quadCoef := pow / QuadCoeffDiv64
newTotalFee := linCoef + quadCoef
fee := newTotalFee - oldTotalFee
mem.cost = newTotalFee
return fee, false
}
}
return 0, false
}
// jitBaseCalc is the same as baseCheck except it doesn't do the look up in the
// gas table. This is done during compilation instead.
func jitBaseCalc(instr instruction, stack *Stack) (uint64, error) {
err := stack.require(instr.spop)
if err != nil {
return 0, err
}
if instr.spush > 0 && stack.len()-instr.spop+instr.spush > int(StackLimit64) {
return 0, fmt.Errorf("stack limit reached %d (%d)", stack.len(), StackLimit64)
}
// 0 on gas means no base calculation
if instr.gas == 0 {
return 0, nil
}
return instr.gas, nil
}
type req64 struct {
stackPop int
gas uint64
stackPush int
}
var _baseCheck64 = map[OpCode]req64{
// opcode | stack pop | gas price | stack push
ADD: {2, GasFastestStep64, 1},
LT: {2, GasFastestStep64, 1},
GT: {2, GasFastestStep64, 1},
SLT: {2, GasFastestStep64, 1},
SGT: {2, GasFastestStep64, 1},
EQ: {2, GasFastestStep64, 1},
ISZERO: {1, GasFastestStep64, 1},
SUB: {2, GasFastestStep64, 1},
AND: {2, GasFastestStep64, 1},
OR: {2, GasFastestStep64, 1},
XOR: {2, GasFastestStep64, 1},
NOT: {1, GasFastestStep64, 1},
BYTE: {2, GasFastestStep64, 1},
CALLDATALOAD: {1, GasFastestStep64, 1},
CALLDATACOPY: {3, GasFastestStep64, 1},
MLOAD: {1, GasFastestStep64, 1},
MSTORE: {2, GasFastestStep64, 0},
MSTORE8: {2, GasFastestStep64, 0},
CODECOPY: {3, GasFastestStep64, 0},
MUL: {2, GasFastStep64, 1},
DIV: {2, GasFastStep64, 1},
SDIV: {2, GasFastStep64, 1},
MOD: {2, GasFastStep64, 1},
SMOD: {2, GasFastStep64, 1},
SIGNEXTEND: {2, GasFastStep64, 1},
ADDMOD: {3, GasMidStep64, 1},
MULMOD: {3, GasMidStep64, 1},
JUMP: {1, GasMidStep64, 0},
JUMPI: {2, GasSlowStep64, 0},
EXP: {2, GasSlowStep64, 1},
ADDRESS: {0, GasQuickStep64, 1},
ORIGIN: {0, GasQuickStep64, 1},
CALLER: {0, GasQuickStep64, 1},
CALLVALUE: {0, GasQuickStep64, 1},
CODESIZE: {0, GasQuickStep64, 1},
GASPRICE: {0, GasQuickStep64, 1},
COINBASE: {0, GasQuickStep64, 1},
TIMESTAMP: {0, GasQuickStep64, 1},
NUMBER: {0, GasQuickStep64, 1},
CALLDATASIZE: {0, GasQuickStep64, 1},
DIFFICULTY: {0, GasQuickStep64, 1},
GASLIMIT: {0, GasQuickStep64, 1},
POP: {1, GasQuickStep64, 0},
PC: {0, GasQuickStep64, 1},
MSIZE: {0, GasQuickStep64, 1},
GAS: {0, GasQuickStep64, 1},
BLOCKHASH: {1, GasExtStep64, 1},
BALANCE: {1, GasExtStep64, 1},
EXTCODESIZE: {1, GasExtStep64, 1},
EXTCODECOPY: {4, GasExtStep64, 0},
SLOAD: {1, params.SloadGas.Uint64(), 1},
SSTORE: {2, 0, 0},
SHA3: {2, params.Sha3Gas.Uint64(), 1},
CREATE: {3, params.CreateGas.Uint64(), 1},
CALL: {7, params.CallGas.Uint64(), 1},
CALLCODE: {7, params.CallGas.Uint64(), 1},
DELEGATECALL: {6, params.CallGas.Uint64(), 1},
JUMPDEST: {0, params.JumpdestGas.Uint64(), 0},
SUICIDE: {1, 0, 0},
RETURN: {2, 0, 0},
PUSH1: {0, GasFastestStep64, 1},
DUP1: {0, 0, 1},
}

View file

@ -18,7 +18,6 @@ package vm
import (
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
@ -58,13 +57,13 @@ func New(env Environment, cfg Config) *EVM {
}
// Run loops and evaluates the contract's code with the given input data
func (evm *EVM) Run(contract *Contract, input []byte) (ret []byte, err error) {
func (evm *EVM) Run(contract *Contract, input []byte) ([]byte, error) {
evm.env.SetDepth(evm.env.Depth() + 1)
defer evm.env.SetDepth(evm.env.Depth() - 1)
if contract.CodeAddr != nil {
if p := Precompiled[contract.CodeAddr.Str()]; p != nil {
return evm.RunPrecompiled(p, input, contract)
return RunPrecompiled(p, input, contract)
}
}
@ -73,393 +72,75 @@ func (evm *EVM) Run(contract *Contract, input []byte) (ret []byte, err error) {
return nil, nil
}
codehash := contract.CodeHash // codehash is used when doing jump dest caching
codehash := contract.CodeHash // codehash is used as an identifier for the programs
if codehash == (common.Hash{}) {
codehash = crypto.Keccak256Hash(contract.Code)
}
var program *Program
if false {
// JIT disabled due to JIT not being Homestead gas reprice ready.
// If the JIT is enabled check the status of the JIT program,
// if it doesn't exist compile a new program in a separate
// goroutine or wait for compilation to finish if the JIT is
// forced.
switch GetProgramStatus(codehash) {
case progReady:
return evm.runProgram(GetProgram(codehash), contract, input)
case progUnknown:
// Create and compile program
program := NewProgram(contract.Code)
CompileProgram(program)
// If the JIT is enabled check the status of the JIT program,
// if it doesn't exist compile a new program in a separate
// goroutine or wait for compilation to finish if the JIT is
// forced.
switch GetProgramStatus(codehash) {
case progReady:
return RunProgram(GetProgram(codehash), evm.env, contract, input)
case progUnknown:
if evm.cfg.ForceJit {
// Create and compile program
program = NewProgram(contract.Code)
perr := CompileProgram(program)
if perr == nil {
return RunProgram(program, evm.env, contract, input)
}
glog.V(logger.Info).Infoln("error compiling program", err)
} else {
// create and compile the program. Compilation
// is done in a separate goroutine
program = NewProgram(contract.Code)
go func() {
err := CompileProgram(program)
if err != nil {
glog.V(logger.Info).Infoln("error compiling program", err)
return
}
}()
}
}
return evm.runProgram(program, contract, input)
case progCompile:
// if the program is already compling wait for the compilation to finish
// and use the program instead of defaulting to the regular byte code vm.
<-WaitCompile(codehash)
return evm.runProgram(GetProgram(codehash), contract, input)
}
return nil, fmt.Errorf("Unexpected return using program %x", codehash)
}
var (
caller = contract.caller
code = contract.Code
instrCount = 0
op OpCode // current opcode
mem = NewMemory() // bound memory
stack = newstack() // local stack
statedb = evm.env.Db() // current state
// For optimisation reason we're using uint64 as the program counter.
// It's theoretically possible to go above 2^64. The YP defines the PC to be uint256. Practically much less so feasible.
pc = uint64(0) // program counter
// jump evaluates and checks whether the given jump destination is a valid one
// if valid move the `pc` otherwise return an error.
jump = func(from uint64, to *big.Int) error {
if !contract.jumpdests.has(codehash, code, to) {
nop := contract.GetOp(to.Uint64())
return fmt.Errorf("invalid jump destination (%v) %v", nop, to)
}
pc = to.Uint64()
return nil
}
newMemSize *big.Int
cost *big.Int
)
func (evm *EVM) runProgram(program *Program, contract *Contract, input []byte) ([]byte, error) {
contract.Input = input
// User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
defer func() {
if err != nil && evm.cfg.Debug {
gas := new(big.Int).SetUint64(contract.gas64)
evm.cfg.Tracer.CaptureState(evm.env, pc, op, gas, cost, mem, stack, contract, evm.env.Depth(), err)
}
}()
var (
pc uint64 = 0 //program.mapping[pcstart]
instrCount uint64 = 0
mem = NewMemory()
stack = newstack()
env = evm.env
)
if glog.V(logger.Debug) {
glog.Infof("running byte VM %x\n", codehash[:4])
glog.Infof("running JIT program %x\n", program.Id[:4])
tstart := time.Now()
defer func() {
glog.Infof("VM %x done. time: %v instrc: %v\n", codehash[:4], time.Since(tstart), instrCount)
glog.Infof("JIT program %x done. time: %v instrc: %v\n", program.Id[:4], time.Since(tstart), instrCount)
}()
}
for ; ; instrCount++ {
// Get the memory location of pc
op = contract.GetOp(pc)
//fmt.Printf("OP %d %v\n", op, op)
// calculate the new memory size and gas price for the current executing opcode
newMemSize, cost, err = calculateGasAndSize(evm.gasTable, evm.env, contract, caller, op, statedb, mem, stack)
homestead := env.ChainConfig().IsHomestead(env.BlockNumber())
for pc < uint64(len(program.instructions)) {
instrCount++
instr := program.instructions[pc]
if instr.Op() == DELEGATECALL && !homestead {
return nil, fmt.Errorf("Invalid opcode 0x%x", instr.Op())
}
ret, err := instr.do(evm, program, &pc, env, contract, mem, stack)
if err != nil {
//gas := new(big.Int).SetUint64(contract.gas64)
//evm.cfg.Tracer.CaptureState(evm.env, pc, instr.Op(), gas, cost, mem, stack, contract, evm.env.Depth(), err)
return nil, err
}
// Use the calculated gas. When insufficient gas is present, use all gas and return an
// Out Of Gas error
if !contract.UseGas(cost.Uint64()) {
return nil, OutOfGasError
if instr.halts() {
return ret, nil
}
// Resize the memory calculated previously
mem.Resize(newMemSize.Uint64())
// Add a log message
if evm.cfg.Debug {
gas := new(big.Int).SetUint64(contract.gas64)
err = evm.cfg.Tracer.CaptureState(evm.env, pc, op, gas, cost, mem, stack, contract, evm.env.Depth(), nil)
if err != nil {
return nil, err
}
}
if opPtr := evm.jumpTable[op]; opPtr.valid {
if opPtr.fn != nil {
opPtr.fn(instruction{}, &pc, evm.env, contract, mem, stack)
} else {
switch op {
case PC:
opPc(instruction{data: new(big.Int).SetUint64(pc)}, &pc, evm.env, contract, mem, stack)
case JUMP:
if err := jump(pc, stack.pop()); err != nil {
return nil, err
}
continue
case JUMPI:
pos, cond := stack.pop(), stack.pop()
if cond.Cmp(common.BigTrue) >= 0 {
if err := jump(pc, pos); err != nil {
return nil, err
}
continue
}
case RETURN:
offset, size := stack.pop(), stack.pop()
ret := mem.GetPtr(offset.Int64(), size.Int64())
return ret, nil
case SUICIDE:
opSuicide(instruction{}, nil, evm.env, contract, mem, stack)
fallthrough
case STOP: // Stop the contract
return nil, nil
}
}
} else {
return nil, fmt.Errorf("Invalid opcode %x", op)
}
pc++
}
}
// calculateGasAndSize calculates the required given the opcode and stack items calculates the new memorysize for
// the operation. This does not reduce gas or resizes the memory.
func calculateGasAndSize(gasTable params.GasTable, env Environment, contract *Contract, caller ContractRef, op OpCode, statedb Database, mem *Memory, stack *Stack) (*big.Int, *big.Int, error) {
var (
gas = new(big.Int)
newMemSize *big.Int = new(big.Int)
)
err := baseCheck(op, stack, gas)
if err != nil {
return nil, nil, err
}
// stack Check, memory resize & gas phase
switch op {
case SUICIDE:
// if suicide is not nil: homestead gas fork
if gasTable.CreateBySuicide != nil {
gas.Set(gasTable.Suicide)
var (
address = common.BigToAddress(stack.data[len(stack.data)-1])
eip158 = env.ChainConfig().IsEIP158(env.BlockNumber())
)
switch {
case eip158:
var (
empty = env.Db().Empty(address) // checking exist avoids going through the trie on nonexistent
transfersValue = statedb.GetBalance(contract.Address()).BitLen() > 0
)
if empty && transfersValue {
gas.Add(gas, gasTable.CreateBySuicide)
}
default:
exist := env.Db().Exist(address)
if !exist {
gas.Add(gas, gasTable.CreateBySuicide)
}
}
}
if !statedb.HasSuicided(contract.Address()) {
statedb.AddRefund(params.SuicideRefundGas)
}
case EXTCODESIZE:
gas.Set(gasTable.ExtcodeSize)
case BALANCE:
gas.Set(gasTable.Balance)
case SLOAD:
gas.Set(gasTable.SLoad)
case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
n := int(op - SWAP1 + 2)
err := stack.require(n)
if err != nil {
return nil, nil, err
}
gas.Set(GasFastestStep)
case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
n := int(op - DUP1 + 1)
err := stack.require(n)
if err != nil {
return nil, nil, err
}
gas.Set(GasFastestStep)
case LOG0, LOG1, LOG2, LOG3, LOG4:
n := int(op - LOG0)
err := stack.require(n + 2)
if err != nil {
return nil, nil, err
}
mSize, mStart := stack.data[stack.len()-2], stack.data[stack.len()-1]
gas.Add(gas, params.LogGas)
gas.Add(gas, new(big.Int).Mul(big.NewInt(int64(n)), params.LogTopicGas))
gas.Add(gas, new(big.Int).Mul(mSize, params.LogDataGas))
newMemSize = calcMemSize(mStart, mSize)
quadMemGas(mem, newMemSize, gas)
case EXP:
expByteLen := int64((stack.data[stack.len()-2].BitLen() + 7) / 8)
gas.Add(gas, new(big.Int).Mul(big.NewInt(expByteLen), gasTable.ExpByte))
case SSTORE:
err := stack.require(2)
if err != nil {
return nil, nil, err
}
var g *big.Int
y, x := stack.data[stack.len()-2], stack.data[stack.len()-1]
val := statedb.GetState(contract.Address(), common.BigToHash(x))
// This checks for 3 scenario's and calculates gas accordingly
// 1. From a zero-value address to a non-zero value (NEW VALUE)
// 2. From a non-zero value address to a zero-value address (DELETE)
// 3. From a non-zero to a non-zero (CHANGE)
if common.EmptyHash(val) && !common.EmptyHash(common.BigToHash(y)) {
// 0 => non 0
g = params.SstoreSetGas
} else if !common.EmptyHash(val) && common.EmptyHash(common.BigToHash(y)) {
statedb.AddRefund(params.SstoreRefundGas)
g = params.SstoreClearGas
} else {
// non 0 => non 0 (or 0 => 0)
g = params.SstoreResetGas
}
gas.Set(g)
case MLOAD:
newMemSize = calcMemSize(stack.peek(), u256(32))
quadMemGas(mem, newMemSize, gas)
case MSTORE8:
newMemSize = calcMemSize(stack.peek(), u256(1))
quadMemGas(mem, newMemSize, gas)
case MSTORE:
newMemSize = calcMemSize(stack.peek(), u256(32))
quadMemGas(mem, newMemSize, gas)
case RETURN:
newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2])
quadMemGas(mem, newMemSize, gas)
case SHA3:
newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2])
words := toWordSize(stack.data[stack.len()-2])
gas.Add(gas, words.Mul(words, params.Sha3WordGas))
quadMemGas(mem, newMemSize, gas)
case CALLDATACOPY:
newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-3])
words := toWordSize(stack.data[stack.len()-3])
gas.Add(gas, words.Mul(words, params.CopyGas))
quadMemGas(mem, newMemSize, gas)
case CODECOPY:
newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-3])
words := toWordSize(stack.data[stack.len()-3])
gas.Add(gas, words.Mul(words, params.CopyGas))
quadMemGas(mem, newMemSize, gas)
case EXTCODECOPY:
gas.Set(gasTable.ExtcodeCopy)
newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-4])
words := toWordSize(stack.data[stack.len()-4])
gas.Add(gas, words.Mul(words, params.CopyGas))
quadMemGas(mem, newMemSize, gas)
case CREATE:
newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-3])
quadMemGas(mem, newMemSize, gas)
case CALL, CALLCODE:
gas.Set(gasTable.Calls)
transfersValue := stack.data[len(stack.data)-3].BitLen() > 0
if op == CALL {
var (
address = common.BigToAddress(stack.data[len(stack.data)-2])
eip158 = env.ChainConfig().IsEIP158(env.BlockNumber())
)
switch {
case eip158:
empty := env.Db().Empty(address)
if empty && transfersValue {
gas.Add(gas, params.CallNewAccountGas)
}
default:
exist := env.Db().Exist(address)
if !exist {
gas.Add(gas, params.CallNewAccountGas)
}
}
}
if transfersValue {
gas.Add(gas, params.CallValueTransferGas)
}
x := calcMemSize(stack.data[stack.len()-6], stack.data[stack.len()-7])
y := calcMemSize(stack.data[stack.len()-4], stack.data[stack.len()-5])
newMemSize = common.BigMax(x, y)
quadMemGas(mem, newMemSize, gas)
cg := new(big.Int).SetUint64(callGas(gasTable, contract.gas64, gas.Uint64(), stack.data[stack.len()-1].Uint64()))
// Replace the stack item with the new gas calculation. This means that
// either the original item is left on the stack or the item is replaced by:
// (availableGas - gas) * 63 / 64
// We replace the stack item so that it's available when the opCall instruction is
// called. This information is otherwise lost due to the dependency on *current*
// available gas.
stack.data[stack.len()-1] = cg
gas.Add(gas, cg)
case DELEGATECALL:
gas.Set(gasTable.Calls)
x := calcMemSize(stack.data[stack.len()-5], stack.data[stack.len()-6])
y := calcMemSize(stack.data[stack.len()-3], stack.data[stack.len()-4])
newMemSize = common.BigMax(x, y)
quadMemGas(mem, newMemSize, gas)
cg := new(big.Int).SetUint64(callGas(gasTable, contract.gas64, gas.Uint64(), stack.data[stack.len()-1].Uint64()))
// Replace the stack item with the new gas calculation. This means that
// either the original item is left on the stack or the item is replaced by:
// (availableGas - gas) * 63 / 64
// We replace the stack item so that it's available when the opCall instruction is
// called.
stack.data[stack.len()-1] = cg
gas.Add(gas, cg)
}
return newMemSize, gas, nil
}
// RunPrecompile runs and evaluate the output of a precompiled contract defined in contracts.go
func (evm *EVM) RunPrecompiled(p *PrecompiledAccount, input []byte, contract *Contract) (ret []byte, err error) {
gas := p.Gas(len(input))
if contract.UseGas(gas.Uint64()) {
ret = p.Call(input)
return ret, nil
} else {
return nil, OutOfGasError
}
contract.Input = nil
return nil, nil
}

View file

@ -16,41 +16,39 @@
package params
import "math/big"
type GasTable struct {
ExtcodeSize *big.Int
ExtcodeCopy *big.Int
Balance *big.Int
SLoad *big.Int
Calls *big.Int
Suicide *big.Int
ExtcodeSize uint64
ExtcodeCopy uint64
Balance uint64
SLoad uint64
Calls uint64
Suicide uint64
ExpByte *big.Int
ExpByte uint64
// CreateBySuicide occurs when the
// refunded account is one that does
// not exist. This logic is similar
// to call. May be left nil. Nil means
// not charged.
CreateBySuicide *big.Int
CreateBySuicide uint64
}
var (
// GasTableHomestead contain the gas prices for
// the homestead phase.
GasTableHomestead = GasTable{
ExtcodeSize: big.NewInt(20),
ExtcodeCopy: big.NewInt(20),
Balance: big.NewInt(20),
SLoad: big.NewInt(50),
Calls: big.NewInt(40),
Suicide: big.NewInt(0),
ExpByte: big.NewInt(10),
ExtcodeSize: 20,
ExtcodeCopy: 20,
Balance: 20,
SLoad: 50,
Calls: 40,
Suicide: 0,
ExpByte: 10,
// explicitly set to nil to indicate
// this rule does not apply to homestead.
CreateBySuicide: nil,
CreateBySuicide: 0,
}
// GasTableHomestead contain the gas re-prices for
@ -58,26 +56,26 @@ var (
//
// TODO rename to GasTableEIP150
GasTableHomesteadGasRepriceFork = GasTable{
ExtcodeSize: big.NewInt(700),
ExtcodeCopy: big.NewInt(700),
Balance: big.NewInt(400),
SLoad: big.NewInt(200),
Calls: big.NewInt(700),
Suicide: big.NewInt(5000),
ExpByte: big.NewInt(10),
ExtcodeSize: 700,
ExtcodeCopy: 700,
Balance: 400,
SLoad: 200,
Calls: 700,
Suicide: 5000,
ExpByte: 10,
CreateBySuicide: big.NewInt(25000),
CreateBySuicide: 25000,
}
GasTableEIP158 = GasTable{
ExtcodeSize: big.NewInt(700),
ExtcodeCopy: big.NewInt(700),
Balance: big.NewInt(400),
SLoad: big.NewInt(200),
Calls: big.NewInt(700),
Suicide: big.NewInt(5000),
ExpByte: big.NewInt(50),
ExtcodeSize: 700,
ExtcodeCopy: 700,
Balance: 400,
SLoad: 200,
Calls: 700,
Suicide: 5000,
ExpByte: 50,
CreateBySuicide: big.NewInt(25000),
CreateBySuicide: 25000,
}
)

View file

@ -167,7 +167,7 @@ type Env struct {
vmTest bool
evm *vm.EVM
evm vm.VirtualMachine
}
func NewEnv(chainConfig *params.ChainConfig, state *state.StateDB) *Env {