Skip to content

Commit 361082e

Browse files
committed
cmd/evm, core/vm, test: refactored VM and core
* 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`.
1 parent f7a7199 commit 361082e

39 files changed

Lines changed: 946 additions & 1062 deletions

‎cmd/evm/main.go‎

Lines changed: 31 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -80,12 +80,17 @@ var (
8080
Name: "sysstat",
8181
Usage: "display system stats",
8282
}
83+
VerbosityFlag = cli.IntFlag{
84+
Name: "verbosity",
85+
Usage: "sets the verbosity level",
86+
}
8387
)
8488

8589
func init() {
8690
app = utils.NewApp("0.2", "the evm command line interface")
8791
app.Flags = []cli.Flag{
8892
DebugFlag,
93+
VerbosityFlag,
8994
ForceJitFlag,
9095
DisableJitFlag,
9196
SysStatFlag,
@@ -105,6 +110,7 @@ func run(ctx *cli.Context) {
105110
vm.EnableJit = !ctx.GlobalBool(DisableJitFlag.Name)
106111

107112
glog.SetToStderr(true)
113+
glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
108114

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

182-
func (self *VMEnv) State() *state.StateDB { return self.state }
183-
func (self *VMEnv) Origin() common.Address { return *self.transactor }
184-
func (self *VMEnv) BlockNumber() *big.Int { return common.Big0 }
185-
func (self *VMEnv) Coinbase() common.Address { return *self.transactor }
186-
func (self *VMEnv) Time() *big.Int { return self.time }
187-
func (self *VMEnv) Difficulty() *big.Int { return common.Big1 }
188-
func (self *VMEnv) BlockHash() []byte { return make([]byte, 32) }
189-
func (self *VMEnv) Value() *big.Int { return self.value }
190-
func (self *VMEnv) GasLimit() *big.Int { return big.NewInt(1000000000) }
191-
func (self *VMEnv) VmType() vm.Type { return vm.StdVmTy }
192-
func (self *VMEnv) Depth() int { return 0 }
193-
func (self *VMEnv) SetDepth(i int) { self.depth = i }
188+
func (self *VMEnv) Db() vm.Database { return self.state }
189+
func (self *VMEnv) MakeSnapshot() vm.Database { return self.state.Copy() }
190+
func (self *VMEnv) SetSnapshot(db vm.Database) { self.state.Set(db.(*state.StateDB)) }
191+
func (self *VMEnv) Origin() common.Address { return *self.transactor }
192+
func (self *VMEnv) BlockNumber() *big.Int { return common.Big0 }
193+
func (self *VMEnv) Coinbase() common.Address { return *self.transactor }
194+
func (self *VMEnv) Time() *big.Int { return self.time }
195+
func (self *VMEnv) Difficulty() *big.Int { return common.Big1 }
196+
func (self *VMEnv) BlockHash() []byte { return make([]byte, 32) }
197+
func (self *VMEnv) Value() *big.Int { return self.value }
198+
func (self *VMEnv) GasLimit() *big.Int { return big.NewInt(1000000000) }
199+
func (self *VMEnv) VmType() vm.Type { return vm.StdVmTy }
200+
func (self *VMEnv) Depth() int { return 0 }
201+
func (self *VMEnv) SetDepth(i int) { self.depth = i }
194202
func (self *VMEnv) GetHash(n uint64) common.Hash {
195203
if self.block.Number().Cmp(big.NewInt(int64(n))) == 0 {
196204
return self.block.Hash()
@@ -203,34 +211,24 @@ func (self *VMEnv) AddStructLog(log vm.StructLog) {
203211
func (self *VMEnv) StructLogs() []vm.StructLog {
204212
return self.logs
205213
}
206-
func (self *VMEnv) AddLog(log *state.Log) {
214+
func (self *VMEnv) AddLog(log *vm.Log) {
207215
self.state.AddLog(log)
208216
}
209-
func (self *VMEnv) CanTransfer(from vm.Account, balance *big.Int) bool {
210-
return from.Balance().Cmp(balance) >= 0
217+
func (self *VMEnv) CanTransfer(from common.Address, balance *big.Int) bool {
218+
return self.state.GetBalance(from).Cmp(balance) >= 0
211219
}
212220
func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) error {
213-
return vm.Transfer(from, to, amount)
214-
}
215-
216-
func (self *VMEnv) vm(addr *common.Address, data []byte, gas, price, value *big.Int) *core.Execution {
217-
return core.NewExecution(self, addr, data, gas, price, value)
221+
return core.Transfer(from, to, amount)
218222
}
219223

220-
func (self *VMEnv) Call(caller vm.ContextRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
221-
exe := self.vm(&addr, data, gas, price, value)
222-
ret, err := exe.Call(addr, caller)
223-
self.Gas = exe.Gas
224-
225-
return ret, err
224+
func (self *VMEnv) Call(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
225+
self.Gas = gas
226+
return core.Call(self, caller, addr, data, gas, price, value)
226227
}
227-
func (self *VMEnv) CallCode(caller vm.ContextRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
228-
a := caller.Address()
229-
exe := self.vm(&a, data, gas, price, value)
230-
return exe.Call(addr, caller)
228+
func (self *VMEnv) CallCode(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
229+
return core.CallCode(self, caller, addr, data, gas, price, value)
231230
}
232231

233-
func (self *VMEnv) Create(caller vm.ContextRef, data []byte, gas, price, value *big.Int) ([]byte, error, vm.ContextRef) {
234-
exe := self.vm(nil, data, gas, price, value)
235-
return exe.Create(caller)
232+
func (self *VMEnv) Create(caller vm.ContractRef, data []byte, gas, price, value *big.Int) ([]byte, common.Address, error) {
233+
return core.Create(self, caller, data, gas, price, value)
236234
}

‎core/block_processor.go‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"github.com/ethereum/go-ethereum/common"
2626
"github.com/ethereum/go-ethereum/core/state"
2727
"github.com/ethereum/go-ethereum/core/types"
28+
"github.com/ethereum/go-ethereum/core/vm"
2829
"github.com/ethereum/go-ethereum/crypto"
2930
"github.com/ethereum/go-ethereum/ethdb"
3031
"github.com/ethereum/go-ethereum/event"
@@ -163,7 +164,7 @@ func (self *BlockProcessor) ApplyTransactions(gp GasPool, statedb *state.StateDB
163164
return receipts, err
164165
}
165166

166-
func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs state.Logs, err error) {
167+
func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs vm.Logs, err error) {
167168
// Processing a blocks may never happen simultaneously
168169
sm.mutex.Lock()
169170
defer sm.mutex.Unlock()
@@ -188,7 +189,7 @@ func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs state.Logs, err
188189
// Process block will attempt to process the given block's transactions and applies them
189190
// on top of the block's parent state (given it exists) and will return wether it was
190191
// successful or not.
191-
func (sm *BlockProcessor) Process(block *types.Block) (logs state.Logs, receipts types.Receipts, err error) {
192+
func (sm *BlockProcessor) Process(block *types.Block) (logs vm.Logs, receipts types.Receipts, err error) {
192193
// Processing a blocks may never happen simultaneously
193194
sm.mutex.Lock()
194195
defer sm.mutex.Unlock()
@@ -204,7 +205,7 @@ func (sm *BlockProcessor) Process(block *types.Block) (logs state.Logs, receipts
204205
return sm.processWithParent(block, parent)
205206
}
206207

207-
func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs state.Logs, receipts types.Receipts, err error) {
208+
func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs vm.Logs, receipts types.Receipts, err error) {
208209
// Create a new state based on the parent's root (e.g., create copy)
209210
state := state.New(parent.Root(), sm.chainDb)
210211
header := block.Header()
@@ -356,7 +357,7 @@ func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) types.Receipts {
356357
// GetLogs returns the logs of the given block. This method is using a two step approach
357358
// where it tries to get it from the (updated) method which gets them from the receipts or
358359
// the depricated way by re-processing the block.
359-
func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
360+
func (sm *BlockProcessor) GetLogs(block *types.Block) (logs vm.Logs, err error) {
360361
receipts := GetBlockReceipts(sm.chainDb, block.Hash())
361362
// coalesce logs
362363
for _, receipt := range receipts {

‎core/block_processor_test.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import (
2424
"github.com/ethereum/go-ethereum/common"
2525
"github.com/ethereum/go-ethereum/core/state"
2626
"github.com/ethereum/go-ethereum/core/types"
27+
"github.com/ethereum/go-ethereum/core/vm"
2728
"github.com/ethereum/go-ethereum/ethdb"
2829
"github.com/ethereum/go-ethereum/event"
2930
"github.com/ethereum/go-ethereum/pow/ezp"
@@ -69,7 +70,7 @@ func TestPutReceipt(t *testing.T) {
6970
hash[0] = 2
7071

7172
receipt := new(types.Receipt)
72-
receipt.SetLogs(state.Logs{&state.Log{
73+
receipt.SetLogs(vm.Logs{&vm.Log{
7374
Address: addr,
7475
Topics: []common.Hash{hash},
7576
Data: []byte("hi"),

‎core/chain_manager_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ import (
2828

2929
"github.com/ethereum/ethash"
3030
"github.com/ethereum/go-ethereum/common"
31-
"github.com/ethereum/go-ethereum/core/state"
3231
"github.com/ethereum/go-ethereum/core/types"
32+
"github.com/ethereum/go-ethereum/core/vm"
3333
"github.com/ethereum/go-ethereum/crypto"
3434
"github.com/ethereum/go-ethereum/ethdb"
3535
"github.com/ethereum/go-ethereum/event"
@@ -361,7 +361,7 @@ func TestChainMultipleInsertions(t *testing.T) {
361361

362362
type bproc struct{}
363363

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

366366
func makeChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Block {
367367
var chain []*types.Block

‎core/events.go‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ import (
2020
"math/big"
2121

2222
"github.com/ethereum/go-ethereum/common"
23-
"github.com/ethereum/go-ethereum/core/state"
2423
"github.com/ethereum/go-ethereum/core/types"
24+
"github.com/ethereum/go-ethereum/core/vm"
2525
)
2626

2727
// TxPreEvent is posted when a transaction enters the transaction pool.
@@ -42,23 +42,23 @@ type RemovedTransactionEvent struct{ Txs types.Transactions }
4242
// ChainSplit is posted when a new head is detected
4343
type ChainSplitEvent struct {
4444
Block *types.Block
45-
Logs state.Logs
45+
Logs vm.Logs
4646
}
4747

4848
type ChainEvent struct {
4949
Block *types.Block
5050
Hash common.Hash
51-
Logs state.Logs
51+
Logs vm.Logs
5252
}
5353

5454
type ChainSideEvent struct {
5555
Block *types.Block
56-
Logs state.Logs
56+
Logs vm.Logs
5757
}
5858

5959
type PendingBlockEvent struct {
6060
Block *types.Block
61-
Logs state.Logs
61+
Logs vm.Logs
6262
}
6363

6464
type ChainUncleEvent struct {

‎core/execution.go‎

Lines changed: 55 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -17,108 +17,104 @@
1717
package core
1818

1919
import (
20+
"errors"
2021
"math/big"
2122

2223
"github.com/ethereum/go-ethereum/common"
23-
"github.com/ethereum/go-ethereum/core/state"
2424
"github.com/ethereum/go-ethereum/core/vm"
2525
"github.com/ethereum/go-ethereum/crypto"
2626
"github.com/ethereum/go-ethereum/params"
2727
)
2828

29-
// Execution is the execution environment for the given call or create action.
30-
type Execution struct {
31-
env vm.Environment
32-
address *common.Address
33-
input []byte
34-
evm vm.VirtualMachine
35-
36-
Gas, price, value *big.Int
29+
// Call executes within the given contract
30+
func Call(env vm.Environment, caller vm.ContractRef, addr common.Address, input []byte, gas, gasPrice, value *big.Int) (ret []byte, err error) {
31+
ret, _, err = exec(env, caller, &addr, &addr, input, env.Db().GetCode(addr), gas, gasPrice, value)
32+
return ret, err
3733
}
3834

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

47-
// Call executes within the given context
48-
func (self *Execution) Call(codeAddr common.Address, caller vm.ContextRef) ([]byte, error) {
49-
// Retrieve the executing code
50-
code := self.env.State().GetCode(codeAddr)
51-
52-
return self.exec(&codeAddr, code, caller)
53-
}
54-
55-
// Create creates a new contract and runs the initialisation procedure of the
56-
// contract. This returns the returned code for the contract and is stored
57-
// elsewhere.
58-
func (self *Execution) Create(caller vm.ContextRef) (ret []byte, err error, account *state.StateObject) {
59-
// Input must be nil for create
60-
code := self.input
61-
self.input = nil
62-
ret, err = self.exec(nil, code, caller)
42+
// Create creates a new contract with the given code
43+
func Create(env vm.Environment, caller vm.ContractRef, code []byte, gas, gasPrice, value *big.Int) (ret []byte, address common.Address, err error) {
44+
ret, address, err = exec(env, caller, nil, nil, nil, code, gas, gasPrice, value)
6345
// Here we get an error if we run into maximum stack depth,
6446
// See: https://github.com/ethereum/yellowpaper/pull/131
6547
// and YP definitions for CREATE instruction
6648
if err != nil {
67-
return nil, err, nil
49+
return nil, address, err
6850
}
69-
account = self.env.State().GetStateObject(*self.address)
70-
return
51+
return ret, address, err
7152
}
7253

73-
// exec executes the given code and executes within the contextAddr context.
74-
func (self *Execution) exec(contextAddr *common.Address, code []byte, caller vm.ContextRef) (ret []byte, err error) {
75-
env := self.env
76-
evm := self.evm
54+
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) {
55+
evm := vm.NewVm(env)
56+
7757
// Depth check execution. Fail if we're trying to execute above the
7858
// limit.
7959
if env.Depth() > int(params.CallCreateDepth.Int64()) {
80-
caller.ReturnGas(self.Gas, self.price)
60+
caller.ReturnGas(gas, gasPrice)
8161

82-
return nil, vm.DepthError
62+
return nil, common.Address{}, vm.DepthError
8363
}
8464

85-
if !env.CanTransfer(env.State().GetStateObject(caller.Address()), self.value) {
86-
caller.ReturnGas(self.Gas, self.price)
65+
if !env.CanTransfer(caller.Address(), value) {
66+
caller.ReturnGas(gas, gasPrice)
8767

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

9171
var createAccount bool
92-
if self.address == nil {
72+
if address == nil {
9373
// Generate a new address
94-
nonce := env.State().GetNonce(caller.Address())
95-
env.State().SetNonce(caller.Address(), nonce+1)
74+
nonce := env.Db().GetNonce(caller.Address())
75+
env.Db().SetNonce(caller.Address(), nonce+1)
9676

97-
addr := crypto.CreateAddress(caller.Address(), nonce)
77+
addr = crypto.CreateAddress(caller.Address(), nonce)
9878

99-
self.address = &addr
79+
address = &addr
10080
createAccount = true
10181
}
102-
snapshot := env.State().Copy()
82+
snapshot := env.MakeSnapshot()
10383

10484
var (
105-
from = env.State().GetStateObject(caller.Address())
106-
to *state.StateObject
85+
from = env.Db().GetAccount(caller.Address())
86+
to vm.Account
10787
)
10888
if createAccount {
109-
to = env.State().CreateAccount(*self.address)
89+
to = env.Db().CreateAccount(*address)
11090
} else {
111-
to = env.State().GetOrNewStateObject(*self.address)
91+
if !env.Db().Exist(*address) {
92+
to = env.Db().CreateAccount(*address)
93+
} else {
94+
to = env.Db().GetAccount(*address)
95+
}
11296
}
113-
vm.Transfer(from, to, self.value)
97+
env.Transfer(from, to, value)
11498

115-
context := vm.NewContext(caller, to, self.value, self.Gas, self.price)
116-
context.SetCallCode(contextAddr, code)
99+
contract := vm.NewContract(caller, to, value, gas, gasPrice)
100+
contract.SetCallCode(codeAddr, code)
117101

118-
ret, err = evm.Run(context, self.input)
102+
ret, err = evm.Run(contract, input)
119103
if err != nil {
120-
env.State().Set(snapshot)
104+
env.SetSnapshot(snapshot) //env.Db().Set(snapshot)
121105
}
122106

123-
return
107+
return ret, addr, err
108+
}
109+
110+
// generic transfer method
111+
func Transfer(from, to vm.Account, amount *big.Int) error {
112+
if from.Balance().Cmp(amount) < 0 {
113+
return errors.New("Insufficient balance in account")
114+
}
115+
116+
from.SubBalance(amount)
117+
to.AddBalance(amount)
118+
119+
return nil
124120
}

0 commit comments

Comments
 (0)