github.com/ylsGit/go-ethereum@v1.6.5/core/state/statedb.go (about)

     1  // Copyright 2014 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 state provides a caching layer atop the Ethereum state trie.
    18  package state
    19  
    20  import (
    21  	"fmt"
    22  	"math/big"
    23  	"sort"
    24  	"sync"
    25  
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/core/types"
    28  	"github.com/ethereum/go-ethereum/crypto"
    29  	"github.com/ethereum/go-ethereum/ethdb"
    30  	"github.com/ethereum/go-ethereum/log"
    31  	"github.com/ethereum/go-ethereum/rlp"
    32  	"github.com/ethereum/go-ethereum/trie"
    33  	lru "github.com/hashicorp/golang-lru"
    34  )
    35  
    36  // Trie cache generation limit after which to evic trie nodes from memory.
    37  var MaxTrieCacheGen = uint16(120)
    38  
    39  const (
    40  	// Number of past tries to keep. This value is chosen such that
    41  	// reasonable chain reorg depths will hit an existing trie.
    42  	maxPastTries = 12
    43  
    44  	// Number of codehash->size associations to keep.
    45  	codeSizeCacheSize = 100000
    46  )
    47  
    48  type revision struct {
    49  	id           int
    50  	journalIndex int
    51  }
    52  
    53  // StateDBs within the ethereum protocol are used to store anything
    54  // within the merkle trie. StateDBs take care of caching and storing
    55  // nested states. It's the general query interface to retrieve:
    56  // * Contracts
    57  // * Accounts
    58  type StateDB struct {
    59  	db            ethdb.Database
    60  	trie          *trie.SecureTrie
    61  	pastTries     []*trie.SecureTrie
    62  	codeSizeCache *lru.Cache
    63  
    64  	// This map holds 'live' objects, which will get modified while processing a state transition.
    65  	stateObjects           map[common.Address]*stateObject
    66  	stateObjectsDirty      map[common.Address]struct{}
    67  	stateObjectsDestructed map[common.Address]struct{}
    68  
    69  	// The refund counter, also used by state transitioning.
    70  	refund *big.Int
    71  
    72  	thash, bhash common.Hash
    73  	txIndex      int
    74  	logs         map[common.Hash][]*types.Log
    75  	logSize      uint
    76  
    77  	preimages map[common.Hash][]byte
    78  
    79  	// Journal of state modifications. This is the backbone of
    80  	// Snapshot and RevertToSnapshot.
    81  	journal        journal
    82  	validRevisions []revision
    83  	nextRevisionId int
    84  
    85  	lock sync.Mutex
    86  }
    87  
    88  // Create a new state from a given trie
    89  func New(root common.Hash, db ethdb.Database) (*StateDB, error) {
    90  	tr, err := trie.NewSecure(root, db, MaxTrieCacheGen)
    91  	if err != nil {
    92  		return nil, err
    93  	}
    94  	csc, _ := lru.New(codeSizeCacheSize)
    95  	return &StateDB{
    96  		db:                     db,
    97  		trie:                   tr,
    98  		codeSizeCache:          csc,
    99  		stateObjects:           make(map[common.Address]*stateObject),
   100  		stateObjectsDirty:      make(map[common.Address]struct{}),
   101  		stateObjectsDestructed: make(map[common.Address]struct{}),
   102  		refund:                 new(big.Int),
   103  		logs:                   make(map[common.Hash][]*types.Log),
   104  		preimages:              make(map[common.Hash][]byte),
   105  	}, nil
   106  }
   107  
   108  // New creates a new statedb by reusing any journalled tries to avoid costly
   109  // disk io.
   110  func (self *StateDB) New(root common.Hash) (*StateDB, error) {
   111  	self.lock.Lock()
   112  	defer self.lock.Unlock()
   113  
   114  	tr, err := self.openTrie(root)
   115  	if err != nil {
   116  		return nil, err
   117  	}
   118  	return &StateDB{
   119  		db:                     self.db,
   120  		trie:                   tr,
   121  		codeSizeCache:          self.codeSizeCache,
   122  		stateObjects:           make(map[common.Address]*stateObject),
   123  		stateObjectsDirty:      make(map[common.Address]struct{}),
   124  		stateObjectsDestructed: make(map[common.Address]struct{}),
   125  		refund:                 new(big.Int),
   126  		logs:                   make(map[common.Hash][]*types.Log),
   127  		preimages:              make(map[common.Hash][]byte),
   128  	}, nil
   129  }
   130  
   131  // Reset clears out all emphemeral state objects from the state db, but keeps
   132  // the underlying state trie to avoid reloading data for the next operations.
   133  func (self *StateDB) Reset(root common.Hash) error {
   134  	self.lock.Lock()
   135  	defer self.lock.Unlock()
   136  
   137  	tr, err := self.openTrie(root)
   138  	if err != nil {
   139  		return err
   140  	}
   141  	self.trie = tr
   142  	self.stateObjects = make(map[common.Address]*stateObject)
   143  	self.stateObjectsDirty = make(map[common.Address]struct{})
   144  	self.stateObjectsDestructed = make(map[common.Address]struct{})
   145  	self.thash = common.Hash{}
   146  	self.bhash = common.Hash{}
   147  	self.txIndex = 0
   148  	self.logs = make(map[common.Hash][]*types.Log)
   149  	self.logSize = 0
   150  	self.preimages = make(map[common.Hash][]byte)
   151  	self.clearJournalAndRefund()
   152  
   153  	return nil
   154  }
   155  
   156  // openTrie creates a trie. It uses an existing trie if one is available
   157  // from the journal if available.
   158  func (self *StateDB) openTrie(root common.Hash) (*trie.SecureTrie, error) {
   159  	for i := len(self.pastTries) - 1; i >= 0; i-- {
   160  		if self.pastTries[i].Hash() == root {
   161  			tr := *self.pastTries[i]
   162  			return &tr, nil
   163  		}
   164  	}
   165  	return trie.NewSecure(root, self.db, MaxTrieCacheGen)
   166  }
   167  
   168  func (self *StateDB) pushTrie(t *trie.SecureTrie) {
   169  	self.lock.Lock()
   170  	defer self.lock.Unlock()
   171  
   172  	if len(self.pastTries) >= maxPastTries {
   173  		copy(self.pastTries, self.pastTries[1:])
   174  		self.pastTries[len(self.pastTries)-1] = t
   175  	} else {
   176  		self.pastTries = append(self.pastTries, t)
   177  	}
   178  }
   179  
   180  func (self *StateDB) AddLog(log *types.Log) {
   181  	self.journal = append(self.journal, addLogChange{txhash: self.thash})
   182  
   183  	log.TxHash = self.thash
   184  	log.BlockHash = self.bhash
   185  	log.TxIndex = uint(self.txIndex)
   186  	log.Index = self.logSize
   187  	self.logs[self.thash] = append(self.logs[self.thash], log)
   188  	self.logSize++
   189  }
   190  
   191  func (self *StateDB) GetLogs(hash common.Hash) []*types.Log {
   192  	return self.logs[hash]
   193  }
   194  
   195  func (self *StateDB) Logs() []*types.Log {
   196  	var logs []*types.Log
   197  	for _, lgs := range self.logs {
   198  		logs = append(logs, lgs...)
   199  	}
   200  	return logs
   201  }
   202  
   203  // AddPreimage records a SHA3 preimage seen by the VM.
   204  func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
   205  	if _, ok := self.preimages[hash]; !ok {
   206  		self.journal = append(self.journal, addPreimageChange{hash: hash})
   207  		pi := make([]byte, len(preimage))
   208  		copy(pi, preimage)
   209  		self.preimages[hash] = pi
   210  	}
   211  }
   212  
   213  // Preimages returns a list of SHA3 preimages that have been submitted.
   214  func (self *StateDB) Preimages() map[common.Hash][]byte {
   215  	return self.preimages
   216  }
   217  
   218  func (self *StateDB) AddRefund(gas *big.Int) {
   219  	self.journal = append(self.journal, refundChange{prev: new(big.Int).Set(self.refund)})
   220  	self.refund.Add(self.refund, gas)
   221  }
   222  
   223  // Exist reports whether the given account address exists in the state.
   224  // Notably this also returns true for suicided accounts.
   225  func (self *StateDB) Exist(addr common.Address) bool {
   226  	return self.getStateObject(addr) != nil
   227  }
   228  
   229  // Empty returns whether the state object is either non-existent
   230  // or empty according to the EIP161 specification (balance = nonce = code = 0)
   231  func (self *StateDB) Empty(addr common.Address) bool {
   232  	so := self.getStateObject(addr)
   233  	return so == nil || so.empty()
   234  }
   235  
   236  // Retrieve the balance from the given address or 0 if object not found
   237  func (self *StateDB) GetBalance(addr common.Address) *big.Int {
   238  	stateObject := self.getStateObject(addr)
   239  	if stateObject != nil {
   240  		return stateObject.Balance()
   241  	}
   242  	return common.Big0
   243  }
   244  
   245  func (self *StateDB) GetNonce(addr common.Address) uint64 {
   246  	stateObject := self.getStateObject(addr)
   247  	if stateObject != nil {
   248  		return stateObject.Nonce()
   249  	}
   250  
   251  	return 0
   252  }
   253  
   254  func (self *StateDB) GetCode(addr common.Address) []byte {
   255  	stateObject := self.getStateObject(addr)
   256  	if stateObject != nil {
   257  		code := stateObject.Code(self.db)
   258  		key := common.BytesToHash(stateObject.CodeHash())
   259  		self.codeSizeCache.Add(key, len(code))
   260  		return code
   261  	}
   262  	return nil
   263  }
   264  
   265  func (self *StateDB) GetCodeSize(addr common.Address) int {
   266  	stateObject := self.getStateObject(addr)
   267  	if stateObject == nil {
   268  		return 0
   269  	}
   270  	key := common.BytesToHash(stateObject.CodeHash())
   271  	if cached, ok := self.codeSizeCache.Get(key); ok {
   272  		return cached.(int)
   273  	}
   274  	size := len(stateObject.Code(self.db))
   275  	if stateObject.dbErr == nil {
   276  		self.codeSizeCache.Add(key, size)
   277  	}
   278  	return size
   279  }
   280  
   281  func (self *StateDB) GetCodeHash(addr common.Address) common.Hash {
   282  	stateObject := self.getStateObject(addr)
   283  	if stateObject == nil {
   284  		return common.Hash{}
   285  	}
   286  	return common.BytesToHash(stateObject.CodeHash())
   287  }
   288  
   289  func (self *StateDB) GetState(a common.Address, b common.Hash) common.Hash {
   290  	stateObject := self.getStateObject(a)
   291  	if stateObject != nil {
   292  		return stateObject.GetState(self.db, b)
   293  	}
   294  	return common.Hash{}
   295  }
   296  
   297  // StorageTrie returns the storage trie of an account.
   298  // The return value is a copy and is nil for non-existent accounts.
   299  func (self *StateDB) StorageTrie(a common.Address) *trie.SecureTrie {
   300  	stateObject := self.getStateObject(a)
   301  	if stateObject == nil {
   302  		return nil
   303  	}
   304  	cpy := stateObject.deepCopy(self, nil)
   305  	return cpy.updateTrie(self.db)
   306  }
   307  
   308  func (self *StateDB) HasSuicided(addr common.Address) bool {
   309  	stateObject := self.getStateObject(addr)
   310  	if stateObject != nil {
   311  		return stateObject.suicided
   312  	}
   313  	return false
   314  }
   315  
   316  /*
   317   * SETTERS
   318   */
   319  
   320  // AddBalance adds amount to the account associated with addr
   321  func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) {
   322  	stateObject := self.GetOrNewStateObject(addr)
   323  	if stateObject != nil {
   324  		stateObject.AddBalance(amount)
   325  	}
   326  }
   327  
   328  // SubBalance subtracts amount from the account associated with addr
   329  func (self *StateDB) SubBalance(addr common.Address, amount *big.Int) {
   330  	stateObject := self.GetOrNewStateObject(addr)
   331  	if stateObject != nil {
   332  		stateObject.SubBalance(amount)
   333  	}
   334  }
   335  
   336  func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) {
   337  	stateObject := self.GetOrNewStateObject(addr)
   338  	if stateObject != nil {
   339  		stateObject.SetBalance(amount)
   340  	}
   341  }
   342  
   343  func (self *StateDB) SetNonce(addr common.Address, nonce uint64) {
   344  	stateObject := self.GetOrNewStateObject(addr)
   345  	if stateObject != nil {
   346  		stateObject.SetNonce(nonce)
   347  	}
   348  }
   349  
   350  func (self *StateDB) SetCode(addr common.Address, code []byte) {
   351  	stateObject := self.GetOrNewStateObject(addr)
   352  	if stateObject != nil {
   353  		stateObject.SetCode(crypto.Keccak256Hash(code), code)
   354  	}
   355  }
   356  
   357  func (self *StateDB) SetState(addr common.Address, key common.Hash, value common.Hash) {
   358  	stateObject := self.GetOrNewStateObject(addr)
   359  	if stateObject != nil {
   360  		stateObject.SetState(self.db, key, value)
   361  	}
   362  }
   363  
   364  // Suicide marks the given account as suicided.
   365  // This clears the account balance.
   366  //
   367  // The account's state object is still available until the state is committed,
   368  // getStateObject will return a non-nil account after Suicide.
   369  func (self *StateDB) Suicide(addr common.Address) bool {
   370  	stateObject := self.getStateObject(addr)
   371  	if stateObject == nil {
   372  		return false
   373  	}
   374  	self.journal = append(self.journal, suicideChange{
   375  		account:     &addr,
   376  		prev:        stateObject.suicided,
   377  		prevbalance: new(big.Int).Set(stateObject.Balance()),
   378  	})
   379  	stateObject.markSuicided()
   380  	stateObject.data.Balance = new(big.Int)
   381  	self.stateObjectsDestructed[addr] = struct{}{}
   382  
   383  	return true
   384  }
   385  
   386  //
   387  // Setting, updating & deleting state object methods
   388  //
   389  
   390  // updateStateObject writes the given object to the trie.
   391  func (self *StateDB) updateStateObject(stateObject *stateObject) {
   392  	addr := stateObject.Address()
   393  	data, err := rlp.EncodeToBytes(stateObject)
   394  	if err != nil {
   395  		panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
   396  	}
   397  	self.trie.Update(addr[:], data)
   398  }
   399  
   400  // deleteStateObject removes the given object from the state trie.
   401  func (self *StateDB) deleteStateObject(stateObject *stateObject) {
   402  	stateObject.deleted = true
   403  	addr := stateObject.Address()
   404  	self.trie.Delete(addr[:])
   405  }
   406  
   407  // Retrieve a state object given my the address. Returns nil if not found.
   408  func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) {
   409  	// Prefer 'live' objects.
   410  	if obj := self.stateObjects[addr]; obj != nil {
   411  		if obj.deleted {
   412  			return nil
   413  		}
   414  		return obj
   415  	}
   416  
   417  	// Load the object from the database.
   418  	enc := self.trie.Get(addr[:])
   419  	if len(enc) == 0 {
   420  		return nil
   421  	}
   422  	var data Account
   423  	if err := rlp.DecodeBytes(enc, &data); err != nil {
   424  		log.Error("Failed to decode state object", "addr", addr, "err", err)
   425  		return nil
   426  	}
   427  	// Insert into the live set.
   428  	obj := newObject(self, addr, data, self.MarkStateObjectDirty)
   429  	self.setStateObject(obj)
   430  	return obj
   431  }
   432  
   433  func (self *StateDB) setStateObject(object *stateObject) {
   434  	self.stateObjects[object.Address()] = object
   435  }
   436  
   437  // Retrieve a state object or create a new state object if nil
   438  func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
   439  	stateObject := self.getStateObject(addr)
   440  	if stateObject == nil || stateObject.deleted {
   441  		stateObject, _ = self.createObject(addr)
   442  	}
   443  	return stateObject
   444  }
   445  
   446  // MarkStateObjectDirty adds the specified object to the dirty map to avoid costly
   447  // state object cache iteration to find a handful of modified ones.
   448  func (self *StateDB) MarkStateObjectDirty(addr common.Address) {
   449  	self.stateObjectsDirty[addr] = struct{}{}
   450  }
   451  
   452  // createObject creates a new state object. If there is an existing account with
   453  // the given address, it is overwritten and returned as the second return value.
   454  func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
   455  	prev = self.getStateObject(addr)
   456  	newobj = newObject(self, addr, Account{}, self.MarkStateObjectDirty)
   457  	newobj.setNonce(0) // sets the object to dirty
   458  	if prev == nil {
   459  		self.journal = append(self.journal, createObjectChange{account: &addr})
   460  	} else {
   461  		self.journal = append(self.journal, resetObjectChange{prev: prev})
   462  	}
   463  	self.setStateObject(newobj)
   464  	return newobj, prev
   465  }
   466  
   467  // CreateAccount explicitly creates a state object. If a state object with the address
   468  // already exists the balance is carried over to the new account.
   469  //
   470  // CreateAccount is called during the EVM CREATE operation. The situation might arise that
   471  // a contract does the following:
   472  //
   473  //   1. sends funds to sha(account ++ (nonce + 1))
   474  //   2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
   475  //
   476  // Carrying over the balance ensures that Ether doesn't disappear.
   477  func (self *StateDB) CreateAccount(addr common.Address) {
   478  	new, prev := self.createObject(addr)
   479  	if prev != nil {
   480  		new.setBalance(prev.data.Balance)
   481  	}
   482  }
   483  
   484  func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) {
   485  	so := db.getStateObject(addr)
   486  	if so == nil {
   487  		return
   488  	}
   489  
   490  	// When iterating over the storage check the cache first
   491  	for h, value := range so.cachedStorage {
   492  		cb(h, value)
   493  	}
   494  
   495  	it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
   496  	for it.Next() {
   497  		// ignore cached values
   498  		key := common.BytesToHash(db.trie.GetKey(it.Key))
   499  		if _, ok := so.cachedStorage[key]; !ok {
   500  			cb(key, common.BytesToHash(it.Value))
   501  		}
   502  	}
   503  }
   504  
   505  // Copy creates a deep, independent copy of the state.
   506  // Snapshots of the copied state cannot be applied to the copy.
   507  func (self *StateDB) Copy() *StateDB {
   508  	self.lock.Lock()
   509  	defer self.lock.Unlock()
   510  
   511  	// Copy all the basic fields, initialize the memory ones
   512  	state := &StateDB{
   513  		db:                     self.db,
   514  		trie:                   self.trie,
   515  		pastTries:              self.pastTries,
   516  		codeSizeCache:          self.codeSizeCache,
   517  		stateObjects:           make(map[common.Address]*stateObject, len(self.stateObjectsDirty)),
   518  		stateObjectsDirty:      make(map[common.Address]struct{}, len(self.stateObjectsDirty)),
   519  		stateObjectsDestructed: make(map[common.Address]struct{}, len(self.stateObjectsDestructed)),
   520  		refund:                 new(big.Int).Set(self.refund),
   521  		logs:                   make(map[common.Hash][]*types.Log, len(self.logs)),
   522  		logSize:                self.logSize,
   523  		preimages:              make(map[common.Hash][]byte),
   524  	}
   525  	// Copy the dirty states, logs, and preimages
   526  	for addr := range self.stateObjectsDirty {
   527  		state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state, state.MarkStateObjectDirty)
   528  		state.stateObjectsDirty[addr] = struct{}{}
   529  		if self.stateObjects[addr].suicided {
   530  			state.stateObjectsDestructed[addr] = struct{}{}
   531  		}
   532  	}
   533  	for hash, logs := range self.logs {
   534  		state.logs[hash] = make([]*types.Log, len(logs))
   535  		copy(state.logs[hash], logs)
   536  	}
   537  	for hash, preimage := range self.preimages {
   538  		state.preimages[hash] = preimage
   539  	}
   540  	return state
   541  }
   542  
   543  // Snapshot returns an identifier for the current revision of the state.
   544  func (self *StateDB) Snapshot() int {
   545  	id := self.nextRevisionId
   546  	self.nextRevisionId++
   547  	self.validRevisions = append(self.validRevisions, revision{id, len(self.journal)})
   548  	return id
   549  }
   550  
   551  // RevertToSnapshot reverts all state changes made since the given revision.
   552  func (self *StateDB) RevertToSnapshot(revid int) {
   553  	// Find the snapshot in the stack of valid snapshots.
   554  	idx := sort.Search(len(self.validRevisions), func(i int) bool {
   555  		return self.validRevisions[i].id >= revid
   556  	})
   557  	if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid {
   558  		panic(fmt.Errorf("revision id %v cannot be reverted", revid))
   559  	}
   560  	snapshot := self.validRevisions[idx].journalIndex
   561  
   562  	// Replay the journal to undo changes.
   563  	for i := len(self.journal) - 1; i >= snapshot; i-- {
   564  		self.journal[i].undo(self)
   565  	}
   566  	self.journal = self.journal[:snapshot]
   567  
   568  	// Remove invalidated snapshots from the stack.
   569  	self.validRevisions = self.validRevisions[:idx]
   570  }
   571  
   572  // GetRefund returns the current value of the refund counter.
   573  // The return value must not be modified by the caller and will become
   574  // invalid at the next call to AddRefund.
   575  func (self *StateDB) GetRefund() *big.Int {
   576  	return self.refund
   577  }
   578  
   579  // IntermediateRoot computes the current root hash of the state trie.
   580  // It is called in between transactions to get the root hash that
   581  // goes into transaction receipts.
   582  func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
   583  	for addr := range s.stateObjectsDirty {
   584  		stateObject := s.stateObjects[addr]
   585  		if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) {
   586  			s.deleteStateObject(stateObject)
   587  		} else {
   588  			stateObject.updateRoot(s.db)
   589  			s.updateStateObject(stateObject)
   590  		}
   591  	}
   592  	// Invalidate journal because reverting across transactions is not allowed.
   593  	s.clearJournalAndRefund()
   594  	return s.trie.Hash()
   595  }
   596  
   597  // Prepare sets the current transaction hash and index and block hash which is
   598  // used when the EVM emits new state logs.
   599  func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) {
   600  	self.thash = thash
   601  	self.bhash = bhash
   602  	self.txIndex = ti
   603  }
   604  
   605  // Finalise finalises the state by removing the self destructed objects
   606  // in the current stateObjectsDestructed buffer and clears the journal
   607  // as well as the refunds.
   608  //
   609  // Please note that Finalise is used by EIP#98 and is used instead of
   610  // IntermediateRoot.
   611  func (s *StateDB) Finalise() {
   612  	for addr := range s.stateObjectsDestructed {
   613  		s.deleteStateObject(s.stateObjects[addr])
   614  	}
   615  	s.clearJournalAndRefund()
   616  }
   617  
   618  // DeleteSuicides flags the suicided objects for deletion so that it
   619  // won't be referenced again when called / queried up on.
   620  //
   621  // DeleteSuicides should not be used for consensus related updates
   622  // under any circumstances.
   623  func (s *StateDB) DeleteSuicides() {
   624  	// Reset refund so that any used-gas calculations can use this method.
   625  	s.clearJournalAndRefund()
   626  
   627  	for addr := range s.stateObjectsDirty {
   628  		stateObject := s.stateObjects[addr]
   629  
   630  		// If the object has been removed by a suicide
   631  		// flag the object as deleted.
   632  		if stateObject.suicided {
   633  			stateObject.deleted = true
   634  		}
   635  		delete(s.stateObjectsDirty, addr)
   636  	}
   637  }
   638  
   639  // Commit commits all state changes to the database.
   640  func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) {
   641  	root, batch := s.CommitBatch(deleteEmptyObjects)
   642  	return root, batch.Write()
   643  }
   644  
   645  // CommitBatch commits all state changes to a write batch but does not
   646  // execute the batch. It is used to validate state changes against
   647  // the root hash stored in a block.
   648  func (s *StateDB) CommitBatch(deleteEmptyObjects bool) (root common.Hash, batch ethdb.Batch) {
   649  	batch = s.db.NewBatch()
   650  	root, _ = s.CommitTo(batch, deleteEmptyObjects)
   651  
   652  	log.Debug("Trie cache stats after commit", "misses", trie.CacheMisses(), "unloads", trie.CacheUnloads())
   653  	return root, batch
   654  }
   655  
   656  func (s *StateDB) clearJournalAndRefund() {
   657  	s.journal = nil
   658  	s.validRevisions = s.validRevisions[:0]
   659  	s.refund = new(big.Int)
   660  }
   661  
   662  // CommitTo writes the state to the given database.
   663  func (s *StateDB) CommitTo(dbw trie.DatabaseWriter, deleteEmptyObjects bool) (root common.Hash, err error) {
   664  	defer s.clearJournalAndRefund()
   665  
   666  	// Commit objects to the trie.
   667  	for addr, stateObject := range s.stateObjects {
   668  		_, isDirty := s.stateObjectsDirty[addr]
   669  		switch {
   670  		case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()):
   671  			// If the object has been removed, don't bother syncing it
   672  			// and just mark it for deletion in the trie.
   673  			s.deleteStateObject(stateObject)
   674  		case isDirty:
   675  			// Write any contract code associated with the state object
   676  			if stateObject.code != nil && stateObject.dirtyCode {
   677  				if err := dbw.Put(stateObject.CodeHash(), stateObject.code); err != nil {
   678  					return common.Hash{}, err
   679  				}
   680  				stateObject.dirtyCode = false
   681  			}
   682  			// Write any storage changes in the state object to its storage trie.
   683  			if err := stateObject.CommitTrie(s.db, dbw); err != nil {
   684  				return common.Hash{}, err
   685  			}
   686  			// Update the object in the main account trie.
   687  			s.updateStateObject(stateObject)
   688  		}
   689  		delete(s.stateObjectsDirty, addr)
   690  	}
   691  	// Write trie changes.
   692  	root, err = s.trie.CommitTo(dbw)
   693  	if err == nil {
   694  		s.pushTrie(s.trie)
   695  	}
   696  	return root, err
   697  }