database.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. "time"
  21. "github.com/VictoriaMetrics/fastcache"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/rawdb"
  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. // Number of state trie in cache
  32. accountTrieCacheSize = 32
  33. // Number of storage Trie in cache
  34. storageTrieCacheSize = 2000
  35. // Cache size granted for caching clean code.
  36. codeCacheSize = 64 * 1024 * 1024
  37. purgeInterval = 600
  38. maxAccountTrieSize = 1024 * 1024
  39. )
  40. // Database wraps access to tries and contract code.
  41. type Database interface {
  42. // OpenTrie opens the main account trie.
  43. OpenTrie(root common.Hash) (Trie, error)
  44. // OpenStorageTrie opens the storage trie of an account.
  45. OpenStorageTrie(addrHash, root common.Hash) (Trie, error)
  46. // CopyTrie returns an independent copy of the given trie.
  47. CopyTrie(Trie) Trie
  48. // ContractCode retrieves a particular contract's code.
  49. ContractCode(addrHash, codeHash common.Hash) ([]byte, error)
  50. // ContractCodeSize retrieves a particular contracts code's size.
  51. ContractCodeSize(addrHash, codeHash common.Hash) (int, error)
  52. // TrieDB retrieves the low level trie database used for data storage.
  53. TrieDB() *trie.Database
  54. // Cache the account trie tree
  55. CacheAccount(root common.Hash, t Trie)
  56. // Cache the storage trie tree
  57. CacheStorage(addrHash common.Hash, root common.Hash, t Trie)
  58. // Purge cache
  59. Purge()
  60. }
  61. // Trie is a Ethereum Merkle Patricia trie.
  62. type Trie interface {
  63. // GetKey returns the sha3 preimage of a hashed key that was previously used
  64. // to store a value.
  65. //
  66. // TODO(fjl): remove this when SecureTrie is removed
  67. GetKey([]byte) []byte
  68. // TryGet returns the value for key stored in the trie. The value bytes must
  69. // not be modified by the caller. If a node was not found in the database, a
  70. // trie.MissingNodeError is returned.
  71. TryGet(key []byte) ([]byte, error)
  72. // TryUpdate associates key with value in the trie. If value has length zero, any
  73. // existing value is deleted from the trie. The value bytes must not be modified
  74. // by the caller while they are stored in the trie. If a node was not found in the
  75. // database, a trie.MissingNodeError is returned.
  76. TryUpdate(key, value []byte) error
  77. // TryDelete removes any existing value for key from the trie. If a node was not
  78. // found in the database, a trie.MissingNodeError is returned.
  79. TryDelete(key []byte) error
  80. // Hash returns the root hash of the trie. It does not write to the database and
  81. // can be used even if the trie doesn't have one.
  82. Hash() common.Hash
  83. // Commit writes all nodes to the trie's memory database, tracking the internal
  84. // and external (for account tries) references.
  85. Commit(onleaf trie.LeafCallback) (common.Hash, error)
  86. // NodeIterator returns an iterator that returns nodes of the trie. Iteration
  87. // starts at the key after the given start key.
  88. NodeIterator(startKey []byte) trie.NodeIterator
  89. // Prove constructs a Merkle proof for key. The result contains all encoded nodes
  90. // on the path to the value at key. The value itself is also included in the last
  91. // node and can be retrieved by verifying the proof.
  92. //
  93. // If the trie does not contain a value for key, the returned proof contains all
  94. // nodes of the longest existing prefix of the key (at least the root), ending
  95. // with the node that proves the absence of the key.
  96. Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error
  97. }
  98. // NewDatabase creates a backing store for state. The returned database is safe for
  99. // concurrent use, but does not retain any recent trie nodes in memory. To keep some
  100. // historical state in memory, use the NewDatabaseWithConfig constructor.
  101. func NewDatabase(db ethdb.Database) Database {
  102. return NewDatabaseWithConfig(db, nil)
  103. }
  104. // NewDatabaseWithConfig creates a backing store for state. The returned database
  105. // is safe for concurrent use and retains a lot of collapsed RLP trie nodes in a
  106. // large memory cache.
  107. func NewDatabaseWithConfig(db ethdb.Database, config *trie.Config) Database {
  108. csc, _ := lru.New(codeSizeCacheSize)
  109. return &cachingDB{
  110. db: trie.NewDatabaseWithConfig(db, config),
  111. codeSizeCache: csc,
  112. codeCache: fastcache.New(codeCacheSize),
  113. }
  114. }
  115. func NewDatabaseWithConfigAndCache(db ethdb.Database, config *trie.Config) Database {
  116. csc, _ := lru.New(codeSizeCacheSize)
  117. atc, _ := lru.New(accountTrieCacheSize)
  118. stc, _ := lru.New(storageTrieCacheSize)
  119. database := &cachingDB{
  120. db: trie.NewDatabaseWithConfig(db, config),
  121. codeSizeCache: csc,
  122. codeCache: fastcache.New(codeCacheSize),
  123. accountTrieCache: atc,
  124. storageTrieCache: stc,
  125. }
  126. go database.purgeLoop()
  127. return database
  128. }
  129. type cachingDB struct {
  130. db *trie.Database
  131. codeSizeCache *lru.Cache
  132. codeCache *fastcache.Cache
  133. accountTrieCache *lru.Cache
  134. storageTrieCache *lru.Cache
  135. }
  136. type triePair struct {
  137. root common.Hash
  138. trie Trie
  139. }
  140. func (db *cachingDB) purgeLoop() {
  141. for {
  142. time.Sleep(purgeInterval * time.Second)
  143. _, accounts, ok := db.accountTrieCache.GetOldest()
  144. if !ok {
  145. continue
  146. }
  147. tr := accounts.(*trie.SecureTrie).GetRawTrie()
  148. if tr.Size() > maxAccountTrieSize {
  149. db.Purge()
  150. }
  151. }
  152. }
  153. // OpenTrie opens the main account trie at a specific root hash.
  154. func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
  155. if db.accountTrieCache != nil {
  156. if tr, exist := db.accountTrieCache.Get(root); exist {
  157. return tr.(Trie).(*trie.SecureTrie).Copy(), nil
  158. }
  159. }
  160. tr, err := trie.NewSecure(root, db.db)
  161. if err != nil {
  162. return nil, err
  163. }
  164. return tr, nil
  165. }
  166. // OpenStorageTrie opens the storage trie of an account.
  167. func (db *cachingDB) OpenStorageTrie(addrHash, root common.Hash) (Trie, error) {
  168. if db.storageTrieCache != nil {
  169. if tries, exist := db.storageTrieCache.Get(addrHash); exist {
  170. triesPairs := tries.([3]*triePair)
  171. for _, triePair := range triesPairs {
  172. if triePair != nil && triePair.root == root {
  173. return triePair.trie.(*trie.SecureTrie).Copy(), nil
  174. }
  175. }
  176. }
  177. }
  178. tr, err := trie.NewSecure(root, db.db)
  179. if err != nil {
  180. return nil, err
  181. }
  182. return tr, nil
  183. }
  184. func (db *cachingDB) CacheAccount(root common.Hash, t Trie) {
  185. if db.accountTrieCache == nil {
  186. return
  187. }
  188. tr := t.(*trie.SecureTrie)
  189. db.accountTrieCache.Add(root, tr.ResetCopy())
  190. }
  191. func (db *cachingDB) CacheStorage(addrHash common.Hash, root common.Hash, t Trie) {
  192. if db.storageTrieCache == nil {
  193. return
  194. }
  195. tr := t.(*trie.SecureTrie)
  196. if tries, exist := db.storageTrieCache.Get(addrHash); exist {
  197. triesArray := tries.([3]*triePair)
  198. newTriesArray := [3]*triePair{
  199. {root: root, trie: tr.ResetCopy()},
  200. triesArray[0],
  201. triesArray[1],
  202. }
  203. db.storageTrieCache.Add(addrHash, newTriesArray)
  204. } else {
  205. triesArray := [3]*triePair{{root: root, trie: tr.ResetCopy()}, nil, nil}
  206. db.storageTrieCache.Add(addrHash, triesArray)
  207. }
  208. }
  209. func (db *cachingDB) Purge() {
  210. if db.storageTrieCache != nil {
  211. db.storageTrieCache.Purge()
  212. }
  213. if db.accountTrieCache != nil {
  214. db.accountTrieCache.Purge()
  215. }
  216. }
  217. // CopyTrie returns an independent copy of the given trie.
  218. func (db *cachingDB) CopyTrie(t Trie) Trie {
  219. switch t := t.(type) {
  220. case *trie.SecureTrie:
  221. return t.Copy()
  222. default:
  223. panic(fmt.Errorf("unknown trie type %T", t))
  224. }
  225. }
  226. // ContractCode retrieves a particular contract's code.
  227. func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
  228. if code := db.codeCache.Get(nil, codeHash.Bytes()); len(code) > 0 {
  229. return code, nil
  230. }
  231. code := rawdb.ReadCode(db.db.DiskDB(), codeHash)
  232. if len(code) > 0 {
  233. db.codeCache.Set(codeHash.Bytes(), code)
  234. db.codeSizeCache.Add(codeHash, len(code))
  235. return code, nil
  236. }
  237. return nil, errors.New("not found")
  238. }
  239. // ContractCodeWithPrefix retrieves a particular contract's code. If the
  240. // code can't be found in the cache, then check the existence with **new**
  241. // db scheme.
  242. func (db *cachingDB) ContractCodeWithPrefix(addrHash, codeHash common.Hash) ([]byte, error) {
  243. if code := db.codeCache.Get(nil, codeHash.Bytes()); len(code) > 0 {
  244. return code, nil
  245. }
  246. code := rawdb.ReadCodeWithPrefix(db.db.DiskDB(), codeHash)
  247. if len(code) > 0 {
  248. db.codeCache.Set(codeHash.Bytes(), code)
  249. db.codeSizeCache.Add(codeHash, len(code))
  250. return code, nil
  251. }
  252. return nil, errors.New("not found")
  253. }
  254. // ContractCodeSize retrieves a particular contracts code's size.
  255. func (db *cachingDB) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
  256. if cached, ok := db.codeSizeCache.Get(codeHash); ok {
  257. return cached.(int), nil
  258. }
  259. code, err := db.ContractCode(addrHash, codeHash)
  260. return len(code), err
  261. }
  262. // TrieDB retrieves any intermediate trie-node caching layer.
  263. func (db *cachingDB) TrieDB() *trie.Database {
  264. return db.db
  265. }