Skip to content

Commit 1e1865b

Browse files
holimankaralabe
authored andcommitted
core: implement background trie prefetcher
Squashed from the following commits: core/state: lazily init snapshot storage map core/state: fix flawed meter on storage reads core/state: make statedb/stateobjects reuse a hasher core/blockchain, core/state: implement new trie prefetcher core: make trie prefetcher deliver tries to statedb core/state: refactor trie_prefetcher, export storage tries blockchain: re-enable the next-block-prefetcher state: remove panics in trie prefetcher core/state/trie_prefetcher: address some review concerns sq
1 parent 93a89b2 commit 1e1865b

7 files changed

Lines changed: 395 additions & 34 deletions

File tree

‎core/blockchain.go‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -201,11 +201,12 @@ type BlockChain struct {
201201
running int32 // 0 if chain is running, 1 when stopped
202202
procInterrupt int32 // interrupt signaler for block processing
203203

204-
engine consensus.Engine
205-
validator Validator // Block and state validator interface
206-
prefetcher Prefetcher // Block state prefetcher interface
207-
processor Processor // Block transaction processor interface
208-
vmConfig vm.Config
204+
engine consensus.Engine
205+
validator Validator // Block and state validator interface
206+
triePrefetcher *state.TriePrefetcher // Trie prefetcher interface
207+
prefetcher Prefetcher
208+
processor Processor // Block transaction processor interface
209+
vmConfig vm.Config
209210

210211
shouldPreserve func(*types.Block) bool // Function used to determine whether should preserve the given block.
211212
terminateInsert func(common.Hash, uint64) bool // Testing hook used to terminate ancient receipt chain insertion.
@@ -249,6 +250,15 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
249250
}
250251
bc.validator = NewBlockValidator(chainConfig, bc, engine)
251252
bc.prefetcher = newStatePrefetcher(chainConfig, bc, engine)
253+
tp := state.NewTriePrefetcher(bc.stateCache)
254+
255+
bc.wg.Add(1)
256+
go func() {
257+
tp.Loop()
258+
bc.wg.Done()
259+
}()
260+
bc.triePrefetcher = tp
261+
252262
bc.processor = NewStateProcessor(chainConfig, bc, engine)
253263

254264
var err error
@@ -991,6 +1001,9 @@ func (bc *BlockChain) Stop() {
9911001
bc.scope.Close()
9921002
close(bc.quit)
9931003
bc.StopInsert()
1004+
if bc.triePrefetcher != nil {
1005+
bc.triePrefetcher.Close()
1006+
}
9941007
bc.wg.Wait()
9951008

9961009
// Ensure that the entirety of the state snapshot is journalled to disk.
@@ -1857,6 +1870,7 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, er
18571870
parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1)
18581871
}
18591872
statedb, err := state.New(parent.Root, bc.stateCache, bc.snaps)
1873+
statedb.UsePrefetcher(bc.triePrefetcher)
18601874
if err != nil {
18611875
return it.index, err
18621876
}
@@ -1891,8 +1905,7 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, er
18911905
storageUpdateTimer.Update(statedb.StorageUpdates) // Storage updates are complete, we can mark them
18921906
snapshotAccountReadTimer.Update(statedb.SnapshotAccountReads) // Account reads are complete, we can mark them
18931907
snapshotStorageReadTimer.Update(statedb.SnapshotStorageReads) // Storage reads are complete, we can mark them
1894-
1895-
triehash := statedb.AccountHashes + statedb.StorageHashes // Save to not double count in validation
1908+
triehash := statedb.AccountHashes + statedb.StorageHashes // Save to not double count in validation
18961909
trieproc := statedb.SnapshotAccountReads + statedb.AccountReads + statedb.AccountUpdates
18971910
trieproc += statedb.SnapshotStorageReads + statedb.StorageReads + statedb.StorageUpdates
18981911

‎core/state/database.go‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,12 +129,20 @@ type cachingDB struct {
129129

130130
// OpenTrie opens the main account trie at a specific root hash.
131131
func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
132-
return trie.NewSecure(root, db.db)
132+
tr, err := trie.NewSecure(root, db.db)
133+
if err != nil {
134+
return nil, err
135+
}
136+
return tr, nil
133137
}
134138

135139
// OpenStorageTrie opens the storage trie of an account.
136140
func (db *cachingDB) OpenStorageTrie(addrHash, root common.Hash) (Trie, error) {
137-
return trie.NewSecure(root, db.db)
141+
tr, err := trie.NewSecure(root, db.db)
142+
if err != nil {
143+
return nil, err
144+
}
145+
return tr, nil
138146
}
139147

140148
// CopyTrie returns an independent copy of the given trie.

‎core/state/state_object.go‎

Lines changed: 52 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -157,11 +157,20 @@ func (s *stateObject) touch() {
157157

158158
func (s *stateObject) getTrie(db Database) Trie {
159159
if s.trie == nil {
160-
var err error
161-
s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root)
162-
if err != nil {
163-
s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{})
164-
s.setError(fmt.Errorf("can't create storage trie: %v", err))
160+
// Try fetching from prefetcher first
161+
// We don't prefetch empty tries
162+
if s.data.Root != emptyRoot && s.db.prefetcher != nil {
163+
// When the miner is creating the pending state, there is no
164+
// prefetcher
165+
s.trie = s.db.prefetcher.GetTrie(s.data.Root)
166+
}
167+
if s.trie == nil {
168+
var err error
169+
s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root)
170+
if err != nil {
171+
s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{})
172+
s.setError(fmt.Errorf("can't create storage trie: %v", err))
173+
}
165174
}
166175
}
167176
return s.trie
@@ -197,12 +206,24 @@ func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Has
197206
}
198207
// If no live objects are available, attempt to use snapshots
199208
var (
200-
enc []byte
201-
err error
209+
enc []byte
210+
err error
211+
meter *time.Duration
202212
)
213+
readStart := time.Now()
214+
if metrics.EnabledExpensive {
215+
// If the snap is 'under construction', the first lookup may fail. If that
216+
// happens, we don't want to double-count the time elapsed. Thus this
217+
// dance with the metering.
218+
defer func() {
219+
if meter != nil {
220+
*meter += time.Since(readStart)
221+
}
222+
}()
223+
}
203224
if s.db.snap != nil {
204225
if metrics.EnabledExpensive {
205-
defer func(start time.Time) { s.db.SnapshotStorageReads += time.Since(start) }(time.Now())
226+
meter = &s.db.SnapshotStorageReads
206227
}
207228
// If the object was destructed in *this* block (and potentially resurrected),
208229
// the storage has been cleared out, and we should *not* consult the previous
@@ -217,8 +238,14 @@ func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Has
217238
}
218239
// If snapshot unavailable or reading from it failed, load from the database
219240
if s.db.snap == nil || err != nil {
241+
if meter != nil {
242+
// If we already spent time checking the snapshot, account for it
243+
// and reset the readStart
244+
*meter += time.Since(readStart)
245+
readStart = time.Now()
246+
}
220247
if metrics.EnabledExpensive {
221-
defer func(start time.Time) { s.db.StorageReads += time.Since(start) }(time.Now())
248+
meter = &s.db.StorageReads
222249
}
223250
if enc, err = s.getTrie(db).TryGet(key.Bytes()); err != nil {
224251
s.setError(err)
@@ -283,8 +310,13 @@ func (s *stateObject) setState(key, value common.Hash) {
283310
// finalise moves all dirty storage slots into the pending area to be hashed or
284311
// committed later. It is invoked at the end of every transaction.
285312
func (s *stateObject) finalise() {
313+
trieChanges := make([]common.Hash, 0, len(s.dirtyStorage))
286314
for key, value := range s.dirtyStorage {
287315
s.pendingStorage[key] = value
316+
trieChanges = append(trieChanges, key)
317+
}
318+
if len(trieChanges) > 0 && s.db.prefetcher != nil && s.data.Root != emptyRoot {
319+
s.db.prefetcher.PrefetchStorage(s.data.Root, trieChanges)
288320
}
289321
if len(s.dirtyStorage) > 0 {
290322
s.dirtyStorage = make(Storage)
@@ -303,18 +335,11 @@ func (s *stateObject) updateTrie(db Database) Trie {
303335
if metrics.EnabledExpensive {
304336
defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now())
305337
}
306-
// Retrieve the snapshot storage map for the object
338+
// The snapshot storage map for the object
307339
var storage map[common.Hash][]byte
308-
if s.db.snap != nil {
309-
// Retrieve the old storage map, if available, create a new one otherwise
310-
storage = s.db.snapStorage[s.addrHash]
311-
if storage == nil {
312-
storage = make(map[common.Hash][]byte)
313-
s.db.snapStorage[s.addrHash] = storage
314-
}
315-
}
316340
// Insert all the pending updates into the trie
317341
tr := s.getTrie(db)
342+
hasher := s.db.hasher
318343
for key, value := range s.pendingStorage {
319344
// Skip noop changes, persist actual changes
320345
if value == s.originStorage[key] {
@@ -331,8 +356,15 @@ func (s *stateObject) updateTrie(db Database) Trie {
331356
s.setError(tr.TryUpdate(key[:], v))
332357
}
333358
// If state snapshotting is active, cache the data til commit
334-
if storage != nil {
335-
storage[crypto.Keccak256Hash(key[:])] = v // v will be nil if value is 0x00
359+
if s.db.snap != nil {
360+
if storage == nil {
361+
// Retrieve the old storage map, if available, create a new one otherwise
362+
if storage = s.db.snapStorage[s.addrHash]; storage == nil {
363+
storage = make(map[common.Hash][]byte)
364+
s.db.snapStorage[s.addrHash] = storage
365+
}
366+
}
367+
storage[crypto.HashData(hasher, key[:])] = v // v will be nil if value is 0x00
336368
}
337369
}
338370
if len(s.pendingStorage) > 0 {

‎core/state/statedb.go‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,11 @@ func (n *proofList) Delete(key []byte) error {
6262
// * Contracts
6363
// * Accounts
6464
type StateDB struct {
65-
db Database
66-
trie Trie
65+
db Database
66+
prefetcher *TriePrefetcher
67+
originalRoot common.Hash // The pre-state root, before any changes were made
68+
trie Trie
69+
hasher crypto.KeccakState
6770

6871
snaps *snapshot.Tree
6972
snap snapshot.Snapshot
@@ -125,6 +128,7 @@ func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error)
125128
sdb := &StateDB{
126129
db: db,
127130
trie: tr,
131+
originalRoot: root,
128132
snaps: snaps,
129133
stateObjects: make(map[common.Address]*stateObject),
130134
stateObjectsPending: make(map[common.Address]struct{}),
@@ -133,6 +137,7 @@ func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error)
133137
preimages: make(map[common.Hash][]byte),
134138
journal: newJournal(),
135139
accessList: newAccessList(),
140+
hasher: crypto.NewKeccakState(),
136141
}
137142
if sdb.snaps != nil {
138143
if sdb.snap = sdb.snaps.Snapshot(root); sdb.snap != nil {
@@ -144,6 +149,13 @@ func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error)
144149
return sdb, nil
145150
}
146151

152+
func (s *StateDB) UsePrefetcher(prefetcher *TriePrefetcher) {
153+
if prefetcher != nil {
154+
s.prefetcher = prefetcher
155+
s.prefetcher.Resume(s.originalRoot)
156+
}
157+
}
158+
147159
// setError remembers the first non-nil error it is called with.
148160
func (s *StateDB) setError(err error) {
149161
if s.dbErr == nil {
@@ -532,7 +544,7 @@ func (s *StateDB) getDeletedStateObject(addr common.Address) *stateObject {
532544
defer func(start time.Time) { s.SnapshotAccountReads += time.Since(start) }(time.Now())
533545
}
534546
var acc *snapshot.Account
535-
if acc, err = s.snap.Account(crypto.Keccak256Hash(addr.Bytes())); err == nil {
547+
if acc, err = s.snap.Account(crypto.HashData(s.hasher, addr.Bytes())); err == nil {
536548
if acc == nil {
537549
return nil
538550
}
@@ -675,6 +687,7 @@ func (s *StateDB) Copy() *StateDB {
675687
logSize: s.logSize,
676688
preimages: make(map[common.Hash][]byte, len(s.preimages)),
677689
journal: newJournal(),
690+
hasher: crypto.NewKeccakState(),
678691
}
679692
// Copy the dirty states, logs, and preimages
680693
for addr := range s.journal.dirties {
@@ -760,6 +773,7 @@ func (s *StateDB) GetRefund() uint64 {
760773
// the journal as well as the refunds. Finalise, however, will not push any updates
761774
// into the tries just yet. Only IntermediateRoot or Commit will do that.
762775
func (s *StateDB) Finalise(deleteEmptyObjects bool) {
776+
var addressesToPrefetch []common.Address
763777
for addr := range s.journal.dirties {
764778
obj, exist := s.stateObjects[addr]
765779
if !exist {
@@ -788,7 +802,17 @@ func (s *StateDB) Finalise(deleteEmptyObjects bool) {
788802
}
789803
s.stateObjectsPending[addr] = struct{}{}
790804
s.stateObjectsDirty[addr] = struct{}{}
805+
// At this point, also ship the address off to the precacher. The precacher
806+
// will start loading tries, and when the change is eventually committed,
807+
// the commit-phase will be a lot faster
808+
if s.prefetcher != nil {
809+
addressesToPrefetch = append(addressesToPrefetch, addr)
810+
}
811+
}
812+
if s.prefetcher != nil {
813+
s.prefetcher.PrefetchAddresses(addressesToPrefetch)
791814
}
815+
792816
// Invalidate journal because reverting across transactions is not allowed.
793817
s.clearJournalAndRefund()
794818
}
@@ -800,6 +824,21 @@ func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
800824
// Finalise all the dirty storage states and write them into the tries
801825
s.Finalise(deleteEmptyObjects)
802826

827+
// Now we're about to start to write changes to the trie. The trie is so
828+
// far _untouched_. We can check with the prefetcher, if it can give us
829+
// a trie which has the same root, but also has some content loaded into it.
830+
// If so, use that one instead.
831+
if s.prefetcher != nil {
832+
s.prefetcher.Pause()
833+
// We only want to do this _once_, if someone calls IntermediateRoot again,
834+
// we shouldn't fetch the trie again
835+
if s.originalRoot != (common.Hash{}) {
836+
if trie := s.prefetcher.GetTrie(s.originalRoot); trie != nil {
837+
s.trie = trie
838+
}
839+
s.originalRoot = common.Hash{}
840+
}
841+
}
803842
for addr := range s.stateObjectsPending {
804843
obj := s.stateObjects[addr]
805844
if obj.deleted {

0 commit comments

Comments
 (0)