database.go 31 KB

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