database.go 31 KB

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