database.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. package state
  17. import (
  18. "errors"
  19. "fmt"
  20. "github.com/VictoriaMetrics/fastcache"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core/rawdb"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. "github.com/ethereum/go-ethereum/trie"
  26. lru "github.com/hashicorp/golang-lru"
  27. )
  28. const (
  29. // Number of codehash->size associations to keep.
  30. codeSizeCacheSize = 100000
  31. // Cache size granted for caching clean code.
  32. codeCacheSize = 64 * 1024 * 1024
  33. )
  34. // Database wraps access to tries and contract code.
  35. type Database interface {
  36. // OpenTrie opens the main account trie.
  37. OpenTrie(root common.Hash) (Trie, error)
  38. // OpenStorageTrie opens the storage trie of an account.
  39. OpenStorageTrie(addrHash, root common.Hash) (Trie, error)
  40. // CopyTrie returns an independent copy of the given trie.
  41. CopyTrie(Trie) Trie
  42. // ContractCode retrieves a particular contract's code.
  43. ContractCode(addrHash, codeHash common.Hash) ([]byte, error)
  44. // ContractCodeSize retrieves a particular contracts code's size.
  45. ContractCodeSize(addrHash, codeHash common.Hash) (int, error)
  46. // TrieDB retrieves the low level trie database used for data storage.
  47. TrieDB() *trie.Database
  48. }
  49. // Trie is a Ethereum Merkle Patricia trie.
  50. type Trie interface {
  51. // GetKey returns the sha3 preimage of a hashed key that was previously used
  52. // to store a value.
  53. //
  54. // TODO(fjl): remove this when StateTrie is removed
  55. GetKey([]byte) []byte
  56. // TryGet returns the value for key stored in the trie. The value bytes must
  57. // not be modified by the caller. If a node was not found in the database, a
  58. // trie.MissingNodeError is returned.
  59. TryGet(key []byte) ([]byte, error)
  60. // TryGetAccount abstract an account read from the trie.
  61. TryGetAccount(key []byte) (*types.StateAccount, error)
  62. // TryUpdate associates key with value in the trie. If value has length zero, any
  63. // existing value is deleted from the trie. The value bytes must not be modified
  64. // by the caller while they are stored in the trie. If a node was not found in the
  65. // database, a trie.MissingNodeError is returned.
  66. TryUpdate(key, value []byte) error
  67. // TryUpdateAccount abstract an account write to the trie.
  68. TryUpdateAccount(key []byte, account *types.StateAccount) error
  69. // TryDelete removes any existing value for key from the trie. If a node was not
  70. // found in the database, a trie.MissingNodeError is returned.
  71. TryDelete(key []byte) error
  72. // TryDeleteAccount abstracts an account deletion from the trie.
  73. TryDeleteAccount(key []byte) error
  74. // Hash returns the root hash of the trie. It does not write to the database and
  75. // can be used even if the trie doesn't have one.
  76. Hash() common.Hash
  77. // Commit collects all dirty nodes in the trie and replace them with the
  78. // corresponding node hash. All collected nodes(including dirty leaves if
  79. // collectLeaf is true) will be encapsulated into a nodeset for return.
  80. // The returned nodeset can be nil if the trie is clean(nothing to commit).
  81. // Once the trie is committed, it's not usable anymore. A new trie must
  82. // be created with new root and updated trie database for following usage
  83. Commit(collectLeaf bool) (common.Hash, *trie.NodeSet, error)
  84. // NodeIterator returns an iterator that returns nodes of the trie. Iteration
  85. // starts at the key after the given start key.
  86. NodeIterator(startKey []byte) trie.NodeIterator
  87. // Prove constructs a Merkle proof for key. The result contains all encoded nodes
  88. // on the path to the value at key. The value itself is also included in the last
  89. // node and can be retrieved by verifying the proof.
  90. //
  91. // If the trie does not contain a value for key, the returned proof contains all
  92. // nodes of the longest existing prefix of the key (at least the root), ending
  93. // with the node that proves the absence of the key.
  94. Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error
  95. }
  96. // NewDatabase creates a backing store for state. The returned database is safe for
  97. // concurrent use, but does not retain any recent trie nodes in memory. To keep some
  98. // historical state in memory, use the NewDatabaseWithConfig constructor.
  99. func NewDatabase(db ethdb.Database) Database {
  100. return NewDatabaseWithConfig(db, nil)
  101. }
  102. // NewDatabaseWithConfig creates a backing store for state. The returned database
  103. // is safe for concurrent use and retains a lot of collapsed RLP trie nodes in a
  104. // large memory cache.
  105. func NewDatabaseWithConfig(db ethdb.Database, config *trie.Config) Database {
  106. csc, _ := lru.New(codeSizeCacheSize)
  107. return &cachingDB{
  108. db: trie.NewDatabaseWithConfig(db, config),
  109. codeSizeCache: csc,
  110. codeCache: fastcache.New(codeCacheSize),
  111. }
  112. }
  113. type cachingDB struct {
  114. db *trie.Database
  115. codeSizeCache *lru.Cache
  116. codeCache *fastcache.Cache
  117. }
  118. // OpenTrie opens the main account trie at a specific root hash.
  119. func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
  120. tr, err := trie.NewStateTrie(common.Hash{}, root, db.db)
  121. if err != nil {
  122. return nil, err
  123. }
  124. return tr, nil
  125. }
  126. // OpenStorageTrie opens the storage trie of an account.
  127. func (db *cachingDB) OpenStorageTrie(addrHash, root common.Hash) (Trie, error) {
  128. tr, err := trie.NewStateTrie(addrHash, root, db.db)
  129. if err != nil {
  130. return nil, err
  131. }
  132. return tr, nil
  133. }
  134. // CopyTrie returns an independent copy of the given trie.
  135. func (db *cachingDB) CopyTrie(t Trie) Trie {
  136. switch t := t.(type) {
  137. case *trie.StateTrie:
  138. return t.Copy()
  139. default:
  140. panic(fmt.Errorf("unknown trie type %T", t))
  141. }
  142. }
  143. // ContractCode retrieves a particular contract's code.
  144. func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
  145. if code := db.codeCache.Get(nil, codeHash.Bytes()); len(code) > 0 {
  146. return code, nil
  147. }
  148. code := rawdb.ReadCode(db.db.DiskDB(), codeHash)
  149. if len(code) > 0 {
  150. db.codeCache.Set(codeHash.Bytes(), code)
  151. db.codeSizeCache.Add(codeHash, len(code))
  152. return code, nil
  153. }
  154. return nil, errors.New("not found")
  155. }
  156. // ContractCodeWithPrefix retrieves a particular contract's code. If the
  157. // code can't be found in the cache, then check the existence with **new**
  158. // db scheme.
  159. func (db *cachingDB) ContractCodeWithPrefix(addrHash, codeHash common.Hash) ([]byte, error) {
  160. if code := db.codeCache.Get(nil, codeHash.Bytes()); len(code) > 0 {
  161. return code, nil
  162. }
  163. code := rawdb.ReadCodeWithPrefix(db.db.DiskDB(), codeHash)
  164. if len(code) > 0 {
  165. db.codeCache.Set(codeHash.Bytes(), code)
  166. db.codeSizeCache.Add(codeHash, len(code))
  167. return code, nil
  168. }
  169. return nil, errors.New("not found")
  170. }
  171. // ContractCodeSize retrieves a particular contracts code's size.
  172. func (db *cachingDB) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
  173. if cached, ok := db.codeSizeCache.Get(codeHash); ok {
  174. return cached.(int), nil
  175. }
  176. code, err := db.ContractCode(addrHash, codeHash)
  177. return len(code), err
  178. }
  179. // TrieDB retrieves any intermediate trie-node caching layer.
  180. func (db *cachingDB) TrieDB() *trie.Database {
  181. return db.db
  182. }