database.go 29 KB

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