database.go 30 KB

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