database.go 30 KB

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