database.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. "fmt"
  19. "github.com/ethereum/go-ethereum/common"
  20. "github.com/ethereum/go-ethereum/ethdb"
  21. "github.com/ethereum/go-ethereum/trie"
  22. lru "github.com/hashicorp/golang-lru"
  23. )
  24. const (
  25. // Number of codehash->size associations to keep.
  26. codeSizeCacheSize = 100000
  27. )
  28. // Database wraps access to tries and contract code.
  29. type Database interface {
  30. // OpenTrie opens the main account trie.
  31. OpenTrie(root common.Hash) (Trie, error)
  32. // OpenStorageTrie opens the storage trie of an account.
  33. OpenStorageTrie(addrHash, root common.Hash) (Trie, error)
  34. // CopyTrie returns an independent copy of the given trie.
  35. CopyTrie(Trie) Trie
  36. // ContractCode retrieves a particular contract's code.
  37. ContractCode(addrHash, codeHash common.Hash) ([]byte, error)
  38. // ContractCodeSize retrieves a particular contracts code's size.
  39. ContractCodeSize(addrHash, codeHash common.Hash) (int, error)
  40. // TrieDB retrieves the low level trie database used for data storage.
  41. TrieDB() *trie.Database
  42. }
  43. // Trie is a Ethereum Merkle Patricia trie.
  44. type Trie interface {
  45. // GetKey returns the sha3 preimage of a hashed key that was previously used
  46. // to store a value.
  47. //
  48. // TODO(fjl): remove this when SecureTrie is removed
  49. GetKey([]byte) []byte
  50. // TryGet returns the value for key stored in the trie. The value bytes must
  51. // not be modified by the caller. If a node was not found in the database, a
  52. // trie.MissingNodeError is returned.
  53. TryGet(key []byte) ([]byte, error)
  54. // TryUpdate associates key with value in the trie. If value has length zero, any
  55. // existing value is deleted from the trie. The value bytes must not be modified
  56. // by the caller while they are stored in the trie. If a node was not found in the
  57. // database, a trie.MissingNodeError is returned.
  58. TryUpdate(key, value []byte) error
  59. // TryDelete removes any existing value for key from the trie. If a node was not
  60. // found in the database, a trie.MissingNodeError is returned.
  61. TryDelete(key []byte) error
  62. // Hash returns the root hash of the trie. It does not write to the database and
  63. // can be used even if the trie doesn't have one.
  64. Hash() common.Hash
  65. // Commit writes all nodes to the trie's memory database, tracking the internal
  66. // and external (for account tries) references.
  67. Commit(onleaf trie.LeafCallback) (common.Hash, error)
  68. // NodeIterator returns an iterator that returns nodes of the trie. Iteration
  69. // starts at the key after the given start key.
  70. NodeIterator(startKey []byte) trie.NodeIterator
  71. // Prove constructs a Merkle proof for key. The result contains all encoded nodes
  72. // on the path to the value at key. The value itself is also included in the last
  73. // node and can be retrieved by verifying the proof.
  74. //
  75. // If the trie does not contain a value for key, the returned proof contains all
  76. // nodes of the longest existing prefix of the key (at least the root), ending
  77. // with the node that proves the absence of the key.
  78. Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error
  79. }
  80. // NewDatabase creates a backing store for state. The returned database is safe for
  81. // concurrent use, but does not retain any recent trie nodes in memory. To keep some
  82. // historical state in memory, use the NewDatabaseWithCache constructor.
  83. func NewDatabase(db ethdb.Database) Database {
  84. return NewDatabaseWithCache(db, 0)
  85. }
  86. // NewDatabaseWithCache creates a backing store for state. The returned database
  87. // is safe for concurrent use and retains a lot of collapsed RLP trie nodes in a
  88. // large memory cache.
  89. func NewDatabaseWithCache(db ethdb.Database, cache int) Database {
  90. csc, _ := lru.New(codeSizeCacheSize)
  91. return &cachingDB{
  92. db: trie.NewDatabaseWithCache(db, cache),
  93. codeSizeCache: csc,
  94. }
  95. }
  96. type cachingDB struct {
  97. db *trie.Database
  98. codeSizeCache *lru.Cache
  99. }
  100. // OpenTrie opens the main account trie at a specific root hash.
  101. func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
  102. return trie.NewSecure(root, db.db)
  103. }
  104. // OpenStorageTrie opens the storage trie of an account.
  105. func (db *cachingDB) OpenStorageTrie(addrHash, root common.Hash) (Trie, error) {
  106. return trie.NewSecure(root, db.db)
  107. }
  108. // CopyTrie returns an independent copy of the given trie.
  109. func (db *cachingDB) CopyTrie(t Trie) Trie {
  110. switch t := t.(type) {
  111. case *trie.SecureTrie:
  112. return t.Copy()
  113. default:
  114. panic(fmt.Errorf("unknown trie type %T", t))
  115. }
  116. }
  117. // ContractCode retrieves a particular contract's code.
  118. func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
  119. code, err := db.db.Node(codeHash)
  120. if err == nil {
  121. db.codeSizeCache.Add(codeHash, len(code))
  122. }
  123. return code, err
  124. }
  125. // ContractCodeSize retrieves a particular contracts code's size.
  126. func (db *cachingDB) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
  127. if cached, ok := db.codeSizeCache.Get(codeHash); ok {
  128. return cached.(int), nil
  129. }
  130. code, err := db.ContractCode(addrHash, codeHash)
  131. return len(code), err
  132. }
  133. // TrieDB retrieves any intermediate trie-node caching layer.
  134. func (db *cachingDB) TrieDB() *trie.Database {
  135. return db.db
  136. }