database.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package trie
  17. import (
  18. "errors"
  19. "fmt"
  20. "io"
  21. "reflect"
  22. "sync"
  23. "time"
  24. "github.com/VictoriaMetrics/fastcache"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/ethdb"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/metrics"
  29. "github.com/ethereum/go-ethereum/rlp"
  30. )
  31. var (
  32. memcacheCleanHitMeter = metrics.NewRegisteredMeter("trie/memcache/clean/hit", nil)
  33. memcacheCleanMissMeter = metrics.NewRegisteredMeter("trie/memcache/clean/miss", nil)
  34. memcacheCleanReadMeter = metrics.NewRegisteredMeter("trie/memcache/clean/read", nil)
  35. memcacheCleanWriteMeter = metrics.NewRegisteredMeter("trie/memcache/clean/write", nil)
  36. memcacheDirtyHitMeter = metrics.NewRegisteredMeter("trie/memcache/dirty/hit", nil)
  37. memcacheDirtyMissMeter = metrics.NewRegisteredMeter("trie/memcache/dirty/miss", nil)
  38. memcacheDirtyReadMeter = metrics.NewRegisteredMeter("trie/memcache/dirty/read", nil)
  39. memcacheDirtyWriteMeter = metrics.NewRegisteredMeter("trie/memcache/dirty/write", nil)
  40. memcacheFlushTimeTimer = metrics.NewRegisteredResettingTimer("trie/memcache/flush/time", nil)
  41. memcacheFlushNodesMeter = metrics.NewRegisteredMeter("trie/memcache/flush/nodes", nil)
  42. memcacheFlushSizeMeter = metrics.NewRegisteredMeter("trie/memcache/flush/size", nil)
  43. memcacheGCTimeTimer = metrics.NewRegisteredResettingTimer("trie/memcache/gc/time", nil)
  44. memcacheGCNodesMeter = metrics.NewRegisteredMeter("trie/memcache/gc/nodes", nil)
  45. memcacheGCSizeMeter = metrics.NewRegisteredMeter("trie/memcache/gc/size", nil)
  46. memcacheCommitTimeTimer = metrics.NewRegisteredResettingTimer("trie/memcache/commit/time", nil)
  47. memcacheCommitNodesMeter = metrics.NewRegisteredMeter("trie/memcache/commit/nodes", nil)
  48. memcacheCommitSizeMeter = metrics.NewRegisteredMeter("trie/memcache/commit/size", nil)
  49. )
  50. // secureKeyPrefix is the database key prefix used to store trie node preimages.
  51. var secureKeyPrefix = []byte("secure-key-")
  52. // secureKeyPrefixLength is the length of the above prefix
  53. const secureKeyPrefixLength = 11
  54. // secureKeyLength is the length of the above prefix + 32byte hash.
  55. const secureKeyLength = secureKeyPrefixLength + 32
  56. // Database is an intermediate write layer between the trie data structures and
  57. // the disk database. The aim is to accumulate trie writes in-memory and only
  58. // periodically flush a couple tries to disk, garbage collecting the remainder.
  59. //
  60. // Note, the trie Database is **not** thread safe in its mutations, but it **is**
  61. // thread safe in providing individual, independent node access. The rationale
  62. // behind this split design is to provide read access to RPC handlers and sync
  63. // servers even while the trie is executing expensive garbage collection.
  64. type Database struct {
  65. diskdb ethdb.KeyValueStore // Persistent storage for matured trie nodes
  66. cleans *fastcache.Cache // GC friendly memory cache of clean node RLPs
  67. dirties map[common.Hash]*cachedNode // Data and references relationships of dirty nodes
  68. oldest common.Hash // Oldest tracked node, flush-list head
  69. newest common.Hash // Newest tracked node, flush-list tail
  70. preimages map[common.Hash][]byte // Preimages of nodes from the secure trie
  71. gctime time.Duration // Time spent on garbage collection since last commit
  72. gcnodes uint64 // Nodes garbage collected since last commit
  73. gcsize common.StorageSize // Data storage garbage collected since last commit
  74. flushtime time.Duration // Time spent on data flushing since last commit
  75. flushnodes uint64 // Nodes flushed since last commit
  76. flushsize common.StorageSize // Data storage flushed since last commit
  77. dirtiesSize common.StorageSize // Storage size of the dirty node cache (exc. metadata)
  78. childrenSize common.StorageSize // Storage size of the external children tracking
  79. preimagesSize common.StorageSize // Storage size of the preimages cache
  80. lock sync.RWMutex
  81. }
  82. // rawNode is a simple binary blob used to differentiate between collapsed trie
  83. // nodes and already encoded RLP binary blobs (while at the same time store them
  84. // in the same cache fields).
  85. type rawNode []byte
  86. func (n rawNode) cache() (hashNode, bool) { panic("this should never end up in a live trie") }
  87. func (n rawNode) fstring(ind string) string { panic("this should never end up in a live trie") }
  88. // rawFullNode represents only the useful data content of a full node, with the
  89. // caches and flags stripped out to minimize its data storage. This type honors
  90. // the same RLP encoding as the original parent.
  91. type rawFullNode [17]node
  92. func (n rawFullNode) cache() (hashNode, bool) { panic("this should never end up in a live trie") }
  93. func (n rawFullNode) fstring(ind string) string { panic("this should never end up in a live trie") }
  94. func (n rawFullNode) EncodeRLP(w io.Writer) error {
  95. var nodes [17]node
  96. for i, child := range n {
  97. if child != nil {
  98. nodes[i] = child
  99. } else {
  100. nodes[i] = nilValueNode
  101. }
  102. }
  103. return rlp.Encode(w, nodes)
  104. }
  105. // rawShortNode represents only the useful data content of a short node, with the
  106. // caches and flags stripped out to minimize its data storage. This type honors
  107. // the same RLP encoding as the original parent.
  108. type rawShortNode struct {
  109. Key []byte
  110. Val node
  111. }
  112. func (n rawShortNode) cache() (hashNode, bool) { panic("this should never end up in a live trie") }
  113. func (n rawShortNode) fstring(ind string) string { panic("this should never end up in a live trie") }
  114. // cachedNode is all the information we know about a single cached node in the
  115. // memory database write layer.
  116. type cachedNode struct {
  117. node node // Cached collapsed trie node, or raw rlp data
  118. size uint16 // Byte size of the useful cached data
  119. parents uint32 // Number of live nodes referencing this one
  120. children map[common.Hash]uint16 // External children referenced by this node
  121. flushPrev common.Hash // Previous node in the flush-list
  122. flushNext common.Hash // Next node in the flush-list
  123. }
  124. // cachedNodeSize is the raw size of a cachedNode data structure without any
  125. // node data included. It's an approximate size, but should be a lot better
  126. // than not counting them.
  127. var cachedNodeSize = int(reflect.TypeOf(cachedNode{}).Size())
  128. // cachedNodeChildrenSize is the raw size of an initialized but empty external
  129. // reference map.
  130. const cachedNodeChildrenSize = 48
  131. // rlp returns the raw rlp encoded blob of the cached node, either directly from
  132. // the cache, or by regenerating it from the collapsed node.
  133. func (n *cachedNode) rlp() []byte {
  134. if node, ok := n.node.(rawNode); ok {
  135. return node
  136. }
  137. blob, err := rlp.EncodeToBytes(n.node)
  138. if err != nil {
  139. panic(err)
  140. }
  141. return blob
  142. }
  143. // obj returns the decoded and expanded trie node, either directly from the cache,
  144. // or by regenerating it from the rlp encoded blob.
  145. func (n *cachedNode) obj(hash common.Hash) node {
  146. if node, ok := n.node.(rawNode); ok {
  147. return mustDecodeNode(hash[:], node)
  148. }
  149. return expandNode(hash[:], n.node)
  150. }
  151. // forChilds invokes the callback for all the tracked children of this node,
  152. // both the implicit ones from inside the node as well as the explicit ones
  153. //from outside the node.
  154. func (n *cachedNode) forChilds(onChild func(hash common.Hash)) {
  155. for child := range n.children {
  156. onChild(child)
  157. }
  158. if _, ok := n.node.(rawNode); !ok {
  159. forGatherChildren(n.node, onChild)
  160. }
  161. }
  162. // forGatherChildren traverses the node hierarchy of a collapsed storage node and
  163. // invokes the callback for all the hashnode children.
  164. func forGatherChildren(n node, onChild func(hash common.Hash)) {
  165. switch n := n.(type) {
  166. case *rawShortNode:
  167. forGatherChildren(n.Val, onChild)
  168. case rawFullNode:
  169. for i := 0; i < 16; i++ {
  170. forGatherChildren(n[i], onChild)
  171. }
  172. case hashNode:
  173. onChild(common.BytesToHash(n))
  174. case valueNode, nil:
  175. default:
  176. panic(fmt.Sprintf("unknown node type: %T", n))
  177. }
  178. }
  179. // simplifyNode traverses the hierarchy of an expanded memory node and discards
  180. // all the internal caches, returning a node that only contains the raw data.
  181. func simplifyNode(n node) node {
  182. switch n := n.(type) {
  183. case *shortNode:
  184. // Short nodes discard the flags and cascade
  185. return &rawShortNode{Key: n.Key, Val: simplifyNode(n.Val)}
  186. case *fullNode:
  187. // Full nodes discard the flags and cascade
  188. node := rawFullNode(n.Children)
  189. for i := 0; i < len(node); i++ {
  190. if node[i] != nil {
  191. node[i] = simplifyNode(node[i])
  192. }
  193. }
  194. return node
  195. case valueNode, hashNode, rawNode:
  196. return n
  197. default:
  198. panic(fmt.Sprintf("unknown node type: %T", n))
  199. }
  200. }
  201. // expandNode traverses the node hierarchy of a collapsed storage node and converts
  202. // all fields and keys into expanded memory form.
  203. func expandNode(hash hashNode, n node) node {
  204. switch n := n.(type) {
  205. case *rawShortNode:
  206. // Short nodes need key and child expansion
  207. return &shortNode{
  208. Key: compactToHex(n.Key),
  209. Val: expandNode(nil, n.Val),
  210. flags: nodeFlag{
  211. hash: hash,
  212. },
  213. }
  214. case rawFullNode:
  215. // Full nodes need child expansion
  216. node := &fullNode{
  217. flags: nodeFlag{
  218. hash: hash,
  219. },
  220. }
  221. for i := 0; i < len(node.Children); i++ {
  222. if n[i] != nil {
  223. node.Children[i] = expandNode(nil, n[i])
  224. }
  225. }
  226. return node
  227. case valueNode, hashNode:
  228. return n
  229. default:
  230. panic(fmt.Sprintf("unknown node type: %T", n))
  231. }
  232. }
  233. // NewDatabase creates a new trie database to store ephemeral trie content before
  234. // its written out to disk or garbage collected. No read cache is created, so all
  235. // data retrievals will hit the underlying disk database.
  236. func NewDatabase(diskdb ethdb.KeyValueStore) *Database {
  237. return NewDatabaseWithCache(diskdb, 0)
  238. }
  239. // NewDatabaseWithCache creates a new trie database to store ephemeral trie content
  240. // before its written out to disk or garbage collected. It also acts as a read cache
  241. // for nodes loaded from disk.
  242. func NewDatabaseWithCache(diskdb ethdb.KeyValueStore, cache int) *Database {
  243. var cleans *fastcache.Cache
  244. if cache > 0 {
  245. cleans = fastcache.New(cache * 1024 * 1024)
  246. }
  247. return &Database{
  248. diskdb: diskdb,
  249. cleans: cleans,
  250. dirties: map[common.Hash]*cachedNode{{}: {
  251. children: make(map[common.Hash]uint16),
  252. }},
  253. preimages: make(map[common.Hash][]byte),
  254. }
  255. }
  256. // DiskDB retrieves the persistent storage backing the trie database.
  257. func (db *Database) DiskDB() ethdb.KeyValueReader {
  258. return db.diskdb
  259. }
  260. // InsertBlob writes a new reference tracked blob to the memory database if it's
  261. // yet unknown. This method should only be used for non-trie nodes that require
  262. // reference counting, since trie nodes are garbage collected directly through
  263. // their embedded children.
  264. func (db *Database) InsertBlob(hash common.Hash, blob []byte) {
  265. db.lock.Lock()
  266. defer db.lock.Unlock()
  267. db.insert(hash, len(blob), rawNode(blob))
  268. }
  269. // insert inserts a collapsed trie node into the memory database. This method is
  270. // a more generic version of InsertBlob, supporting both raw blob insertions as
  271. // well ex trie node insertions. The blob size must be specified to allow proper
  272. // size tracking.
  273. func (db *Database) insert(hash common.Hash, size int, node node) {
  274. // If the node's already cached, skip
  275. if _, ok := db.dirties[hash]; ok {
  276. return
  277. }
  278. memcacheDirtyWriteMeter.Mark(int64(size))
  279. // Create the cached entry for this node
  280. entry := &cachedNode{
  281. node: simplifyNode(node),
  282. size: uint16(size),
  283. flushPrev: db.newest,
  284. }
  285. entry.forChilds(func(child common.Hash) {
  286. if c := db.dirties[child]; c != nil {
  287. c.parents++
  288. }
  289. })
  290. db.dirties[hash] = entry
  291. // Update the flush-list endpoints
  292. if db.oldest == (common.Hash{}) {
  293. db.oldest, db.newest = hash, hash
  294. } else {
  295. db.dirties[db.newest].flushNext, db.newest = hash, hash
  296. }
  297. db.dirtiesSize += common.StorageSize(common.HashLength + entry.size)
  298. }
  299. // insertPreimage writes a new trie node pre-image to the memory database if it's
  300. // yet unknown. The method will NOT make a copy of the slice,
  301. // only use if the preimage will NOT be changed later on.
  302. //
  303. // Note, this method assumes that the database's lock is held!
  304. func (db *Database) insertPreimage(hash common.Hash, preimage []byte) {
  305. if _, ok := db.preimages[hash]; ok {
  306. return
  307. }
  308. db.preimages[hash] = preimage
  309. db.preimagesSize += common.StorageSize(common.HashLength + len(preimage))
  310. }
  311. // node retrieves a cached trie node from memory, or returns nil if none can be
  312. // found in the memory cache.
  313. func (db *Database) node(hash common.Hash) node {
  314. // Retrieve the node from the clean cache if available
  315. if db.cleans != nil {
  316. if enc := db.cleans.Get(nil, hash[:]); enc != nil {
  317. memcacheCleanHitMeter.Mark(1)
  318. memcacheCleanReadMeter.Mark(int64(len(enc)))
  319. return mustDecodeNode(hash[:], enc)
  320. }
  321. }
  322. // Retrieve the node from the dirty cache if available
  323. db.lock.RLock()
  324. dirty := db.dirties[hash]
  325. db.lock.RUnlock()
  326. if dirty != nil {
  327. memcacheDirtyHitMeter.Mark(1)
  328. memcacheDirtyReadMeter.Mark(int64(dirty.size))
  329. return dirty.obj(hash)
  330. }
  331. memcacheDirtyMissMeter.Mark(1)
  332. // Content unavailable in memory, attempt to retrieve from disk
  333. enc, err := db.diskdb.Get(hash[:])
  334. if err != nil || enc == nil {
  335. return nil
  336. }
  337. if db.cleans != nil {
  338. db.cleans.Set(hash[:], enc)
  339. memcacheCleanMissMeter.Mark(1)
  340. memcacheCleanWriteMeter.Mark(int64(len(enc)))
  341. }
  342. return mustDecodeNode(hash[:], enc)
  343. }
  344. // Node retrieves an encoded cached trie node from memory. If it cannot be found
  345. // cached, the method queries the persistent database for the content.
  346. func (db *Database) Node(hash common.Hash) ([]byte, error) {
  347. // It doesn't make sense to retrieve the metaroot
  348. if hash == (common.Hash{}) {
  349. return nil, errors.New("not found")
  350. }
  351. // Retrieve the node from the clean cache if available
  352. if db.cleans != nil {
  353. if enc := db.cleans.Get(nil, hash[:]); enc != nil {
  354. memcacheCleanHitMeter.Mark(1)
  355. memcacheCleanReadMeter.Mark(int64(len(enc)))
  356. return enc, nil
  357. }
  358. }
  359. // Retrieve the node from the dirty cache if available
  360. db.lock.RLock()
  361. dirty := db.dirties[hash]
  362. db.lock.RUnlock()
  363. if dirty != nil {
  364. memcacheDirtyHitMeter.Mark(1)
  365. memcacheDirtyReadMeter.Mark(int64(dirty.size))
  366. return dirty.rlp(), nil
  367. }
  368. memcacheDirtyMissMeter.Mark(1)
  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(secureKey(hash))
  392. }
  393. // secureKey returns the database key for the preimage of key (as a newly
  394. // allocated byte-slice)
  395. func secureKey(hash common.Hash) []byte {
  396. buf := make([]byte, secureKeyLength)
  397. copy(buf, secureKeyPrefix)
  398. copy(buf[secureKeyPrefixLength:], hash[:])
  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. node.forChilds(func(hash common.Hash) {
  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. // We reuse an ephemeral buffer for the keys. The batch Put operation
  527. // copies it internally, so we can reuse it.
  528. var keyBuf [secureKeyLength]byte
  529. copy(keyBuf[:], secureKeyPrefix)
  530. // If the preimage cache got large enough, push to disk. If it's still small
  531. // leave for later to deduplicate writes.
  532. flushPreimages := db.preimagesSize > 4*1024*1024
  533. if flushPreimages {
  534. for hash, preimage := range db.preimages {
  535. copy(keyBuf[secureKeyPrefixLength:], hash[:])
  536. if err := batch.Put(keyBuf[:], preimage); err != nil {
  537. log.Error("Failed to commit preimage from trie database", "err", err)
  538. return err
  539. }
  540. if batch.ValueSize() > ethdb.IdealBatchSize {
  541. if err := batch.Write(); err != nil {
  542. return err
  543. }
  544. batch.Reset()
  545. }
  546. }
  547. }
  548. // Keep committing nodes from the flush-list until we're below allowance
  549. oldest := db.oldest
  550. for size > limit && oldest != (common.Hash{}) {
  551. // Fetch the oldest referenced node and push into the batch
  552. node := db.dirties[oldest]
  553. if err := batch.Put(oldest[:], node.rlp()); err != nil {
  554. return err
  555. }
  556. // If we exceeded the ideal batch size, commit and reset
  557. if batch.ValueSize() >= ethdb.IdealBatchSize {
  558. if err := batch.Write(); err != nil {
  559. log.Error("Failed to write flush list to disk", "err", err)
  560. return err
  561. }
  562. batch.Reset()
  563. }
  564. // Iterate to the next flush item, or abort if the size cap was achieved. Size
  565. // is the total size, including the useful cached data (hash -> blob), the
  566. // cache item metadata, as well as external children mappings.
  567. size -= common.StorageSize(common.HashLength + int(node.size) + cachedNodeSize)
  568. if node.children != nil {
  569. size -= common.StorageSize(cachedNodeChildrenSize + len(node.children)*(common.HashLength+2))
  570. }
  571. oldest = node.flushNext
  572. }
  573. // Flush out any remainder data from the last batch
  574. if err := batch.Write(); err != nil {
  575. log.Error("Failed to write flush list to disk", "err", err)
  576. return err
  577. }
  578. // Write successful, clear out the flushed data
  579. db.lock.Lock()
  580. defer db.lock.Unlock()
  581. if flushPreimages {
  582. db.preimages = make(map[common.Hash][]byte)
  583. db.preimagesSize = 0
  584. }
  585. for db.oldest != oldest {
  586. node := db.dirties[db.oldest]
  587. delete(db.dirties, db.oldest)
  588. db.oldest = node.flushNext
  589. db.dirtiesSize -= common.StorageSize(common.HashLength + int(node.size))
  590. if node.children != nil {
  591. db.childrenSize -= common.StorageSize(cachedNodeChildrenSize + len(node.children)*(common.HashLength+2))
  592. }
  593. }
  594. if db.oldest != (common.Hash{}) {
  595. db.dirties[db.oldest].flushPrev = common.Hash{}
  596. }
  597. db.flushnodes += uint64(nodes - len(db.dirties))
  598. db.flushsize += storage - db.dirtiesSize
  599. db.flushtime += time.Since(start)
  600. memcacheFlushTimeTimer.Update(time.Since(start))
  601. memcacheFlushSizeMeter.Mark(int64(storage - db.dirtiesSize))
  602. memcacheFlushNodesMeter.Mark(int64(nodes - len(db.dirties)))
  603. log.Debug("Persisted nodes from memory database", "nodes", nodes-len(db.dirties), "size", storage-db.dirtiesSize, "time", time.Since(start),
  604. "flushnodes", db.flushnodes, "flushsize", db.flushsize, "flushtime", db.flushtime, "livenodes", len(db.dirties), "livesize", db.dirtiesSize)
  605. return nil
  606. }
  607. // Commit iterates over all the children of a particular node, writes them out
  608. // to disk, forcefully tearing down all references in both directions. As a side
  609. // effect, all pre-images accumulated up to this point are also written.
  610. //
  611. // Note, this method is a non-synchronized mutator. It is unsafe to call this
  612. // concurrently with other mutators.
  613. func (db *Database) Commit(node common.Hash, report bool, callback func(common.Hash)) error {
  614. // Create a database batch to flush persistent data out. It is important that
  615. // outside code doesn't see an inconsistent state (referenced data removed from
  616. // memory cache during commit but not yet in persistent storage). This is ensured
  617. // by only uncaching existing data when the database write finalizes.
  618. start := time.Now()
  619. batch := db.diskdb.NewBatch()
  620. // We reuse an ephemeral buffer for the keys. The batch Put operation
  621. // copies it internally, so we can reuse it.
  622. var keyBuf [secureKeyLength]byte
  623. copy(keyBuf[:], secureKeyPrefix)
  624. // Move all of the accumulated preimages into a write batch
  625. for hash, preimage := range db.preimages {
  626. copy(keyBuf[secureKeyPrefixLength:], hash[:])
  627. if err := batch.Put(keyBuf[:], preimage); err != nil {
  628. log.Error("Failed to commit preimage from trie database", "err", err)
  629. return err
  630. }
  631. // If the batch is too large, flush to disk
  632. if batch.ValueSize() > ethdb.IdealBatchSize {
  633. if err := batch.Write(); err != nil {
  634. return err
  635. }
  636. batch.Reset()
  637. }
  638. }
  639. // Since we're going to replay trie node writes into the clean cache, flush out
  640. // any batched pre-images before continuing.
  641. if err := batch.Write(); err != nil {
  642. return err
  643. }
  644. batch.Reset()
  645. // Move the trie itself into the batch, flushing if enough data is accumulated
  646. nodes, storage := len(db.dirties), db.dirtiesSize
  647. uncacher := &cleaner{db}
  648. if err := db.commit(node, batch, uncacher, callback); err != nil {
  649. log.Error("Failed to commit trie from trie database", "err", err)
  650. return err
  651. }
  652. // Trie mostly committed to disk, flush any batch leftovers
  653. if err := batch.Write(); err != nil {
  654. log.Error("Failed to write trie to disk", "err", err)
  655. return err
  656. }
  657. // Uncache any leftovers in the last batch
  658. db.lock.Lock()
  659. defer db.lock.Unlock()
  660. batch.Replay(uncacher)
  661. batch.Reset()
  662. // Reset the storage counters and bumpd metrics
  663. db.preimages = make(map[common.Hash][]byte)
  664. db.preimagesSize = 0
  665. memcacheCommitTimeTimer.Update(time.Since(start))
  666. memcacheCommitSizeMeter.Mark(int64(storage - db.dirtiesSize))
  667. memcacheCommitNodesMeter.Mark(int64(nodes - len(db.dirties)))
  668. logger := log.Info
  669. if !report {
  670. logger = log.Debug
  671. }
  672. 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,
  673. "gcnodes", db.gcnodes, "gcsize", db.gcsize, "gctime", db.gctime, "livenodes", len(db.dirties), "livesize", db.dirtiesSize)
  674. // Reset the garbage collection statistics
  675. db.gcnodes, db.gcsize, db.gctime = 0, 0, 0
  676. db.flushnodes, db.flushsize, db.flushtime = 0, 0, 0
  677. return nil
  678. }
  679. // commit is the private locked version of Commit.
  680. func (db *Database) commit(hash common.Hash, batch ethdb.Batch, uncacher *cleaner, callback func(common.Hash)) error {
  681. // If the node does not exist, it's a previously committed node
  682. node, ok := db.dirties[hash]
  683. if !ok {
  684. return nil
  685. }
  686. var err error
  687. node.forChilds(func(child common.Hash) {
  688. if err == nil {
  689. err = db.commit(child, batch, uncacher, callback)
  690. }
  691. })
  692. if err != nil {
  693. return err
  694. }
  695. if err := batch.Put(hash[:], node.rlp()); err != nil {
  696. return err
  697. }
  698. if callback != nil {
  699. callback(hash)
  700. }
  701. // If we've reached an optimal batch size, commit and start over
  702. if batch.ValueSize() >= ethdb.IdealBatchSize {
  703. if err := batch.Write(); err != nil {
  704. return err
  705. }
  706. db.lock.Lock()
  707. batch.Replay(uncacher)
  708. batch.Reset()
  709. db.lock.Unlock()
  710. }
  711. return nil
  712. }
  713. // cleaner is a database batch replayer that takes a batch of write operations
  714. // and cleans up the trie database from anything written to disk.
  715. type cleaner struct {
  716. db *Database
  717. }
  718. // Put reacts to database writes and implements dirty data uncaching. This is the
  719. // post-processing step of a commit operation where the already persisted trie is
  720. // removed from the dirty cache and moved into the clean cache. The reason behind
  721. // the two-phase commit is to ensure ensure data availability while moving from
  722. // memory to disk.
  723. func (c *cleaner) Put(key []byte, rlp []byte) error {
  724. hash := common.BytesToHash(key)
  725. // If the node does not exist, we're done on this path
  726. node, ok := c.db.dirties[hash]
  727. if !ok {
  728. return nil
  729. }
  730. // Node still exists, remove it from the flush-list
  731. switch hash {
  732. case c.db.oldest:
  733. c.db.oldest = node.flushNext
  734. c.db.dirties[node.flushNext].flushPrev = common.Hash{}
  735. case c.db.newest:
  736. c.db.newest = node.flushPrev
  737. c.db.dirties[node.flushPrev].flushNext = common.Hash{}
  738. default:
  739. c.db.dirties[node.flushPrev].flushNext = node.flushNext
  740. c.db.dirties[node.flushNext].flushPrev = node.flushPrev
  741. }
  742. // Remove the node from the dirty cache
  743. delete(c.db.dirties, hash)
  744. c.db.dirtiesSize -= common.StorageSize(common.HashLength + int(node.size))
  745. if node.children != nil {
  746. c.db.dirtiesSize -= common.StorageSize(cachedNodeChildrenSize + len(node.children)*(common.HashLength+2))
  747. }
  748. // Move the flushed node into the clean cache to prevent insta-reloads
  749. if c.db.cleans != nil {
  750. c.db.cleans.Set(hash[:], rlp)
  751. memcacheCleanWriteMeter.Mark(int64(len(rlp)))
  752. }
  753. return nil
  754. }
  755. func (c *cleaner) Delete(key []byte) error {
  756. panic("not implemented")
  757. }
  758. // Size returns the current storage size of the memory cache in front of the
  759. // persistent database layer.
  760. func (db *Database) Size() (common.StorageSize, common.StorageSize) {
  761. db.lock.RLock()
  762. defer db.lock.RUnlock()
  763. // db.dirtiesSize only contains the useful data in the cache, but when reporting
  764. // the total memory consumption, the maintenance metadata is also needed to be
  765. // counted.
  766. var metadataSize = common.StorageSize((len(db.dirties) - 1) * cachedNodeSize)
  767. var metarootRefs = common.StorageSize(len(db.dirties[common.Hash{}].children) * (common.HashLength + 2))
  768. return db.dirtiesSize + db.childrenSize + metadataSize - metarootRefs, db.preimagesSize
  769. }