github.com/ccm-chain/ccmchain@v1.0.0/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  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"sort"
    25  	"time"
    26  
    27  	"github.com/ccm-chain/ccmchain/common"
    28  	"github.com/ccm-chain/ccmchain/core/rawdb"
    29  	"github.com/ccm-chain/ccmchain/core/state/snapshot"
    30  	"github.com/ccm-chain/ccmchain/core/types"
    31  	"github.com/ccm-chain/ccmchain/crypto"
    32  	"github.com/ccm-chain/ccmchain/log"
    33  	"github.com/ccm-chain/ccmchain/metrics"
    34  	"github.com/ccm-chain/ccmchain/rlp"
    35  	"github.com/ccm-chain/ccmchain/trie"
    36  )
    37  
    38  type revision struct {
    39  	id           int
    40  	journalIndex int
    41  }
    42  
    43  var (
    44  	// emptyRoot is the known root hash of an empty trie.
    45  	emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
    46  )
    47  
    48  type proofList [][]byte
    49  
    50  func (n *proofList) Put(key []byte, value []byte) error {
    51  	*n = append(*n, value)
    52  	return nil
    53  }
    54  
    55  func (n *proofList) Delete(key []byte) error {
    56  	panic("not supported")
    57  }
    58  
    59  // StateDB structs within the ethereum protocol are used to store anything
    60  // within the merkle trie. StateDBs take care of caching and storing
    61  // nested states. It's the general query interface to retrieve:
    62  // * Contracts
    63  // * Accounts
    64  type StateDB struct {
    65  	db   Database
    66  	trie Trie
    67  
    68  	snaps         *snapshot.Tree
    69  	snap          snapshot.Snapshot
    70  	snapDestructs map[common.Hash]struct{}
    71  	snapAccounts  map[common.Hash][]byte
    72  	snapStorage   map[common.Hash]map[common.Hash][]byte
    73  
    74  	// This map holds 'live' objects, which will get modified while processing a state transition.
    75  	stateObjects        map[common.Address]*stateObject
    76  	stateObjectsPending map[common.Address]struct{} // State objects finalized but not yet written to the trie
    77  	stateObjectsDirty   map[common.Address]struct{} // State objects modified in the current execution
    78  
    79  	// DB error.
    80  	// State objects are used by the consensus core and VM which are
    81  	// unable to deal with database-level errors. Any error that occurs
    82  	// during a database read is memoized here and will eventually be returned
    83  	// by StateDB.Commit.
    84  	dbErr error
    85  
    86  	// The refund counter, also used by state transitioning.
    87  	refund uint64
    88  
    89  	thash, bhash common.Hash
    90  	txIndex      int
    91  	logs         map[common.Hash][]*types.Log
    92  	logSize      uint
    93  
    94  	preimages map[common.Hash][]byte
    95  
    96  	// Journal of state modifications. This is the backbone of
    97  	// Snapshot and RevertToSnapshot.
    98  	journal        *journal
    99  	validRevisions []revision
   100  	nextRevisionId int
   101  
   102  	// Measurements gathered during execution for debugging purposes
   103  	AccountReads         time.Duration
   104  	AccountHashes        time.Duration
   105  	AccountUpdates       time.Duration
   106  	AccountCommits       time.Duration
   107  	StorageReads         time.Duration
   108  	StorageHashes        time.Duration
   109  	StorageUpdates       time.Duration
   110  	StorageCommits       time.Duration
   111  	SnapshotAccountReads time.Duration
   112  	SnapshotStorageReads time.Duration
   113  	SnapshotCommits      time.Duration
   114  }
   115  
   116  // New creates a new state from a given trie.
   117  func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) {
   118  	tr, err := db.OpenTrie(root)
   119  	if err != nil {
   120  		return nil, err
   121  	}
   122  	sdb := &StateDB{
   123  		db:                  db,
   124  		trie:                tr,
   125  		snaps:               snaps,
   126  		stateObjects:        make(map[common.Address]*stateObject),
   127  		stateObjectsPending: make(map[common.Address]struct{}),
   128  		stateObjectsDirty:   make(map[common.Address]struct{}),
   129  		logs:                make(map[common.Hash][]*types.Log),
   130  		preimages:           make(map[common.Hash][]byte),
   131  		journal:             newJournal(),
   132  	}
   133  	if sdb.snaps != nil {
   134  		if sdb.snap = sdb.snaps.Snapshot(root); sdb.snap != nil {
   135  			sdb.snapDestructs = make(map[common.Hash]struct{})
   136  			sdb.snapAccounts = make(map[common.Hash][]byte)
   137  			sdb.snapStorage = make(map[common.Hash]map[common.Hash][]byte)
   138  		}
   139  	}
   140  	return sdb, nil
   141  }
   142  
   143  // setError remembers the first non-nil error it is called with.
   144  func (s *StateDB) setError(err error) {
   145  	if s.dbErr == nil {
   146  		s.dbErr = err
   147  	}
   148  }
   149  
   150  func (s *StateDB) Error() error {
   151  	return s.dbErr
   152  }
   153  
   154  // Reset clears out all ephemeral state objects from the state db, but keeps
   155  // the underlying state trie to avoid reloading data for the next operations.
   156  func (s *StateDB) Reset(root common.Hash) error {
   157  	tr, err := s.db.OpenTrie(root)
   158  	if err != nil {
   159  		return err
   160  	}
   161  	s.trie = tr
   162  	s.stateObjects = make(map[common.Address]*stateObject)
   163  	s.stateObjectsPending = make(map[common.Address]struct{})
   164  	s.stateObjectsDirty = make(map[common.Address]struct{})
   165  	s.thash = common.Hash{}
   166  	s.bhash = common.Hash{}
   167  	s.txIndex = 0
   168  	s.logs = make(map[common.Hash][]*types.Log)
   169  	s.logSize = 0
   170  	s.preimages = make(map[common.Hash][]byte)
   171  	s.clearJournalAndRefund()
   172  
   173  	if s.snaps != nil {
   174  		s.snapAccounts, s.snapDestructs, s.snapStorage = nil, nil, nil
   175  		if s.snap = s.snaps.Snapshot(root); s.snap != nil {
   176  			s.snapDestructs = make(map[common.Hash]struct{})
   177  			s.snapAccounts = make(map[common.Hash][]byte)
   178  			s.snapStorage = make(map[common.Hash]map[common.Hash][]byte)
   179  		}
   180  	}
   181  	return nil
   182  }
   183  
   184  func (s *StateDB) AddLog(log *types.Log) {
   185  	s.journal.append(addLogChange{txhash: s.thash})
   186  
   187  	log.TxHash = s.thash
   188  	log.BlockHash = s.bhash
   189  	log.TxIndex = uint(s.txIndex)
   190  	log.Index = s.logSize
   191  	s.logs[s.thash] = append(s.logs[s.thash], log)
   192  	s.logSize++
   193  }
   194  
   195  func (s *StateDB) GetLogs(hash common.Hash) []*types.Log {
   196  	return s.logs[hash]
   197  }
   198  
   199  func (s *StateDB) Logs() []*types.Log {
   200  	var logs []*types.Log
   201  	for _, lgs := range s.logs {
   202  		logs = append(logs, lgs...)
   203  	}
   204  	return logs
   205  }
   206  
   207  // AddPreimage records a SHA3 preimage seen by the VM.
   208  func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
   209  	if _, ok := s.preimages[hash]; !ok {
   210  		s.journal.append(addPreimageChange{hash: hash})
   211  		pi := make([]byte, len(preimage))
   212  		copy(pi, preimage)
   213  		s.preimages[hash] = pi
   214  	}
   215  }
   216  
   217  // Preimages returns a list of SHA3 preimages that have been submitted.
   218  func (s *StateDB) Preimages() map[common.Hash][]byte {
   219  	return s.preimages
   220  }
   221  
   222  // AddRefund adds gas to the refund counter
   223  func (s *StateDB) AddRefund(gas uint64) {
   224  	s.journal.append(refundChange{prev: s.refund})
   225  	s.refund += gas
   226  }
   227  
   228  // SubRefund removes gas from the refund counter.
   229  // This method will panic if the refund counter goes below zero
   230  func (s *StateDB) SubRefund(gas uint64) {
   231  	s.journal.append(refundChange{prev: s.refund})
   232  	if gas > s.refund {
   233  		panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund))
   234  	}
   235  	s.refund -= gas
   236  }
   237  
   238  // Exist reports whether the given account address exists in the state.
   239  // Notably this also returns true for suicided accounts.
   240  func (s *StateDB) Exist(addr common.Address) bool {
   241  	return s.getStateObject(addr) != nil
   242  }
   243  
   244  // Empty returns whether the state object is either non-existent
   245  // or empty according to the EIP161 specification (balance = nonce = code = 0)
   246  func (s *StateDB) Empty(addr common.Address) bool {
   247  	so := s.getStateObject(addr)
   248  	return so == nil || so.empty()
   249  }
   250  
   251  // GetBalance retrieves the balance from the given address or 0 if object not found
   252  func (s *StateDB) GetBalance(addr common.Address) *big.Int {
   253  	stateObject := s.getStateObject(addr)
   254  	if stateObject != nil {
   255  		return stateObject.Balance()
   256  	}
   257  	return common.Big0
   258  }
   259  
   260  func (s *StateDB) GetNonce(addr common.Address) uint64 {
   261  	stateObject := s.getStateObject(addr)
   262  	if stateObject != nil {
   263  		return stateObject.Nonce()
   264  	}
   265  
   266  	return 0
   267  }
   268  
   269  // TxIndex returns the current transaction index set by Prepare.
   270  func (s *StateDB) TxIndex() int {
   271  	return s.txIndex
   272  }
   273  
   274  // BlockHash returns the current block hash set by Prepare.
   275  func (s *StateDB) BlockHash() common.Hash {
   276  	return s.bhash
   277  }
   278  
   279  func (s *StateDB) GetCode(addr common.Address) []byte {
   280  	stateObject := s.getStateObject(addr)
   281  	if stateObject != nil {
   282  		return stateObject.Code(s.db)
   283  	}
   284  	return nil
   285  }
   286  
   287  func (s *StateDB) GetCodeSize(addr common.Address) int {
   288  	stateObject := s.getStateObject(addr)
   289  	if stateObject != nil {
   290  		return stateObject.CodeSize(s.db)
   291  	}
   292  	return 0
   293  }
   294  
   295  func (s *StateDB) GetCodeHash(addr common.Address) common.Hash {
   296  	stateObject := s.getStateObject(addr)
   297  	if stateObject == nil {
   298  		return common.Hash{}
   299  	}
   300  	return common.BytesToHash(stateObject.CodeHash())
   301  }
   302  
   303  // GetState retrieves a value from the given account's storage trie.
   304  func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash {
   305  	stateObject := s.getStateObject(addr)
   306  	if stateObject != nil {
   307  		return stateObject.GetState(s.db, hash)
   308  	}
   309  	return common.Hash{}
   310  }
   311  
   312  // GetProof returns the MerkleProof for a given Account
   313  func (s *StateDB) GetProof(a common.Address) ([][]byte, error) {
   314  	var proof proofList
   315  	err := s.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof)
   316  	return [][]byte(proof), err
   317  }
   318  
   319  // GetStorageProof returns the StorageProof for given key
   320  func (s *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
   321  	var proof proofList
   322  	trie := s.StorageTrie(a)
   323  	if trie == nil {
   324  		return proof, errors.New("storage trie for requested address does not exist")
   325  	}
   326  	err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof)
   327  	return [][]byte(proof), err
   328  }
   329  
   330  // GetCommittedState retrieves a value from the given account's committed storage trie.
   331  func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
   332  	stateObject := s.getStateObject(addr)
   333  	if stateObject != nil {
   334  		return stateObject.GetCommittedState(s.db, hash)
   335  	}
   336  	return common.Hash{}
   337  }
   338  
   339  // Database retrieves the low level database supporting the lower level trie ops.
   340  func (s *StateDB) Database() Database {
   341  	return s.db
   342  }
   343  
   344  // StorageTrie returns the storage trie of an account.
   345  // The return value is a copy and is nil for non-existent accounts.
   346  func (s *StateDB) StorageTrie(addr common.Address) Trie {
   347  	stateObject := s.getStateObject(addr)
   348  	if stateObject == nil {
   349  		return nil
   350  	}
   351  	cpy := stateObject.deepCopy(s)
   352  	cpy.updateTrie(s.db)
   353  	return cpy.getTrie(s.db)
   354  }
   355  
   356  func (s *StateDB) HasSuicided(addr common.Address) bool {
   357  	stateObject := s.getStateObject(addr)
   358  	if stateObject != nil {
   359  		return stateObject.suicided
   360  	}
   361  	return false
   362  }
   363  
   364  /*
   365   * SETTERS
   366   */
   367  
   368  // AddBalance adds amount to the account associated with addr.
   369  func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) {
   370  	stateObject := s.GetOrNewStateObject(addr)
   371  	if stateObject != nil {
   372  		stateObject.AddBalance(amount)
   373  	}
   374  }
   375  
   376  // SubBalance subtracts amount from the account associated with addr.
   377  func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) {
   378  	stateObject := s.GetOrNewStateObject(addr)
   379  	if stateObject != nil {
   380  		stateObject.SubBalance(amount)
   381  	}
   382  }
   383  
   384  func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) {
   385  	stateObject := s.GetOrNewStateObject(addr)
   386  	if stateObject != nil {
   387  		stateObject.SetBalance(amount)
   388  	}
   389  }
   390  
   391  func (s *StateDB) SetNonce(addr common.Address, nonce uint64) {
   392  	stateObject := s.GetOrNewStateObject(addr)
   393  	if stateObject != nil {
   394  		stateObject.SetNonce(nonce)
   395  	}
   396  }
   397  
   398  func (s *StateDB) SetCode(addr common.Address, code []byte) {
   399  	stateObject := s.GetOrNewStateObject(addr)
   400  	if stateObject != nil {
   401  		stateObject.SetCode(crypto.Keccak256Hash(code), code)
   402  	}
   403  }
   404  
   405  func (s *StateDB) SetState(addr common.Address, key, value common.Hash) {
   406  	stateObject := s.GetOrNewStateObject(addr)
   407  	if stateObject != nil {
   408  		stateObject.SetState(s.db, key, value)
   409  	}
   410  }
   411  
   412  // SetStorage replaces the entire storage for the specified account with given
   413  // storage. This function should only be used for debugging.
   414  func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) {
   415  	stateObject := s.GetOrNewStateObject(addr)
   416  	if stateObject != nil {
   417  		stateObject.SetStorage(storage)
   418  	}
   419  }
   420  
   421  // Suicide marks the given account as suicided.
   422  // This clears the account balance.
   423  //
   424  // The account's state object is still available until the state is committed,
   425  // getStateObject will return a non-nil account after Suicide.
   426  func (s *StateDB) Suicide(addr common.Address) bool {
   427  	stateObject := s.getStateObject(addr)
   428  	if stateObject == nil {
   429  		return false
   430  	}
   431  	s.journal.append(suicideChange{
   432  		account:     &addr,
   433  		prev:        stateObject.suicided,
   434  		prevbalance: new(big.Int).Set(stateObject.Balance()),
   435  	})
   436  	stateObject.markSuicided()
   437  	stateObject.data.Balance = new(big.Int)
   438  
   439  	return true
   440  }
   441  
   442  //
   443  // Setting, updating & deleting state object methods.
   444  //
   445  
   446  // updateStateObject writes the given object to the trie.
   447  func (s *StateDB) updateStateObject(obj *stateObject) {
   448  	// Track the amount of time wasted on updating the account from the trie
   449  	if metrics.EnabledExpensive {
   450  		defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
   451  	}
   452  	// Encode the account and update the account trie
   453  	addr := obj.Address()
   454  
   455  	data, err := rlp.EncodeToBytes(obj)
   456  	if err != nil {
   457  		panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
   458  	}
   459  	if err = s.trie.TryUpdate(addr[:], data); err != nil {
   460  		s.setError(fmt.Errorf("updateStateObject (%x) error: %v", addr[:], err))
   461  	}
   462  
   463  	// If state snapshotting is active, cache the data til commit. Note, this
   464  	// update mechanism is not symmetric to the deletion, because whereas it is
   465  	// enough to track account updates at commit time, deletions need tracking
   466  	// at transaction boundary level to ensure we capture state clearing.
   467  	if s.snap != nil {
   468  		s.snapAccounts[obj.addrHash] = snapshot.SlimAccountRLP(obj.data.Nonce, obj.data.Balance, obj.data.Root, obj.data.CodeHash)
   469  	}
   470  }
   471  
   472  // deleteStateObject removes the given object from the state trie.
   473  func (s *StateDB) deleteStateObject(obj *stateObject) {
   474  	// Track the amount of time wasted on deleting the account from the trie
   475  	if metrics.EnabledExpensive {
   476  		defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
   477  	}
   478  	// Delete the account from the trie
   479  	addr := obj.Address()
   480  	if err := s.trie.TryDelete(addr[:]); err != nil {
   481  		s.setError(fmt.Errorf("deleteStateObject (%x) error: %v", addr[:], err))
   482  	}
   483  }
   484  
   485  // getStateObject retrieves a state object given by the address, returning nil if
   486  // the object is not found or was deleted in this execution context. If you need
   487  // to differentiate between non-existent/just-deleted, use getDeletedStateObject.
   488  func (s *StateDB) getStateObject(addr common.Address) *stateObject {
   489  	if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted {
   490  		return obj
   491  	}
   492  	return nil
   493  }
   494  
   495  // getDeletedStateObject is similar to getStateObject, but instead of returning
   496  // nil for a deleted state object, it returns the actual object with the deleted
   497  // flag set. This is needed by the state journal to revert to the correct s-
   498  // destructed object instead of wiping all knowledge about the state object.
   499  func (s *StateDB) getDeletedStateObject(addr common.Address) *stateObject {
   500  	// Prefer live objects if any is available
   501  	if obj := s.stateObjects[addr]; obj != nil {
   502  		return obj
   503  	}
   504  	// If no live objects are available, attempt to use snapshots
   505  	var (
   506  		data *Account
   507  		err  error
   508  	)
   509  	if s.snap != nil {
   510  		if metrics.EnabledExpensive {
   511  			defer func(start time.Time) { s.SnapshotAccountReads += time.Since(start) }(time.Now())
   512  		}
   513  		var acc *snapshot.Account
   514  		if acc, err = s.snap.Account(crypto.Keccak256Hash(addr.Bytes())); err == nil {
   515  			if acc == nil {
   516  				return nil
   517  			}
   518  			data = &Account{
   519  				Nonce:    acc.Nonce,
   520  				Balance:  acc.Balance,
   521  				CodeHash: acc.CodeHash,
   522  				Root:     common.BytesToHash(acc.Root),
   523  			}
   524  			if len(data.CodeHash) == 0 {
   525  				data.CodeHash = emptyCodeHash
   526  			}
   527  			if data.Root == (common.Hash{}) {
   528  				data.Root = emptyRoot
   529  			}
   530  		}
   531  	}
   532  	// If snapshot unavailable or reading from it failed, load from the database
   533  	if s.snap == nil || err != nil {
   534  		if metrics.EnabledExpensive {
   535  			defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now())
   536  		}
   537  		enc, err := s.trie.TryGet(addr.Bytes())
   538  		if err != nil {
   539  			s.setError(fmt.Errorf("getDeleteStateObject (%x) error: %v", addr.Bytes(), err))
   540  			return nil
   541  		}
   542  		if len(enc) == 0 {
   543  			return nil
   544  		}
   545  		data = new(Account)
   546  		if err := rlp.DecodeBytes(enc, data); err != nil {
   547  			log.Error("Failed to decode state object", "addr", addr, "err", err)
   548  			return nil
   549  		}
   550  	}
   551  	// Insert into the live set
   552  	obj := newObject(s, addr, *data)
   553  	s.setStateObject(obj)
   554  	return obj
   555  }
   556  
   557  func (s *StateDB) setStateObject(object *stateObject) {
   558  	s.stateObjects[object.Address()] = object
   559  }
   560  
   561  // GetOrNewStateObject retrieves a state object or create a new state object if nil.
   562  func (s *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
   563  	stateObject := s.getStateObject(addr)
   564  	if stateObject == nil {
   565  		stateObject, _ = s.createObject(addr)
   566  	}
   567  	return stateObject
   568  }
   569  
   570  // createObject creates a new state object. If there is an existing account with
   571  // the given address, it is overwritten and returned as the second return value.
   572  func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
   573  	prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that!
   574  
   575  	var prevdestruct bool
   576  	if s.snap != nil && prev != nil {
   577  		_, prevdestruct = s.snapDestructs[prev.addrHash]
   578  		if !prevdestruct {
   579  			s.snapDestructs[prev.addrHash] = struct{}{}
   580  		}
   581  	}
   582  	newobj = newObject(s, addr, Account{})
   583  	newobj.setNonce(0) // sets the object to dirty
   584  	if prev == nil {
   585  		s.journal.append(createObjectChange{account: &addr})
   586  	} else {
   587  		s.journal.append(resetObjectChange{prev: prev, prevdestruct: prevdestruct})
   588  	}
   589  	s.setStateObject(newobj)
   590  	if prev != nil && !prev.deleted {
   591  		return newobj, prev
   592  	}
   593  	return newobj, nil
   594  }
   595  
   596  // CreateAccount explicitly creates a state object. If a state object with the address
   597  // already exists the balance is carried over to the new account.
   598  //
   599  // CreateAccount is called during the EVM CREATE operation. The situation might arise that
   600  // a contract does the following:
   601  //
   602  //   1. sends funds to sha(account ++ (nonce + 1))
   603  //   2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
   604  //
   605  // Carrying over the balance ensures that Ether doesn't disappear.
   606  func (s *StateDB) CreateAccount(addr common.Address) {
   607  	newObj, prev := s.createObject(addr)
   608  	if prev != nil {
   609  		newObj.setBalance(prev.data.Balance)
   610  	}
   611  }
   612  
   613  func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {
   614  	so := db.getStateObject(addr)
   615  	if so == nil {
   616  		return nil
   617  	}
   618  	it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
   619  
   620  	for it.Next() {
   621  		key := common.BytesToHash(db.trie.GetKey(it.Key))
   622  		if value, dirty := so.dirtyStorage[key]; dirty {
   623  			if !cb(key, value) {
   624  				return nil
   625  			}
   626  			continue
   627  		}
   628  
   629  		if len(it.Value) > 0 {
   630  			_, content, _, err := rlp.Split(it.Value)
   631  			if err != nil {
   632  				return err
   633  			}
   634  			if !cb(key, common.BytesToHash(content)) {
   635  				return nil
   636  			}
   637  		}
   638  	}
   639  	return nil
   640  }
   641  
   642  // Copy creates a deep, independent copy of the state.
   643  // Snapshots of the copied state cannot be applied to the copy.
   644  func (s *StateDB) Copy() *StateDB {
   645  	// Copy all the basic fields, initialize the memory ones
   646  	state := &StateDB{
   647  		db:                  s.db,
   648  		trie:                s.db.CopyTrie(s.trie),
   649  		stateObjects:        make(map[common.Address]*stateObject, len(s.journal.dirties)),
   650  		stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)),
   651  		stateObjectsDirty:   make(map[common.Address]struct{}, len(s.journal.dirties)),
   652  		refund:              s.refund,
   653  		logs:                make(map[common.Hash][]*types.Log, len(s.logs)),
   654  		logSize:             s.logSize,
   655  		preimages:           make(map[common.Hash][]byte, len(s.preimages)),
   656  		journal:             newJournal(),
   657  	}
   658  	// Copy the dirty states, logs, and preimages
   659  	for addr := range s.journal.dirties {
   660  		// As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527),
   661  		// and in the Finalise-method, there is a case where an object is in the journal but not
   662  		// in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
   663  		// nil
   664  		if object, exist := s.stateObjects[addr]; exist {
   665  			// Even though the original object is dirty, we are not copying the journal,
   666  			// so we need to make sure that anyside effect the journal would have caused
   667  			// during a commit (or similar op) is already applied to the copy.
   668  			state.stateObjects[addr] = object.deepCopy(state)
   669  
   670  			state.stateObjectsDirty[addr] = struct{}{}   // Mark the copy dirty to force internal (code/state) commits
   671  			state.stateObjectsPending[addr] = struct{}{} // Mark the copy pending to force external (account) commits
   672  		}
   673  	}
   674  	// Above, we don't copy the actual journal. This means that if the copy is copied, the
   675  	// loop above will be a no-op, since the copy's journal is empty.
   676  	// Thus, here we iterate over stateObjects, to enable copies of copies
   677  	for addr := range s.stateObjectsPending {
   678  		if _, exist := state.stateObjects[addr]; !exist {
   679  			state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
   680  		}
   681  		state.stateObjectsPending[addr] = struct{}{}
   682  	}
   683  	for addr := range s.stateObjectsDirty {
   684  		if _, exist := state.stateObjects[addr]; !exist {
   685  			state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
   686  		}
   687  		state.stateObjectsDirty[addr] = struct{}{}
   688  	}
   689  	for hash, logs := range s.logs {
   690  		cpy := make([]*types.Log, len(logs))
   691  		for i, l := range logs {
   692  			cpy[i] = new(types.Log)
   693  			*cpy[i] = *l
   694  		}
   695  		state.logs[hash] = cpy
   696  	}
   697  	for hash, preimage := range s.preimages {
   698  		state.preimages[hash] = preimage
   699  	}
   700  	return state
   701  }
   702  
   703  // Snapshot returns an identifier for the current revision of the state.
   704  func (s *StateDB) Snapshot() int {
   705  	id := s.nextRevisionId
   706  	s.nextRevisionId++
   707  	s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()})
   708  	return id
   709  }
   710  
   711  // RevertToSnapshot reverts all state changes made since the given revision.
   712  func (s *StateDB) RevertToSnapshot(revid int) {
   713  	// Find the snapshot in the stack of valid snapshots.
   714  	idx := sort.Search(len(s.validRevisions), func(i int) bool {
   715  		return s.validRevisions[i].id >= revid
   716  	})
   717  	if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid {
   718  		panic(fmt.Errorf("revision id %v cannot be reverted", revid))
   719  	}
   720  	snapshot := s.validRevisions[idx].journalIndex
   721  
   722  	// Replay the journal to undo changes and remove invalidated snapshots
   723  	s.journal.revert(s, snapshot)
   724  	s.validRevisions = s.validRevisions[:idx]
   725  }
   726  
   727  // GetRefund returns the current value of the refund counter.
   728  func (s *StateDB) GetRefund() uint64 {
   729  	return s.refund
   730  }
   731  
   732  // Finalise finalises the state by removing the s destructed objects and clears
   733  // the journal as well as the refunds. Finalise, however, will not push any updates
   734  // into the tries just yet. Only IntermediateRoot or Commit will do that.
   735  func (s *StateDB) Finalise(deleteEmptyObjects bool) {
   736  	for addr := range s.journal.dirties {
   737  		obj, exist := s.stateObjects[addr]
   738  		if !exist {
   739  			// ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
   740  			// That tx goes out of gas, and although the notion of 'touched' does not exist there, the
   741  			// touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
   742  			// it will persist in the journal even though the journal is reverted. In this special circumstance,
   743  			// it may exist in `s.journal.dirties` but not in `s.stateObjects`.
   744  			// Thus, we can safely ignore it here
   745  			continue
   746  		}
   747  		if obj.suicided || (deleteEmptyObjects && obj.empty()) {
   748  			obj.deleted = true
   749  
   750  			// If state snapshotting is active, also mark the destruction there.
   751  			// Note, we can't do this only at the end of a block because multiple
   752  			// transactions within the same block might self destruct and then
   753  			// ressurrect an account; but the snapshotter needs both events.
   754  			if s.snap != nil {
   755  				s.snapDestructs[obj.addrHash] = struct{}{} // We need to maintain account deletions explicitly (will remain set indefinitely)
   756  				delete(s.snapAccounts, obj.addrHash)       // Clear out any previously updated account data (may be recreated via a ressurrect)
   757  				delete(s.snapStorage, obj.addrHash)        // Clear out any previously updated storage data (may be recreated via a ressurrect)
   758  			}
   759  		} else {
   760  			obj.finalise()
   761  		}
   762  		s.stateObjectsPending[addr] = struct{}{}
   763  		s.stateObjectsDirty[addr] = struct{}{}
   764  	}
   765  	// Invalidate journal because reverting across transactions is not allowed.
   766  	s.clearJournalAndRefund()
   767  }
   768  
   769  // IntermediateRoot computes the current root hash of the state trie.
   770  // It is called in between transactions to get the root hash that
   771  // goes into transaction receipts.
   772  func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
   773  	// Finalise all the dirty storage states and write them into the tries
   774  	s.Finalise(deleteEmptyObjects)
   775  
   776  	for addr := range s.stateObjectsPending {
   777  		obj := s.stateObjects[addr]
   778  		if obj.deleted {
   779  			s.deleteStateObject(obj)
   780  		} else {
   781  			obj.updateRoot(s.db)
   782  			s.updateStateObject(obj)
   783  		}
   784  	}
   785  	if len(s.stateObjectsPending) > 0 {
   786  		s.stateObjectsPending = make(map[common.Address]struct{})
   787  	}
   788  	// Track the amount of time wasted on hashing the account trie
   789  	if metrics.EnabledExpensive {
   790  		defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now())
   791  	}
   792  	return s.trie.Hash()
   793  }
   794  
   795  // Prepare sets the current transaction hash and index and block hash which is
   796  // used when the EVM emits new state logs.
   797  func (s *StateDB) Prepare(thash, bhash common.Hash, ti int) {
   798  	s.thash = thash
   799  	s.bhash = bhash
   800  	s.txIndex = ti
   801  }
   802  
   803  func (s *StateDB) clearJournalAndRefund() {
   804  	if len(s.journal.entries) > 0 {
   805  		s.journal = newJournal()
   806  		s.refund = 0
   807  	}
   808  	s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entires
   809  }
   810  
   811  // Commit writes the state to the underlying in-memory trie database.
   812  func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) {
   813  	if s.dbErr != nil {
   814  		return common.Hash{}, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr)
   815  	}
   816  	// Finalize any pending changes and merge everything into the tries
   817  	s.IntermediateRoot(deleteEmptyObjects)
   818  
   819  	// Commit objects to the trie, measuring the elapsed time
   820  	codeWriter := s.db.TrieDB().DiskDB().NewBatch()
   821  	for addr := range s.stateObjectsDirty {
   822  		if obj := s.stateObjects[addr]; !obj.deleted {
   823  			// Write any contract code associated with the state object
   824  			if obj.code != nil && obj.dirtyCode {
   825  				rawdb.WriteCode(codeWriter, common.BytesToHash(obj.CodeHash()), obj.code)
   826  				obj.dirtyCode = false
   827  			}
   828  			// Write any storage changes in the state object to its storage trie
   829  			if err := obj.CommitTrie(s.db); err != nil {
   830  				return common.Hash{}, err
   831  			}
   832  		}
   833  	}
   834  	if len(s.stateObjectsDirty) > 0 {
   835  		s.stateObjectsDirty = make(map[common.Address]struct{})
   836  	}
   837  	if codeWriter.ValueSize() > 0 {
   838  		if err := codeWriter.Write(); err != nil {
   839  			log.Crit("Failed to commit dirty codes", "error", err)
   840  		}
   841  	}
   842  	// Write the account trie changes, measuing the amount of wasted time
   843  	var start time.Time
   844  	if metrics.EnabledExpensive {
   845  		start = time.Now()
   846  	}
   847  	// The onleaf func is called _serially_, so we can reuse the same account
   848  	// for unmarshalling every time.
   849  	var account Account
   850  	root, err := s.trie.Commit(func(leaf []byte, parent common.Hash) error {
   851  		if err := rlp.DecodeBytes(leaf, &account); err != nil {
   852  			return nil
   853  		}
   854  		if account.Root != emptyRoot {
   855  			s.db.TrieDB().Reference(account.Root, parent)
   856  		}
   857  		return nil
   858  	})
   859  	if metrics.EnabledExpensive {
   860  		s.AccountCommits += time.Since(start)
   861  	}
   862  	// If snapshotting is enabled, update the snapshot tree with this new version
   863  	if s.snap != nil {
   864  		if metrics.EnabledExpensive {
   865  			defer func(start time.Time) { s.SnapshotCommits += time.Since(start) }(time.Now())
   866  		}
   867  		// Only update if there's a state transition (skip empty Clique blocks)
   868  		if parent := s.snap.Root(); parent != root {
   869  			if err := s.snaps.Update(root, parent, s.snapDestructs, s.snapAccounts, s.snapStorage); err != nil {
   870  				log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err)
   871  			}
   872  			if err := s.snaps.Cap(root, 127); err != nil { // Persistent layer is 128th, the last available trie
   873  				log.Warn("Failed to cap snapshot tree", "root", root, "layers", 127, "err", err)
   874  			}
   875  		}
   876  		s.snap, s.snapDestructs, s.snapAccounts, s.snapStorage = nil, nil, nil, nil
   877  	}
   878  	return root, err
   879  }