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