Skip to content

Commit bbc4ea4

Browse files
obscurenfjl
authored andcommitted
core/vm: improved EVM run loop & instruction calling (bnb-chain#3378)
The run loop, which previously contained custom opcode executes have been removed and has been simplified to a few checks. Each operation consists of 4 elements: execution function, gas cost function, stack validation function and memory size function. The execution function implements the operation's runtime behaviour, the gas cost function implements the operation gas costs function and greatly depends on the memory and stack, the stack validation function validates the stack and makes sure that enough items can be popped off and pushed on and the memory size function calculates the memory required for the operation and returns it. This commit also allows the EVM to go unmetered. This is helpful for offline operations such as contract calls.
1 parent 2126d81 commit bbc4ea4

44 files changed

Lines changed: 1653 additions & 1996 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallM
229229
evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain)
230230
// Create a new environment which holds all relevant information
231231
// about the transaction and calling mechanisms.
232-
vmenv := vm.NewEnvironment(evmContext, statedb, chainConfig, vm.Config{})
232+
vmenv := vm.NewEVM(evmContext, statedb, chainConfig, vm.Config{})
233233
gaspool := new(core.GasPool).AddGas(common.MaxBig)
234234
ret, gasUsed, _, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
235235
return ret, gasUsed, err

‎cmd/evm/main.go‎

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -44,14 +44,6 @@ var (
4444
Name: "debug",
4545
Usage: "output full trace logs",
4646
}
47-
ForceJitFlag = cli.BoolFlag{
48-
Name: "forcejit",
49-
Usage: "forces jit compilation",
50-
}
51-
DisableJitFlag = cli.BoolFlag{
52-
Name: "nojit",
53-
Usage: "disabled jit compilation",
54-
}
5547
CodeFlag = cli.StringFlag{
5648
Name: "code",
5749
Usage: "EVM code",
@@ -95,15 +87,17 @@ var (
9587
Name: "create",
9688
Usage: "indicates the action should be create rather than call",
9789
}
90+
DisableGasMeteringFlag = cli.BoolFlag{
91+
Name: "nogasmetering",
92+
Usage: "disable gas metering",
93+
}
9894
)
9995

10096
func init() {
10197
app.Flags = []cli.Flag{
10298
CreateFlag,
10399
DebugFlag,
104100
VerbosityFlag,
105-
ForceJitFlag,
106-
DisableJitFlag,
107101
SysStatFlag,
108102
CodeFlag,
109103
CodeFileFlag,
@@ -112,6 +106,7 @@ func init() {
112106
ValueFlag,
113107
DumpFlag,
114108
InputFlag,
109+
DisableGasMeteringFlag,
115110
}
116111
app.Action = run
117112
}
@@ -165,7 +160,8 @@ func run(ctx *cli.Context) error {
165160
GasPrice: common.Big(ctx.GlobalString(PriceFlag.Name)),
166161
Value: common.Big(ctx.GlobalString(ValueFlag.Name)),
167162
EVMConfig: vm.Config{
168-
Tracer: logger,
163+
Tracer: logger,
164+
DisableGasMetering: ctx.GlobalBool(DisableGasMeteringFlag.Name),
169165
},
170166
})
171167
} else {
@@ -179,7 +175,8 @@ func run(ctx *cli.Context) error {
179175
GasPrice: common.Big(ctx.GlobalString(PriceFlag.Name)),
180176
Value: common.Big(ctx.GlobalString(ValueFlag.Name)),
181177
EVMConfig: vm.Config{
182-
Tracer: logger,
178+
Tracer: logger,
179+
DisableGasMetering: ctx.GlobalBool(DisableGasMeteringFlag.Name),
183180
},
184181
})
185182
}

‎core/chain_makers.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ func (b *BlockGen) AddTx(tx *types.Transaction) {
108108
b.SetCoinbase(common.Address{})
109109
}
110110
b.statedb.StartRecord(tx.Hash(), common.Hash{}, len(b.txs))
111-
receipt, _, _, err := ApplyTransaction(b.config, nil, b.gasPool, b.statedb, b.header, tx, b.header.GasUsed, vm.Config{})
111+
receipt, _, err := ApplyTransaction(b.config, nil, b.gasPool, b.statedb, b.header, tx, b.header.GasUsed, vm.Config{})
112112
if err != nil {
113113
panic(err)
114114
}

‎core/state_processor.go‎

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -74,37 +74,36 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
7474
for i, tx := range block.Transactions() {
7575
//fmt.Println("tx:", i)
7676
statedb.StartRecord(tx.Hash(), block.Hash(), i)
77-
receipt, logs, _, err := ApplyTransaction(p.config, p.bc, gp, statedb, header, tx, totalUsedGas, cfg)
77+
receipt, _, err := ApplyTransaction(p.config, p.bc, gp, statedb, header, tx, totalUsedGas, cfg)
7878
if err != nil {
7979
return nil, nil, nil, err
8080
}
8181
receipts = append(receipts, receipt)
82-
allLogs = append(allLogs, logs...)
82+
allLogs = append(allLogs, receipt.Logs...)
8383
}
8484
AccumulateRewards(statedb, header, block.Uncles())
8585

8686
return receipts, allLogs, totalUsedGas, err
8787
}
8888

8989
// ApplyTransaction attempts to apply a transaction to the given state database
90-
// and uses the input parameters for its environment.
91-
//
92-
// ApplyTransactions returns the generated receipts and vm logs during the
93-
// execution of the state transition phase.
94-
func ApplyTransaction(config *params.ChainConfig, bc *BlockChain, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *big.Int, cfg vm.Config) (*types.Receipt, vm.Logs, *big.Int, error) {
90+
// and uses the input parameters for its environment. It returns the receipt
91+
// for the transaction, gas used and an error if the transaction failed,
92+
// indicating the block was invalid.
93+
func ApplyTransaction(config *params.ChainConfig, bc *BlockChain, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *big.Int, cfg vm.Config) (*types.Receipt, *big.Int, error) {
9594
msg, err := tx.AsMessage(types.MakeSigner(config, header.Number))
9695
if err != nil {
97-
return nil, nil, nil, err
96+
return nil, nil, err
9897
}
9998
// Create a new context to be used in the EVM environment
10099
context := NewEVMContext(msg, header, bc)
101100
// Create a new environment which holds all relevant information
102101
// about the transaction and calling mechanisms.
103-
vmenv := vm.NewEnvironment(context, statedb, config, vm.Config{})
102+
vmenv := vm.NewEVM(context, statedb, config, vm.Config{})
104103
// Apply the transaction to the current state (included in the env)
105104
_, gas, err := ApplyMessage(vmenv, msg, gp)
106105
if err != nil {
107-
return nil, nil, nil, err
106+
return nil, nil, err
108107
}
109108

110109
// Update the state with pending changes
@@ -125,7 +124,7 @@ func ApplyTransaction(config *params.ChainConfig, bc *BlockChain, gp *GasPool, s
125124

126125
glog.V(logger.Debug).Infoln(receipt)
127126

128-
return receipt, receipt.Logs, gas, err
127+
return receipt, gas, err
129128
}
130129

131130
// AccumulateRewards credits the coinbase of the given block with the

‎core/state_transition.go‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ type StateTransition struct {
5757
data []byte
5858
state vm.StateDB
5959

60-
env *vm.Environment
60+
env *vm.EVM
6161
}
6262

6363
// Message represents a message sent to a contract.
@@ -106,7 +106,7 @@ func IntrinsicGas(data []byte, contractCreation, homestead bool) *big.Int {
106106
}
107107

108108
// NewStateTransition initialises and returns a new state transition object.
109-
func NewStateTransition(env *vm.Environment, msg Message, gp *GasPool) *StateTransition {
109+
func NewStateTransition(env *vm.EVM, msg Message, gp *GasPool) *StateTransition {
110110
return &StateTransition{
111111
gp: gp,
112112
env: env,
@@ -127,7 +127,7 @@ func NewStateTransition(env *vm.Environment, msg Message, gp *GasPool) *StateTra
127127
// the gas used (which includes gas refunds) and an error if it failed. An error always
128128
// indicates a core error meaning that the message would always fail for that particular
129129
// state and would never be accepted within a block.
130-
func ApplyMessage(env *vm.Environment, msg Message, gp *GasPool) ([]byte, *big.Int, error) {
130+
func ApplyMessage(env *vm.EVM, msg Message, gp *GasPool) ([]byte, *big.Int, error) {
131131
st := NewStateTransition(env, msg, gp)
132132

133133
ret, _, gasUsed, err := st.TransitionDb()
@@ -159,7 +159,7 @@ func (self *StateTransition) to() vm.Account {
159159

160160
func (self *StateTransition) useGas(amount *big.Int) error {
161161
if self.gas.Cmp(amount) < 0 {
162-
return vm.OutOfGasError
162+
return vm.ErrOutOfGas
163163
}
164164
self.gas.Sub(self.gas, amount)
165165

@@ -233,7 +233,7 @@ func (self *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *b
233233
)
234234
if contractCreation {
235235
ret, _, vmerr = vmenv.Create(sender, self.data, self.gas, self.value)
236-
if homestead && err == vm.CodeStoreOutOfGasError {
236+
if homestead && err == vm.ErrCodeStoreOutOfGas {
237237
self.gas = Big0
238238
}
239239
} else {

‎core/vm/contracts.go‎

Lines changed: 62 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -26,64 +26,45 @@ import (
2626
"github.com/ethereum/go-ethereum/params"
2727
)
2828

29-
// PrecompiledAccount represents a native ethereum contract
30-
type PrecompiledAccount struct {
31-
Gas func(l int) *big.Int
32-
fn func(in []byte) []byte
29+
// Precompiled contract is the basic interface for native Go contracts. The implementation
30+
// requires a deterministic gas count based on the input size of the Run method of the
31+
// contract.
32+
type PrecompiledContract interface {
33+
RequiredGas(inputSize int) *big.Int // RequiredPrice calculates the contract gas use
34+
Run(input []byte) []byte // Run runs the precompiled contract
3335
}
3436

35-
// Call calls the native function
36-
func (self PrecompiledAccount) Call(in []byte) []byte {
37-
return self.fn(in)
37+
// Precompiled contains the default set of ethereum contracts
38+
var PrecompiledContracts = map[common.Address]PrecompiledContract{
39+
common.BytesToAddress([]byte{1}): &ecrecover{},
40+
common.BytesToAddress([]byte{2}): &sha256{},
41+
common.BytesToAddress([]byte{3}): &ripemd160{},
42+
common.BytesToAddress([]byte{4}): &dataCopy{},
3843
}
3944

40-
// Precompiled contains the default set of ethereum contracts
41-
var Precompiled = PrecompiledContracts()
42-
43-
// PrecompiledContracts returns the default set of precompiled ethereum
44-
// contracts defined by the ethereum yellow paper.
45-
func PrecompiledContracts() map[string]*PrecompiledAccount {
46-
return map[string]*PrecompiledAccount{
47-
// ECRECOVER
48-
string(common.LeftPadBytes([]byte{1}, 20)): &PrecompiledAccount{func(l int) *big.Int {
49-
return params.EcrecoverGas
50-
}, ecrecoverFunc},
51-
52-
// SHA256
53-
string(common.LeftPadBytes([]byte{2}, 20)): &PrecompiledAccount{func(l int) *big.Int {
54-
n := big.NewInt(int64(l+31) / 32)
55-
n.Mul(n, params.Sha256WordGas)
56-
return n.Add(n, params.Sha256Gas)
57-
}, sha256Func},
58-
59-
// RIPEMD160
60-
string(common.LeftPadBytes([]byte{3}, 20)): &PrecompiledAccount{func(l int) *big.Int {
61-
n := big.NewInt(int64(l+31) / 32)
62-
n.Mul(n, params.Ripemd160WordGas)
63-
return n.Add(n, params.Ripemd160Gas)
64-
}, ripemd160Func},
65-
66-
string(common.LeftPadBytes([]byte{4}, 20)): &PrecompiledAccount{func(l int) *big.Int {
67-
n := big.NewInt(int64(l+31) / 32)
68-
n.Mul(n, params.IdentityWordGas)
69-
70-
return n.Add(n, params.IdentityGas)
71-
}, memCpy},
45+
// RunPrecompile runs and evaluate the output of a precompiled contract defined in contracts.go
46+
func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract) (ret []byte, err error) {
47+
gas := p.RequiredGas(len(input))
48+
if contract.UseGas(gas) {
49+
ret = p.Run(input)
50+
51+
return ret, nil
52+
} else {
53+
return nil, ErrOutOfGas
7254
}
7355
}
7456

75-
func sha256Func(in []byte) []byte {
76-
return crypto.Sha256(in)
77-
}
57+
// ECRECOVER implemented as a native contract
58+
type ecrecover struct{}
7859

79-
func ripemd160Func(in []byte) []byte {
80-
return common.LeftPadBytes(crypto.Ripemd160(in), 32)
60+
func (c *ecrecover) RequiredGas(inputSize int) *big.Int {
61+
return params.EcrecoverGas
8162
}
8263

83-
const ecRecoverInputLength = 128
64+
func (c *ecrecover) Run(in []byte) []byte {
65+
const ecRecoverInputLength = 128
8466

85-
func ecrecoverFunc(in []byte) []byte {
86-
in = common.RightPadBytes(in, 128)
67+
in = common.RightPadBytes(in, ecRecoverInputLength)
8768
// "in" is (hash, v, r, s), each 32 bytes
8869
// but for ecrecover we want (r, s, v)
8970

@@ -108,6 +89,39 @@ func ecrecoverFunc(in []byte) []byte {
10889
return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32)
10990
}
11091

111-
func memCpy(in []byte) []byte {
92+
// SHA256 implemented as a native contract
93+
type sha256 struct{}
94+
95+
func (c *sha256) RequiredGas(inputSize int) *big.Int {
96+
n := big.NewInt(int64(inputSize+31) / 32)
97+
n.Mul(n, params.Sha256WordGas)
98+
return n.Add(n, params.Sha256Gas)
99+
}
100+
func (c *sha256) Run(in []byte) []byte {
101+
return crypto.Sha256(in)
102+
}
103+
104+
// RIPMED160 implemented as a native contract
105+
type ripemd160 struct{}
106+
107+
func (c *ripemd160) RequiredGas(inputSize int) *big.Int {
108+
n := big.NewInt(int64(inputSize+31) / 32)
109+
n.Mul(n, params.Ripemd160WordGas)
110+
return n.Add(n, params.Ripemd160Gas)
111+
}
112+
func (c *ripemd160) Run(in []byte) []byte {
113+
return common.LeftPadBytes(crypto.Ripemd160(in), 32)
114+
}
115+
116+
// data copy implemented as a native contract
117+
type dataCopy struct{}
118+
119+
func (c *dataCopy) RequiredGas(inputSize int) *big.Int {
120+
n := big.NewInt(int64(inputSize+31) / 32)
121+
n.Mul(n, params.IdentityWordGas)
122+
123+
return n.Add(n, params.IdentityGas)
124+
}
125+
func (c *dataCopy) Run(in []byte) []byte {
112126
return in
113127
}

0 commit comments

Comments
 (0)