database.go 29 KB

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