database.go 31 KB

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