github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/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/zhiqiangxu/go-ethereum/common"
    28  	"github.com/zhiqiangxu/go-ethereum/core/state/snapshot"
    29  	"github.com/zhiqiangxu/go-ethereum/core/types"
    30  	"github.com/zhiqiangxu/go-ethereum/crypto"
    31  	"github.com/zhiqiangxu/go-ethereum/log"
    32  	"github.com/zhiqiangxu/go-ethereum/metrics"
    33  	"github.com/zhiqiangxu/go-ethereum/rlp"
    34  	"github.com/zhiqiangxu/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[:])); err == nil {
   517  			if acc == nil {
   518  				return nil
   519  			}
   520  			data.Nonce, data.Balance, data.CodeHash = acc.Nonce, acc.Balance, acc.CodeHash
   521  			if len(data.CodeHash) == 0 {
   522  				data.CodeHash = emptyCodeHash
   523  			}
   524  			data.Root = common.BytesToHash(acc.Root)
   525  			if data.Root == (common.Hash{}) {
   526  				data.Root = emptyRoot
   527  			}
   528  		}
   529  	}
   530  	// If snapshot unavailable or reading from it failed, load from the database
   531  	if s.snap == nil || err != nil {
   532  		if metrics.EnabledExpensive {
   533  			defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now())
   534  		}
   535  		enc, err := s.trie.TryGet(addr[:])
   536  		if err != nil {
   537  			s.setError(fmt.Errorf("getDeleteStateObject (%x) error: %v", addr[:], err))
   538  			return nil
   539  		}
   540  		if len(enc) == 0 {
   541  			return nil
   542  		}
   543  		if err := rlp.DecodeBytes(enc, &data); err != nil {
   544  			log.Error("Failed to decode state object", "addr", addr, "err", err)
   545  			return nil
   546  		}
   547  	}
   548  	// Insert into the live set
   549  	obj := newObject(s, addr, data)
   550  	s.setStateObject(obj)
   551  	return obj
   552  }
   553  
   554  func (s *StateDB) setStateObject(object *stateObject) {
   555  	s.stateObjects[object.Address()] = object
   556  }
   557  
   558  // Retrieve a state object or create a new state object if nil.
   559  func (s *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
   560  	stateObject := s.getStateObject(addr)
   561  	if stateObject == nil {
   562  		stateObject, _ = s.createObject(addr)
   563  	}
   564  	return stateObject
   565  }
   566  
   567  // createObject creates a new state object. If there is an existing account with
   568  // the given address, it is overwritten and returned as the second return value.
   569  func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
   570  	prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that!
   571  
   572  	var prevdestruct bool
   573  	if s.snap != nil && prev != nil {
   574  		_, prevdestruct = s.snapDestructs[prev.addrHash]
   575  		if !prevdestruct {
   576  			s.snapDestructs[prev.addrHash] = struct{}{}
   577  		}
   578  	}
   579  	newobj = newObject(s, addr, Account{})
   580  	newobj.setNonce(0) // sets the object to dirty
   581  	if prev == nil {
   582  		s.journal.append(createObjectChange{account: &addr})
   583  	} else {
   584  		s.journal.append(resetObjectChange{prev: prev, prevdestruct: prevdestruct})
   585  	}
   586  	s.setStateObject(newobj)
   587  	return newobj, prev
   588  }
   589  
   590  // CreateAccount explicitly creates a state object. If a state object with the address
   591  // already exists the balance is carried over to the new account.
   592  //
   593  // CreateAccount is called during the EVM CREATE operation. The situation might arise that
   594  // a contract does the following:
   595  //
   596  //   1. sends funds to sha(account ++ (nonce + 1))
   597  //   2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
   598  //
   599  // Carrying over the balance ensures that Ether doesn't disappear.
   600  func (s *StateDB) CreateAccount(addr common.Address) {
   601  	newObj, prev := s.createObject(addr)
   602  	if prev != nil {
   603  		newObj.setBalance(prev.data.Balance)
   604  	}
   605  }
   606  
   607  func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {
   608  	so := db.getStateObject(addr)
   609  	if so == nil {
   610  		return nil
   611  	}
   612  	it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
   613  
   614  	for it.Next() {
   615  		key := common.BytesToHash(db.trie.GetKey(it.Key))
   616  		if value, dirty := so.dirtyStorage[key]; dirty {
   617  			if !cb(key, value) {
   618  				return nil
   619  			}
   620  			continue
   621  		}
   622  
   623  		if len(it.Value) > 0 {
   624  			_, content, _, err := rlp.Split(it.Value)
   625  			if err != nil {
   626  				return err
   627  			}
   628  			if !cb(key, common.BytesToHash(content)) {
   629  				return nil
   630  			}
   631  		}
   632  	}
   633  	return nil
   634  }
   635  
   636  // Copy creates a deep, independent copy of the state.
   637  // Snapshots of the copied state cannot be applied to the copy.
   638  func (s *StateDB) Copy() *StateDB {
   639  	// Copy all the basic fields, initialize the memory ones
   640  	state := &StateDB{
   641  		db:                  s.db,
   642  		trie:                s.db.CopyTrie(s.trie),
   643  		stateObjects:        make(map[common.Address]*stateObject, len(s.journal.dirties)),
   644  		stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)),
   645  		stateObjectsDirty:   make(map[common.Address]struct{}, len(s.journal.dirties)),
   646  		refund:              s.refund,
   647  		logs:                make(map[common.Hash][]*types.Log, len(s.logs)),
   648  		logSize:             s.logSize,
   649  		preimages:           make(map[common.Hash][]byte, len(s.preimages)),
   650  		journal:             newJournal(),
   651  	}
   652  	// Copy the dirty states, logs, and preimages
   653  	for addr := range s.journal.dirties {
   654  		// As documented [here](https://github.com/zhiqiangxu/go-ethereum/pull/16485#issuecomment-380438527),
   655  		// and in the Finalise-method, there is a case where an object is in the journal but not
   656  		// in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
   657  		// nil
   658  		if object, exist := s.stateObjects[addr]; exist {
   659  			// Even though the original object is dirty, we are not copying the journal,
   660  			// so we need to make sure that anyside effect the journal would have caused
   661  			// during a commit (or similar op) is already applied to the copy.
   662  			state.stateObjects[addr] = object.deepCopy(state)
   663  
   664  			state.stateObjectsDirty[addr] = struct{}{}   // Mark the copy dirty to force internal (code/state) commits
   665  			state.stateObjectsPending[addr] = struct{}{} // Mark the copy pending to force external (account) commits
   666  		}
   667  	}
   668  	// Above, we don't copy the actual journal. This means that if the copy is copied, the
   669  	// loop above will be a no-op, since the copy's journal is empty.
   670  	// Thus, here we iterate over stateObjects, to enable copies of copies
   671  	for addr := range s.stateObjectsPending {
   672  		if _, exist := state.stateObjects[addr]; !exist {
   673  			state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
   674  		}
   675  		state.stateObjectsPending[addr] = struct{}{}
   676  	}
   677  	for addr := range s.stateObjectsDirty {
   678  		if _, exist := state.stateObjects[addr]; !exist {
   679  			state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
   680  		}
   681  		state.stateObjectsDirty[addr] = struct{}{}
   682  	}
   683  	for hash, logs := range s.logs {
   684  		cpy := make([]*types.Log, len(logs))
   685  		for i, l := range logs {
   686  			cpy[i] = new(types.Log)
   687  			*cpy[i] = *l
   688  		}
   689  		state.logs[hash] = cpy
   690  	}
   691  	for hash, preimage := range s.preimages {
   692  		state.preimages[hash] = preimage
   693  	}
   694  	return state
   695  }
   696  
   697  // Snapshot returns an identifier for the current revision of the state.
   698  func (s *StateDB) Snapshot() int {
   699  	id := s.nextRevisionId
   700  	s.nextRevisionId++
   701  	s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()})
   702  	return id
   703  }
   704  
   705  // RevertToSnapshot reverts all state changes made since the given revision.
   706  func (s *StateDB) RevertToSnapshot(revid int) {
   707  	// Find the snapshot in the stack of valid snapshots.
   708  	idx := sort.Search(len(s.validRevisions), func(i int) bool {
   709  		return s.validRevisions[i].id >= revid
   710  	})
   711  	if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid {
   712  		panic(fmt.Errorf("revision id %v cannot be reverted", revid))
   713  	}
   714  	snapshot := s.validRevisions[idx].journalIndex
   715  
   716  	// Replay the journal to undo changes and remove invalidated snapshots
   717  	s.journal.revert(s, snapshot)
   718  	s.validRevisions = s.validRevisions[:idx]
   719  }
   720  
   721  // GetRefund returns the current value of the refund counter.
   722  func (s *StateDB) GetRefund() uint64 {
   723  	return s.refund
   724  }
   725  
   726  // Finalise finalises the state by removing the s destructed objects and clears
   727  // the journal as well as the refunds. Finalise, however, will not push any updates
   728  // into the tries just yet. Only IntermediateRoot or Commit will do that.
   729  func (s *StateDB) Finalise(deleteEmptyObjects bool) {
   730  	for addr := range s.journal.dirties {
   731  		obj, exist := s.stateObjects[addr]
   732  		if !exist {
   733  			// ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
   734  			// That tx goes out of gas, and although the notion of 'touched' does not exist there, the
   735  			// touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
   736  			// it will persist in the journal even though the journal is reverted. In this special circumstance,
   737  			// it may exist in `s.journal.dirties` but not in `s.stateObjects`.
   738  			// Thus, we can safely ignore it here
   739  			continue
   740  		}
   741  		if obj.suicided || (deleteEmptyObjects && obj.empty()) {
   742  			obj.deleted = true
   743  
   744  			// If state snapshotting is active, also mark the destruction there.
   745  			// Note, we can't do this only at the end of a block because multiple
   746  			// transactions within the same block might self destruct and then
   747  			// ressurrect an account; but the snapshotter needs both events.
   748  			if s.snap != nil {
   749  				s.snapDestructs[obj.addrHash] = struct{}{} // We need to maintain account deletions explicitly (will remain set indefinitely)
   750  				delete(s.snapAccounts, obj.addrHash)       // Clear out any previously updated account data (may be recreated via a ressurrect)
   751  				delete(s.snapStorage, obj.addrHash)        // Clear out any previously updated storage data (may be recreated via a ressurrect)
   752  			}
   753  		} else {
   754  			obj.finalise()
   755  		}
   756  		s.stateObjectsPending[addr] = struct{}{}
   757  		s.stateObjectsDirty[addr] = struct{}{}
   758  	}
   759  	// Invalidate journal because reverting across transactions is not allowed.
   760  	s.clearJournalAndRefund()
   761  }
   762  
   763  // IntermediateRoot computes the current root hash of the state trie.
   764  // It is called in between transactions to get the root hash that
   765  // goes into transaction receipts.
   766  func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
   767  	// Finalise all the dirty storage states and write them into the tries
   768  	s.Finalise(deleteEmptyObjects)
   769  
   770  	for addr := range s.stateObjectsPending {
   771  		obj := s.stateObjects[addr]
   772  		if obj.deleted {
   773  			s.deleteStateObject(obj)
   774  		} else {
   775  			obj.updateRoot(s.db)
   776  			s.updateStateObject(obj)
   777  		}
   778  	}
   779  	if len(s.stateObjectsPending) > 0 {
   780  		s.stateObjectsPending = make(map[common.Address]struct{})
   781  	}
   782  	// Track the amount of time wasted on hashing the account trie
   783  	if metrics.EnabledExpensive {
   784  		defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now())
   785  	}
   786  	return s.trie.Hash()
   787  }
   788  
   789  // Prepare sets the current transaction hash and index and block hash which is
   790  // used when the EVM emits new state logs.
   791  func (s *StateDB) Prepare(thash, bhash common.Hash, ti int) {
   792  	s.thash = thash
   793  	s.bhash = bhash
   794  	s.txIndex = ti
   795  }
   796  
   797  func (s *StateDB) clearJournalAndRefund() {
   798  	if len(s.journal.entries) > 0 {
   799  		s.journal = newJournal()
   800  		s.refund = 0
   801  	}
   802  	s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entires
   803  }
   804  
   805  // Commit writes the state to the underlying in-memory trie database.
   806  func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) {
   807  	if s.dbErr != nil {
   808  		return common.Hash{}, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr)
   809  	}
   810  	// Finalize any pending changes and merge everything into the tries
   811  	s.IntermediateRoot(deleteEmptyObjects)
   812  
   813  	// Commit objects to the trie, measuring the elapsed time
   814  	for addr := range s.stateObjectsDirty {
   815  		if obj := s.stateObjects[addr]; !obj.deleted {
   816  			// Write any contract code associated with the state object
   817  			if obj.code != nil && obj.dirtyCode {
   818  				s.db.TrieDB().InsertBlob(common.BytesToHash(obj.CodeHash()), obj.code)
   819  				obj.dirtyCode = false
   820  			}
   821  			// Write any storage changes in the state object to its storage trie
   822  			if err := obj.CommitTrie(s.db); err != nil {
   823  				return common.Hash{}, err
   824  			}
   825  		}
   826  	}
   827  	if len(s.stateObjectsDirty) > 0 {
   828  		s.stateObjectsDirty = make(map[common.Address]struct{})
   829  	}
   830  	// Write the account trie changes, measuing the amount of wasted time
   831  	var start time.Time
   832  	if metrics.EnabledExpensive {
   833  		start = time.Now()
   834  	}
   835  	// The onleaf func is called _serially_, so we can reuse the same account
   836  	// for unmarshalling every time.
   837  	var account Account
   838  	root, err := s.trie.Commit(func(leaf []byte, parent common.Hash) error {
   839  		if err := rlp.DecodeBytes(leaf, &account); err != nil {
   840  			return nil
   841  		}
   842  		if account.Root != emptyRoot {
   843  			s.db.TrieDB().Reference(account.Root, parent)
   844  		}
   845  		code := common.BytesToHash(account.CodeHash)
   846  		if code != emptyCode {
   847  			s.db.TrieDB().Reference(code, parent)
   848  		}
   849  		return nil
   850  	})
   851  	if metrics.EnabledExpensive {
   852  		s.AccountCommits += time.Since(start)
   853  	}
   854  	// If snapshotting is enabled, update the snapshot tree with this new version
   855  	if s.snap != nil {
   856  		if metrics.EnabledExpensive {
   857  			defer func(start time.Time) { s.SnapshotCommits += time.Since(start) }(time.Now())
   858  		}
   859  		// Only update if there's a state transition (skip empty Clique blocks)
   860  		if parent := s.snap.Root(); parent != root {
   861  			if err := s.snaps.Update(root, parent, s.snapDestructs, s.snapAccounts, s.snapStorage); err != nil {
   862  				log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err)
   863  			}
   864  			if err := s.snaps.Cap(root, 127); err != nil { // Persistent layer is 128th, the last available trie
   865  				log.Warn("Failed to cap snapshot tree", "root", root, "layers", 127, "err", err)
   866  			}
   867  		}
   868  		s.snap, s.snapDestructs, s.snapAccounts, s.snapStorage = nil, nil, nil, nil
   869  	}
   870  	return root, err
   871  }