database.go 26 KB

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