database.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. "sync"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/ethdb"
  22. "github.com/ethereum/go-ethereum/trie"
  23. lru "github.com/hashicorp/golang-lru"
  24. )
  25. // Trie cache generation limit after which to evict trie nodes from memory.
  26. var MaxTrieCacheGen = uint16(120)
  27. const (
  28. // Number of past tries to keep. This value is chosen such that
  29. // reasonable chain reorg depths will hit an existing trie.
  30. maxPastTries = 12
  31. // Number of codehash->size associations to keep.
  32. codeSizeCacheSize = 100000
  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 Trie.
  50. type Trie interface {
  51. TryGet(key []byte) ([]byte, error)
  52. TryUpdate(key, value []byte) error
  53. TryDelete(key []byte) error
  54. Commit(onleaf trie.LeafCallback) (common.Hash, error)
  55. Hash() common.Hash
  56. NodeIterator(startKey []byte) trie.NodeIterator
  57. GetKey([]byte) []byte // TODO(fjl): remove this when SecureTrie is removed
  58. Prove(key []byte, fromLevel uint, proofDb ethdb.Writer) error
  59. }
  60. // NewDatabase creates a backing store for state. The returned database is safe for
  61. // concurrent use and retains a few recent expanded trie nodes in memory. To keep
  62. // more historical state in memory, use the NewDatabaseWithCache constructor.
  63. func NewDatabase(db ethdb.Database) Database {
  64. return NewDatabaseWithCache(db, 0)
  65. }
  66. // NewDatabase creates a backing store for state. The returned database is safe for
  67. // concurrent use and retains both a few recent expanded trie nodes in memory, as
  68. // well as a lot of collapsed RLP trie nodes in a large memory cache.
  69. func NewDatabaseWithCache(db ethdb.Database, cache int) Database {
  70. csc, _ := lru.New(codeSizeCacheSize)
  71. return &cachingDB{
  72. db: trie.NewDatabaseWithCache(db, cache),
  73. codeSizeCache: csc,
  74. }
  75. }
  76. type cachingDB struct {
  77. db *trie.Database
  78. mu sync.Mutex
  79. pastTries []*trie.SecureTrie
  80. codeSizeCache *lru.Cache
  81. }
  82. // OpenTrie opens the main account trie.
  83. func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
  84. db.mu.Lock()
  85. defer db.mu.Unlock()
  86. for i := len(db.pastTries) - 1; i >= 0; i-- {
  87. if db.pastTries[i].Hash() == root {
  88. return cachedTrie{db.pastTries[i].Copy(), db}, nil
  89. }
  90. }
  91. tr, err := trie.NewSecure(root, db.db, MaxTrieCacheGen)
  92. if err != nil {
  93. return nil, err
  94. }
  95. return cachedTrie{tr, db}, nil
  96. }
  97. func (db *cachingDB) pushTrie(t *trie.SecureTrie) {
  98. db.mu.Lock()
  99. defer db.mu.Unlock()
  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. // OpenStorageTrie opens the storage trie of an account.
  108. func (db *cachingDB) OpenStorageTrie(addrHash, root common.Hash) (Trie, error) {
  109. return trie.NewSecure(root, db.db, 0)
  110. }
  111. // CopyTrie returns an independent copy of the given trie.
  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. // ContractCode retrieves a particular contract's code.
  123. func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
  124. code, err := db.db.Node(codeHash)
  125. if err == nil {
  126. db.codeSizeCache.Add(codeHash, len(code))
  127. }
  128. return code, err
  129. }
  130. // ContractCodeSize retrieves a particular contracts code's size.
  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. return len(code), err
  137. }
  138. // TrieDB retrieves any intermediate trie-node caching layer.
  139. func (db *cachingDB) TrieDB() *trie.Database {
  140. return db.db
  141. }
  142. // cachedTrie inserts its trie into a cachingDB on commit.
  143. type cachedTrie struct {
  144. *trie.SecureTrie
  145. db *cachingDB
  146. }
  147. func (m cachedTrie) Commit(onleaf trie.LeafCallback) (common.Hash, error) {
  148. root, err := m.SecureTrie.Commit(onleaf)
  149. if err == nil {
  150. m.db.pushTrie(m.SecureTrie)
  151. }
  152. return root, err
  153. }
  154. func (m cachedTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.Writer) error {
  155. return m.SecureTrie.Prove(key, fromLevel, proofDb)
  156. }