database.go 9.5 KB

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