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