database.go 29 KB

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