database.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. // Copyright 2018 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 trie
  17. import (
  18. "fmt"
  19. "io"
  20. "sync"
  21. "time"
  22. "github.com/allegro/bigcache"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/metrics"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. )
  29. var (
  30. memcacheCleanHitMeter = metrics.NewRegisteredMeter("trie/memcache/clean/hit", nil)
  31. memcacheCleanMissMeter = metrics.NewRegisteredMeter("trie/memcache/clean/miss", nil)
  32. memcacheCleanReadMeter = metrics.NewRegisteredMeter("trie/memcache/clean/read", nil)
  33. memcacheCleanWriteMeter = metrics.NewRegisteredMeter("trie/memcache/clean/write", nil)
  34. memcacheFlushTimeTimer = metrics.NewRegisteredResettingTimer("trie/memcache/flush/time", nil)
  35. memcacheFlushNodesMeter = metrics.NewRegisteredMeter("trie/memcache/flush/nodes", nil)
  36. memcacheFlushSizeMeter = metrics.NewRegisteredMeter("trie/memcache/flush/size", nil)
  37. memcacheGCTimeTimer = metrics.NewRegisteredResettingTimer("trie/memcache/gc/time", nil)
  38. memcacheGCNodesMeter = metrics.NewRegisteredMeter("trie/memcache/gc/nodes", nil)
  39. memcacheGCSizeMeter = metrics.NewRegisteredMeter("trie/memcache/gc/size", nil)
  40. memcacheCommitTimeTimer = metrics.NewRegisteredResettingTimer("trie/memcache/commit/time", nil)
  41. memcacheCommitNodesMeter = metrics.NewRegisteredMeter("trie/memcache/commit/nodes", nil)
  42. memcacheCommitSizeMeter = metrics.NewRegisteredMeter("trie/memcache/commit/size", nil)
  43. )
  44. // secureKeyPrefix is the database key prefix used to store trie node preimages.
  45. var secureKeyPrefix = []byte("secure-key-")
  46. // secureKeyLength is the length of the above prefix + 32byte hash.
  47. const secureKeyLength = 11 + 32
  48. // Database is an intermediate write layer between the trie data structures and
  49. // the disk database. The aim is to accumulate trie writes in-memory and only
  50. // periodically flush a couple tries to disk, garbage collecting the remainder.
  51. type Database struct {
  52. diskdb ethdb.KeyValueStore // Persistent storage for matured trie nodes
  53. cleans *bigcache.BigCache // GC friendly memory cache of clean node RLPs
  54. dirties map[common.Hash]*cachedNode // Data and references relationships of dirty nodes
  55. oldest common.Hash // Oldest tracked node, flush-list head
  56. newest common.Hash // Newest tracked node, flush-list tail
  57. preimages map[common.Hash][]byte // Preimages of nodes from the secure trie
  58. seckeybuf [secureKeyLength]byte // Ephemeral buffer for calculating preimage keys
  59. gctime time.Duration // Time spent on garbage collection since last commit
  60. gcnodes uint64 // Nodes garbage collected since last commit
  61. gcsize common.StorageSize // Data storage garbage collected since last commit
  62. flushtime time.Duration // Time spent on data flushing since last commit
  63. flushnodes uint64 // Nodes flushed since last commit
  64. flushsize common.StorageSize // Data storage flushed since last commit
  65. dirtiesSize common.StorageSize // Storage size of the dirty node cache (exc. flushlist)
  66. preimagesSize common.StorageSize // Storage size of the preimages cache
  67. lock sync.RWMutex
  68. }
  69. // rawNode is a simple binary blob used to differentiate between collapsed trie
  70. // nodes and already encoded RLP binary blobs (while at the same time store them
  71. // in the same cache fields).
  72. type rawNode []byte
  73. func (n rawNode) canUnload(uint16, uint16) bool { panic("this should never end up in a live trie") }
  74. func (n rawNode) cache() (hashNode, bool) { panic("this should never end up in a live trie") }
  75. func (n rawNode) fstring(ind string) string { panic("this should never end up in a live trie") }
  76. // rawFullNode represents only the useful data content of a full node, with the
  77. // caches and flags stripped out to minimize its data storage. This type honors
  78. // the same RLP encoding as the original parent.
  79. type rawFullNode [17]node
  80. func (n rawFullNode) canUnload(uint16, uint16) bool { panic("this should never end up in a live trie") }
  81. func (n rawFullNode) cache() (hashNode, bool) { panic("this should never end up in a live trie") }
  82. func (n rawFullNode) fstring(ind string) string { panic("this should never end up in a live trie") }
  83. func (n rawFullNode) EncodeRLP(w io.Writer) error {
  84. var nodes [17]node
  85. for i, child := range n {
  86. if child != nil {
  87. nodes[i] = child
  88. } else {
  89. nodes[i] = nilValueNode
  90. }
  91. }
  92. return rlp.Encode(w, nodes)
  93. }
  94. // rawShortNode represents only the useful data content of a short node, with the
  95. // caches and flags stripped out to minimize its data storage. This type honors
  96. // the same RLP encoding as the original parent.
  97. type rawShortNode struct {
  98. Key []byte
  99. Val node
  100. }
  101. func (n rawShortNode) canUnload(uint16, uint16) bool { panic("this should never end up in a live trie") }
  102. func (n rawShortNode) cache() (hashNode, bool) { panic("this should never end up in a live trie") }
  103. func (n rawShortNode) fstring(ind string) string { panic("this should never end up in a live trie") }
  104. // cachedNode is all the information we know about a single cached node in the
  105. // memory database write layer.
  106. type cachedNode struct {
  107. node node // Cached collapsed trie node, or raw rlp data
  108. size uint16 // Byte size of the useful cached data
  109. parents uint32 // Number of live nodes referencing this one
  110. children map[common.Hash]uint16 // External children referenced by this node
  111. flushPrev common.Hash // Previous node in the flush-list
  112. flushNext common.Hash // Next node in the flush-list
  113. }
  114. // rlp returns the raw rlp encoded blob of the cached node, either directly from
  115. // the cache, or by regenerating it from the collapsed node.
  116. func (n *cachedNode) rlp() []byte {
  117. if node, ok := n.node.(rawNode); ok {
  118. return node
  119. }
  120. blob, err := rlp.EncodeToBytes(n.node)
  121. if err != nil {
  122. panic(err)
  123. }
  124. return blob
  125. }
  126. // obj returns the decoded and expanded trie node, either directly from the cache,
  127. // or by regenerating it from the rlp encoded blob.
  128. func (n *cachedNode) obj(hash common.Hash, cachegen uint16) node {
  129. if node, ok := n.node.(rawNode); ok {
  130. return mustDecodeNode(hash[:], node, cachegen)
  131. }
  132. return expandNode(hash[:], n.node, cachegen)
  133. }
  134. // childs returns all the tracked children of this node, both the implicit ones
  135. // from inside the node as well as the explicit ones from outside the node.
  136. func (n *cachedNode) childs() []common.Hash {
  137. children := make([]common.Hash, 0, 16)
  138. for child := range n.children {
  139. children = append(children, child)
  140. }
  141. if _, ok := n.node.(rawNode); !ok {
  142. gatherChildren(n.node, &children)
  143. }
  144. return children
  145. }
  146. // gatherChildren traverses the node hierarchy of a collapsed storage node and
  147. // retrieves all the hashnode children.
  148. func gatherChildren(n node, children *[]common.Hash) {
  149. switch n := n.(type) {
  150. case *rawShortNode:
  151. gatherChildren(n.Val, children)
  152. case rawFullNode:
  153. for i := 0; i < 16; i++ {
  154. gatherChildren(n[i], children)
  155. }
  156. case hashNode:
  157. *children = append(*children, common.BytesToHash(n))
  158. case valueNode, nil:
  159. default:
  160. panic(fmt.Sprintf("unknown node type: %T", n))
  161. }
  162. }
  163. // simplifyNode traverses the hierarchy of an expanded memory node and discards
  164. // all the internal caches, returning a node that only contains the raw data.
  165. func simplifyNode(n node) node {
  166. switch n := n.(type) {
  167. case *shortNode:
  168. // Short nodes discard the flags and cascade
  169. return &rawShortNode{Key: n.Key, Val: simplifyNode(n.Val)}
  170. case *fullNode:
  171. // Full nodes discard the flags and cascade
  172. node := rawFullNode(n.Children)
  173. for i := 0; i < len(node); i++ {
  174. if node[i] != nil {
  175. node[i] = simplifyNode(node[i])
  176. }
  177. }
  178. return node
  179. case valueNode, hashNode, rawNode:
  180. return n
  181. default:
  182. panic(fmt.Sprintf("unknown node type: %T", n))
  183. }
  184. }
  185. // expandNode traverses the node hierarchy of a collapsed storage node and converts
  186. // all fields and keys into expanded memory form.
  187. func expandNode(hash hashNode, n node, cachegen uint16) node {
  188. switch n := n.(type) {
  189. case *rawShortNode:
  190. // Short nodes need key and child expansion
  191. return &shortNode{
  192. Key: compactToHex(n.Key),
  193. Val: expandNode(nil, n.Val, cachegen),
  194. flags: nodeFlag{
  195. hash: hash,
  196. gen: cachegen,
  197. },
  198. }
  199. case rawFullNode:
  200. // Full nodes need child expansion
  201. node := &fullNode{
  202. flags: nodeFlag{
  203. hash: hash,
  204. gen: cachegen,
  205. },
  206. }
  207. for i := 0; i < len(node.Children); i++ {
  208. if n[i] != nil {
  209. node.Children[i] = expandNode(nil, n[i], cachegen)
  210. }
  211. }
  212. return node
  213. case valueNode, hashNode:
  214. return n
  215. default:
  216. panic(fmt.Sprintf("unknown node type: %T", n))
  217. }
  218. }
  219. // NewDatabase creates a new trie database to store ephemeral trie content before
  220. // its written out to disk or garbage collected. No read cache is created, so all
  221. // data retrievals will hit the underlying disk database.
  222. func NewDatabase(diskdb ethdb.KeyValueStore) *Database {
  223. return NewDatabaseWithCache(diskdb, 0)
  224. }
  225. // NewDatabaseWithCache creates a new trie database to store ephemeral trie content
  226. // before its written out to disk or garbage collected. It also acts as a read cache
  227. // for nodes loaded from disk.
  228. func NewDatabaseWithCache(diskdb ethdb.KeyValueStore, cache int) *Database {
  229. var cleans *bigcache.BigCache
  230. if cache > 0 {
  231. cleans, _ = bigcache.NewBigCache(bigcache.Config{
  232. Shards: 1024,
  233. LifeWindow: time.Hour,
  234. MaxEntriesInWindow: cache * 1024,
  235. MaxEntrySize: 512,
  236. HardMaxCacheSize: cache,
  237. })
  238. }
  239. return &Database{
  240. diskdb: diskdb,
  241. cleans: cleans,
  242. dirties: map[common.Hash]*cachedNode{{}: {}},
  243. preimages: make(map[common.Hash][]byte),
  244. }
  245. }
  246. // DiskDB retrieves the persistent storage backing the trie database.
  247. func (db *Database) DiskDB() ethdb.Reader {
  248. return db.diskdb
  249. }
  250. // InsertBlob writes a new reference tracked blob to the memory database if it's
  251. // yet unknown. This method should only be used for non-trie nodes that require
  252. // reference counting, since trie nodes are garbage collected directly through
  253. // their embedded children.
  254. func (db *Database) InsertBlob(hash common.Hash, blob []byte) {
  255. db.lock.Lock()
  256. defer db.lock.Unlock()
  257. db.insert(hash, blob, rawNode(blob))
  258. }
  259. // insert inserts a collapsed trie node into the memory database. This method is
  260. // a more generic version of InsertBlob, supporting both raw blob insertions as
  261. // well ex trie node insertions. The blob must always be specified to allow proper
  262. // size tracking.
  263. func (db *Database) insert(hash common.Hash, blob []byte, node node) {
  264. // If the node's already cached, skip
  265. if _, ok := db.dirties[hash]; ok {
  266. return
  267. }
  268. // Create the cached entry for this node
  269. entry := &cachedNode{
  270. node: simplifyNode(node),
  271. size: uint16(len(blob)),
  272. flushPrev: db.newest,
  273. }
  274. for _, child := range entry.childs() {
  275. if c := db.dirties[child]; c != nil {
  276. c.parents++
  277. }
  278. }
  279. db.dirties[hash] = entry
  280. // Update the flush-list endpoints
  281. if db.oldest == (common.Hash{}) {
  282. db.oldest, db.newest = hash, hash
  283. } else {
  284. db.dirties[db.newest].flushNext, db.newest = hash, hash
  285. }
  286. db.dirtiesSize += common.StorageSize(common.HashLength + entry.size)
  287. }
  288. // insertPreimage writes a new trie node pre-image to the memory database if it's
  289. // yet unknown. The method will make a copy of the slice.
  290. //
  291. // Note, this method assumes that the database's lock is held!
  292. func (db *Database) insertPreimage(hash common.Hash, preimage []byte) {
  293. if _, ok := db.preimages[hash]; ok {
  294. return
  295. }
  296. db.preimages[hash] = common.CopyBytes(preimage)
  297. db.preimagesSize += common.StorageSize(common.HashLength + len(preimage))
  298. }
  299. // node retrieves a cached trie node from memory, or returns nil if none can be
  300. // found in the memory cache.
  301. func (db *Database) node(hash common.Hash, cachegen uint16) node {
  302. // Retrieve the node from the clean cache if available
  303. if db.cleans != nil {
  304. if enc, err := db.cleans.Get(string(hash[:])); err == nil && enc != nil {
  305. memcacheCleanHitMeter.Mark(1)
  306. memcacheCleanReadMeter.Mark(int64(len(enc)))
  307. return mustDecodeNode(hash[:], enc, cachegen)
  308. }
  309. }
  310. // Retrieve the node from the dirty cache if available
  311. db.lock.RLock()
  312. dirty := db.dirties[hash]
  313. db.lock.RUnlock()
  314. if dirty != nil {
  315. return dirty.obj(hash, cachegen)
  316. }
  317. // Content unavailable in memory, attempt to retrieve from disk
  318. enc, err := db.diskdb.Get(hash[:])
  319. if err != nil || enc == nil {
  320. return nil
  321. }
  322. if db.cleans != nil {
  323. db.cleans.Set(string(hash[:]), enc)
  324. memcacheCleanMissMeter.Mark(1)
  325. memcacheCleanWriteMeter.Mark(int64(len(enc)))
  326. }
  327. return mustDecodeNode(hash[:], enc, cachegen)
  328. }
  329. // Node retrieves an encoded cached trie node from memory. If it cannot be found
  330. // cached, the method queries the persistent database for the content.
  331. func (db *Database) Node(hash common.Hash) ([]byte, error) {
  332. // Retrieve the node from the clean cache if available
  333. if db.cleans != nil {
  334. if enc, err := db.cleans.Get(string(hash[:])); err == nil && enc != nil {
  335. memcacheCleanHitMeter.Mark(1)
  336. memcacheCleanReadMeter.Mark(int64(len(enc)))
  337. return enc, nil
  338. }
  339. }
  340. // Retrieve the node from the dirty cache if available
  341. db.lock.RLock()
  342. dirty := db.dirties[hash]
  343. db.lock.RUnlock()
  344. if dirty != nil {
  345. return dirty.rlp(), nil
  346. }
  347. // Content unavailable in memory, attempt to retrieve from disk
  348. enc, err := db.diskdb.Get(hash[:])
  349. if err == nil && enc != nil {
  350. if db.cleans != nil {
  351. db.cleans.Set(string(hash[:]), enc)
  352. memcacheCleanMissMeter.Mark(1)
  353. memcacheCleanWriteMeter.Mark(int64(len(enc)))
  354. }
  355. }
  356. return enc, err
  357. }
  358. // preimage retrieves a cached trie node pre-image from memory. If it cannot be
  359. // found cached, the method queries the persistent database for the content.
  360. func (db *Database) preimage(hash common.Hash) ([]byte, error) {
  361. // Retrieve the node from cache if available
  362. db.lock.RLock()
  363. preimage := db.preimages[hash]
  364. db.lock.RUnlock()
  365. if preimage != nil {
  366. return preimage, nil
  367. }
  368. // Content unavailable in memory, attempt to retrieve from disk
  369. return db.diskdb.Get(db.secureKey(hash[:]))
  370. }
  371. // secureKey returns the database key for the preimage of key, as an ephemeral
  372. // buffer. The caller must not hold onto the return value because it will become
  373. // invalid on the next call.
  374. func (db *Database) secureKey(key []byte) []byte {
  375. buf := append(db.seckeybuf[:0], secureKeyPrefix...)
  376. buf = append(buf, key...)
  377. return buf
  378. }
  379. // Nodes retrieves the hashes of all the nodes cached within the memory database.
  380. // This method is extremely expensive and should only be used to validate internal
  381. // states in test code.
  382. func (db *Database) Nodes() []common.Hash {
  383. db.lock.RLock()
  384. defer db.lock.RUnlock()
  385. var hashes = make([]common.Hash, 0, len(db.dirties))
  386. for hash := range db.dirties {
  387. if hash != (common.Hash{}) { // Special case for "root" references/nodes
  388. hashes = append(hashes, hash)
  389. }
  390. }
  391. return hashes
  392. }
  393. // Reference adds a new reference from a parent node to a child node.
  394. func (db *Database) Reference(child common.Hash, parent common.Hash) {
  395. db.lock.RLock()
  396. defer db.lock.RUnlock()
  397. db.reference(child, parent)
  398. }
  399. // reference is the private locked version of Reference.
  400. func (db *Database) reference(child common.Hash, parent common.Hash) {
  401. // If the node does not exist, it's a node pulled from disk, skip
  402. node, ok := db.dirties[child]
  403. if !ok {
  404. return
  405. }
  406. // If the reference already exists, only duplicate for roots
  407. if db.dirties[parent].children == nil {
  408. db.dirties[parent].children = make(map[common.Hash]uint16)
  409. } else if _, ok = db.dirties[parent].children[child]; ok && parent != (common.Hash{}) {
  410. return
  411. }
  412. node.parents++
  413. db.dirties[parent].children[child]++
  414. }
  415. // Dereference removes an existing reference from a root node.
  416. func (db *Database) Dereference(root common.Hash) {
  417. // Sanity check to ensure that the meta-root is not removed
  418. if root == (common.Hash{}) {
  419. log.Error("Attempted to dereference the trie cache meta root")
  420. return
  421. }
  422. db.lock.Lock()
  423. defer db.lock.Unlock()
  424. nodes, storage, start := len(db.dirties), db.dirtiesSize, time.Now()
  425. db.dereference(root, common.Hash{})
  426. db.gcnodes += uint64(nodes - len(db.dirties))
  427. db.gcsize += storage - db.dirtiesSize
  428. db.gctime += time.Since(start)
  429. memcacheGCTimeTimer.Update(time.Since(start))
  430. memcacheGCSizeMeter.Mark(int64(storage - db.dirtiesSize))
  431. memcacheGCNodesMeter.Mark(int64(nodes - len(db.dirties)))
  432. log.Debug("Dereferenced trie from memory database", "nodes", nodes-len(db.dirties), "size", storage-db.dirtiesSize, "time", time.Since(start),
  433. "gcnodes", db.gcnodes, "gcsize", db.gcsize, "gctime", db.gctime, "livenodes", len(db.dirties), "livesize", db.dirtiesSize)
  434. }
  435. // dereference is the private locked version of Dereference.
  436. func (db *Database) dereference(child common.Hash, parent common.Hash) {
  437. // Dereference the parent-child
  438. node := db.dirties[parent]
  439. if node.children != nil && node.children[child] > 0 {
  440. node.children[child]--
  441. if node.children[child] == 0 {
  442. delete(node.children, child)
  443. }
  444. }
  445. // If the child does not exist, it's a previously committed node.
  446. node, ok := db.dirties[child]
  447. if !ok {
  448. return
  449. }
  450. // If there are no more references to the child, delete it and cascade
  451. if node.parents > 0 {
  452. // This is a special cornercase where a node loaded from disk (i.e. not in the
  453. // memcache any more) gets reinjected as a new node (short node split into full,
  454. // then reverted into short), causing a cached node to have no parents. That is
  455. // no problem in itself, but don't make maxint parents out of it.
  456. node.parents--
  457. }
  458. if node.parents == 0 {
  459. // Remove the node from the flush-list
  460. switch child {
  461. case db.oldest:
  462. db.oldest = node.flushNext
  463. db.dirties[node.flushNext].flushPrev = common.Hash{}
  464. case db.newest:
  465. db.newest = node.flushPrev
  466. db.dirties[node.flushPrev].flushNext = common.Hash{}
  467. default:
  468. db.dirties[node.flushPrev].flushNext = node.flushNext
  469. db.dirties[node.flushNext].flushPrev = node.flushPrev
  470. }
  471. // Dereference all children and delete the node
  472. for _, hash := range node.childs() {
  473. db.dereference(hash, child)
  474. }
  475. delete(db.dirties, child)
  476. db.dirtiesSize -= common.StorageSize(common.HashLength + int(node.size))
  477. }
  478. }
  479. // Cap iteratively flushes old but still referenced trie nodes until the total
  480. // memory usage goes below the given threshold.
  481. func (db *Database) Cap(limit common.StorageSize) error {
  482. // Create a database batch to flush persistent data out. It is important that
  483. // outside code doesn't see an inconsistent state (referenced data removed from
  484. // memory cache during commit but not yet in persistent storage). This is ensured
  485. // by only uncaching existing data when the database write finalizes.
  486. db.lock.RLock()
  487. nodes, storage, start := len(db.dirties), db.dirtiesSize, time.Now()
  488. batch := db.diskdb.NewBatch()
  489. // db.dirtiesSize only contains the useful data in the cache, but when reporting
  490. // the total memory consumption, the maintenance metadata is also needed to be
  491. // counted. For every useful node, we track 2 extra hashes as the flushlist.
  492. size := db.dirtiesSize + common.StorageSize((len(db.dirties)-1)*2*common.HashLength)
  493. // If the preimage cache got large enough, push to disk. If it's still small
  494. // leave for later to deduplicate writes.
  495. flushPreimages := db.preimagesSize > 4*1024*1024
  496. if flushPreimages {
  497. for hash, preimage := range db.preimages {
  498. if err := batch.Put(db.secureKey(hash[:]), preimage); err != nil {
  499. log.Error("Failed to commit preimage from trie database", "err", err)
  500. db.lock.RUnlock()
  501. return err
  502. }
  503. if batch.ValueSize() > ethdb.IdealBatchSize {
  504. if err := batch.Write(); err != nil {
  505. db.lock.RUnlock()
  506. return err
  507. }
  508. batch.Reset()
  509. }
  510. }
  511. }
  512. // Keep committing nodes from the flush-list until we're below allowance
  513. oldest := db.oldest
  514. for size > limit && oldest != (common.Hash{}) {
  515. // Fetch the oldest referenced node and push into the batch
  516. node := db.dirties[oldest]
  517. if err := batch.Put(oldest[:], node.rlp()); err != nil {
  518. db.lock.RUnlock()
  519. return err
  520. }
  521. // If we exceeded the ideal batch size, commit and reset
  522. if batch.ValueSize() >= ethdb.IdealBatchSize {
  523. if err := batch.Write(); err != nil {
  524. log.Error("Failed to write flush list to disk", "err", err)
  525. db.lock.RUnlock()
  526. return err
  527. }
  528. batch.Reset()
  529. }
  530. // Iterate to the next flush item, or abort if the size cap was achieved. Size
  531. // is the total size, including both the useful cached data (hash -> blob), as
  532. // well as the flushlist metadata (2*hash). When flushing items from the cache,
  533. // we need to reduce both.
  534. size -= common.StorageSize(3*common.HashLength + int(node.size))
  535. oldest = node.flushNext
  536. }
  537. // Flush out any remainder data from the last batch
  538. if err := batch.Write(); err != nil {
  539. log.Error("Failed to write flush list to disk", "err", err)
  540. db.lock.RUnlock()
  541. return err
  542. }
  543. db.lock.RUnlock()
  544. // Write successful, clear out the flushed data
  545. db.lock.Lock()
  546. defer db.lock.Unlock()
  547. if flushPreimages {
  548. db.preimages = make(map[common.Hash][]byte)
  549. db.preimagesSize = 0
  550. }
  551. for db.oldest != oldest {
  552. node := db.dirties[db.oldest]
  553. delete(db.dirties, db.oldest)
  554. db.oldest = node.flushNext
  555. db.dirtiesSize -= common.StorageSize(common.HashLength + int(node.size))
  556. }
  557. if db.oldest != (common.Hash{}) {
  558. db.dirties[db.oldest].flushPrev = common.Hash{}
  559. }
  560. db.flushnodes += uint64(nodes - len(db.dirties))
  561. db.flushsize += storage - db.dirtiesSize
  562. db.flushtime += time.Since(start)
  563. memcacheFlushTimeTimer.Update(time.Since(start))
  564. memcacheFlushSizeMeter.Mark(int64(storage - db.dirtiesSize))
  565. memcacheFlushNodesMeter.Mark(int64(nodes - len(db.dirties)))
  566. log.Debug("Persisted nodes from memory database", "nodes", nodes-len(db.dirties), "size", storage-db.dirtiesSize, "time", time.Since(start),
  567. "flushnodes", db.flushnodes, "flushsize", db.flushsize, "flushtime", db.flushtime, "livenodes", len(db.dirties), "livesize", db.dirtiesSize)
  568. return nil
  569. }
  570. // Commit iterates over all the children of a particular node, writes them out
  571. // to disk, forcefully tearing down all references in both directions.
  572. //
  573. // As a side effect, all pre-images accumulated up to this point are also written.
  574. func (db *Database) Commit(node common.Hash, report bool) error {
  575. // Create a database batch to flush persistent data out. It is important that
  576. // outside code doesn't see an inconsistent state (referenced data removed from
  577. // memory cache during commit but not yet in persistent storage). This is ensured
  578. // by only uncaching existing data when the database write finalizes.
  579. db.lock.RLock()
  580. start := time.Now()
  581. batch := db.diskdb.NewBatch()
  582. // Move all of the accumulated preimages into a write batch
  583. for hash, preimage := range db.preimages {
  584. if err := batch.Put(db.secureKey(hash[:]), preimage); err != nil {
  585. log.Error("Failed to commit preimage from trie database", "err", err)
  586. db.lock.RUnlock()
  587. return err
  588. }
  589. if batch.ValueSize() > ethdb.IdealBatchSize {
  590. if err := batch.Write(); err != nil {
  591. db.lock.RUnlock()
  592. return err
  593. }
  594. batch.Reset()
  595. }
  596. }
  597. // Move the trie itself into the batch, flushing if enough data is accumulated
  598. nodes, storage := len(db.dirties), db.dirtiesSize
  599. if err := db.commit(node, batch); err != nil {
  600. log.Error("Failed to commit trie from trie database", "err", err)
  601. db.lock.RUnlock()
  602. return err
  603. }
  604. // Write batch ready, unlock for readers during persistence
  605. if err := batch.Write(); err != nil {
  606. log.Error("Failed to write trie to disk", "err", err)
  607. db.lock.RUnlock()
  608. return err
  609. }
  610. db.lock.RUnlock()
  611. // Write successful, clear out the flushed data
  612. db.lock.Lock()
  613. defer db.lock.Unlock()
  614. db.preimages = make(map[common.Hash][]byte)
  615. db.preimagesSize = 0
  616. db.uncache(node)
  617. memcacheCommitTimeTimer.Update(time.Since(start))
  618. memcacheCommitSizeMeter.Mark(int64(storage - db.dirtiesSize))
  619. memcacheCommitNodesMeter.Mark(int64(nodes - len(db.dirties)))
  620. logger := log.Info
  621. if !report {
  622. logger = log.Debug
  623. }
  624. logger("Persisted trie from memory database", "nodes", nodes-len(db.dirties)+int(db.flushnodes), "size", storage-db.dirtiesSize+db.flushsize, "time", time.Since(start)+db.flushtime,
  625. "gcnodes", db.gcnodes, "gcsize", db.gcsize, "gctime", db.gctime, "livenodes", len(db.dirties), "livesize", db.dirtiesSize)
  626. // Reset the garbage collection statistics
  627. db.gcnodes, db.gcsize, db.gctime = 0, 0, 0
  628. db.flushnodes, db.flushsize, db.flushtime = 0, 0, 0
  629. return nil
  630. }
  631. // commit is the private locked version of Commit.
  632. func (db *Database) commit(hash common.Hash, batch ethdb.Batch) error {
  633. // If the node does not exist, it's a previously committed node
  634. node, ok := db.dirties[hash]
  635. if !ok {
  636. return nil
  637. }
  638. for _, child := range node.childs() {
  639. if err := db.commit(child, batch); err != nil {
  640. return err
  641. }
  642. }
  643. if err := batch.Put(hash[:], node.rlp()); err != nil {
  644. return err
  645. }
  646. // If we've reached an optimal batch size, commit and start over
  647. if batch.ValueSize() >= ethdb.IdealBatchSize {
  648. if err := batch.Write(); err != nil {
  649. return err
  650. }
  651. batch.Reset()
  652. }
  653. return nil
  654. }
  655. // uncache is the post-processing step of a commit operation where the already
  656. // persisted trie is removed from the cache. The reason behind the two-phase
  657. // commit is to ensure consistent data availability while moving from memory
  658. // to disk.
  659. func (db *Database) uncache(hash common.Hash) {
  660. // If the node does not exist, we're done on this path
  661. node, ok := db.dirties[hash]
  662. if !ok {
  663. return
  664. }
  665. // Node still exists, remove it from the flush-list
  666. switch hash {
  667. case db.oldest:
  668. db.oldest = node.flushNext
  669. db.dirties[node.flushNext].flushPrev = common.Hash{}
  670. case db.newest:
  671. db.newest = node.flushPrev
  672. db.dirties[node.flushPrev].flushNext = common.Hash{}
  673. default:
  674. db.dirties[node.flushPrev].flushNext = node.flushNext
  675. db.dirties[node.flushNext].flushPrev = node.flushPrev
  676. }
  677. // Uncache the node's subtries and remove the node itself too
  678. for _, child := range node.childs() {
  679. db.uncache(child)
  680. }
  681. delete(db.dirties, hash)
  682. db.dirtiesSize -= common.StorageSize(common.HashLength + int(node.size))
  683. }
  684. // Size returns the current storage size of the memory cache in front of the
  685. // persistent database layer.
  686. func (db *Database) Size() (common.StorageSize, common.StorageSize) {
  687. db.lock.RLock()
  688. defer db.lock.RUnlock()
  689. // db.dirtiesSize only contains the useful data in the cache, but when reporting
  690. // the total memory consumption, the maintenance metadata is also needed to be
  691. // counted. For every useful node, we track 2 extra hashes as the flushlist.
  692. var flushlistSize = common.StorageSize((len(db.dirties) - 1) * 2 * common.HashLength)
  693. return db.dirtiesSize + flushlistSize, db.preimagesSize
  694. }
  695. // verifyIntegrity is a debug method to iterate over the entire trie stored in
  696. // memory and check whether every node is reachable from the meta root. The goal
  697. // is to find any errors that might cause memory leaks and or trie nodes to go
  698. // missing.
  699. //
  700. // This method is extremely CPU and memory intensive, only use when must.
  701. func (db *Database) verifyIntegrity() {
  702. // Iterate over all the cached nodes and accumulate them into a set
  703. reachable := map[common.Hash]struct{}{{}: {}}
  704. for child := range db.dirties[common.Hash{}].children {
  705. db.accumulate(child, reachable)
  706. }
  707. // Find any unreachable but cached nodes
  708. var unreachable []string
  709. for hash, node := range db.dirties {
  710. if _, ok := reachable[hash]; !ok {
  711. unreachable = append(unreachable, fmt.Sprintf("%x: {Node: %v, Parents: %d, Prev: %x, Next: %x}",
  712. hash, node.node, node.parents, node.flushPrev, node.flushNext))
  713. }
  714. }
  715. if len(unreachable) != 0 {
  716. panic(fmt.Sprintf("trie cache memory leak: %v", unreachable))
  717. }
  718. }
  719. // accumulate iterates over the trie defined by hash and accumulates all the
  720. // cached children found in memory.
  721. func (db *Database) accumulate(hash common.Hash, reachable map[common.Hash]struct{}) {
  722. // Mark the node reachable if present in the memory cache
  723. node, ok := db.dirties[hash]
  724. if !ok {
  725. return
  726. }
  727. reachable[hash] = struct{}{}
  728. // Iterate over all the children and accumulate them too
  729. for _, child := range node.childs() {
  730. db.accumulate(child, reachable)
  731. }
  732. }