Skip to content

Commit 2045a2b

Browse files
core, all: split vm.Context into BlockContext and TxContext (#21672)
* all: core: split vm.Config into BlockConfig and TxConfig * core: core/vm: reset EVM between tx in block instead of creating new * core/vm: added docs
1 parent 6f4cccf commit 2045a2b

24 files changed

Lines changed: 183 additions & 139 deletions

‎accounts/abi/bind/backends/simulated.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -542,10 +542,11 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallM
542542
// Execute the call.
543543
msg := callMsg{call}
544544

545-
evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain, nil)
545+
txContext := core.NewEVMTxContext(msg)
546+
evmContext := core.NewEVMBlockContext(block.Header(), b.blockchain, nil)
546547
// Create a new environment which holds all relevant information
547548
// about the transaction and calling mechanisms.
548-
vmEnv := vm.NewEVM(evmContext, stateDB, b.config, vm.Config{})
549+
vmEnv := vm.NewEVM(evmContext, txContext, stateDB, b.config, vm.Config{})
549550
gasPool := new(core.GasPool).AddGas(math.MaxUint64)
550551

551552
return core.NewStateTransition(vmEnv, msg, gasPool).TransitionDb()

‎cmd/evm/internal/t8ntool/execution.go‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
110110
txIndex = 0
111111
)
112112
gaspool.AddGas(pre.Env.GasLimit)
113-
vmContext := vm.Context{
113+
vmContext := vm.BlockContext{
114114
CanTransfer: core.CanTransfer,
115115
Transfer: core.Transfer,
116116
Coinbase: pre.Env.Coinbase,
@@ -119,7 +119,6 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
119119
Difficulty: pre.Env.Difficulty,
120120
GasLimit: pre.Env.GasLimit,
121121
GetHash: getHash,
122-
// GasPrice and Origin needs to be set per transaction
123122
}
124123
// If DAO is supported/enabled, we need to handle it here. In geth 'proper', it's
125124
// done in StateProcessor.Process(block, ...), right before transactions are applied.
@@ -143,10 +142,9 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
143142
vmConfig.Tracer = tracer
144143
vmConfig.Debug = (tracer != nil)
145144
statedb.Prepare(tx.Hash(), blockHash, txIndex)
146-
vmContext.GasPrice = msg.GasPrice()
147-
vmContext.Origin = msg.From()
145+
txContext := core.NewEVMTxContext(msg)
148146

149-
evm := vm.NewEVM(vmContext, statedb, chainConfig, vmConfig)
147+
evm := vm.NewEVM(vmContext, txContext, statedb, chainConfig, vmConfig)
150148
if chainConfig.IsYoloV2(vmContext.BlockNumber) {
151149
statedb.AddAddressToAccessList(msg.From())
152150
if dst := msg.To(); dst != nil {
@@ -185,7 +183,7 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
185183
receipt.GasUsed = msgResult.UsedGas
186184
// if the transaction created a contract, store the creation address in the receipt.
187185
if msg.To() == nil {
188-
receipt.ContractAddress = crypto.CreateAddress(evm.Context.Origin, tx.Nonce())
186+
receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
189187
}
190188
// Set the receipt logs and create a bloom for filtering
191189
receipt.Logs = statedb.GetLogs(tx.Hash())

‎cmd/geth/retesteth.go‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -671,12 +671,13 @@ func (api *RetestethAPI) AccountRange(ctx context.Context,
671671
}
672672
// Recompute transactions up to the target index.
673673
signer := types.MakeSigner(api.blockchain.Config(), block.Number())
674+
context := core.NewEVMBlockContext(block.Header(), api.blockchain, nil)
674675
for idx, tx := range block.Transactions() {
675676
// Assemble the transaction call message and return if the requested offset
676677
msg, _ := tx.AsMessage(signer)
677-
context := core.NewEVMContext(msg, block.Header(), api.blockchain, nil)
678+
txContext := core.NewEVMTxContext(msg)
678679
// Not yet the searched for transaction, execute on top of the current state
679-
vmenv := vm.NewEVM(context, statedb, api.blockchain.Config(), vm.Config{})
680+
vmenv := vm.NewEVM(context, txContext, statedb, api.blockchain.Config(), vm.Config{})
680681
if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
681682
return AccountRangeResult{}, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
682683
}
@@ -781,12 +782,13 @@ func (api *RetestethAPI) StorageRangeAt(ctx context.Context,
781782
}
782783
// Recompute transactions up to the target index.
783784
signer := types.MakeSigner(api.blockchain.Config(), block.Number())
785+
context := core.NewEVMBlockContext(block.Header(), api.blockchain, nil)
784786
for idx, tx := range block.Transactions() {
785787
// Assemble the transaction call message and return if the requested offset
786788
msg, _ := tx.AsMessage(signer)
787-
context := core.NewEVMContext(msg, block.Header(), api.blockchain, nil)
789+
txContext := core.NewEVMTxContext(msg)
788790
// Not yet the searched for transaction, execute on top of the current state
789-
vmenv := vm.NewEVM(context, statedb, api.blockchain.Config(), vm.Config{})
791+
vmenv := vm.NewEVM(context, txContext, statedb, api.blockchain.Config(), vm.Config{})
790792
if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
791793
return StorageRangeResult{}, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
792794
}

‎core/evm.go‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,26 +35,32 @@ type ChainContext interface {
3535
GetHeader(common.Hash, uint64) *types.Header
3636
}
3737

38-
// NewEVMContext creates a new context for use in the EVM.
39-
func NewEVMContext(msg Message, header *types.Header, chain ChainContext, author *common.Address) vm.Context {
38+
// NewEVMBlockContext creates a new context for use in the EVM.
39+
func NewEVMBlockContext(header *types.Header, chain ChainContext, author *common.Address) vm.BlockContext {
4040
// If we don't have an explicit author (i.e. not mining), extract from the header
4141
var beneficiary common.Address
4242
if author == nil {
4343
beneficiary, _ = chain.Engine().Author(header) // Ignore error, we're past header validation
4444
} else {
4545
beneficiary = *author
4646
}
47-
return vm.Context{
47+
return vm.BlockContext{
4848
CanTransfer: CanTransfer,
4949
Transfer: Transfer,
5050
GetHash: GetHashFn(header, chain),
51-
Origin: msg.From(),
5251
Coinbase: beneficiary,
5352
BlockNumber: new(big.Int).Set(header.Number),
5453
Time: new(big.Int).SetUint64(header.Time),
5554
Difficulty: new(big.Int).Set(header.Difficulty),
5655
GasLimit: header.GasLimit,
57-
GasPrice: new(big.Int).Set(msg.GasPrice()),
56+
}
57+
}
58+
59+
// NewEVMTxContext creates a new transaction context for a single transaction.
60+
func NewEVMTxContext(msg Message) vm.TxContext {
61+
return vm.TxContext{
62+
Origin: msg.From(),
63+
GasPrice: new(big.Int).Set(msg.GasPrice()),
5864
}
5965
}
6066

‎core/state_prefetcher.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,9 @@ func precacheTransaction(config *params.ChainConfig, bc ChainContext, author *co
8686
return err
8787
}
8888
// Create the EVM and execute the transaction
89-
context := NewEVMContext(msg, header, bc, author)
90-
vm := vm.NewEVM(context, statedb, config, cfg)
89+
context := NewEVMBlockContext(header, bc, author)
90+
txContext := NewEVMTxContext(msg)
91+
vm := vm.NewEVM(context, txContext, statedb, config, cfg)
9192

9293
_, err = ApplyMessage(vm, msg, gaspool)
9394
return err

‎core/state_processor.go‎

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,16 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
6565
if p.config.DAOForkSupport && p.config.DAOForkBlock != nil && p.config.DAOForkBlock.Cmp(block.Number()) == 0 {
6666
misc.ApplyDAOHardFork(statedb)
6767
}
68+
blockContext := NewEVMBlockContext(header, p.bc, nil)
69+
vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, p.config, cfg)
6870
// Iterate over and process the individual transactions
6971
for i, tx := range block.Transactions() {
72+
msg, err := tx.AsMessage(types.MakeSigner(p.config, header.Number))
73+
if err != nil {
74+
return nil, nil, 0, err
75+
}
7076
statedb.Prepare(tx.Hash(), block.Hash(), i)
71-
receipt, err := ApplyTransaction(p.config, p.bc, nil, gp, statedb, header, tx, usedGas, cfg)
77+
receipt, err := applyTransaction(msg, p.config, p.bc, nil, gp, statedb, header, tx, usedGas, vmenv)
7278
if err != nil {
7379
return nil, nil, 0, err
7480
}
@@ -81,34 +87,25 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
8187
return receipts, allLogs, *usedGas, nil
8288
}
8389

84-
// ApplyTransaction attempts to apply a transaction to the given state database
85-
// and uses the input parameters for its environment. It returns the receipt
86-
// for the transaction, gas used and an error if the transaction failed,
87-
// indicating the block was invalid.
88-
func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, error) {
89-
msg, err := tx.AsMessage(types.MakeSigner(config, header.Number))
90-
if err != nil {
91-
return nil, err
92-
}
90+
func applyTransaction(msg types.Message, config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, evm *vm.EVM) (*types.Receipt, error) {
9391
// Create a new context to be used in the EVM environment
94-
context := NewEVMContext(msg, header, bc, author)
95-
// Create a new environment which holds all relevant information
96-
// about the transaction and calling mechanisms.
97-
vmenv := vm.NewEVM(context, statedb, config, cfg)
98-
92+
txContext := NewEVMTxContext(msg)
93+
// Add addresses to access list if applicable
9994
if config.IsYoloV2(header.Number) {
10095
statedb.AddAddressToAccessList(msg.From())
10196
if dst := msg.To(); dst != nil {
10297
statedb.AddAddressToAccessList(*dst)
10398
// If it's a create-tx, the destination will be added inside evm.create
10499
}
105-
for _, addr := range vmenv.ActivePrecompiles() {
100+
for _, addr := range evm.ActivePrecompiles() {
106101
statedb.AddAddressToAccessList(addr)
107102
}
108103
}
109104

105+
// Update the evm with the new transaction context.
106+
evm.Reset(txContext, statedb)
110107
// Apply the transaction to the current state (included in the env)
111-
result, err := ApplyMessage(vmenv, msg, gp)
108+
result, err := ApplyMessage(evm, msg, gp)
112109
if err != nil {
113110
return nil, err
114111
}
@@ -128,7 +125,7 @@ func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *commo
128125
receipt.GasUsed = result.UsedGas
129126
// if the transaction created a contract, store the creation address in the receipt.
130127
if msg.To() == nil {
131-
receipt.ContractAddress = crypto.CreateAddress(vmenv.Context.Origin, tx.Nonce())
128+
receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
132129
}
133130
// Set the receipt logs and create a bloom for filtering
134131
receipt.Logs = statedb.GetLogs(tx.Hash())
@@ -139,3 +136,18 @@ func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *commo
139136

140137
return receipt, err
141138
}
139+
140+
// ApplyTransaction attempts to apply a transaction to the given state database
141+
// and uses the input parameters for its environment. It returns the receipt
142+
// for the transaction, gas used and an error if the transaction failed,
143+
// indicating the block was invalid.
144+
func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, error) {
145+
msg, err := tx.AsMessage(types.MakeSigner(config, header.Number))
146+
if err != nil {
147+
return nil, err
148+
}
149+
// Create a new context to be used in the EVM environment
150+
blockContext := NewEVMBlockContext(header, bc, author)
151+
vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg)
152+
return applyTransaction(msg, config, bc, author, gp, statedb, header, tx, usedGas, vmenv)
153+
}

‎core/state_transition.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -230,8 +230,8 @@ func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
230230
}
231231
msg := st.msg
232232
sender := vm.AccountRef(msg.From())
233-
homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber)
234-
istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.BlockNumber)
233+
homestead := st.evm.ChainConfig().IsHomestead(st.evm.Context.BlockNumber)
234+
istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.Context.BlockNumber)
235235
contractCreation := msg.To() == nil
236236

237237
// Check clauses 4-5, subtract intrinsic gas if everything is correct
@@ -245,7 +245,7 @@ func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
245245
st.gas -= gas
246246

247247
// Check clause 6
248-
if msg.Value().Sign() > 0 && !st.evm.CanTransfer(st.state, msg.From(), msg.Value()) {
248+
if msg.Value().Sign() > 0 && !st.evm.Context.CanTransfer(st.state, msg.From(), msg.Value()) {
249249
return nil, ErrInsufficientFundsForTransfer
250250
}
251251
var (
@@ -260,7 +260,7 @@ func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
260260
ret, st.gas, vmerr = st.evm.Call(sender, st.to(), st.data, st.gas, st.value)
261261
}
262262
st.refundGas()
263-
st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
263+
st.state.AddBalance(st.evm.Context.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
264264

265265
return &ExecutionResult{
266266
UsedGas: st.gasUsed(),

‎core/vm/evm.go‎

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,9 @@ func run(evm *EVM, contract *Contract, input []byte, readOnly bool) ([]byte, err
9191
return nil, errors.New("no compatible interpreter")
9292
}
9393

94-
// Context provides the EVM with auxiliary information. Once provided
94+
// BlockContext provides the EVM with auxiliary information. Once provided
9595
// it shouldn't be modified.
96-
type Context struct {
96+
type BlockContext struct {
9797
// CanTransfer returns whether the account contains
9898
// sufficient ether to transfer the value
9999
CanTransfer CanTransferFunc
@@ -102,10 +102,6 @@ type Context struct {
102102
// GetHash returns the hash corresponding to n
103103
GetHash GetHashFunc
104104

105-
// Message information
106-
Origin common.Address // Provides information for ORIGIN
107-
GasPrice *big.Int // Provides information for GASPRICE
108-
109105
// Block information
110106
Coinbase common.Address // Provides information for COINBASE
111107
GasLimit uint64 // Provides information for GASLIMIT
@@ -114,6 +110,14 @@ type Context struct {
114110
Difficulty *big.Int // Provides information for DIFFICULTY
115111
}
116112

113+
// TxContext provides the EVM with information about a transaction.
114+
// All fields can change between transactions.
115+
type TxContext struct {
116+
// Message information
117+
Origin common.Address // Provides information for ORIGIN
118+
GasPrice *big.Int // Provides information for GASPRICE
119+
}
120+
117121
// EVM is the Ethereum Virtual Machine base object and provides
118122
// the necessary tools to run a contract on the given state with
119123
// the provided context. It should be noted that any error
@@ -125,7 +129,8 @@ type Context struct {
125129
// The EVM should never be reused and is not thread safe.
126130
type EVM struct {
127131
// Context provides auxiliary blockchain related information
128-
Context
132+
Context BlockContext
133+
TxContext
129134
// StateDB gives access to the underlying state
130135
StateDB StateDB
131136
// Depth is the current call stack
@@ -153,17 +158,18 @@ type EVM struct {
153158

154159
// NewEVM returns a new EVM. The returned EVM is not thread safe and should
155160
// only ever be used *once*.
156-
func NewEVM(ctx Context, statedb StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
161+
func NewEVM(blockCtx BlockContext, txCtx TxContext, statedb StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
157162
evm := &EVM{
158-
Context: ctx,
163+
Context: blockCtx,
164+
TxContext: txCtx,
159165
StateDB: statedb,
160166
vmConfig: vmConfig,
161167
chainConfig: chainConfig,
162-
chainRules: chainConfig.Rules(ctx.BlockNumber),
168+
chainRules: chainConfig.Rules(blockCtx.BlockNumber),
163169
interpreters: make([]Interpreter, 0, 1),
164170
}
165171

166-
if chainConfig.IsEWASM(ctx.BlockNumber) {
172+
if chainConfig.IsEWASM(blockCtx.BlockNumber) {
167173
// to be implemented by EVM-C and Wagon PRs.
168174
// if vmConfig.EWASMInterpreter != "" {
169175
// extIntOpts := strings.Split(vmConfig.EWASMInterpreter, ":")
@@ -187,6 +193,13 @@ func NewEVM(ctx Context, statedb StateDB, chainConfig *params.ChainConfig, vmCon
187193
return evm
188194
}
189195

196+
// Reset resets the EVM with a new transaction context.Reset
197+
// This is not threadsafe and should only be done very cautiously.
198+
func (evm *EVM) Reset(txCtx TxContext, statedb StateDB) {
199+
evm.TxContext = txCtx
200+
evm.StateDB = statedb
201+
}
202+
190203
// Cancel cancels any running EVM operation. This may be called concurrently and
191204
// it's safe to be called multiple times.
192205
func (evm *EVM) Cancel() {
@@ -233,7 +246,7 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas
233246
}
234247
evm.StateDB.CreateAccount(addr)
235248
}
236-
evm.Transfer(evm.StateDB, caller.Address(), addr, value)
249+
evm.Context.Transfer(evm.StateDB, caller.Address(), addr, value)
237250

238251
// Capture the tracer start/end events in debug mode
239252
if evm.vmConfig.Debug && evm.depth == 0 {
@@ -426,7 +439,7 @@ func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64,
426439
if evm.depth > int(params.CallCreateDepth) {
427440
return nil, common.Address{}, gas, ErrDepth
428441
}
429-
if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
442+
if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
430443
return nil, common.Address{}, gas, ErrInsufficientBalance
431444
}
432445
nonce := evm.StateDB.GetNonce(caller.Address())
@@ -447,7 +460,7 @@ func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64,
447460
if evm.chainRules.IsEIP158 {
448461
evm.StateDB.SetNonce(address, 1)
449462
}
450-
evm.Transfer(evm.StateDB, caller.Address(), address, value)
463+
evm.Context.Transfer(evm.StateDB, caller.Address(), address, value)
451464

452465
// Initialise a new contract and set the code that is to be used by the EVM.
453466
// The contract is a scoped environment for this execution context only.

‎core/vm/gas_table_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,11 +87,11 @@ func TestEIP2200(t *testing.T) {
8787
statedb.SetState(address, common.Hash{}, common.BytesToHash([]byte{tt.original}))
8888
statedb.Finalise(true) // Push the state into the "original" slot
8989

90-
vmctx := Context{
90+
vmctx := BlockContext{
9191
CanTransfer: func(StateDB, common.Address, *big.Int) bool { return true },
9292
Transfer: func(StateDB, common.Address, common.Address, *big.Int) {},
9393
}
94-
vmenv := NewEVM(vmctx, statedb, params.AllEthashProtocolChanges, Config{ExtraEips: []int{2200}})
94+
vmenv := NewEVM(vmctx, TxContext{}, statedb, params.AllEthashProtocolChanges, Config{ExtraEips: []int{2200}})
9595

9696
_, gas, err := vmenv.Call(AccountRef(common.Address{}), address, nil, tt.gaspool, new(big.Int))
9797
if err != tt.failure {

0 commit comments

Comments
 (0)