github.com/theQRL/go-zond@v0.1.1/core/state/database.go (about) 1 // Copyright 2017 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 state 18 19 import ( 20 "errors" 21 "fmt" 22 23 "github.com/theQRL/go-zond/common" 24 "github.com/theQRL/go-zond/common/lru" 25 "github.com/theQRL/go-zond/core/rawdb" 26 "github.com/theQRL/go-zond/core/types" 27 "github.com/theQRL/go-zond/crypto" 28 "github.com/theQRL/go-zond/zonddb" 29 "github.com/theQRL/go-zond/trie" 30 "github.com/theQRL/go-zond/trie/trienode" 31 ) 32 33 const ( 34 // Number of codehash->size associations to keep. 35 codeSizeCacheSize = 100000 36 37 // Cache size granted for caching clean code. 38 codeCacheSize = 64 * 1024 * 1024 39 ) 40 41 // Database wraps access to tries and contract code. 42 type Database interface { 43 // OpenTrie opens the main account trie. 44 OpenTrie(root common.Hash) (Trie, error) 45 46 // OpenStorageTrie opens the storage trie of an account. 47 OpenStorageTrie(stateRoot common.Hash, address common.Address, root common.Hash) (Trie, error) 48 49 // CopyTrie returns an independent copy of the given trie. 50 CopyTrie(Trie) Trie 51 52 // ContractCode retrieves a particular contract's code. 53 ContractCode(addr common.Address, codeHash common.Hash) ([]byte, error) 54 55 // ContractCodeSize retrieves a particular contracts code's size. 56 ContractCodeSize(addr common.Address, codeHash common.Hash) (int, error) 57 58 // DiskDB returns the underlying key-value disk database. 59 DiskDB() zonddb.KeyValueStore 60 61 // TrieDB returns the underlying trie database for managing trie nodes. 62 TrieDB() *trie.Database 63 } 64 65 // Trie is a Ethereum Merkle Patricia trie. 66 type Trie interface { 67 // GetKey returns the sha3 preimage of a hashed key that was previously used 68 // to store a value. 69 // 70 // TODO(fjl): remove this when StateTrie is removed 71 GetKey([]byte) []byte 72 73 // GetStorage returns the value for key stored in the trie. The value bytes 74 // must not be modified by the caller. If a node was not found in the database, 75 // a trie.MissingNodeError is returned. 76 GetStorage(addr common.Address, key []byte) ([]byte, error) 77 78 // GetAccount abstracts an account read from the trie. It retrieves the 79 // account blob from the trie with provided account address and decodes it 80 // with associated decoding algorithm. If the specified account is not in 81 // the trie, nil will be returned. If the trie is corrupted(e.g. some nodes 82 // are missing or the account blob is incorrect for decoding), an error will 83 // be returned. 84 GetAccount(address common.Address) (*types.StateAccount, error) 85 86 // UpdateStorage associates key with value in the trie. If value has length zero, 87 // any existing value is deleted from the trie. The value bytes must not be modified 88 // by the caller while they are stored in the trie. If a node was not found in the 89 // database, a trie.MissingNodeError is returned. 90 UpdateStorage(addr common.Address, key, value []byte) error 91 92 // UpdateAccount abstracts an account write to the trie. It encodes the 93 // provided account object with associated algorithm and then updates it 94 // in the trie with provided address. 95 UpdateAccount(address common.Address, account *types.StateAccount) error 96 97 // UpdateContractCode abstracts code write to the trie. It is expected 98 // to be moved to the stateWriter interface when the latter is ready. 99 UpdateContractCode(address common.Address, codeHash common.Hash, code []byte) error 100 101 // DeleteStorage removes any existing value for key from the trie. If a node 102 // was not found in the database, a trie.MissingNodeError is returned. 103 DeleteStorage(addr common.Address, key []byte) error 104 105 // DeleteAccount abstracts an account deletion from the trie. 106 DeleteAccount(address common.Address) error 107 108 // Hash returns the root hash of the trie. It does not write to the database and 109 // can be used even if the trie doesn't have one. 110 Hash() common.Hash 111 112 // Commit collects all dirty nodes in the trie and replace them with the 113 // corresponding node hash. All collected nodes(including dirty leaves if 114 // collectLeaf is true) will be encapsulated into a nodeset for return. 115 // The returned nodeset can be nil if the trie is clean(nothing to commit). 116 // Once the trie is committed, it's not usable anymore. A new trie must 117 // be created with new root and updated trie database for following usage 118 Commit(collectLeaf bool) (common.Hash, *trienode.NodeSet, error) 119 120 // NodeIterator returns an iterator that returns nodes of the trie. Iteration 121 // starts at the key after the given start key. And error will be returned 122 // if fails to create node iterator. 123 NodeIterator(startKey []byte) (trie.NodeIterator, error) 124 125 // Prove constructs a Merkle proof for key. The result contains all encoded nodes 126 // on the path to the value at key. The value itself is also included in the last 127 // node and can be retrieved by verifying the proof. 128 // 129 // If the trie does not contain a value for key, the returned proof contains all 130 // nodes of the longest existing prefix of the key (at least the root), ending 131 // with the node that proves the absence of the key. 132 Prove(key []byte, proofDb zonddb.KeyValueWriter) error 133 } 134 135 // NewDatabase creates a backing store for state. The returned database is safe for 136 // concurrent use, but does not retain any recent trie nodes in memory. To keep some 137 // historical state in memory, use the NewDatabaseWithConfig constructor. 138 func NewDatabase(db zonddb.Database) Database { 139 return NewDatabaseWithConfig(db, nil) 140 } 141 142 // NewDatabaseWithConfig creates a backing store for state. The returned database 143 // is safe for concurrent use and retains a lot of collapsed RLP trie nodes in a 144 // large memory cache. 145 func NewDatabaseWithConfig(db zonddb.Database, config *trie.Config) Database { 146 return &cachingDB{ 147 disk: db, 148 codeSizeCache: lru.NewCache[common.Hash, int](codeSizeCacheSize), 149 codeCache: lru.NewSizeConstrainedCache[common.Hash, []byte](codeCacheSize), 150 triedb: trie.NewDatabase(db, config), 151 } 152 } 153 154 // NewDatabaseWithNodeDB creates a state database with an already initialized node database. 155 func NewDatabaseWithNodeDB(db zonddb.Database, triedb *trie.Database) Database { 156 return &cachingDB{ 157 disk: db, 158 codeSizeCache: lru.NewCache[common.Hash, int](codeSizeCacheSize), 159 codeCache: lru.NewSizeConstrainedCache[common.Hash, []byte](codeCacheSize), 160 triedb: triedb, 161 } 162 } 163 164 type cachingDB struct { 165 disk zonddb.KeyValueStore 166 codeSizeCache *lru.Cache[common.Hash, int] 167 codeCache *lru.SizeConstrainedCache[common.Hash, []byte] 168 triedb *trie.Database 169 } 170 171 // OpenTrie opens the main account trie at a specific root hash. 172 func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) { 173 tr, err := trie.NewStateTrie(trie.StateTrieID(root), db.triedb) 174 if err != nil { 175 return nil, err 176 } 177 return tr, nil 178 } 179 180 // OpenStorageTrie opens the storage trie of an account. 181 func (db *cachingDB) OpenStorageTrie(stateRoot common.Hash, address common.Address, root common.Hash) (Trie, error) { 182 tr, err := trie.NewStateTrie(trie.StorageTrieID(stateRoot, crypto.Keccak256Hash(address.Bytes()), root), db.triedb) 183 if err != nil { 184 return nil, err 185 } 186 return tr, nil 187 } 188 189 // CopyTrie returns an independent copy of the given trie. 190 func (db *cachingDB) CopyTrie(t Trie) Trie { 191 switch t := t.(type) { 192 case *trie.StateTrie: 193 return t.Copy() 194 default: 195 panic(fmt.Errorf("unknown trie type %T", t)) 196 } 197 } 198 199 // ContractCode retrieves a particular contract's code. 200 func (db *cachingDB) ContractCode(address common.Address, codeHash common.Hash) ([]byte, error) { 201 code, _ := db.codeCache.Get(codeHash) 202 if len(code) > 0 { 203 return code, nil 204 } 205 code = rawdb.ReadCode(db.disk, codeHash) 206 if len(code) > 0 { 207 db.codeCache.Add(codeHash, code) 208 db.codeSizeCache.Add(codeHash, len(code)) 209 return code, nil 210 } 211 return nil, errors.New("not found") 212 } 213 214 // ContractCodeWithPrefix retrieves a particular contract's code. If the 215 // code can't be found in the cache, then check the existence with **new** 216 // db scheme. 217 func (db *cachingDB) ContractCodeWithPrefix(address common.Address, codeHash common.Hash) ([]byte, error) { 218 code, _ := db.codeCache.Get(codeHash) 219 if len(code) > 0 { 220 return code, nil 221 } 222 code = rawdb.ReadCodeWithPrefix(db.disk, codeHash) 223 if len(code) > 0 { 224 db.codeCache.Add(codeHash, code) 225 db.codeSizeCache.Add(codeHash, len(code)) 226 return code, nil 227 } 228 return nil, errors.New("not found") 229 } 230 231 // ContractCodeSize retrieves a particular contracts code's size. 232 func (db *cachingDB) ContractCodeSize(addr common.Address, codeHash common.Hash) (int, error) { 233 if cached, ok := db.codeSizeCache.Get(codeHash); ok { 234 return cached, nil 235 } 236 code, err := db.ContractCode(addr, codeHash) 237 return len(code), err 238 } 239 240 // DiskDB returns the underlying key-value disk database. 241 func (db *cachingDB) DiskDB() zonddb.KeyValueStore { 242 return db.disk 243 } 244 245 // TrieDB retrieves any intermediate trie-node caching layer. 246 func (db *cachingDB) TrieDB() *trie.Database { 247 return db.triedb 248 }