Skip to content

Commit

Permalink
cmd/evm, core/vm, test: refactored VM and core
Browse files Browse the repository at this point in the history
* Moved `vm.Transfer` to `core` package and changed execution to call
`env.Transfer` instead of `core.Transfer` directly.
* core/vm: byte code VM moved to jump table instead of switch
* Moved `vm.Transfer` to `core` package and changed execution to call
  `env.Transfer` instead of `core.Transfer` directly.
* Byte code VM now shares the same code as the JITVM
* Renamed Context to Contract
* Changed initialiser of state transition & unexported methods
* Removed the Execution object and refactor `Call`, `CallCode` &
  `Create` in to their own functions instead of being methods.
* Removed the hard dep on the state for the VM. The VM now
  depends on a Database interface returned by the environment. In the
  process the core now depends less on the statedb by usage of the env
* Moved `Log` from package `core/state` to package `core/vm`.
  • Loading branch information
obscuren committed Oct 3, 2015
1 parent f7a7199 commit 361082e
Show file tree
Hide file tree
Showing 39 changed files with 946 additions and 1,062 deletions.
64 changes: 31 additions & 33 deletions cmd/evm/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,17 @@ var (
Name: "sysstat",
Usage: "display system stats",
}
VerbosityFlag = cli.IntFlag{
Name: "verbosity",
Usage: "sets the verbosity level",
}
)

func init() {
app = utils.NewApp("0.2", "the evm command line interface")
app.Flags = []cli.Flag{
DebugFlag,
VerbosityFlag,
ForceJitFlag,
DisableJitFlag,
SysStatFlag,
Expand All @@ -105,6 +110,7 @@ func run(ctx *cli.Context) {
vm.EnableJit = !ctx.GlobalBool(DisableJitFlag.Name)

glog.SetToStderr(true)
glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))

db, _ := ethdb.NewMemDatabase()
statedb := state.New(common.Hash{}, db)
Expand Down Expand Up @@ -179,18 +185,20 @@ func NewEnv(state *state.StateDB, transactor common.Address, value *big.Int) *VM
}
}

func (self *VMEnv) State() *state.StateDB { return self.state }
func (self *VMEnv) Origin() common.Address { return *self.transactor }
func (self *VMEnv) BlockNumber() *big.Int { return common.Big0 }
func (self *VMEnv) Coinbase() common.Address { return *self.transactor }
func (self *VMEnv) Time() *big.Int { return self.time }
func (self *VMEnv) Difficulty() *big.Int { return common.Big1 }
func (self *VMEnv) BlockHash() []byte { return make([]byte, 32) }
func (self *VMEnv) Value() *big.Int { return self.value }
func (self *VMEnv) GasLimit() *big.Int { return big.NewInt(1000000000) }
func (self *VMEnv) VmType() vm.Type { return vm.StdVmTy }
func (self *VMEnv) Depth() int { return 0 }
func (self *VMEnv) SetDepth(i int) { self.depth = i }
func (self *VMEnv) Db() vm.Database { return self.state }
func (self *VMEnv) MakeSnapshot() vm.Database { return self.state.Copy() }
func (self *VMEnv) SetSnapshot(db vm.Database) { self.state.Set(db.(*state.StateDB)) }
func (self *VMEnv) Origin() common.Address { return *self.transactor }
func (self *VMEnv) BlockNumber() *big.Int { return common.Big0 }
func (self *VMEnv) Coinbase() common.Address { return *self.transactor }
func (self *VMEnv) Time() *big.Int { return self.time }
func (self *VMEnv) Difficulty() *big.Int { return common.Big1 }
func (self *VMEnv) BlockHash() []byte { return make([]byte, 32) }
func (self *VMEnv) Value() *big.Int { return self.value }
func (self *VMEnv) GasLimit() *big.Int { return big.NewInt(1000000000) }
func (self *VMEnv) VmType() vm.Type { return vm.StdVmTy }
func (self *VMEnv) Depth() int { return 0 }
func (self *VMEnv) SetDepth(i int) { self.depth = i }
func (self *VMEnv) GetHash(n uint64) common.Hash {
if self.block.Number().Cmp(big.NewInt(int64(n))) == 0 {
return self.block.Hash()
Expand All @@ -203,34 +211,24 @@ func (self *VMEnv) AddStructLog(log vm.StructLog) {
func (self *VMEnv) StructLogs() []vm.StructLog {
return self.logs
}
func (self *VMEnv) AddLog(log *state.Log) {
func (self *VMEnv) AddLog(log *vm.Log) {
self.state.AddLog(log)
}
func (self *VMEnv) CanTransfer(from vm.Account, balance *big.Int) bool {
return from.Balance().Cmp(balance) >= 0
func (self *VMEnv) CanTransfer(from common.Address, balance *big.Int) bool {
return self.state.GetBalance(from).Cmp(balance) >= 0
}
func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) error {
return vm.Transfer(from, to, amount)
}

func (self *VMEnv) vm(addr *common.Address, data []byte, gas, price, value *big.Int) *core.Execution {
return core.NewExecution(self, addr, data, gas, price, value)
return core.Transfer(from, to, amount)
}

func (self *VMEnv) Call(caller vm.ContextRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
exe := self.vm(&addr, data, gas, price, value)
ret, err := exe.Call(addr, caller)
self.Gas = exe.Gas

return ret, err
func (self *VMEnv) Call(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
self.Gas = gas
return core.Call(self, caller, addr, data, gas, price, value)
}
func (self *VMEnv) CallCode(caller vm.ContextRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
a := caller.Address()
exe := self.vm(&a, data, gas, price, value)
return exe.Call(addr, caller)
func (self *VMEnv) CallCode(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
return core.CallCode(self, caller, addr, data, gas, price, value)
}

func (self *VMEnv) Create(caller vm.ContextRef, data []byte, gas, price, value *big.Int) ([]byte, error, vm.ContextRef) {
exe := self.vm(nil, data, gas, price, value)
return exe.Create(caller)
func (self *VMEnv) Create(caller vm.ContractRef, data []byte, gas, price, value *big.Int) ([]byte, common.Address, error) {
return core.Create(self, caller, data, gas, price, value)
}
9 changes: 5 additions & 4 deletions core/block_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
Expand Down Expand Up @@ -163,7 +164,7 @@ func (self *BlockProcessor) ApplyTransactions(gp GasPool, statedb *state.StateDB
return receipts, err
}

func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs state.Logs, err error) {
func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs vm.Logs, err error) {
// Processing a blocks may never happen simultaneously
sm.mutex.Lock()
defer sm.mutex.Unlock()
Expand All @@ -188,7 +189,7 @@ func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs state.Logs, err
// Process block will attempt to process the given block's transactions and applies them
// on top of the block's parent state (given it exists) and will return wether it was
// successful or not.
func (sm *BlockProcessor) Process(block *types.Block) (logs state.Logs, receipts types.Receipts, err error) {
func (sm *BlockProcessor) Process(block *types.Block) (logs vm.Logs, receipts types.Receipts, err error) {
// Processing a blocks may never happen simultaneously
sm.mutex.Lock()
defer sm.mutex.Unlock()
Expand All @@ -204,7 +205,7 @@ func (sm *BlockProcessor) Process(block *types.Block) (logs state.Logs, receipts
return sm.processWithParent(block, parent)
}

func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs state.Logs, receipts types.Receipts, err error) {
func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs vm.Logs, receipts types.Receipts, err error) {
// Create a new state based on the parent's root (e.g., create copy)
state := state.New(parent.Root(), sm.chainDb)
header := block.Header()
Expand Down Expand Up @@ -356,7 +357,7 @@ func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) types.Receipts {
// GetLogs returns the logs of the given block. This method is using a two step approach
// where it tries to get it from the (updated) method which gets them from the receipts or
// the depricated way by re-processing the block.
func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
func (sm *BlockProcessor) GetLogs(block *types.Block) (logs vm.Logs, err error) {
receipts := GetBlockReceipts(sm.chainDb, block.Hash())
// coalesce logs
for _, receipt := range receipts {
Expand Down
3 changes: 2 additions & 1 deletion core/block_processor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/pow/ezp"
Expand Down Expand Up @@ -69,7 +70,7 @@ func TestPutReceipt(t *testing.T) {
hash[0] = 2

receipt := new(types.Receipt)
receipt.SetLogs(state.Logs{&state.Log{
receipt.SetLogs(vm.Logs{&vm.Log{
Address: addr,
Topics: []common.Hash{hash},
Data: []byte("hi"),
Expand Down
4 changes: 2 additions & 2 deletions core/chain_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ import (

"github.com/ethereum/ethash"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
Expand Down Expand Up @@ -361,7 +361,7 @@ func TestChainMultipleInsertions(t *testing.T) {

type bproc struct{}

func (bproc) Process(*types.Block) (state.Logs, types.Receipts, error) { return nil, nil, nil }
func (bproc) Process(*types.Block) (vm.Logs, types.Receipts, error) { return nil, nil, nil }

func makeChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Block {
var chain []*types.Block
Expand Down
10 changes: 5 additions & 5 deletions core/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ import (
"math/big"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
)

// TxPreEvent is posted when a transaction enters the transaction pool.
Expand All @@ -42,23 +42,23 @@ type RemovedTransactionEvent struct{ Txs types.Transactions }
// ChainSplit is posted when a new head is detected
type ChainSplitEvent struct {
Block *types.Block
Logs state.Logs
Logs vm.Logs
}

type ChainEvent struct {
Block *types.Block
Hash common.Hash
Logs state.Logs
Logs vm.Logs
}

type ChainSideEvent struct {
Block *types.Block
Logs state.Logs
Logs vm.Logs
}

type PendingBlockEvent struct {
Block *types.Block
Logs state.Logs
Logs vm.Logs
}

type ChainUncleEvent struct {
Expand Down
114 changes: 55 additions & 59 deletions core/execution.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,108 +17,104 @@
package core

import (
"errors"
"math/big"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/params"
)

// Execution is the execution environment for the given call or create action.
type Execution struct {
env vm.Environment
address *common.Address
input []byte
evm vm.VirtualMachine

Gas, price, value *big.Int
// Call executes within the given contract
func Call(env vm.Environment, caller vm.ContractRef, addr common.Address, input []byte, gas, gasPrice, value *big.Int) (ret []byte, err error) {
ret, _, err = exec(env, caller, &addr, &addr, input, env.Db().GetCode(addr), gas, gasPrice, value)
return ret, err
}

// NewExecution returns a new execution environment that handles all calling
// and creation logic defined by the YP.
func NewExecution(env vm.Environment, address *common.Address, input []byte, gas, gasPrice, value *big.Int) *Execution {
exe := &Execution{env: env, address: address, input: input, Gas: gas, price: gasPrice, value: value}
exe.evm = vm.NewVm(env)
return exe
// CallCode executes the given address' code as the given contract address
func CallCode(env vm.Environment, caller vm.ContractRef, addr common.Address, input []byte, gas, gasPrice, value *big.Int) (ret []byte, err error) {
prev := caller.Address()
ret, _, err = exec(env, caller, &prev, &addr, input, env.Db().GetCode(addr), gas, gasPrice, value)
return ret, err
}

// Call executes within the given context
func (self *Execution) Call(codeAddr common.Address, caller vm.ContextRef) ([]byte, error) {
// Retrieve the executing code
code := self.env.State().GetCode(codeAddr)

return self.exec(&codeAddr, code, caller)
}

// Create creates a new contract and runs the initialisation procedure of the
// contract. This returns the returned code for the contract and is stored
// elsewhere.
func (self *Execution) Create(caller vm.ContextRef) (ret []byte, err error, account *state.StateObject) {
// Input must be nil for create
code := self.input
self.input = nil
ret, err = self.exec(nil, code, caller)
// Create creates a new contract with the given code
func Create(env vm.Environment, caller vm.ContractRef, code []byte, gas, gasPrice, value *big.Int) (ret []byte, address common.Address, err error) {
ret, address, err = exec(env, caller, nil, nil, nil, code, gas, gasPrice, value)
// Here we get an error if we run into maximum stack depth,
// See: https://github.com/ethereum/yellowpaper/pull/131
// and YP definitions for CREATE instruction
if err != nil {
return nil, err, nil
return nil, address, err
}
account = self.env.State().GetStateObject(*self.address)
return
return ret, address, err
}

// exec executes the given code and executes within the contextAddr context.
func (self *Execution) exec(contextAddr *common.Address, code []byte, caller vm.ContextRef) (ret []byte, err error) {
env := self.env
evm := self.evm
func exec(env vm.Environment, caller vm.ContractRef, address, codeAddr *common.Address, input, code []byte, gas, gasPrice, value *big.Int) (ret []byte, addr common.Address, err error) {
evm := vm.NewVm(env)

// Depth check execution. Fail if we're trying to execute above the
// limit.
if env.Depth() > int(params.CallCreateDepth.Int64()) {
caller.ReturnGas(self.Gas, self.price)
caller.ReturnGas(gas, gasPrice)

return nil, vm.DepthError
return nil, common.Address{}, vm.DepthError
}

if !env.CanTransfer(env.State().GetStateObject(caller.Address()), self.value) {
caller.ReturnGas(self.Gas, self.price)
if !env.CanTransfer(caller.Address(), value) {
caller.ReturnGas(gas, gasPrice)

return nil, ValueTransferErr("insufficient funds to transfer value. Req %v, has %v", self.value, env.State().GetBalance(caller.Address()))
return nil, common.Address{}, ValueTransferErr("insufficient funds to transfer value. Req %v, has %v", value, env.Db().GetBalance(caller.Address()))
}

var createAccount bool
if self.address == nil {
if address == nil {
// Generate a new address
nonce := env.State().GetNonce(caller.Address())
env.State().SetNonce(caller.Address(), nonce+1)
nonce := env.Db().GetNonce(caller.Address())
env.Db().SetNonce(caller.Address(), nonce+1)

addr := crypto.CreateAddress(caller.Address(), nonce)
addr = crypto.CreateAddress(caller.Address(), nonce)

self.address = &addr
address = &addr
createAccount = true
}
snapshot := env.State().Copy()
snapshot := env.MakeSnapshot()

var (
from = env.State().GetStateObject(caller.Address())
to *state.StateObject
from = env.Db().GetAccount(caller.Address())
to vm.Account
)
if createAccount {
to = env.State().CreateAccount(*self.address)
to = env.Db().CreateAccount(*address)
} else {
to = env.State().GetOrNewStateObject(*self.address)
if !env.Db().Exist(*address) {
to = env.Db().CreateAccount(*address)
} else {
to = env.Db().GetAccount(*address)
}
}
vm.Transfer(from, to, self.value)
env.Transfer(from, to, value)

context := vm.NewContext(caller, to, self.value, self.Gas, self.price)
context.SetCallCode(contextAddr, code)
contract := vm.NewContract(caller, to, value, gas, gasPrice)
contract.SetCallCode(codeAddr, code)

ret, err = evm.Run(context, self.input)
ret, err = evm.Run(contract, input)
if err != nil {
env.State().Set(snapshot)
env.SetSnapshot(snapshot) //env.Db().Set(snapshot)
}

return
return ret, addr, err
}

// generic transfer method
func Transfer(from, to vm.Account, amount *big.Int) error {
if from.Balance().Cmp(amount) < 0 {
return errors.New("Insufficient balance in account")
}

from.SubBalance(amount)
to.AddBalance(amount)

return nil
}
Loading

0 comments on commit 361082e

Please sign in to comment.