github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/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/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/core/rawdb"
    29  	"github.com/ethereum/go-ethereum/core/state/snapshot"
    30  	"github.com/ethereum/go-ethereum/core/types"
    31  	"github.com/ethereum/go-ethereum/crypto"
    32  	"github.com/ethereum/go-ethereum/log"
    33  	"github.com/ethereum/go-ethereum/metrics"
    34  	"github.com/ethereum/go-ethereum/rlp"
    35  	"github.com/ethereum/go-ethereum/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  	prefetcher *triePrefetcher
    67  	trie       Trie
    68  	hasher     crypto.KeccakState
    69  
    70  	// originalRoot is the pre-state root, before any changes were made.
    71  	// It will be updated when the Commit is called.
    72  	originalRoot common.Hash
    73  
    74  	snaps         *snapshot.Tree
    75  	snap          snapshot.Snapshot
    76  	snapDestructs map[common.Hash]struct{}
    77  	snapAccounts  map[common.Hash][]byte
    78  	snapStorage   map[common.Hash]map[common.Hash][]byte
    79  
    80  	// This map holds 'live' objects, which will get modified while processing a state transition.
    81  	stateObjects        map[common.Address]*stateObject
    82  	stateObjectsPending map[common.Address]struct{} // State objects finalized but not yet written to the trie
    83  	stateObjectsDirty   map[common.Address]struct{} // State objects modified in the current execution
    84  
    85  	// DB error.
    86  	// State objects are used by the consensus core and VM which are
    87  	// unable to deal with database-level errors. Any error that occurs
    88  	// during a database read is memoized here and will eventually be returned
    89  	// by StateDB.Commit.
    90  	dbErr error
    91  
    92  	// The refund counter, also used by state transitioning.
    93  	refund uint64
    94  
    95  	thash   common.Hash
    96  	txIndex int
    97  	logs    map[common.Hash][]*types.Log
    98  	logSize uint
    99  
   100  	preimages map[common.Hash][]byte
   101  
   102  	// Per-transaction access list
   103  	accessList *accessList
   104  
   105  	// Journal of state modifications. This is the backbone of
   106  	// Snapshot and RevertToSnapshot.
   107  	journal        *journal
   108  	validRevisions []revision
   109  	nextRevisionId int
   110  
   111  	// Measurements gathered during execution for debugging purposes
   112  	AccountReads         time.Duration
   113  	AccountHashes        time.Duration
   114  	AccountUpdates       time.Duration
   115  	AccountCommits       time.Duration
   116  	StorageReads         time.Duration
   117  	StorageHashes        time.Duration
   118  	StorageUpdates       time.Duration
   119  	StorageCommits       time.Duration
   120  	SnapshotAccountReads time.Duration
   121  	SnapshotStorageReads time.Duration
   122  	SnapshotCommits      time.Duration
   123  	TrieDBCommits        time.Duration
   124  
   125  	AccountUpdated int
   126  	StorageUpdated int
   127  	AccountDeleted int
   128  	StorageDeleted int
   129  }
   130  
   131  // New creates a new state from a given trie.
   132  func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) {
   133  	tr, err := db.OpenTrie(root)
   134  	if err != nil {
   135  		return nil, err
   136  	}
   137  	sdb := &StateDB{
   138  		db:                  db,
   139  		trie:                tr,
   140  		originalRoot:        root,
   141  		snaps:               snaps,
   142  		stateObjects:        make(map[common.Address]*stateObject),
   143  		stateObjectsPending: make(map[common.Address]struct{}),
   144  		stateObjectsDirty:   make(map[common.Address]struct{}),
   145  		logs:                make(map[common.Hash][]*types.Log),
   146  		preimages:           make(map[common.Hash][]byte),
   147  		journal:             newJournal(),
   148  		accessList:          newAccessList(),
   149  		hasher:              crypto.NewKeccakState(),
   150  	}
   151  	if sdb.snaps != nil {
   152  		if sdb.snap = sdb.snaps.Snapshot(root); sdb.snap != nil {
   153  			sdb.snapDestructs = make(map[common.Hash]struct{})
   154  			sdb.snapAccounts = make(map[common.Hash][]byte)
   155  			sdb.snapStorage = make(map[common.Hash]map[common.Hash][]byte)
   156  		}
   157  	}
   158  	return sdb, nil
   159  }
   160  
   161  // StartPrefetcher initializes a new trie prefetcher to pull in nodes from the
   162  // state trie concurrently while the state is mutated so that when we reach the
   163  // commit phase, most of the needed data is already hot.
   164  func (s *StateDB) StartPrefetcher(namespace string) {
   165  	if s.prefetcher != nil {
   166  		s.prefetcher.close()
   167  		s.prefetcher = nil
   168  	}
   169  	if s.snap != nil {
   170  		s.prefetcher = newTriePrefetcher(s.db, s.originalRoot, namespace)
   171  	}
   172  }
   173  
   174  // StopPrefetcher terminates a running prefetcher and reports any leftover stats
   175  // from the gathered metrics.
   176  func (s *StateDB) StopPrefetcher() {
   177  	if s.prefetcher != nil {
   178  		s.prefetcher.close()
   179  		s.prefetcher = nil
   180  	}
   181  }
   182  
   183  // setError remembers the first non-nil error it is called with.
   184  func (s *StateDB) setError(err error) {
   185  	if s.dbErr == nil {
   186  		s.dbErr = err
   187  	}
   188  }
   189  
   190  func (s *StateDB) Error() error {
   191  	return s.dbErr
   192  }
   193  
   194  func (s *StateDB) AddLog(log *types.Log) {
   195  	s.journal.append(addLogChange{txhash: s.thash})
   196  
   197  	log.TxHash = s.thash
   198  	log.TxIndex = uint(s.txIndex)
   199  	log.Index = s.logSize
   200  	s.logs[s.thash] = append(s.logs[s.thash], log)
   201  	s.logSize++
   202  }
   203  
   204  func (s *StateDB) GetLogs(hash common.Hash, blockHash common.Hash) []*types.Log {
   205  	logs := s.logs[hash]
   206  	for _, l := range logs {
   207  		l.BlockHash = blockHash
   208  	}
   209  	return logs
   210  }
   211  
   212  func (s *StateDB) Logs() []*types.Log {
   213  	var logs []*types.Log
   214  	for _, lgs := range s.logs {
   215  		logs = append(logs, lgs...)
   216  	}
   217  	return logs
   218  }
   219  
   220  // AddPreimage records a SHA3 preimage seen by the VM.
   221  func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
   222  	if _, ok := s.preimages[hash]; !ok {
   223  		s.journal.append(addPreimageChange{hash: hash})
   224  		pi := make([]byte, len(preimage))
   225  		copy(pi, preimage)
   226  		s.preimages[hash] = pi
   227  	}
   228  }
   229  
   230  // Preimages returns a list of SHA3 preimages that have been submitted.
   231  func (s *StateDB) Preimages() map[common.Hash][]byte {
   232  	return s.preimages
   233  }
   234  
   235  // AddRefund adds gas to the refund counter
   236  func (s *StateDB) AddRefund(gas uint64) {
   237  	s.journal.append(refundChange{prev: s.refund})
   238  	s.refund += gas
   239  }
   240  
   241  // SubRefund removes gas from the refund counter.
   242  // This method will panic if the refund counter goes below zero
   243  func (s *StateDB) SubRefund(gas uint64) {
   244  	s.journal.append(refundChange{prev: s.refund})
   245  	if gas > s.refund {
   246  		panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund))
   247  	}
   248  	s.refund -= gas
   249  }
   250  
   251  // Exist reports whether the given account address exists in the state.
   252  // Notably this also returns true for suicided accounts.
   253  func (s *StateDB) Exist(addr common.Address) bool {
   254  	return s.getStateObject(addr) != nil
   255  }
   256  
   257  // Empty returns whether the state object is either non-existent
   258  // or empty according to the EIP161 specification (balance = nonce = code = 0)
   259  func (s *StateDB) Empty(addr common.Address) bool {
   260  	so := s.getStateObject(addr)
   261  	return so == nil || so.empty()
   262  }
   263  
   264  // GetBalance retrieves the balance from the given address or 0 if object not found
   265  func (s *StateDB) GetBalance(addr common.Address) *big.Int {
   266  	stateObject := s.getStateObject(addr)
   267  	if stateObject != nil {
   268  		return stateObject.Balance()
   269  	}
   270  	return common.Big0
   271  }
   272  
   273  func (s *StateDB) GetNonce(addr common.Address) uint64 {
   274  	stateObject := s.getStateObject(addr)
   275  	if stateObject != nil {
   276  		return stateObject.Nonce()
   277  	}
   278  
   279  	return 0
   280  }
   281  
   282  // TxIndex returns the current transaction index set by Prepare.
   283  func (s *StateDB) TxIndex() int {
   284  	return s.txIndex
   285  }
   286  
   287  func (s *StateDB) GetCode(addr common.Address) []byte {
   288  	stateObject := s.getStateObject(addr)
   289  	if stateObject != nil {
   290  		return stateObject.Code(s.db)
   291  	}
   292  	return nil
   293  }
   294  
   295  func (s *StateDB) GetCodeSize(addr common.Address) int {
   296  	stateObject := s.getStateObject(addr)
   297  	if stateObject != nil {
   298  		return stateObject.CodeSize(s.db)
   299  	}
   300  	return 0
   301  }
   302  
   303  func (s *StateDB) GetCodeHash(addr common.Address) common.Hash {
   304  	stateObject := s.getStateObject(addr)
   305  	if stateObject == nil {
   306  		return common.Hash{}
   307  	}
   308  	return common.BytesToHash(stateObject.CodeHash())
   309  }
   310  
   311  // GetState retrieves a value from the given account's storage trie.
   312  func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash {
   313  	stateObject := s.getStateObject(addr)
   314  	if stateObject != nil {
   315  		return stateObject.GetState(s.db, hash)
   316  	}
   317  	return common.Hash{}
   318  }
   319  
   320  // GetProof returns the Merkle proof for a given account.
   321  func (s *StateDB) GetProof(addr common.Address) ([][]byte, error) {
   322  	return s.GetProofByHash(crypto.Keccak256Hash(addr.Bytes()))
   323  }
   324  
   325  // GetProofByHash returns the Merkle proof for a given account.
   326  func (s *StateDB) GetProofByHash(addrHash common.Hash) ([][]byte, error) {
   327  	var proof proofList
   328  	err := s.trie.Prove(addrHash[:], 0, &proof)
   329  	return proof, err
   330  }
   331  
   332  // GetStorageProof returns the Merkle proof for given storage slot.
   333  func (s *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
   334  	var proof proofList
   335  	trie := s.StorageTrie(a)
   336  	if trie == nil {
   337  		return proof, errors.New("storage trie for requested address does not exist")
   338  	}
   339  	err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof)
   340  	return proof, err
   341  }
   342  
   343  // GetCommittedState retrieves a value from the given account's committed storage trie.
   344  func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
   345  	stateObject := s.getStateObject(addr)
   346  	if stateObject != nil {
   347  		return stateObject.GetCommittedState(s.db, hash)
   348  	}
   349  	return common.Hash{}
   350  }
   351  
   352  // Database retrieves the low level database supporting the lower level trie ops.
   353  func (s *StateDB) Database() Database {
   354  	return s.db
   355  }
   356  
   357  // StorageTrie returns the storage trie of an account.
   358  // The return value is a copy and is nil for non-existent accounts.
   359  func (s *StateDB) StorageTrie(addr common.Address) Trie {
   360  	stateObject := s.getStateObject(addr)
   361  	if stateObject == nil {
   362  		return nil
   363  	}
   364  	cpy := stateObject.deepCopy(s)
   365  	cpy.updateTrie(s.db)
   366  	return cpy.getTrie(s.db)
   367  }
   368  
   369  func (s *StateDB) HasSuicided(addr common.Address) bool {
   370  	stateObject := s.getStateObject(addr)
   371  	if stateObject != nil {
   372  		return stateObject.suicided
   373  	}
   374  	return false
   375  }
   376  
   377  /*
   378   * SETTERS
   379   */
   380  
   381  // AddBalance adds amount to the account associated with addr.
   382  func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) {
   383  	stateObject := s.GetOrNewStateObject(addr)
   384  	if stateObject != nil {
   385  		stateObject.AddBalance(amount)
   386  	}
   387  }
   388  
   389  // SubBalance subtracts amount from the account associated with addr.
   390  func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) {
   391  	stateObject := s.GetOrNewStateObject(addr)
   392  	if stateObject != nil {
   393  		stateObject.SubBalance(amount)
   394  	}
   395  }
   396  
   397  func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) {
   398  	stateObject := s.GetOrNewStateObject(addr)
   399  	if stateObject != nil {
   400  		stateObject.SetBalance(amount)
   401  	}
   402  }
   403  
   404  func (s *StateDB) SetNonce(addr common.Address, nonce uint64) {
   405  	stateObject := s.GetOrNewStateObject(addr)
   406  	if stateObject != nil {
   407  		stateObject.SetNonce(nonce)
   408  	}
   409  }
   410  
   411  func (s *StateDB) SetCode(addr common.Address, code []byte) {
   412  	stateObject := s.GetOrNewStateObject(addr)
   413  	if stateObject != nil {
   414  		stateObject.SetCode(crypto.Keccak256Hash(code), code)
   415  	}
   416  }
   417  
   418  func (s *StateDB) SetState(addr common.Address, key, value common.Hash) {
   419  	stateObject := s.GetOrNewStateObject(addr)
   420  	if stateObject != nil {
   421  		stateObject.SetState(s.db, key, value)
   422  	}
   423  }
   424  
   425  // SetStorage replaces the entire storage for the specified account with given
   426  // storage. This function should only be used for debugging.
   427  func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) {
   428  	stateObject := s.GetOrNewStateObject(addr)
   429  	if stateObject != nil {
   430  		stateObject.SetStorage(storage)
   431  	}
   432  }
   433  
   434  // Suicide marks the given account as suicided.
   435  // This clears the account balance.
   436  //
   437  // The account's state object is still available until the state is committed,
   438  // getStateObject will return a non-nil account after Suicide.
   439  func (s *StateDB) Suicide(addr common.Address) bool {
   440  	stateObject := s.getStateObject(addr)
   441  	if stateObject == nil {
   442  		return false
   443  	}
   444  	s.journal.append(suicideChange{
   445  		account:     &addr,
   446  		prev:        stateObject.suicided,
   447  		prevbalance: new(big.Int).Set(stateObject.Balance()),
   448  	})
   449  	stateObject.markSuicided()
   450  	stateObject.data.Balance = new(big.Int)
   451  
   452  	return true
   453  }
   454  
   455  //
   456  // Setting, updating & deleting state object methods.
   457  //
   458  
   459  // updateStateObject writes the given object to the trie.
   460  func (s *StateDB) updateStateObject(obj *stateObject) {
   461  	// Track the amount of time wasted on updating the account from the trie
   462  	if metrics.EnabledExpensive {
   463  		defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
   464  	}
   465  	// Encode the account and update the account trie
   466  	addr := obj.Address()
   467  	if err := s.trie.TryUpdateAccount(addr[:], &obj.data); err != nil {
   468  		s.setError(fmt.Errorf("updateStateObject (%x) error: %v", addr[:], err))
   469  	}
   470  
   471  	// If state snapshotting is active, cache the data til commit. Note, this
   472  	// update mechanism is not symmetric to the deletion, because whereas it is
   473  	// enough to track account updates at commit time, deletions need tracking
   474  	// at transaction boundary level to ensure we capture state clearing.
   475  	if s.snap != nil {
   476  		s.snapAccounts[obj.addrHash] = snapshot.SlimAccountRLP(obj.data.Nonce, obj.data.Balance, obj.data.Root, obj.data.CodeHash)
   477  	}
   478  }
   479  
   480  // deleteStateObject removes the given object from the state trie.
   481  func (s *StateDB) deleteStateObject(obj *stateObject) {
   482  	// Track the amount of time wasted on deleting the account from the trie
   483  	if metrics.EnabledExpensive {
   484  		defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
   485  	}
   486  	// Delete the account from the trie
   487  	addr := obj.Address()
   488  	if err := s.trie.TryDeleteAccount(addr[:]); err != nil {
   489  		s.setError(fmt.Errorf("deleteStateObject (%x) error: %v", addr[:], err))
   490  	}
   491  }
   492  
   493  // getStateObject retrieves a state object given by the address, returning nil if
   494  // the object is not found or was deleted in this execution context. If you need
   495  // to differentiate between non-existent/just-deleted, use getDeletedStateObject.
   496  func (s *StateDB) getStateObject(addr common.Address) *stateObject {
   497  	if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted {
   498  		return obj
   499  	}
   500  	return nil
   501  }
   502  
   503  // getDeletedStateObject is similar to getStateObject, but instead of returning
   504  // nil for a deleted state object, it returns the actual object with the deleted
   505  // flag set. This is needed by the state journal to revert to the correct s-
   506  // destructed object instead of wiping all knowledge about the state object.
   507  func (s *StateDB) getDeletedStateObject(addr common.Address) *stateObject {
   508  	// Prefer live objects if any is available
   509  	if obj := s.stateObjects[addr]; obj != nil {
   510  		return obj
   511  	}
   512  	// If no live objects are available, attempt to use snapshots
   513  	var data *types.StateAccount
   514  	if s.snap != nil {
   515  		start := time.Now()
   516  		acc, err := s.snap.Account(crypto.HashData(s.hasher, addr.Bytes()))
   517  		if metrics.EnabledExpensive {
   518  			s.SnapshotAccountReads += time.Since(start)
   519  		}
   520  		if err == nil {
   521  			if acc == nil {
   522  				return nil
   523  			}
   524  			data = &types.StateAccount{
   525  				Nonce:    acc.Nonce,
   526  				Balance:  acc.Balance,
   527  				CodeHash: acc.CodeHash,
   528  				Root:     common.BytesToHash(acc.Root),
   529  			}
   530  			if len(data.CodeHash) == 0 {
   531  				data.CodeHash = emptyCodeHash
   532  			}
   533  			if data.Root == (common.Hash{}) {
   534  				data.Root = emptyRoot
   535  			}
   536  		}
   537  	}
   538  	// If snapshot unavailable or reading from it failed, load from the database
   539  	if data == nil {
   540  		start := time.Now()
   541  		var err error
   542  		data, err = s.trie.TryGetAccount(addr.Bytes())
   543  		if metrics.EnabledExpensive {
   544  			s.AccountReads += time.Since(start)
   545  		}
   546  		if err != nil {
   547  			s.setError(fmt.Errorf("getDeleteStateObject (%x) error: %w", addr.Bytes(), err))
   548  			return nil
   549  		}
   550  		if data == nil {
   551  			return nil
   552  		}
   553  	}
   554  	// Insert into the live set
   555  	obj := newObject(s, addr, *data)
   556  	s.setStateObject(obj)
   557  	return obj
   558  }
   559  
   560  func (s *StateDB) setStateObject(object *stateObject) {
   561  	s.stateObjects[object.Address()] = object
   562  }
   563  
   564  // GetOrNewStateObject retrieves a state object or create a new state object if nil.
   565  func (s *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
   566  	stateObject := s.getStateObject(addr)
   567  	if stateObject == nil {
   568  		stateObject, _ = s.createObject(addr)
   569  	}
   570  	return stateObject
   571  }
   572  
   573  // createObject creates a new state object. If there is an existing account with
   574  // the given address, it is overwritten and returned as the second return value.
   575  func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
   576  	prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that!
   577  
   578  	var prevdestruct bool
   579  	if s.snap != nil && prev != nil {
   580  		_, prevdestruct = s.snapDestructs[prev.addrHash]
   581  		if !prevdestruct {
   582  			s.snapDestructs[prev.addrHash] = struct{}{}
   583  		}
   584  	}
   585  	newobj = newObject(s, addr, types.StateAccount{})
   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  	if prev != nil && !prev.deleted {
   593  		return newobj, prev
   594  	}
   595  	return newobj, nil
   596  }
   597  
   598  // CreateAccount explicitly creates a state object. If a state object with the address
   599  // already exists the balance is carried over to the new account.
   600  //
   601  // CreateAccount is called during the EVM CREATE operation. The situation might arise that
   602  // a contract does the following:
   603  //
   604  //  1. sends funds to sha(account ++ (nonce + 1))
   605  //  2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
   606  //
   607  // Carrying over the balance ensures that Ether doesn't disappear.
   608  func (s *StateDB) CreateAccount(addr common.Address) {
   609  	newObj, prev := s.createObject(addr)
   610  	if prev != nil {
   611  		newObj.setBalance(prev.data.Balance)
   612  	}
   613  }
   614  
   615  func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {
   616  	so := db.getStateObject(addr)
   617  	if so == nil {
   618  		return nil
   619  	}
   620  	it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
   621  
   622  	for it.Next() {
   623  		key := common.BytesToHash(db.trie.GetKey(it.Key))
   624  		if value, dirty := so.dirtyStorage[key]; dirty {
   625  			if !cb(key, value) {
   626  				return nil
   627  			}
   628  			continue
   629  		}
   630  
   631  		if len(it.Value) > 0 {
   632  			_, content, _, err := rlp.Split(it.Value)
   633  			if err != nil {
   634  				return err
   635  			}
   636  			if !cb(key, common.BytesToHash(content)) {
   637  				return nil
   638  			}
   639  		}
   640  	}
   641  	return nil
   642  }
   643  
   644  // Copy creates a deep, independent copy of the state.
   645  // Snapshots of the copied state cannot be applied to the copy.
   646  func (s *StateDB) Copy() *StateDB {
   647  	// Copy all the basic fields, initialize the memory ones
   648  	state := &StateDB{
   649  		db:                  s.db,
   650  		trie:                s.db.CopyTrie(s.trie),
   651  		originalRoot:        s.originalRoot,
   652  		stateObjects:        make(map[common.Address]*stateObject, len(s.journal.dirties)),
   653  		stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)),
   654  		stateObjectsDirty:   make(map[common.Address]struct{}, len(s.journal.dirties)),
   655  		refund:              s.refund,
   656  		logs:                make(map[common.Hash][]*types.Log, len(s.logs)),
   657  		logSize:             s.logSize,
   658  		preimages:           make(map[common.Hash][]byte, len(s.preimages)),
   659  		journal:             newJournal(),
   660  		hasher:              crypto.NewKeccakState(),
   661  	}
   662  	// Copy the dirty states, logs, and preimages
   663  	for addr := range s.journal.dirties {
   664  		// As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527),
   665  		// and in the Finalise-method, there is a case where an object is in the journal but not
   666  		// in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
   667  		// nil
   668  		if object, exist := s.stateObjects[addr]; exist {
   669  			// Even though the original object is dirty, we are not copying the journal,
   670  			// so we need to make sure that anyside effect the journal would have caused
   671  			// during a commit (or similar op) is already applied to the copy.
   672  			state.stateObjects[addr] = object.deepCopy(state)
   673  
   674  			state.stateObjectsDirty[addr] = struct{}{}   // Mark the copy dirty to force internal (code/state) commits
   675  			state.stateObjectsPending[addr] = struct{}{} // Mark the copy pending to force external (account) commits
   676  		}
   677  	}
   678  	// Above, we don't copy the actual journal. This means that if the copy is copied, the
   679  	// loop above will be a no-op, since the copy's journal is empty.
   680  	// Thus, here we iterate over stateObjects, to enable copies of copies
   681  	for addr := range s.stateObjectsPending {
   682  		if _, exist := state.stateObjects[addr]; !exist {
   683  			state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
   684  		}
   685  		state.stateObjectsPending[addr] = struct{}{}
   686  	}
   687  	for addr := range s.stateObjectsDirty {
   688  		if _, exist := state.stateObjects[addr]; !exist {
   689  			state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
   690  		}
   691  		state.stateObjectsDirty[addr] = struct{}{}
   692  	}
   693  	for hash, logs := range s.logs {
   694  		cpy := make([]*types.Log, len(logs))
   695  		for i, l := range logs {
   696  			cpy[i] = new(types.Log)
   697  			*cpy[i] = *l
   698  		}
   699  		state.logs[hash] = cpy
   700  	}
   701  	for hash, preimage := range s.preimages {
   702  		state.preimages[hash] = preimage
   703  	}
   704  	// Do we need to copy the access list? In practice: No. At the start of a
   705  	// transaction, the access list is empty. In practice, we only ever copy state
   706  	// _between_ transactions/blocks, never in the middle of a transaction.
   707  	// However, it doesn't cost us much to copy an empty list, so we do it anyway
   708  	// to not blow up if we ever decide copy it in the middle of a transaction
   709  	state.accessList = s.accessList.Copy()
   710  
   711  	// If there's a prefetcher running, make an inactive copy of it that can
   712  	// only access data but does not actively preload (since the user will not
   713  	// know that they need to explicitly terminate an active copy).
   714  	if s.prefetcher != nil {
   715  		state.prefetcher = s.prefetcher.copy()
   716  	}
   717  	if s.snaps != nil {
   718  		// In order for the miner to be able to use and make additions
   719  		// to the snapshot tree, we need to copy that aswell.
   720  		// Otherwise, any block mined by ourselves will cause gaps in the tree,
   721  		// and force the miner to operate trie-backed only
   722  		state.snaps = s.snaps
   723  		state.snap = s.snap
   724  		// deep copy needed
   725  		state.snapDestructs = make(map[common.Hash]struct{})
   726  		for k, v := range s.snapDestructs {
   727  			state.snapDestructs[k] = v
   728  		}
   729  		state.snapAccounts = make(map[common.Hash][]byte)
   730  		for k, v := range s.snapAccounts {
   731  			state.snapAccounts[k] = v
   732  		}
   733  		state.snapStorage = make(map[common.Hash]map[common.Hash][]byte)
   734  		for k, v := range s.snapStorage {
   735  			temp := make(map[common.Hash][]byte)
   736  			for kk, vv := range v {
   737  				temp[kk] = vv
   738  			}
   739  			state.snapStorage[k] = temp
   740  		}
   741  	}
   742  	return state
   743  }
   744  
   745  // Snapshot returns an identifier for the current revision of the state.
   746  func (s *StateDB) Snapshot() int {
   747  	id := s.nextRevisionId
   748  	s.nextRevisionId++
   749  	s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()})
   750  	return id
   751  }
   752  
   753  // RevertToSnapshot reverts all state changes made since the given revision.
   754  func (s *StateDB) RevertToSnapshot(revid int) {
   755  	// Find the snapshot in the stack of valid snapshots.
   756  	idx := sort.Search(len(s.validRevisions), func(i int) bool {
   757  		return s.validRevisions[i].id >= revid
   758  	})
   759  	if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid {
   760  		panic(fmt.Errorf("revision id %v cannot be reverted", revid))
   761  	}
   762  	snapshot := s.validRevisions[idx].journalIndex
   763  
   764  	// Replay the journal to undo changes and remove invalidated snapshots
   765  	s.journal.revert(s, snapshot)
   766  	s.validRevisions = s.validRevisions[:idx]
   767  }
   768  
   769  // GetRefund returns the current value of the refund counter.
   770  func (s *StateDB) GetRefund() uint64 {
   771  	return s.refund
   772  }
   773  
   774  // Finalise finalises the state by removing the destructed objects and clears
   775  // the journal as well as the refunds. Finalise, however, will not push any updates
   776  // into the tries just yet. Only IntermediateRoot or Commit will do that.
   777  func (s *StateDB) Finalise(deleteEmptyObjects bool) {
   778  	addressesToPrefetch := make([][]byte, 0, len(s.journal.dirties))
   779  	for addr := range s.journal.dirties {
   780  		obj, exist := s.stateObjects[addr]
   781  		if !exist {
   782  			// ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
   783  			// That tx goes out of gas, and although the notion of 'touched' does not exist there, the
   784  			// touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
   785  			// it will persist in the journal even though the journal is reverted. In this special circumstance,
   786  			// it may exist in `s.journal.dirties` but not in `s.stateObjects`.
   787  			// Thus, we can safely ignore it here
   788  			continue
   789  		}
   790  		if obj.suicided || (deleteEmptyObjects && obj.empty()) {
   791  			obj.deleted = true
   792  
   793  			// If state snapshotting is active, also mark the destruction there.
   794  			// Note, we can't do this only at the end of a block because multiple
   795  			// transactions within the same block might self destruct and then
   796  			// resurrect an account; but the snapshotter needs both events.
   797  			if s.snap != nil {
   798  				s.snapDestructs[obj.addrHash] = struct{}{} // We need to maintain account deletions explicitly (will remain set indefinitely)
   799  				delete(s.snapAccounts, obj.addrHash)       // Clear out any previously updated account data (may be recreated via a ressurrect)
   800  				delete(s.snapStorage, obj.addrHash)        // Clear out any previously updated storage data (may be recreated via a ressurrect)
   801  			}
   802  		} else {
   803  			obj.finalise(true) // Prefetch slots in the background
   804  		}
   805  		s.stateObjectsPending[addr] = struct{}{}
   806  		s.stateObjectsDirty[addr] = struct{}{}
   807  
   808  		// At this point, also ship the address off to the precacher. The precacher
   809  		// will start loading tries, and when the change is eventually committed,
   810  		// the commit-phase will be a lot faster
   811  		addressesToPrefetch = append(addressesToPrefetch, common.CopyBytes(addr[:])) // Copy needed for closure
   812  	}
   813  	if s.prefetcher != nil && len(addressesToPrefetch) > 0 {
   814  		s.prefetcher.prefetch(common.Hash{}, s.originalRoot, addressesToPrefetch)
   815  	}
   816  	// Invalidate journal because reverting across transactions is not allowed.
   817  	s.clearJournalAndRefund()
   818  }
   819  
   820  // IntermediateRoot computes the current root hash of the state trie.
   821  // It is called in between transactions to get the root hash that
   822  // goes into transaction receipts.
   823  func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
   824  	// Finalise all the dirty storage states and write them into the tries
   825  	s.Finalise(deleteEmptyObjects)
   826  
   827  	// If there was a trie prefetcher operating, it gets aborted and irrevocably
   828  	// modified after we start retrieving tries. Remove it from the statedb after
   829  	// this round of use.
   830  	//
   831  	// This is weird pre-byzantium since the first tx runs with a prefetcher and
   832  	// the remainder without, but pre-byzantium even the initial prefetcher is
   833  	// useless, so no sleep lost.
   834  	prefetcher := s.prefetcher
   835  	if s.prefetcher != nil {
   836  		defer func() {
   837  			s.prefetcher.close()
   838  			s.prefetcher = nil
   839  		}()
   840  	}
   841  	// Although naively it makes sense to retrieve the account trie and then do
   842  	// the contract storage and account updates sequentially, that short circuits
   843  	// the account prefetcher. Instead, let's process all the storage updates
   844  	// first, giving the account prefetches just a few more milliseconds of time
   845  	// to pull useful data from disk.
   846  	for addr := range s.stateObjectsPending {
   847  		if obj := s.stateObjects[addr]; !obj.deleted {
   848  			obj.updateRoot(s.db)
   849  		}
   850  	}
   851  	// Now we're about to start to write changes to the trie. The trie is so far
   852  	// _untouched_. We can check with the prefetcher, if it can give us a trie
   853  	// which has the same root, but also has some content loaded into it.
   854  	if prefetcher != nil {
   855  		if trie := prefetcher.trie(common.Hash{}, s.originalRoot); trie != nil {
   856  			s.trie = trie
   857  		}
   858  	}
   859  	usedAddrs := make([][]byte, 0, len(s.stateObjectsPending))
   860  	for addr := range s.stateObjectsPending {
   861  		if obj := s.stateObjects[addr]; obj.deleted {
   862  			s.deleteStateObject(obj)
   863  			s.AccountDeleted += 1
   864  		} else {
   865  			s.updateStateObject(obj)
   866  			s.AccountUpdated += 1
   867  		}
   868  		usedAddrs = append(usedAddrs, common.CopyBytes(addr[:])) // Copy needed for closure
   869  	}
   870  	if prefetcher != nil {
   871  		prefetcher.used(common.Hash{}, s.originalRoot, usedAddrs)
   872  	}
   873  	if len(s.stateObjectsPending) > 0 {
   874  		s.stateObjectsPending = make(map[common.Address]struct{})
   875  	}
   876  	// Track the amount of time wasted on hashing the account trie
   877  	if metrics.EnabledExpensive {
   878  		defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now())
   879  	}
   880  	return s.trie.Hash()
   881  }
   882  
   883  // Prepare sets the current transaction hash and index which are
   884  // used when the EVM emits new state logs.
   885  func (s *StateDB) Prepare(thash common.Hash, ti int) {
   886  	s.thash = thash
   887  	s.txIndex = ti
   888  }
   889  
   890  func (s *StateDB) clearJournalAndRefund() {
   891  	if len(s.journal.entries) > 0 {
   892  		s.journal = newJournal()
   893  		s.refund = 0
   894  	}
   895  	s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entries
   896  }
   897  
   898  // Commit writes the state to the underlying in-memory trie database.
   899  func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) {
   900  	if s.dbErr != nil {
   901  		return common.Hash{}, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr)
   902  	}
   903  	// Finalize any pending changes and merge everything into the tries
   904  	s.IntermediateRoot(deleteEmptyObjects)
   905  
   906  	// Commit objects to the trie, measuring the elapsed time
   907  	var (
   908  		accountTrieNodesUpdated int
   909  		accountTrieNodesDeleted int
   910  		storageTrieNodesUpdated int
   911  		storageTrieNodesDeleted int
   912  		nodes                   = trie.NewMergedNodeSet()
   913  	)
   914  	codeWriter := s.db.DiskDB().NewBatch()
   915  	for addr := range s.stateObjectsDirty {
   916  		if obj := s.stateObjects[addr]; !obj.deleted {
   917  			// Write any contract code associated with the state object
   918  			if obj.code != nil && obj.dirtyCode {
   919  				rawdb.WriteCode(codeWriter, common.BytesToHash(obj.CodeHash()), obj.code)
   920  				obj.dirtyCode = false
   921  			}
   922  			// Write any storage changes in the state object to its storage trie
   923  			set, err := obj.CommitTrie(s.db)
   924  			if err != nil {
   925  				return common.Hash{}, err
   926  			}
   927  			// Merge the dirty nodes of storage trie into global set
   928  			if set != nil {
   929  				if err := nodes.Merge(set); err != nil {
   930  					return common.Hash{}, err
   931  				}
   932  				updates, deleted := set.Size()
   933  				storageTrieNodesUpdated += updates
   934  				storageTrieNodesDeleted += deleted
   935  			}
   936  		}
   937  	}
   938  	if len(s.stateObjectsDirty) > 0 {
   939  		s.stateObjectsDirty = make(map[common.Address]struct{})
   940  	}
   941  	if codeWriter.ValueSize() > 0 {
   942  		if err := codeWriter.Write(); err != nil {
   943  			log.Crit("Failed to commit dirty codes", "error", err)
   944  		}
   945  	}
   946  	// Write the account trie changes, measuring the amount of wasted time
   947  	var start time.Time
   948  	if metrics.EnabledExpensive {
   949  		start = time.Now()
   950  	}
   951  	root, set, err := s.trie.Commit(true)
   952  	if err != nil {
   953  		return common.Hash{}, err
   954  	}
   955  	// Merge the dirty nodes of account trie into global set
   956  	if set != nil {
   957  		if err := nodes.Merge(set); err != nil {
   958  			return common.Hash{}, err
   959  		}
   960  		accountTrieNodesUpdated, accountTrieNodesDeleted = set.Size()
   961  	}
   962  	if metrics.EnabledExpensive {
   963  		s.AccountCommits += time.Since(start)
   964  
   965  		accountUpdatedMeter.Mark(int64(s.AccountUpdated))
   966  		storageUpdatedMeter.Mark(int64(s.StorageUpdated))
   967  		accountDeletedMeter.Mark(int64(s.AccountDeleted))
   968  		storageDeletedMeter.Mark(int64(s.StorageDeleted))
   969  		accountTrieUpdatedMeter.Mark(int64(accountTrieNodesUpdated))
   970  		accountTrieDeletedMeter.Mark(int64(accountTrieNodesDeleted))
   971  		storageTriesUpdatedMeter.Mark(int64(storageTrieNodesUpdated))
   972  		storageTriesDeletedMeter.Mark(int64(storageTrieNodesDeleted))
   973  		s.AccountUpdated, s.AccountDeleted = 0, 0
   974  		s.StorageUpdated, s.StorageDeleted = 0, 0
   975  	}
   976  	// If snapshotting is enabled, update the snapshot tree with this new version
   977  	if s.snap != nil {
   978  		start := time.Now()
   979  		// Only update if there's a state transition (skip empty Clique blocks)
   980  		if parent := s.snap.Root(); parent != root {
   981  			if err := s.snaps.Update(root, parent, s.snapDestructs, s.snapAccounts, s.snapStorage); err != nil {
   982  				log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err)
   983  			}
   984  			// Keep 128 diff layers in the memory, persistent layer is 129th.
   985  			// - head layer is paired with HEAD state
   986  			// - head-1 layer is paired with HEAD-1 state
   987  			// - head-127 layer(bottom-most diff layer) is paired with HEAD-127 state
   988  			if err := s.snaps.Cap(root, 128); err != nil {
   989  				log.Warn("Failed to cap snapshot tree", "root", root, "layers", 128, "err", err)
   990  			}
   991  		}
   992  		if metrics.EnabledExpensive {
   993  			s.SnapshotCommits += time.Since(start)
   994  		}
   995  		s.snap, s.snapDestructs, s.snapAccounts, s.snapStorage = nil, nil, nil, nil
   996  	}
   997  	if root == (common.Hash{}) {
   998  		root = emptyRoot
   999  	}
  1000  	origin := s.originalRoot
  1001  	if origin == (common.Hash{}) {
  1002  		origin = emptyRoot
  1003  	}
  1004  	if root != origin {
  1005  		start := time.Now()
  1006  		if err := s.db.TrieDB().Update(nodes); err != nil {
  1007  			return common.Hash{}, err
  1008  		}
  1009  		s.originalRoot = root
  1010  		if metrics.EnabledExpensive {
  1011  			s.TrieDBCommits += time.Since(start)
  1012  		}
  1013  	}
  1014  	return root, nil
  1015  }
  1016  
  1017  // PrepareAccessList handles the preparatory steps for executing a state transition with
  1018  // regards to both EIP-2929 and EIP-2930:
  1019  //
  1020  // - Add sender to access list (2929)
  1021  // - Add destination to access list (2929)
  1022  // - Add precompiles to access list (2929)
  1023  // - Add the contents of the optional tx access list (2930)
  1024  //
  1025  // This method should only be called if Berlin/2929+2930 is applicable at the current number.
  1026  func (s *StateDB) PrepareAccessList(sender common.Address, dst *common.Address, precompiles []common.Address, list types.AccessList) {
  1027  	// Clear out any leftover from previous executions
  1028  	s.accessList = newAccessList()
  1029  
  1030  	s.AddAddressToAccessList(sender)
  1031  	if dst != nil {
  1032  		s.AddAddressToAccessList(*dst)
  1033  		// If it's a create-tx, the destination will be added inside evm.create
  1034  	}
  1035  	for _, addr := range precompiles {
  1036  		s.AddAddressToAccessList(addr)
  1037  	}
  1038  	for _, el := range list {
  1039  		s.AddAddressToAccessList(el.Address)
  1040  		for _, key := range el.StorageKeys {
  1041  			s.AddSlotToAccessList(el.Address, key)
  1042  		}
  1043  	}
  1044  }
  1045  
  1046  // AddAddressToAccessList adds the given address to the access list
  1047  func (s *StateDB) AddAddressToAccessList(addr common.Address) {
  1048  	if s.accessList.AddAddress(addr) {
  1049  		s.journal.append(accessListAddAccountChange{&addr})
  1050  	}
  1051  }
  1052  
  1053  // AddSlotToAccessList adds the given (address, slot)-tuple to the access list
  1054  func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash) {
  1055  	addrMod, slotMod := s.accessList.AddSlot(addr, slot)
  1056  	if addrMod {
  1057  		// In practice, this should not happen, since there is no way to enter the
  1058  		// scope of 'address' without having the 'address' become already added
  1059  		// to the access list (via call-variant, create, etc).
  1060  		// Better safe than sorry, though
  1061  		s.journal.append(accessListAddAccountChange{&addr})
  1062  	}
  1063  	if slotMod {
  1064  		s.journal.append(accessListAddSlotChange{
  1065  			address: &addr,
  1066  			slot:    &slot,
  1067  		})
  1068  	}
  1069  }
  1070  
  1071  // AddressInAccessList returns true if the given address is in the access list.
  1072  func (s *StateDB) AddressInAccessList(addr common.Address) bool {
  1073  	return s.accessList.ContainsAddress(addr)
  1074  }
  1075  
  1076  // SlotInAccessList returns true if the given (address, slot)-tuple is in the access list.
  1077  func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool) {
  1078  	return s.accessList.Contains(addr, slot)
  1079  }