From 7655b97198a620d7a02a2e03b7136287e2e05991 Mon Sep 17 00:00:00 2001 From: Krish Date: Fri, 22 Sep 2023 10:33:35 +0800 Subject: [PATCH 1/2] fix: use cache first when get StorageTrie/Trie --- core/state/database.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/core/state/database.go b/core/state/database.go index da26719816..b520fb3b80 100644 --- a/core/state/database.go +++ b/core/state/database.go @@ -238,6 +238,13 @@ func (db *cachingDB) purgeLoop() { // OpenTrie opens the main account trie at a specific root hash. func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) { + //try cache first + if db.accountTrieCache != nil { + if tr, ok := db.accountTrieCache.Get(root); ok { + return tr.(*trie.SecureTrie), nil + } + } + tr, err := trie.NewStateTrie(trie.StateTrieID(root), db.triedb) if err != nil { return nil, err @@ -247,6 +254,17 @@ func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) { // OpenStorageTrie opens the storage trie of an account. func (db *cachingDB) OpenStorageTrie(stateRoot common.Hash, addrHash, root common.Hash) (Trie, error) { + // try cache first + if db.storageTrieCache != nil { + if tries, exist := db.storageTrieCache.Get(addrHash); exist { + for _, triePair := range tries { + if triePair != nil && triePair.root == root { + return triePair.trie.(*trie.SecureTrie).Copy(), nil + } + } + } + } + tr, err := trie.NewStateTrie(trie.StorageTrieID(stateRoot, addrHash, root), db.triedb) if err != nil { return nil, err From ea76cd9ae0b1341f3fb9381e9b6e38431c6e2f3d Mon Sep 17 00:00:00 2001 From: Krish Date: Fri, 5 Jan 2024 15:53:13 +0800 Subject: [PATCH 2/2] update: use Copy() & update LRU cache --- core/state/database.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/state/database.go b/core/state/database.go index b520fb3b80..e65bcbdd44 100644 --- a/core/state/database.go +++ b/core/state/database.go @@ -241,7 +241,7 @@ func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) { //try cache first if db.accountTrieCache != nil { if tr, ok := db.accountTrieCache.Get(root); ok { - return tr.(*trie.SecureTrie), nil + return tr.(Trie).(*trie.SecureTrie).Copy(), nil } } @@ -249,6 +249,7 @@ func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) { if err != nil { return nil, err } + db.CacheAccount(root, tr) return tr, nil } @@ -269,6 +270,7 @@ func (db *cachingDB) OpenStorageTrie(stateRoot common.Hash, addrHash, root commo if err != nil { return nil, err } + db.CacheStorage(addrHash, root, tr) return tr, nil }