database.go 7.5 KB

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