Skip to content

Commit 89a3245

Browse files
holimankaralabe
authored andcommitted
core/vm: faster create/create2 (#17806)
* core/vm/runtim: benchmark create/create2 * core/vm: do less hashing in CREATE2 * core/vm: avoid storing jumpdest analysis for initcode * core/vm: avoid unneccesary lookups, remove unused fields * core/vm: go formatting tests * core/vm: save jumpdest analysis locally * core/vm: use common.Hash instead of nil, fix review comments * core/vm: removed type destinations * core/vm: correct check for empty hash * eth: more elegant api_tracer * core/vm: address review concerns
1 parent 8c63d0d commit 89a3245

9 files changed

Lines changed: 163 additions & 55 deletions

File tree

‎core/vm/analysis.go‎

Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -16,34 +16,6 @@
1616

1717
package vm
1818

19-
import (
20-
"math/big"
21-
22-
"github.com/ethereum/go-ethereum/common"
23-
)
24-
25-
// destinations stores one map per contract (keyed by hash of code).
26-
// The maps contain an entry for each location of a JUMPDEST
27-
// instruction.
28-
type destinations map[common.Hash]bitvec
29-
30-
// has checks whether code has a JUMPDEST at dest.
31-
func (d destinations) has(codehash common.Hash, code []byte, dest *big.Int) bool {
32-
// PC cannot go beyond len(code) and certainly can't be bigger than 63bits.
33-
// Don't bother checking for JUMPDEST in that case.
34-
udest := dest.Uint64()
35-
if dest.BitLen() >= 63 || udest >= uint64(len(code)) {
36-
return false
37-
}
38-
39-
m, analysed := d[codehash]
40-
if !analysed {
41-
m = codeBitmap(code)
42-
d[codehash] = m
43-
}
44-
return OpCode(code[udest]) == JUMPDEST && m.codeSegment(udest)
45-
}
46-
4719
// bitvec is a bit vector which maps bytes in a program.
4820
// An unset bit means the byte is an opcode, a set bit means
4921
// it's data (i.e. argument of PUSHxx).

‎core/vm/analysis_test.go‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,11 @@
1616

1717
package vm
1818

19-
import "testing"
19+
import (
20+
"testing"
21+
22+
"github.com/ethereum/go-ethereum/crypto"
23+
)
2024

2125
func TestJumpDestAnalysis(t *testing.T) {
2226
tests := []struct {
@@ -49,5 +53,23 @@ func TestJumpDestAnalysis(t *testing.T) {
4953
t.Fatalf("expected %x, got %02x", test.exp, ret[test.which])
5054
}
5155
}
56+
}
5257

58+
func BenchmarkJumpdestAnalysis_1200k(bench *testing.B) {
59+
// 1.4 ms
60+
code := make([]byte, 1200000)
61+
bench.ResetTimer()
62+
for i := 0; i < bench.N; i++ {
63+
codeBitmap(code)
64+
}
65+
bench.StopTimer()
66+
}
67+
func BenchmarkJumpdestHashing_1200k(bench *testing.B) {
68+
// 4 ms
69+
code := make([]byte, 1200000)
70+
bench.ResetTimer()
71+
for i := 0; i < bench.N; i++ {
72+
crypto.Keccak256Hash(code)
73+
}
74+
bench.StopTimer()
5375
}

‎core/vm/contract.go‎

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,8 @@ type Contract struct {
4949
caller ContractRef
5050
self ContractRef
5151

52-
jumpdests destinations // result of JUMPDEST analysis.
52+
jumpdests map[common.Hash]bitvec // Aggregated result of JUMPDEST analysis.
53+
analysis bitvec // Locally cached result of JUMPDEST analysis
5354

5455
Code []byte
5556
CodeHash common.Hash
@@ -58,21 +59,17 @@ type Contract struct {
5859

5960
Gas uint64
6061
value *big.Int
61-
62-
Args []byte
63-
64-
DelegateCall bool
6562
}
6663

6764
// NewContract returns a new contract environment for the execution of EVM.
6865
func NewContract(caller ContractRef, object ContractRef, value *big.Int, gas uint64) *Contract {
69-
c := &Contract{CallerAddress: caller.Address(), caller: caller, self: object, Args: nil}
66+
c := &Contract{CallerAddress: caller.Address(), caller: caller, self: object}
7067

7168
if parent, ok := caller.(*Contract); ok {
7269
// Reuse JUMPDEST analysis from parent context if available.
7370
c.jumpdests = parent.jumpdests
7471
} else {
75-
c.jumpdests = make(destinations)
72+
c.jumpdests = make(map[common.Hash]bitvec)
7673
}
7774

7875
// Gas should be a pointer so it can safely be reduced through the run
@@ -84,10 +81,42 @@ func NewContract(caller ContractRef, object ContractRef, value *big.Int, gas uin
8481
return c
8582
}
8683

84+
func (c *Contract) validJumpdest(dest *big.Int) bool {
85+
udest := dest.Uint64()
86+
// PC cannot go beyond len(code) and certainly can't be bigger than 63bits.
87+
// Don't bother checking for JUMPDEST in that case.
88+
if dest.BitLen() >= 63 || udest >= uint64(len(c.Code)) {
89+
return false
90+
}
91+
// Only JUMPDESTs allowed for destinations
92+
if OpCode(c.Code[udest]) != JUMPDEST {
93+
return false
94+
}
95+
// Do we have a contract hash already?
96+
if c.CodeHash != (common.Hash{}) {
97+
// Does parent context have the analysis?
98+
analysis, exist := c.jumpdests[c.CodeHash]
99+
if !exist {
100+
// Do the analysis and save in parent context
101+
// We do not need to store it in c.analysis
102+
analysis = codeBitmap(c.Code)
103+
c.jumpdests[c.CodeHash] = analysis
104+
}
105+
return analysis.codeSegment(udest)
106+
}
107+
// We don't have the code hash, most likely a piece of initcode not already
108+
// in state trie. In that case, we do an analysis, and save it locally, so
109+
// we don't have to recalculate it for every JUMP instruction in the execution
110+
// However, we don't save it within the parent context
111+
if c.analysis == nil {
112+
c.analysis = codeBitmap(c.Code)
113+
}
114+
return c.analysis.codeSegment(udest)
115+
}
116+
87117
// AsDelegate sets the contract to be a delegate call and returns the current
88118
// contract (for chaining calls)
89119
func (c *Contract) AsDelegate() *Contract {
90-
c.DelegateCall = true
91120
// NOTE: caller must, at all times be a contract. It should never happen
92121
// that caller is something other than a Contract.
93122
parent := c.caller.(*Contract)
@@ -138,16 +167,18 @@ func (c *Contract) Value() *big.Int {
138167
return c.value
139168
}
140169

141-
// SetCode sets the code to the contract
142-
func (c *Contract) SetCode(hash common.Hash, code []byte) {
143-
c.Code = code
144-
c.CodeHash = hash
145-
}
146-
147170
// SetCallCode sets the code of the contract and address of the backing data
148171
// object
149172
func (c *Contract) SetCallCode(addr *common.Address, hash common.Hash, code []byte) {
150173
c.Code = code
151174
c.CodeHash = hash
152175
c.CodeAddr = addr
153176
}
177+
178+
// SetCodeOptionalHash can be used to provide code, but it's optional to provide hash.
179+
// In case hash is not provided, the jumpdest analysis will not be saved to the parent context
180+
func (c *Contract) SetCodeOptionalHash(addr *common.Address, codeAndHash *codeAndHash) {
181+
c.Code = codeAndHash.code
182+
c.CodeHash = codeAndHash.hash
183+
c.CodeAddr = addr
184+
}

‎core/vm/evm.go‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -212,12 +212,12 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas
212212
evm.StateDB.CreateAccount(addr)
213213
}
214214
evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
215-
216215
// Initialise a new contract and set the code that is to be used by the EVM.
217216
// The contract is a scoped environment for this execution context only.
218217
contract := NewContract(caller, to, value, gas)
219218
contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
220219

220+
// Even if the account has no code, we need to continue because it might be a precompile
221221
start := time.Now()
222222

223223
// Capture the tracer start/end events in debug mode
@@ -352,8 +352,20 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte
352352
return ret, contract.Gas, err
353353
}
354354

355+
type codeAndHash struct {
356+
code []byte
357+
hash common.Hash
358+
}
359+
360+
func (c *codeAndHash) Hash() common.Hash {
361+
if c.hash == (common.Hash{}) {
362+
c.hash = crypto.Keccak256Hash(c.code)
363+
}
364+
return c.hash
365+
}
366+
355367
// create creates a new contract using code as deployment code.
356-
func (evm *EVM) create(caller ContractRef, code []byte, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
368+
func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
357369
// Depth check execution. Fail if we're trying to execute above the
358370
// limit.
359371
if evm.depth > int(params.CallCreateDepth) {
@@ -382,14 +394,14 @@ func (evm *EVM) create(caller ContractRef, code []byte, gas uint64, value *big.I
382394
// EVM. The contract is a scoped environment for this execution context
383395
// only.
384396
contract := NewContract(caller, AccountRef(address), value, gas)
385-
contract.SetCallCode(&address, crypto.Keccak256Hash(code), code)
397+
contract.SetCodeOptionalHash(&address, codeAndHash)
386398

387399
if evm.vmConfig.NoRecursion && evm.depth > 0 {
388400
return nil, address, gas, nil
389401
}
390402

391403
if evm.vmConfig.Debug && evm.depth == 0 {
392-
evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, code, gas, value)
404+
evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value)
393405
}
394406
start := time.Now()
395407

@@ -433,16 +445,17 @@ func (evm *EVM) create(caller ContractRef, code []byte, gas uint64, value *big.I
433445
// Create creates a new contract using code as deployment code.
434446
func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
435447
contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
436-
return evm.create(caller, code, gas, value, contractAddr)
448+
return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
437449
}
438450

439451
// Create2 creates a new contract using code as deployment code.
440452
//
441453
// The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
442454
// instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
443455
func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
444-
contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), code)
445-
return evm.create(caller, code, gas, endowment, contractAddr)
456+
codeAndHash := &codeAndHash{code: code}
457+
contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), codeAndHash.Hash().Bytes())
458+
return evm.create(caller, codeAndHash, gas, endowment, contractAddr)
446459
}
447460

448461
// ChainConfig returns the environment's chain configuration

‎core/vm/instructions.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -620,7 +620,7 @@ func opSstore(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memor
620620

621621
func opJump(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
622622
pos := stack.pop()
623-
if !contract.jumpdests.has(contract.CodeHash, contract.Code, pos) {
623+
if !contract.validJumpdest(pos) {
624624
nop := contract.GetOp(pos.Uint64())
625625
return nil, fmt.Errorf("invalid jump destination (%v) %v", nop, pos)
626626
}
@@ -633,7 +633,7 @@ func opJump(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory
633633
func opJumpi(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
634634
pos, cond := stack.pop(), stack.pop()
635635
if cond.Sign() != 0 {
636-
if !contract.jumpdests.has(contract.CodeHash, contract.Code, pos) {
636+
if !contract.validJumpdest(pos) {
637637
nop := contract.GetOp(pos.Uint64())
638638
return nil, fmt.Errorf("invalid jump destination (%v) %v", nop, pos)
639639
}

‎core/vm/runtime/runtime_test.go‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
"github.com/ethereum/go-ethereum/core/state"
2727
"github.com/ethereum/go-ethereum/core/vm"
2828
"github.com/ethereum/go-ethereum/ethdb"
29+
"github.com/ethereum/go-ethereum/params"
2930
)
3031

3132
func TestDefaults(t *testing.T) {
@@ -148,3 +149,57 @@ func BenchmarkCall(b *testing.B) {
148149
}
149150
}
150151
}
152+
func benchmarkEVM_Create(bench *testing.B, code string) {
153+
var (
154+
statedb, _ = state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
155+
sender = common.BytesToAddress([]byte("sender"))
156+
receiver = common.BytesToAddress([]byte("receiver"))
157+
)
158+
159+
statedb.CreateAccount(sender)
160+
statedb.SetCode(receiver, common.FromHex(code))
161+
runtimeConfig := Config{
162+
Origin: sender,
163+
State: statedb,
164+
GasLimit: 10000000,
165+
Difficulty: big.NewInt(0x200000),
166+
Time: new(big.Int).SetUint64(0),
167+
Coinbase: common.Address{},
168+
BlockNumber: new(big.Int).SetUint64(1),
169+
ChainConfig: &params.ChainConfig{
170+
ChainID: big.NewInt(1),
171+
HomesteadBlock: new(big.Int),
172+
ByzantiumBlock: new(big.Int),
173+
ConstantinopleBlock: new(big.Int),
174+
DAOForkBlock: new(big.Int),
175+
DAOForkSupport: false,
176+
EIP150Block: new(big.Int),
177+
EIP155Block: new(big.Int),
178+
EIP158Block: new(big.Int),
179+
},
180+
EVMConfig: vm.Config{},
181+
}
182+
// Warm up the intpools and stuff
183+
bench.ResetTimer()
184+
for i := 0; i < bench.N; i++ {
185+
Call(receiver, []byte{}, &runtimeConfig)
186+
}
187+
bench.StopTimer()
188+
}
189+
190+
func BenchmarkEVM_CREATE_500(bench *testing.B) {
191+
// initcode size 500K, repeatedly calls CREATE and then modifies the mem contents
192+
benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056")
193+
}
194+
func BenchmarkEVM_CREATE2_500(bench *testing.B) {
195+
// initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents
196+
benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056")
197+
}
198+
func BenchmarkEVM_CREATE_1200(bench *testing.B) {
199+
// initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents
200+
benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056")
201+
}
202+
func BenchmarkEVM_CREATE2_1200(bench *testing.B) {
203+
// initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents
204+
benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056")
205+
}

‎crypto/crypto.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,9 @@ func CreateAddress(b common.Address, nonce uint64) common.Address {
7777
}
7878

7979
// CreateAddress2 creates an ethereum address given the address bytes, initial
80-
// contract code and a salt.
81-
func CreateAddress2(b common.Address, salt [32]byte, code []byte) common.Address {
82-
return common.BytesToAddress(Keccak256([]byte{0xff}, b.Bytes(), salt[:], Keccak256(code))[12:])
80+
// contract code hash and a salt.
81+
func CreateAddress2(b common.Address, salt [32]byte, inithash []byte) common.Address {
82+
return common.BytesToAddress(Keccak256([]byte{0xff}, b.Bytes(), salt[:], inithash)[12:])
8383
}
8484

8585
// ToECDSA creates a private key with the given D value.

‎eth/api_tracer.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,15 @@ func (api *PrivateDebugAPI) TraceBlockFromFile(ctx context.Context, file string,
391391
return api.TraceBlock(ctx, blob, config)
392392
}
393393

394+
// TraceBadBlock returns the structured logs created during the execution of a block
395+
// within the blockchain 'badblocks' cache
396+
func (api *PrivateDebugAPI) TraceBadBlock(ctx context.Context, index int, config *TraceConfig) ([]*txTraceResult, error) {
397+
if blocks := api.eth.blockchain.BadBlocks(); index < len(blocks) {
398+
return api.traceBlock(ctx, blocks[index], config)
399+
}
400+
return nil, fmt.Errorf("index out of range")
401+
}
402+
394403
// traceBlock configures a new tracer according to the provided configuration, and
395404
// executes all the transactions contained within. The return value will be one item
396405
// per transaction, dependent on the requestd tracer.

‎internal/web3ext/web3ext.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,12 @@ web3._extend({
378378
params: 2,
379379
inputFormatter: [null, null]
380380
}),
381+
new web3._extend.Method({
382+
name: 'traceBadBlock',
383+
call: 'debug_traceBadBlock',
384+
params: 1,
385+
inputFormatter: [null]
386+
}),
381387
new web3._extend.Method({
382388
name: 'traceBlockByNumber',
383389
call: 'debug_traceBlockByNumber',

0 commit comments

Comments
 (0)