Skip to content

Commit bb9631c

Browse files
committed
core: prefetch next block state concurrently
1 parent 86e7790 commit bb9631c

6 files changed

Lines changed: 193 additions & 75 deletions

File tree

‎core/blockchain.go‎

Lines changed: 51 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,9 @@ var (
6262
blockExecutionTimer = metrics.NewRegisteredTimer("chain/execution", nil)
6363
blockWriteTimer = metrics.NewRegisteredTimer("chain/write", nil)
6464

65+
blockPrefetchExecuteTimer = metrics.NewRegisteredTimer("chain/prefetch/executes", nil)
66+
blockPrefetchInterruptMeter = metrics.NewRegisteredMeter("chain/prefetch/interrupts", nil)
67+
6568
ErrNoGenesis = errors.New("Genesis not found in chain")
6669
)
6770

@@ -126,7 +129,6 @@ type BlockChain struct {
126129
genesisBlock *types.Block
127130

128131
chainmu sync.RWMutex // blockchain insertion lock
129-
procmu sync.RWMutex // block processor lock
130132

131133
checkpoint int // checkpoint counts towards the new checkpoint
132134
currentBlock atomic.Value // Current head of the block chain
@@ -145,10 +147,11 @@ type BlockChain struct {
145147
procInterrupt int32 // interrupt signaler for block processing
146148
wg sync.WaitGroup // chain processing wait group for shutting down
147149

148-
engine consensus.Engine
149-
processor Processor // block processor interface
150-
validator Validator // block and state validator interface
151-
vmConfig vm.Config
150+
engine consensus.Engine
151+
validator Validator // Block and state validator interface
152+
prefetcher Prefetcher // Block state prefetcher interface
153+
processor Processor // Block transaction processor interface
154+
vmConfig vm.Config
152155

153156
badBlocks *lru.Cache // Bad block cache
154157
shouldPreserve func(*types.Block) bool // Function used to determine whether should preserve the given block.
@@ -189,8 +192,9 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
189192
vmConfig: vmConfig,
190193
badBlocks: badBlocks,
191194
}
192-
bc.SetValidator(NewBlockValidator(chainConfig, bc, engine))
193-
bc.SetProcessor(NewStateProcessor(chainConfig, bc, engine))
195+
bc.validator = NewBlockValidator(chainConfig, bc, engine)
196+
bc.prefetcher = newStatePrefetcher(chainConfig, bc, engine)
197+
bc.processor = NewStateProcessor(chainConfig, bc, engine)
194198

195199
var err error
196200
bc.hc, err = NewHeaderChain(db, chainConfig, engine, bc.getProcInterrupt)
@@ -381,31 +385,13 @@ func (bc *BlockChain) CurrentFastBlock() *types.Block {
381385
return bc.currentFastBlock.Load().(*types.Block)
382386
}
383387

384-
// SetProcessor sets the processor required for making state modifications.
385-
func (bc *BlockChain) SetProcessor(processor Processor) {
386-
bc.procmu.Lock()
387-
defer bc.procmu.Unlock()
388-
bc.processor = processor
389-
}
390-
391-
// SetValidator sets the validator which is used to validate incoming blocks.
392-
func (bc *BlockChain) SetValidator(validator Validator) {
393-
bc.procmu.Lock()
394-
defer bc.procmu.Unlock()
395-
bc.validator = validator
396-
}
397-
398388
// Validator returns the current validator.
399389
func (bc *BlockChain) Validator() Validator {
400-
bc.procmu.RLock()
401-
defer bc.procmu.RUnlock()
402390
return bc.validator
403391
}
404392

405393
// Processor returns the current processor.
406394
func (bc *BlockChain) Processor() Processor {
407-
bc.procmu.RLock()
408-
defer bc.procmu.RUnlock()
409395
return bc.processor
410396
}
411397

@@ -1147,7 +1133,7 @@ func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
11471133
// is imported, but then new canon-head is added before the actual sidechain
11481134
// completes, then the historic state could be pruned again
11491135
func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []interface{}, []*types.Log, error) {
1150-
// If the chain is terminating, don't even bother starting u
1136+
// If the chain is terminating, don't even bother starting up
11511137
if atomic.LoadInt32(&bc.procInterrupt) == 1 {
11521138
return 0, nil, nil, nil
11531139
}
@@ -1175,7 +1161,7 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []
11751161
defer close(abort)
11761162

11771163
// Peek the error for the first block to decide the directing import logic
1178-
it := newInsertIterator(chain, results, bc.Validator())
1164+
it := newInsertIterator(chain, results, bc.validator)
11791165

11801166
block, err := it.next()
11811167

@@ -1238,54 +1224,74 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []
12381224
if parent == nil {
12391225
parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1)
12401226
}
1241-
state, err := state.New(parent.Root, bc.stateCache)
1227+
statedb, err := state.New(parent.Root, bc.stateCache)
12421228
if err != nil {
12431229
return it.index, events, coalescedLogs, err
12441230
}
1245-
// Process block using the parent state as reference point.
1231+
// If we have a followup block, run that against the current state to pre-cache
1232+
// transactions and probabilistically some of the account/storage trie nodes.
1233+
var followupInterrupt uint32
1234+
1235+
if followup, err := it.peek(); followup != nil && err == nil {
1236+
go func(start time.Time) {
1237+
throwaway, _ := state.New(parent.Root, bc.stateCache)
1238+
bc.prefetcher.Prefetch(followup, throwaway, bc.vmConfig, &followupInterrupt)
1239+
1240+
blockPrefetchExecuteTimer.Update(time.Since(start))
1241+
if atomic.LoadUint32(&followupInterrupt) == 1 {
1242+
blockPrefetchInterruptMeter.Mark(1)
1243+
}
1244+
}(time.Now())
1245+
}
1246+
// Process block using the parent state as reference point
12461247
substart := time.Now()
1247-
receipts, logs, usedGas, err := bc.processor.Process(block, state, bc.vmConfig)
1248+
receipts, logs, usedGas, err := bc.processor.Process(block, statedb, bc.vmConfig)
12481249
if err != nil {
12491250
bc.reportBlock(block, receipts, err)
1251+
atomic.StoreUint32(&followupInterrupt, 1)
12501252
return it.index, events, coalescedLogs, err
12511253
}
12521254
// Update the metrics touched during block processing
1253-
accountReadTimer.Update(state.AccountReads) // Account reads are complete, we can mark them
1254-
storageReadTimer.Update(state.StorageReads) // Storage reads are complete, we can mark them
1255-
accountUpdateTimer.Update(state.AccountUpdates) // Account updates are complete, we can mark them
1256-
storageUpdateTimer.Update(state.StorageUpdates) // Storage updates are complete, we can mark them
1255+
accountReadTimer.Update(statedb.AccountReads) // Account reads are complete, we can mark them
1256+
storageReadTimer.Update(statedb.StorageReads) // Storage reads are complete, we can mark them
1257+
accountUpdateTimer.Update(statedb.AccountUpdates) // Account updates are complete, we can mark them
1258+
storageUpdateTimer.Update(statedb.StorageUpdates) // Storage updates are complete, we can mark them
12571259

1258-
triehash := state.AccountHashes + state.StorageHashes // Save to not double count in validation
1259-
trieproc := state.AccountReads + state.AccountUpdates
1260-
trieproc += state.StorageReads + state.StorageUpdates
1260+
triehash := statedb.AccountHashes + statedb.StorageHashes // Save to not double count in validation
1261+
trieproc := statedb.AccountReads + statedb.AccountUpdates
1262+
trieproc += statedb.StorageReads + statedb.StorageUpdates
12611263

12621264
blockExecutionTimer.Update(time.Since(substart) - trieproc - triehash)
12631265

12641266
// Validate the state using the default validator
12651267
substart = time.Now()
1266-
if err := bc.Validator().ValidateState(block, state, receipts, usedGas); err != nil {
1268+
if err := bc.validator.ValidateState(block, statedb, receipts, usedGas); err != nil {
12671269
bc.reportBlock(block, receipts, err)
1270+
atomic.StoreUint32(&followupInterrupt, 1)
12681271
return it.index, events, coalescedLogs, err
12691272
}
12701273
proctime := time.Since(start)
12711274

12721275
// Update the metrics touched during block validation
1273-
accountHashTimer.Update(state.AccountHashes) // Account hashes are complete, we can mark them
1274-
storageHashTimer.Update(state.StorageHashes) // Storage hashes are complete, we can mark them
1276+
accountHashTimer.Update(statedb.AccountHashes) // Account hashes are complete, we can mark them
1277+
storageHashTimer.Update(statedb.StorageHashes) // Storage hashes are complete, we can mark them
12751278

1276-
blockValidationTimer.Update(time.Since(substart) - (state.AccountHashes + state.StorageHashes - triehash))
1279+
blockValidationTimer.Update(time.Since(substart) - (statedb.AccountHashes + statedb.StorageHashes - triehash))
12771280

12781281
// Write the block to the chain and get the status.
12791282
substart = time.Now()
1280-
status, err := bc.writeBlockWithState(block, receipts, state)
1283+
status, err := bc.writeBlockWithState(block, receipts, statedb)
12811284
if err != nil {
1285+
atomic.StoreUint32(&followupInterrupt, 1)
12821286
return it.index, events, coalescedLogs, err
12831287
}
1288+
atomic.StoreUint32(&followupInterrupt, 1)
1289+
12841290
// Update the metrics touched during block commit
1285-
accountCommitTimer.Update(state.AccountCommits) // Account commits are complete, we can mark them
1286-
storageCommitTimer.Update(state.StorageCommits) // Storage commits are complete, we can mark them
1291+
accountCommitTimer.Update(statedb.AccountCommits) // Account commits are complete, we can mark them
1292+
storageCommitTimer.Update(statedb.StorageCommits) // Storage commits are complete, we can mark them
12871293

1288-
blockWriteTimer.Update(time.Since(substart) - state.AccountCommits - state.StorageCommits)
1294+
blockWriteTimer.Update(time.Since(substart) - statedb.AccountCommits - statedb.StorageCommits)
12891295
blockInsertTimer.UpdateSince(start)
12901296

12911297
switch status {

‎core/blockchain_insert.go‎

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,13 @@ func (st *insertStats) report(chain []*types.Block, index int, dirty common.Stor
8080

8181
// insertIterator is a helper to assist during chain import.
8282
type insertIterator struct {
83-
chain types.Blocks
84-
results <-chan error
85-
index int
86-
validator Validator
83+
chain types.Blocks // Chain of blocks being iterated over
84+
85+
results <-chan error // Verification result sink from the consensus engine
86+
errors []error // Header verification errors for the blocks
87+
88+
index int // Current offset of the iterator
89+
validator Validator // Validator to run if verification succeeds
8790
}
8891

8992
// newInsertIterator creates a new iterator based on the given blocks, which are
@@ -92,6 +95,7 @@ func newInsertIterator(chain types.Blocks, results <-chan error, validator Valid
9295
return &insertIterator{
9396
chain: chain,
9497
results: results,
98+
errors: make([]error, 0, len(chain)),
9599
index: -1,
96100
validator: validator,
97101
}
@@ -100,17 +104,44 @@ func newInsertIterator(chain types.Blocks, results <-chan error, validator Valid
100104
// next returns the next block in the iterator, along with any potential validation
101105
// error for that block. When the end is reached, it will return (nil, nil).
102106
func (it *insertIterator) next() (*types.Block, error) {
107+
// If we reached the end of the chain, abort
103108
if it.index+1 >= len(it.chain) {
104109
it.index = len(it.chain)
105110
return nil, nil
106111
}
112+
// Advance the iterator and wait for verification result if not yet done
107113
it.index++
108-
if err := <-it.results; err != nil {
109-
return it.chain[it.index], err
114+
if len(it.errors) <= it.index {
115+
it.errors = append(it.errors, <-it.results)
116+
}
117+
if it.errors[it.index] != nil {
118+
return it.chain[it.index], it.errors[it.index]
110119
}
120+
// Block header valid, run body validation and return
111121
return it.chain[it.index], it.validator.ValidateBody(it.chain[it.index])
112122
}
113123

124+
// peek returns the next block in the iterator, along with any potential validation
125+
// error for that block, but does **not** advance the iterator.
126+
//
127+
// Both header and body validation errors (nil too) is cached into the iterator
128+
// to avoid duplicating work on the following next() call.
129+
func (it *insertIterator) peek() (*types.Block, error) {
130+
// If we reached the end of the chain, abort
131+
if it.index+1 >= len(it.chain) {
132+
return nil, nil
133+
}
134+
// Wait for verification result if not yet done
135+
if len(it.errors) <= it.index+1 {
136+
it.errors = append(it.errors, <-it.results)
137+
}
138+
if it.errors[it.index+1] != nil {
139+
return it.chain[it.index+1], it.errors[it.index+1]
140+
}
141+
// Block header valid, ignore body validation since we don't have a parent anyway
142+
return it.chain[it.index+1], nil
143+
}
144+
114145
// previous returns the previous header that was being processed, or nil.
115146
func (it *insertIterator) previous() *types.Header {
116147
if it.index < 1 {

‎core/blockchain_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error {
144144
if err != nil {
145145
return err
146146
}
147-
receipts, _, usedGas, err := blockchain.Processor().Process(block, statedb, vm.Config{})
147+
receipts, _, usedGas, err := blockchain.processor.Process(block, statedb, vm.Config{})
148148
if err != nil {
149149
blockchain.reportBlock(block, receipts, err)
150150
return err

‎core/state_prefetcher.go‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
// Copyright 2019 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package core
18+
19+
import (
20+
"sync/atomic"
21+
22+
"github.com/ethereum/go-ethereum/common"
23+
"github.com/ethereum/go-ethereum/consensus"
24+
"github.com/ethereum/go-ethereum/core/state"
25+
"github.com/ethereum/go-ethereum/core/types"
26+
"github.com/ethereum/go-ethereum/core/vm"
27+
"github.com/ethereum/go-ethereum/params"
28+
)
29+
30+
// statePrefetcher is a basic Prefetcher, which blindly executes a block on top
31+
// of an arbitrary state with the goal of prefetching potentially useful state
32+
// data from disk before the main block processor start executing.
33+
type statePrefetcher struct {
34+
config *params.ChainConfig // Chain configuration options
35+
bc *BlockChain // Canonical block chain
36+
engine consensus.Engine // Consensus engine used for block rewards
37+
}
38+
39+
// newStatePrefetcher initialises a new statePrefetcher.
40+
func newStatePrefetcher(config *params.ChainConfig, bc *BlockChain, engine consensus.Engine) *statePrefetcher {
41+
return &statePrefetcher{
42+
config: config,
43+
bc: bc,
44+
engine: engine,
45+
}
46+
}
47+
48+
// Prefetch processes the state changes according to the Ethereum rules by running
49+
// the transaction messages using the statedb, but any changes are discarded. The
50+
// only goal is to pre-cache transaction signatures and state trie nodes.
51+
func (p *statePrefetcher) Prefetch(block *types.Block, statedb *state.StateDB, cfg vm.Config, interrupt *uint32) {
52+
var (
53+
header = block.Header()
54+
gaspool = new(GasPool).AddGas(block.GasLimit())
55+
)
56+
// Iterate over and process the individual transactions
57+
for i, tx := range block.Transactions() {
58+
// If block precaching was interrupted, abort
59+
if interrupt != nil && atomic.LoadUint32(interrupt) == 1 {
60+
return
61+
}
62+
// Block precaching permitted to continue, execute the transaction
63+
statedb.Prepare(tx.Hash(), block.Hash(), i)
64+
if err := precacheTransaction(p.config, p.bc, nil, gaspool, statedb, header, tx, cfg); err != nil {
65+
return // Ugh, something went horribly wrong, bail out
66+
}
67+
}
68+
}
69+
70+
// precacheTransaction attempts to apply a transaction to the given state database
71+
// and uses the input parameters for its environment. The goal is not to execute
72+
// the transaction successfully, rather to warm up touched data slots.
73+
func precacheTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gaspool *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, cfg vm.Config) error {
74+
// Convert the transaction into an executable message and pre-cache its sender
75+
msg, err := tx.AsMessage(types.MakeSigner(config, header.Number))
76+
if err != nil {
77+
return err
78+
}
79+
// Create the EVM and execute the transaction
80+
context := NewEVMContext(msg, header, bc, author)
81+
vm := vm.NewEVM(context, statedb, config, cfg)
82+
83+
_, _, _, err = ApplyMessage(vm, msg, gaspool)
84+
return err
85+
}

‎core/types.go‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import (
2525
// Validator is an interface which defines the standard for block validation. It
2626
// is only responsible for validating block contents, as the header validation is
2727
// done by the specific consensus engines.
28-
//
2928
type Validator interface {
3029
// ValidateBody validates the given block's content.
3130
ValidateBody(block *types.Block) error
@@ -35,12 +34,18 @@ type Validator interface {
3534
ValidateState(block *types.Block, state *state.StateDB, receipts types.Receipts, usedGas uint64) error
3635
}
3736

37+
// Prefetcher is an interface for pre-caching transaction signatures and state.
38+
type Prefetcher interface {
39+
// Prefetch processes the state changes according to the Ethereum rules by running
40+
// the transaction messages using the statedb, but any changes are discarded. The
41+
// only goal is to pre-cache transaction signatures and state trie nodes.
42+
Prefetch(block *types.Block, statedb *state.StateDB, cfg vm.Config, interrupt *uint32)
43+
}
44+
3845
// Processor is an interface for processing blocks using a given initial state.
39-
//
40-
// Process takes the block to be processed and the statedb upon which the
41-
// initial state is based. It should return the receipts generated, amount
42-
// of gas used in the process and return an error if any of the internal rules
43-
// failed.
4446
type Processor interface {
47+
// Process processes the state changes according to the Ethereum rules by running
48+
// the transaction messages using the statedb and applying any rewards to both
49+
// the processor (coinbase) and any included uncles.
4550
Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error)
4651
}

0 commit comments

Comments
 (0)