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