github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/core/state/database.go (about) 1 // Copyright 2017 The Spectrum Authors 2 // This file is part of the Spectrum library. 3 // 4 // The Spectrum 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 Spectrum 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 Spectrum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package state 18 19 import ( 20 "fmt" 21 "sync" 22 23 "github.com/SmartMeshFoundation/Spectrum/common" 24 "github.com/SmartMeshFoundation/Spectrum/ethdb" 25 "github.com/SmartMeshFoundation/Spectrum/trie" 26 lru "github.com/hashicorp/golang-lru" 27 ) 28 29 // Trie cache generation limit after which to evic trie nodes from memory. 30 var MaxTrieCacheGen = uint16(120) 31 32 const ( 33 // Number of past tries to keep. This value is chosen such that 34 // reasonable chain reorg depths will hit an existing trie. 35 maxPastTries = 12 36 37 // Number of codehash->size associations to keep. 38 codeSizeCacheSize = 100000 39 ) 40 41 // Database wraps access to tries and contract code. 42 type Database interface { 43 // Accessing tries: 44 // OpenTrie opens the main account trie. 45 // OpenStorageTrie opens the storage trie of an account. 46 OpenTrie(root common.Hash) (Trie, error) 47 OpenStorageTrie(addrHash, root common.Hash) (Trie, error) 48 // Accessing contract code: 49 ContractCode(addrHash, codeHash common.Hash) ([]byte, error) 50 ContractCodeSize(addrHash, codeHash common.Hash) (int, error) 51 // CopyTrie returns an independent copy of the given trie. 52 CopyTrie(Trie) Trie 53 } 54 55 // Trie is a Ethereum Merkle Trie. 56 type Trie interface { 57 TryGet(key []byte) ([]byte, error) 58 TryUpdate(key, value []byte) error 59 TryDelete(key []byte) error 60 CommitTo(trie.DatabaseWriter) (common.Hash, error) 61 Hash() common.Hash 62 NodeIterator(startKey []byte) trie.NodeIterator 63 GetKey([]byte) []byte // TODO(fjl): remove this when SecureTrie is removed 64 } 65 66 // NewDatabase creates a backing store for state. The returned database is safe for 67 // concurrent use and retains cached trie nodes in memory. 68 func NewDatabase(db ethdb.Database) Database { 69 csc, _ := lru.New(codeSizeCacheSize) 70 return &cachingDB{db: db, codeSizeCache: csc} 71 } 72 73 type cachingDB struct { 74 db ethdb.Database 75 mu sync.Mutex 76 pastTries []*trie.SecureTrie 77 codeSizeCache *lru.Cache 78 } 79 80 func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) { 81 db.mu.Lock() 82 defer db.mu.Unlock() 83 84 for i := len(db.pastTries) - 1; i >= 0; i-- { 85 if db.pastTries[i].Hash() == root { 86 return cachedTrie{db.pastTries[i].Copy(), db}, nil 87 } 88 } 89 tr, err := trie.NewSecure(root, db.db, MaxTrieCacheGen) 90 if err != nil { 91 return nil, err 92 } 93 return cachedTrie{tr, db}, nil 94 } 95 96 func (db *cachingDB) pushTrie(t *trie.SecureTrie) { 97 db.mu.Lock() 98 defer db.mu.Unlock() 99 100 if len(db.pastTries) >= maxPastTries { 101 copy(db.pastTries, db.pastTries[1:]) 102 db.pastTries[len(db.pastTries)-1] = t 103 } else { 104 db.pastTries = append(db.pastTries, t) 105 } 106 } 107 108 func (db *cachingDB) OpenStorageTrie(addrHash, root common.Hash) (Trie, error) { 109 return trie.NewSecure(root, db.db, 0) 110 } 111 112 func (db *cachingDB) CopyTrie(t Trie) Trie { 113 switch t := t.(type) { 114 case cachedTrie: 115 return cachedTrie{t.SecureTrie.Copy(), db} 116 case *trie.SecureTrie: 117 return t.Copy() 118 default: 119 panic(fmt.Errorf("unknown trie type %T", t)) 120 } 121 } 122 123 func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) { 124 code, err := db.db.Get(codeHash[:]) 125 if err == nil { 126 db.codeSizeCache.Add(codeHash, len(code)) 127 } 128 return code, err 129 } 130 131 func (db *cachingDB) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) { 132 if cached, ok := db.codeSizeCache.Get(codeHash); ok { 133 return cached.(int), nil 134 } 135 code, err := db.ContractCode(addrHash, codeHash) 136 if err == nil { 137 db.codeSizeCache.Add(codeHash, len(code)) 138 } 139 return len(code), err 140 } 141 142 // cachedTrie inserts its trie into a cachingDB on commit. 143 type cachedTrie struct { 144 *trie.SecureTrie 145 db *cachingDB 146 } 147 148 func (m cachedTrie) CommitTo(dbw trie.DatabaseWriter) (common.Hash, error) { 149 root, err := m.SecureTrie.CommitTo(dbw) 150 if err == nil { 151 m.db.pushTrie(m.SecureTrie) 152 } 153 return root, err 154 }