diff --git a/cmd/geth/main.go b/cmd/geth/main.go index 65311ca418..e2e85f2965 100644 --- a/cmd/geth/main.go +++ b/cmd/geth/main.go @@ -171,9 +171,7 @@ participating. utils.WhisperEnabledFlag, utils.DevModeFlag, utils.TestNetFlag, - utils.VMForceJitFlag, - utils.VMJitCacheFlag, - utils.VMEnableJitFlag, + utils.VMCacheFlag, utils.NetworkIdFlag, utils.RPCCORSDomainFlag, utils.MetricsEnabledFlag, diff --git a/cmd/geth/usage.go b/cmd/geth/usage.go index dc1788aad2..a95f310ec7 100644 --- a/cmd/geth/usage.go +++ b/cmd/geth/usage.go @@ -144,9 +144,7 @@ var AppHelpFlagGroups = []flagGroup{ { Name: "VIRTUAL MACHINE", Flags: []cli.Flag{ - utils.VMEnableJitFlag, - utils.VMForceJitFlag, - utils.VMJitCacheFlag, + utils.VMCacheFlag, }, }, { diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index 0be499c5bc..a94f34484d 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -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" @@ -213,18 +211,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 @@ -454,9 +444,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, "/") } @@ -665,16 +652,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 := ð.Config{ Etherbase: MakeEtherbase(stack.AccountManager(), ctx), ChainConfig: MakeChainConfig(ctx, stack), @@ -686,8 +663,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)), diff --git a/core/vm/contracts.go b/core/vm/contracts.go index b45f14724b..63ddd8ab78 100644 --- a/core/vm/contracts.go +++ b/core/vm/contracts.go @@ -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 { diff --git a/core/vm/doc.go b/core/vm/doc.go index 239be2cfec..2021416729 100644 --- a/core/vm/doc.go +++ b/core/vm/doc.go @@ -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 diff --git a/core/vm/gas.go b/core/vm/gas.go index 440ee864d7..77585c681f 100644 --- a/core/vm/gas.go +++ b/core/vm/gas.go @@ -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 . - package vm import ( "fmt" + gmath "math" "math/big" "github.com/ethereum/go-ethereum/common" @@ -25,157 +10,166 @@ 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) - - GasReturn = big.NewInt(0) - GasStop = big.NewInt(0) - - GasContractByte = big.NewInt(200) + maxInt63 = new(big.Int).Exp(big.NewInt(2), big.NewInt(63), big.NewInt(0)) + maxIntCap = new(big.Int).Sub(maxInt63, big.NewInt(1)) ) -// 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 - } +var ( + StackLimit64 = params.StackLimit.Uint64() + GasQuickStep64 uint64 = 2 + GasFastestStep64 uint64 = 3 + GasFastStep64 uint64 = 5 + GasMidStep64 uint64 = 8 + GasSlowStep64 uint64 = 10 + GasExtStep64 uint64 = 20 - if r, ok := _baseCheck[op]; ok { - err := stack.require(r.stackPop) - if err != nil { - return err - } + GasReturn64 uint64 = 0 + GasStop64 uint64 = 0 - 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 -} + 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 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, GasExtStep, 1}, - EXTCODESIZE: {1, GasExtStep, 1}, - EXTCODECOPY: {4, GasExtStep, 0}, - SLOAD: {1, params.SloadGas, 1}, - SSTORE: {2, Zero, 0}, - SHA3: {2, params.Sha3Gas, 1}, - CREATE: {3, params.CreateGas, 1}, - CALL: {7, params.CallGas, 1}, - CALLCODE: {7, params.CallGas, 1}, - DELEGATECALL: {6, params.CallGas, 1}, - JUMPDEST: {0, params.JumpdestGas, 0}, - SUICIDE: {1, Zero, 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, 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}, } diff --git a/core/vm/jit.go b/core/vm/program.go similarity index 83% rename from core/vm/jit.go rename to core/vm/program.go index 39635034cb..85e8fb9d98 100644 --- a/core/vm/jit.go +++ b/core/vm/program.go @@ -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.RuleSet().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 @@ -410,7 +361,7 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi } gas += gasLogData - newMemSize, sizeFault = calcMemSize64(mStart, mSize) + newMemSize, sizeFault = calcMemSize(mStart, mSize) case EXP: x := uint64(len(stack.data[stack.len()-2].Bytes())) if !math.IsMulSafe(x, ExpByteGas64) { @@ -448,15 +399,15 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi statedb.AddRefund(params.SuicideRefundGas) } case MLOAD: - newMemSize, sizeFault = calcMemSize64(stack.peek(), u256(32)) + newMemSize, sizeFault = calcMemSize(stack.peek(), u256(32)) case MSTORE8: - newMemSize, sizeFault = calcMemSize64(stack.peek(), u256(1)) + newMemSize, sizeFault = calcMemSize(stack.peek(), u256(1)) case MSTORE: - newMemSize, sizeFault = calcMemSize64(stack.peek(), u256(32)) + newMemSize, sizeFault = calcMemSize(stack.peek(), u256(32)) case RETURN: - newMemSize, sizeFault = calcMemSize64(stack.peek(), stack.data[stack.len()-2]) + newMemSize, sizeFault = calcMemSize(stack.peek(), stack.data[stack.len()-2]) 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 +415,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 } @@ -474,12 +425,12 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi } gas += wordsGas 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 } @@ -489,12 +440,12 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi } gas += wordsGas 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 } @@ -504,12 +455,12 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi } gas += wordsGas 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 } @@ -519,7 +470,7 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi } gas += wordsGas case CREATE: - newMemSize, sizeFault = calcMemSize64(stack.data[stack.len()-2], stack.data[stack.len()-3]) + newMemSize, sizeFault = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-3]) case CALL, CALLCODE: callGas := stack.data[stack.len()-1] if callGas.BitLen() > 64 { @@ -543,11 +494,11 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi 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 } @@ -563,11 +514,11 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi } gas += callGas.Uint64() - x, xSizeFault := calcMemSize64(stack.data[stack.len()-5], stack.data[stack.len()-6]) + 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 } @@ -578,9 +529,23 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi return 0, 0, OutOfGasError } - memGas, _ := calcQuadMemGas64(mem, newMemSize) + memGas, _ := calcQuadMemGas(mem, newMemSize) if !math.IsAddSafe(gas, memGas) { return 0, 0, OutOfGasError } - return toWordSize64(newMemSize) * 32, gas + memGas, nil + return toWordSize(newMemSize) * 32, gas + memGas, 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 } diff --git a/core/vm/jit_optimiser.go b/core/vm/program_optimiser.go similarity index 98% rename from core/vm/jit_optimiser.go rename to core/vm/program_optimiser.go index 831af1ed10..6d1ac93264 100644 --- a/core/vm/jit_optimiser.go +++ b/core/vm/program_optimiser.go @@ -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) diff --git a/core/vm/jit_test.go b/core/vm/program_test.go similarity index 100% rename from core/vm/jit_test.go rename to core/vm/program_test.go diff --git a/core/vm/jit_util.go b/core/vm/program_util.go similarity index 100% rename from core/vm/jit_util.go rename to core/vm/program_util.go diff --git a/core/vm/jit_util_test.go b/core/vm/program_util_test.go similarity index 100% rename from core/vm/jit_util_test.go rename to core/vm/program_util_test.go diff --git a/core/vm/uint64.go b/core/vm/uint64.go deleted file mode 100644 index 96d1e76364..0000000000 --- a/core/vm/uint64.go +++ /dev/null @@ -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}, -} diff --git a/core/vm/vm.go b/core/vm/vm.go index 7e81f856ad..908f4721f8 100644 --- a/core/vm/vm.go +++ b/core/vm/vm.go @@ -18,14 +18,12 @@ package vm import ( "fmt" - "math/big" "time" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger/glog" - "github.com/ethereum/go-ethereum/params" ) // Config are the configuration options for the EVM @@ -56,13 +54,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) } } @@ -71,301 +69,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 evm.cfg.EnableJit { - // 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 - } - }() - } - } + // 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) + + 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) - // calculate the new memory size and gas price for the current executing opcode - newMemSize, cost, err = calculateGasAndSize(evm.env, contract, caller, op, statedb, mem, stack) + homestead := env.RuleSet().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 { + //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) - evm.cfg.Tracer.CaptureState(evm.env, pc, op, gas, cost, mem, stack, contract, evm.env.Depth(), nil) - } - - 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(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 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) - case EXP: - gas.Add(gas, new(big.Int).Mul(big.NewInt(int64(len(stack.data[stack.len()-2].Bytes()))), params.ExpByteGas)) - 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 SUICIDE: - if !statedb.HasSuicided(contract.Address()) { - statedb.AddRefund(params.SuicideRefundGas) - } - case MLOAD: - newMemSize = calcMemSize(stack.peek(), u256(32)) - case MSTORE8: - newMemSize = calcMemSize(stack.peek(), u256(1)) - case MSTORE: - newMemSize = calcMemSize(stack.peek(), u256(32)) - case RETURN: - newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2]) - 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)) - 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)) - 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)) - case 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)) - - case CREATE: - newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-3]) - case CALL, CALLCODE: - gas.Add(gas, stack.data[stack.len()-1]) - - if op == CALL { - if !env.Db().Exist(common.BigToAddress(stack.data[stack.len()-2])) { - gas.Add(gas, params.CallNewAccountGas) - } - } - - if len(stack.data[stack.len()-3].Bytes()) > 0 { - 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) - case DELEGATECALL: - gas.Add(gas, stack.data[stack.len()-1]) - - 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) - - 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 } diff --git a/core/vm_env.go b/core/vm_env.go index a95165f17c..f46a04330f 100644 --- a/core/vm_env.go +++ b/core/vm_env.go @@ -41,11 +41,11 @@ func GetHashFn(ref common.Hash, chain *BlockChain) func(n uint64) common.Hash { } type VMEnv struct { - chainConfig *ChainConfig // Chain configuration - state *state.StateDB // State to use for executing - evm *vm.EVM // The Ethereum Virtual Machine - depth int // Current execution depth - msg Message // Message appliod + chainConfig *ChainConfig // Chain configuration + state *state.StateDB // State to use for executing + evm vm.VirtualMachine // The Ethereum Virtual Machine + depth int // Current execution depth + msg Message // Message appliod header *types.Header // Header information chain *BlockChain // Blockchain handle diff --git a/tests/util.go b/tests/util.go index e51820cd9c..e0ee7a7d55 100644 --- a/tests/util.go +++ b/tests/util.go @@ -176,7 +176,7 @@ type Env struct { vmTest bool - evm *vm.EVM + evm vm.VirtualMachine } func NewEnv(ruleSet RuleSet, state *state.StateDB) *Env {