database.go 30 KB

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