database.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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.Putter) error
  59. }
  60. // NewDatabase creates a backing store for state. The returned database is safe for
  61. // concurrent use and retains cached trie nodes in memory. The pool is an optional
  62. // intermediate trie-node memory pool between the low level storage layer and the
  63. // high level trie abstraction.
  64. func NewDatabase(db ethdb.Database) Database {
  65. csc, _ := lru.New(codeSizeCacheSize)
  66. return &cachingDB{
  67. db: trie.NewDatabase(db),
  68. codeSizeCache: csc,
  69. }
  70. }
  71. type cachingDB struct {
  72. db *trie.Database
  73. mu sync.Mutex
  74. pastTries []*trie.SecureTrie
  75. codeSizeCache *lru.Cache
  76. }
  77. // OpenTrie opens the main account trie.
  78. func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
  79. db.mu.Lock()
  80. defer db.mu.Unlock()
  81. for i := len(db.pastTries) - 1; i >= 0; i-- {
  82. if db.pastTries[i].Hash() == root {
  83. return cachedTrie{db.pastTries[i].Copy(), db}, nil
  84. }
  85. }
  86. tr, err := trie.NewSecure(root, db.db, MaxTrieCacheGen)
  87. if err != nil {
  88. return nil, err
  89. }
  90. return cachedTrie{tr, db}, nil
  91. }
  92. func (db *cachingDB) pushTrie(t *trie.SecureTrie) {
  93. db.mu.Lock()
  94. defer db.mu.Unlock()
  95. if len(db.pastTries) >= maxPastTries {
  96. copy(db.pastTries, db.pastTries[1:])
  97. db.pastTries[len(db.pastTries)-1] = t
  98. } else {
  99. db.pastTries = append(db.pastTries, t)
  100. }
  101. }
  102. // OpenStorageTrie opens the storage trie of an account.
  103. func (db *cachingDB) OpenStorageTrie(addrHash, root common.Hash) (Trie, error) {
  104. return trie.NewSecure(root, db.db, 0)
  105. }
  106. // CopyTrie returns an independent copy of the given trie.
  107. func (db *cachingDB) CopyTrie(t Trie) Trie {
  108. switch t := t.(type) {
  109. case cachedTrie:
  110. return cachedTrie{t.SecureTrie.Copy(), db}
  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. }
  137. // cachedTrie inserts its trie into a cachingDB on commit.
  138. type cachedTrie struct {
  139. *trie.SecureTrie
  140. db *cachingDB
  141. }
  142. func (m cachedTrie) Commit(onleaf trie.LeafCallback) (common.Hash, error) {
  143. root, err := m.SecureTrie.Commit(onleaf)
  144. if err == nil {
  145. m.db.pushTrie(m.SecureTrie)
  146. }
  147. return root, err
  148. }
  149. func (m cachedTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error {
  150. return m.SecureTrie.Prove(key, fromLevel, proofDb)
  151. }