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

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package state provides a caching layer atop the Ethereum state trie.
    18  package state
    19  
    20  import (
    21  	"fmt"
    22  	"maps"
    23  	"math/big"
    24  	"slices"
    25  	"sort"
    26  	"sync"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/core/rawdb"
    31  	"github.com/ethereum/go-ethereum/core/state/snapshot"
    32  	"github.com/ethereum/go-ethereum/core/tracing"
    33  	"github.com/ethereum/go-ethereum/core/types"
    34  	"github.com/ethereum/go-ethereum/crypto"
    35  	"github.com/ethereum/go-ethereum/log"
    36  	"github.com/ethereum/go-ethereum/params"
    37  	"github.com/ethereum/go-ethereum/trie"
    38  	"github.com/ethereum/go-ethereum/trie/trienode"
    39  	"github.com/ethereum/go-ethereum/trie/triestate"
    40  	"github.com/holiman/uint256"
    41  	"golang.org/x/sync/errgroup"
    42  )
    43  
    44  // TriesInMemory represents the number of layers that are kept in RAM.
    45  const TriesInMemory = 128
    46  
    47  type revision struct {
    48  	id           int
    49  	journalIndex int
    50  }
    51  
    52  type mutationType int
    53  
    54  const (
    55  	update mutationType = iota
    56  	deletion
    57  )
    58  
    59  type mutation struct {
    60  	typ     mutationType
    61  	applied bool
    62  }
    63  
    64  func (m *mutation) copy() *mutation {
    65  	return &mutation{typ: m.typ, applied: m.applied}
    66  }
    67  
    68  func (m *mutation) isDelete() bool {
    69  	return m.typ == deletion
    70  }
    71  
    72  // StateDB structs within the ethereum protocol are used to store anything
    73  // within the merkle trie. StateDBs take care of caching and storing
    74  // nested states. It's the general query interface to retrieve:
    75  //
    76  // * Contracts
    77  // * Accounts
    78  //
    79  // Once the state is committed, tries cached in stateDB (including account
    80  // trie, storage tries) will no longer be functional. A new state instance
    81  // must be created with new root and updated database for accessing post-
    82  // commit states.
    83  type StateDB struct {
    84  	db         Database
    85  	prefetcher *triePrefetcher
    86  	trie       Trie
    87  	hasher     crypto.KeccakState
    88  	logger     *tracing.Hooks
    89  	snaps      *snapshot.Tree    // Nil if snapshot is not available
    90  	snap       snapshot.Snapshot // Nil if snapshot is not available
    91  
    92  	// originalRoot is the pre-state root, before any changes were made.
    93  	// It will be updated when the Commit is called.
    94  	originalRoot common.Hash
    95  
    96  	// These maps hold the state changes (including the corresponding
    97  	// original value) that occurred in this **block**.
    98  	accounts       map[common.Hash][]byte                    // The mutated accounts in 'slim RLP' encoding
    99  	storages       map[common.Hash]map[common.Hash][]byte    // The mutated slots in prefix-zero trimmed rlp format
   100  	accountsOrigin map[common.Address][]byte                 // The original value of mutated accounts in 'slim RLP' encoding
   101  	storagesOrigin map[common.Address]map[common.Hash][]byte // The original value of mutated slots in prefix-zero trimmed rlp format
   102  
   103  	// This map holds 'live' objects, which will get modified while
   104  	// processing a state transition.
   105  	stateObjects map[common.Address]*stateObject
   106  
   107  	// This map holds 'deleted' objects. An object with the same address
   108  	// might also occur in the 'stateObjects' map due to account
   109  	// resurrection. The account value is tracked as the original value
   110  	// before the transition. This map is populated at the transaction
   111  	// boundaries.
   112  	stateObjectsDestruct map[common.Address]*types.StateAccount
   113  
   114  	// This map tracks the account mutations that occurred during the
   115  	// transition. Uncommitted mutations belonging to the same account
   116  	// can be merged into a single one which is equivalent from database's
   117  	// perspective. This map is populated at the transaction boundaries.
   118  	mutations map[common.Address]*mutation
   119  
   120  	// DB error.
   121  	// State objects are used by the consensus core and VM which are
   122  	// unable to deal with database-level errors. Any error that occurs
   123  	// during a database read is memoized here and will eventually be
   124  	// returned by StateDB.Commit. Notably, this error is also shared
   125  	// by all cached state objects in case the database failure occurs
   126  	// when accessing state of accounts.
   127  	dbErr error
   128  
   129  	// The refund counter, also used by state transitioning.
   130  	refund uint64
   131  
   132  	// The tx context and all occurred logs in the scope of transaction.
   133  	thash   common.Hash
   134  	txIndex int
   135  	logs    map[common.Hash][]*types.Log
   136  	logSize uint
   137  
   138  	// Preimages occurred seen by VM in the scope of block.
   139  	preimages map[common.Hash][]byte
   140  
   141  	// Per-transaction access list
   142  	accessList *accessList
   143  
   144  	// Transient storage
   145  	transientStorage transientStorage
   146  
   147  	// Journal of state modifications. This is the backbone of
   148  	// Snapshot and RevertToSnapshot.
   149  	journal        *journal
   150  	validRevisions []revision
   151  	nextRevisionId int
   152  
   153  	// Measurements gathered during execution for debugging purposes
   154  	AccountReads         time.Duration
   155  	AccountHashes        time.Duration
   156  	AccountUpdates       time.Duration
   157  	AccountCommits       time.Duration
   158  	StorageReads         time.Duration
   159  	StorageUpdates       time.Duration
   160  	StorageCommits       time.Duration
   161  	SnapshotAccountReads time.Duration
   162  	SnapshotStorageReads time.Duration
   163  	SnapshotCommits      time.Duration
   164  	TrieDBCommits        time.Duration
   165  
   166  	AccountUpdated int
   167  	StorageUpdated int
   168  	AccountDeleted int
   169  	StorageDeleted int
   170  
   171  	// Testing hooks
   172  	onCommit func(states *triestate.Set) // Hook invoked when commit is performed
   173  }
   174  
   175  // New creates a new state from a given trie.
   176  func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) {
   177  	tr, err := db.OpenTrie(root)
   178  	if err != nil {
   179  		return nil, err
   180  	}
   181  	sdb := &StateDB{
   182  		db:                   db,
   183  		trie:                 tr,
   184  		originalRoot:         root,
   185  		snaps:                snaps,
   186  		accounts:             make(map[common.Hash][]byte),
   187  		storages:             make(map[common.Hash]map[common.Hash][]byte),
   188  		accountsOrigin:       make(map[common.Address][]byte),
   189  		storagesOrigin:       make(map[common.Address]map[common.Hash][]byte),
   190  		stateObjects:         make(map[common.Address]*stateObject),
   191  		stateObjectsDestruct: make(map[common.Address]*types.StateAccount),
   192  		mutations:            make(map[common.Address]*mutation),
   193  		logs:                 make(map[common.Hash][]*types.Log),
   194  		preimages:            make(map[common.Hash][]byte),
   195  		journal:              newJournal(),
   196  		accessList:           newAccessList(),
   197  		transientStorage:     newTransientStorage(),
   198  		hasher:               crypto.NewKeccakState(),
   199  	}
   200  	if sdb.snaps != nil {
   201  		sdb.snap = sdb.snaps.Snapshot(root)
   202  	}
   203  	return sdb, nil
   204  }
   205  
   206  // SetLogger sets the logger for account update hooks.
   207  func (s *StateDB) SetLogger(l *tracing.Hooks) {
   208  	s.logger = l
   209  }
   210  
   211  // StartPrefetcher initializes a new trie prefetcher to pull in nodes from the
   212  // state trie concurrently while the state is mutated so that when we reach the
   213  // commit phase, most of the needed data is already hot.
   214  func (s *StateDB) StartPrefetcher(namespace string) {
   215  	if s.prefetcher != nil {
   216  		s.prefetcher.close()
   217  		s.prefetcher = nil
   218  	}
   219  	if s.snap != nil {
   220  		s.prefetcher = newTriePrefetcher(s.db, s.originalRoot, namespace)
   221  	}
   222  }
   223  
   224  // StopPrefetcher terminates a running prefetcher and reports any leftover stats
   225  // from the gathered metrics.
   226  func (s *StateDB) StopPrefetcher() {
   227  	if s.prefetcher != nil {
   228  		s.prefetcher.close()
   229  		s.prefetcher = nil
   230  	}
   231  }
   232  
   233  // setError remembers the first non-nil error it is called with.
   234  func (s *StateDB) setError(err error) {
   235  	if s.dbErr == nil {
   236  		s.dbErr = err
   237  	}
   238  }
   239  
   240  // Error returns the memorized database failure occurred earlier.
   241  func (s *StateDB) Error() error {
   242  	return s.dbErr
   243  }
   244  
   245  func (s *StateDB) AddLog(log *types.Log) {
   246  	s.journal.append(addLogChange{txhash: s.thash})
   247  
   248  	log.TxHash = s.thash
   249  	log.TxIndex = uint(s.txIndex)
   250  	log.Index = s.logSize
   251  	if s.logger != nil && s.logger.OnLog != nil {
   252  		s.logger.OnLog(log)
   253  	}
   254  	s.logs[s.thash] = append(s.logs[s.thash], log)
   255  	s.logSize++
   256  }
   257  
   258  // GetLogs returns the logs matching the specified transaction hash, and annotates
   259  // them with the given blockNumber and blockHash.
   260  func (s *StateDB) GetLogs(hash common.Hash, blockNumber uint64, blockHash common.Hash) []*types.Log {
   261  	logs := s.logs[hash]
   262  	for _, l := range logs {
   263  		l.BlockNumber = blockNumber
   264  		l.BlockHash = blockHash
   265  	}
   266  	return logs
   267  }
   268  
   269  func (s *StateDB) Logs() []*types.Log {
   270  	var logs []*types.Log
   271  	for _, lgs := range s.logs {
   272  		logs = append(logs, lgs...)
   273  	}
   274  	return logs
   275  }
   276  
   277  // AddPreimage records a SHA3 preimage seen by the VM.
   278  func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
   279  	if _, ok := s.preimages[hash]; !ok {
   280  		s.journal.append(addPreimageChange{hash: hash})
   281  		s.preimages[hash] = slices.Clone(preimage)
   282  	}
   283  }
   284  
   285  // Preimages returns a list of SHA3 preimages that have been submitted.
   286  func (s *StateDB) Preimages() map[common.Hash][]byte {
   287  	return s.preimages
   288  }
   289  
   290  // AddRefund adds gas to the refund counter
   291  func (s *StateDB) AddRefund(gas uint64) {
   292  	s.journal.append(refundChange{prev: s.refund})
   293  	s.refund += gas
   294  }
   295  
   296  // SubRefund removes gas from the refund counter.
   297  // This method will panic if the refund counter goes below zero
   298  func (s *StateDB) SubRefund(gas uint64) {
   299  	s.journal.append(refundChange{prev: s.refund})
   300  	if gas > s.refund {
   301  		panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund))
   302  	}
   303  	s.refund -= gas
   304  }
   305  
   306  // Exist reports whether the given account address exists in the state.
   307  // Notably this also returns true for self-destructed accounts.
   308  func (s *StateDB) Exist(addr common.Address) bool {
   309  	return s.getStateObject(addr) != nil
   310  }
   311  
   312  // Empty returns whether the state object is either non-existent
   313  // or empty according to the EIP161 specification (balance = nonce = code = 0)
   314  func (s *StateDB) Empty(addr common.Address) bool {
   315  	so := s.getStateObject(addr)
   316  	return so == nil || so.empty()
   317  }
   318  
   319  // GetBalance retrieves the balance from the given address or 0 if object not found
   320  func (s *StateDB) GetBalance(addr common.Address) *uint256.Int {
   321  	stateObject := s.getStateObject(addr)
   322  	if stateObject != nil {
   323  		return stateObject.Balance()
   324  	}
   325  	return common.U2560
   326  }
   327  
   328  // GetNonce retrieves the nonce from the given address or 0 if object not found
   329  func (s *StateDB) GetNonce(addr common.Address) uint64 {
   330  	stateObject := s.getStateObject(addr)
   331  	if stateObject != nil {
   332  		return stateObject.Nonce()
   333  	}
   334  
   335  	return 0
   336  }
   337  
   338  // GetStorageRoot retrieves the storage root from the given address or empty
   339  // if object not found.
   340  func (s *StateDB) GetStorageRoot(addr common.Address) common.Hash {
   341  	stateObject := s.getStateObject(addr)
   342  	if stateObject != nil {
   343  		return stateObject.Root()
   344  	}
   345  	return common.Hash{}
   346  }
   347  
   348  // TxIndex returns the current transaction index set by Prepare.
   349  func (s *StateDB) TxIndex() int {
   350  	return s.txIndex
   351  }
   352  
   353  func (s *StateDB) GetCode(addr common.Address) []byte {
   354  	stateObject := s.getStateObject(addr)
   355  	if stateObject != nil {
   356  		return stateObject.Code()
   357  	}
   358  	return nil
   359  }
   360  
   361  func (s *StateDB) GetCodeSize(addr common.Address) int {
   362  	stateObject := s.getStateObject(addr)
   363  	if stateObject != nil {
   364  		return stateObject.CodeSize()
   365  	}
   366  	return 0
   367  }
   368  
   369  func (s *StateDB) GetCodeHash(addr common.Address) common.Hash {
   370  	stateObject := s.getStateObject(addr)
   371  	if stateObject != nil {
   372  		return common.BytesToHash(stateObject.CodeHash())
   373  	}
   374  	return common.Hash{}
   375  }
   376  
   377  // GetState retrieves a value from the given account's storage trie.
   378  func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash {
   379  	stateObject := s.getStateObject(addr)
   380  	if stateObject != nil {
   381  		return stateObject.GetState(hash)
   382  	}
   383  	return common.Hash{}
   384  }
   385  
   386  // GetCommittedState retrieves a value from the given account's committed storage trie.
   387  func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
   388  	stateObject := s.getStateObject(addr)
   389  	if stateObject != nil {
   390  		return stateObject.GetCommittedState(hash)
   391  	}
   392  	return common.Hash{}
   393  }
   394  
   395  // Database retrieves the low level database supporting the lower level trie ops.
   396  func (s *StateDB) Database() Database {
   397  	return s.db
   398  }
   399  
   400  func (s *StateDB) HasSelfDestructed(addr common.Address) bool {
   401  	stateObject := s.getStateObject(addr)
   402  	if stateObject != nil {
   403  		return stateObject.selfDestructed
   404  	}
   405  	return false
   406  }
   407  
   408  /*
   409   * SETTERS
   410   */
   411  
   412  // AddBalance adds amount to the account associated with addr.
   413  func (s *StateDB) AddBalance(addr common.Address, amount *uint256.Int, reason tracing.BalanceChangeReason) {
   414  	stateObject := s.getOrNewStateObject(addr)
   415  	if stateObject != nil {
   416  		stateObject.AddBalance(amount, reason)
   417  	}
   418  }
   419  
   420  // SubBalance subtracts amount from the account associated with addr.
   421  func (s *StateDB) SubBalance(addr common.Address, amount *uint256.Int, reason tracing.BalanceChangeReason) {
   422  	stateObject := s.getOrNewStateObject(addr)
   423  	if stateObject != nil {
   424  		stateObject.SubBalance(amount, reason)
   425  	}
   426  }
   427  
   428  func (s *StateDB) SetBalance(addr common.Address, amount *uint256.Int, reason tracing.BalanceChangeReason) {
   429  	stateObject := s.getOrNewStateObject(addr)
   430  	if stateObject != nil {
   431  		stateObject.SetBalance(amount, reason)
   432  	}
   433  }
   434  
   435  func (s *StateDB) SetNonce(addr common.Address, nonce uint64) {
   436  	stateObject := s.getOrNewStateObject(addr)
   437  	if stateObject != nil {
   438  		stateObject.SetNonce(nonce)
   439  	}
   440  }
   441  
   442  func (s *StateDB) SetCode(addr common.Address, code []byte) {
   443  	stateObject := s.getOrNewStateObject(addr)
   444  	if stateObject != nil {
   445  		stateObject.SetCode(crypto.Keccak256Hash(code), code)
   446  	}
   447  }
   448  
   449  func (s *StateDB) SetState(addr common.Address, key, value common.Hash) {
   450  	stateObject := s.getOrNewStateObject(addr)
   451  	if stateObject != nil {
   452  		stateObject.SetState(key, value)
   453  	}
   454  }
   455  
   456  // SetStorage replaces the entire storage for the specified account with given
   457  // storage. This function should only be used for debugging and the mutations
   458  // must be discarded afterwards.
   459  func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) {
   460  	// SetStorage needs to wipe existing storage. We achieve this by pretending
   461  	// that the account self-destructed earlier in this block, by flagging
   462  	// it in stateObjectsDestruct. The effect of doing so is that storage lookups
   463  	// will not hit disk, since it is assumed that the disk-data is belonging
   464  	// to a previous incarnation of the object.
   465  	//
   466  	// TODO(rjl493456442) this function should only be supported by 'unwritable'
   467  	// state and all mutations made should all be discarded afterwards.
   468  	if _, ok := s.stateObjectsDestruct[addr]; !ok {
   469  		s.stateObjectsDestruct[addr] = nil
   470  	}
   471  	stateObject := s.getOrNewStateObject(addr)
   472  	for k, v := range storage {
   473  		stateObject.SetState(k, v)
   474  	}
   475  }
   476  
   477  // SelfDestruct marks the given account as selfdestructed.
   478  // This clears the account balance.
   479  //
   480  // The account's state object is still available until the state is committed,
   481  // getStateObject will return a non-nil account after SelfDestruct.
   482  func (s *StateDB) SelfDestruct(addr common.Address) {
   483  	stateObject := s.getStateObject(addr)
   484  	if stateObject == nil {
   485  		return
   486  	}
   487  	var (
   488  		prev = new(uint256.Int).Set(stateObject.Balance())
   489  		n    = new(uint256.Int)
   490  	)
   491  	s.journal.append(selfDestructChange{
   492  		account:     &addr,
   493  		prev:        stateObject.selfDestructed,
   494  		prevbalance: prev,
   495  	})
   496  	if s.logger != nil && s.logger.OnBalanceChange != nil && prev.Sign() > 0 {
   497  		s.logger.OnBalanceChange(addr, prev.ToBig(), n.ToBig(), tracing.BalanceDecreaseSelfdestruct)
   498  	}
   499  	stateObject.markSelfdestructed()
   500  	stateObject.data.Balance = n
   501  }
   502  
   503  func (s *StateDB) Selfdestruct6780(addr common.Address) {
   504  	stateObject := s.getStateObject(addr)
   505  	if stateObject == nil {
   506  		return
   507  	}
   508  	if stateObject.newContract {
   509  		s.SelfDestruct(addr)
   510  	}
   511  }
   512  
   513  // SetTransientState sets transient storage for a given account. It
   514  // adds the change to the journal so that it can be rolled back
   515  // to its previous value if there is a revert.
   516  func (s *StateDB) SetTransientState(addr common.Address, key, value common.Hash) {
   517  	prev := s.GetTransientState(addr, key)
   518  	if prev == value {
   519  		return
   520  	}
   521  	s.journal.append(transientStorageChange{
   522  		account:  &addr,
   523  		key:      key,
   524  		prevalue: prev,
   525  	})
   526  	s.setTransientState(addr, key, value)
   527  }
   528  
   529  // setTransientState is a lower level setter for transient storage. It
   530  // is called during a revert to prevent modifications to the journal.
   531  func (s *StateDB) setTransientState(addr common.Address, key, value common.Hash) {
   532  	s.transientStorage.Set(addr, key, value)
   533  }
   534  
   535  // GetTransientState gets transient storage for a given account.
   536  func (s *StateDB) GetTransientState(addr common.Address, key common.Hash) common.Hash {
   537  	return s.transientStorage.Get(addr, key)
   538  }
   539  
   540  //
   541  // Setting, updating & deleting state object methods.
   542  //
   543  
   544  // updateStateObject writes the given object to the trie.
   545  func (s *StateDB) updateStateObject(obj *stateObject) {
   546  	// Track the amount of time wasted on updating the account from the trie
   547  	defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
   548  
   549  	// Encode the account and update the account trie
   550  	addr := obj.Address()
   551  	if err := s.trie.UpdateAccount(addr, &obj.data); err != nil {
   552  		s.setError(fmt.Errorf("updateStateObject (%x) error: %v", addr[:], err))
   553  	}
   554  	if obj.dirtyCode {
   555  		s.trie.UpdateContractCode(obj.Address(), common.BytesToHash(obj.CodeHash()), obj.code)
   556  	}
   557  	// Cache the data until commit. Note, this update mechanism is not symmetric
   558  	// to the deletion, because whereas it is enough to track account updates
   559  	// at commit time, deletions need tracking at transaction boundary level to
   560  	// ensure we capture state clearing.
   561  	s.accounts[obj.addrHash] = types.SlimAccountRLP(obj.data)
   562  
   563  	// Track the original value of mutated account, nil means it was not present.
   564  	// Skip if it has been tracked (because updateStateObject may be called
   565  	// multiple times in a block).
   566  	if _, ok := s.accountsOrigin[obj.address]; !ok {
   567  		if obj.origin == nil {
   568  			s.accountsOrigin[obj.address] = nil
   569  		} else {
   570  			s.accountsOrigin[obj.address] = types.SlimAccountRLP(*obj.origin)
   571  		}
   572  	}
   573  }
   574  
   575  // deleteStateObject removes the given object from the state trie.
   576  func (s *StateDB) deleteStateObject(addr common.Address) {
   577  	// Track the amount of time wasted on deleting the account from the trie
   578  	defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
   579  
   580  	// Delete the account from the trie
   581  	if err := s.trie.DeleteAccount(addr); err != nil {
   582  		s.setError(fmt.Errorf("deleteStateObject (%x) error: %v", addr[:], err))
   583  	}
   584  }
   585  
   586  // getStateObject retrieves a state object given by the address, returning nil if
   587  // the object is not found or was deleted in this execution context.
   588  func (s *StateDB) getStateObject(addr common.Address) *stateObject {
   589  	// Prefer live objects if any is available
   590  	if obj := s.stateObjects[addr]; obj != nil {
   591  		return obj
   592  	}
   593  	// Short circuit if the account is already destructed in this block.
   594  	if _, ok := s.stateObjectsDestruct[addr]; ok {
   595  		return nil
   596  	}
   597  	// If no live objects are available, attempt to use snapshots
   598  	var data *types.StateAccount
   599  	if s.snap != nil {
   600  		start := time.Now()
   601  		acc, err := s.snap.Account(crypto.HashData(s.hasher, addr.Bytes()))
   602  		s.SnapshotAccountReads += time.Since(start)
   603  
   604  		if err == nil {
   605  			if acc == nil {
   606  				return nil
   607  			}
   608  			data = &types.StateAccount{
   609  				Nonce:    acc.Nonce,
   610  				Balance:  acc.Balance,
   611  				CodeHash: acc.CodeHash,
   612  				Root:     common.BytesToHash(acc.Root),
   613  			}
   614  			if len(data.CodeHash) == 0 {
   615  				data.CodeHash = types.EmptyCodeHash.Bytes()
   616  			}
   617  			if data.Root == (common.Hash{}) {
   618  				data.Root = types.EmptyRootHash
   619  			}
   620  		}
   621  	}
   622  	// If snapshot unavailable or reading from it failed, load from the database
   623  	if data == nil {
   624  		start := time.Now()
   625  		var err error
   626  		data, err = s.trie.GetAccount(addr)
   627  		s.AccountReads += time.Since(start)
   628  
   629  		if err != nil {
   630  			s.setError(fmt.Errorf("getDeleteStateObject (%x) error: %w", addr.Bytes(), err))
   631  			return nil
   632  		}
   633  		if data == nil {
   634  			return nil
   635  		}
   636  	}
   637  	// Insert into the live set
   638  	obj := newObject(s, addr, data)
   639  	s.setStateObject(obj)
   640  	return obj
   641  }
   642  
   643  func (s *StateDB) setStateObject(object *stateObject) {
   644  	s.stateObjects[object.Address()] = object
   645  }
   646  
   647  // getOrNewStateObject retrieves a state object or create a new state object if nil.
   648  func (s *StateDB) getOrNewStateObject(addr common.Address) *stateObject {
   649  	obj := s.getStateObject(addr)
   650  	if obj == nil {
   651  		obj = s.createObject(addr)
   652  	}
   653  	return obj
   654  }
   655  
   656  // createObject creates a new state object. The assumption is held there is no
   657  // existing account with the given address, otherwise it will be silently overwritten.
   658  func (s *StateDB) createObject(addr common.Address) *stateObject {
   659  	obj := newObject(s, addr, nil)
   660  	s.journal.append(createObjectChange{account: &addr})
   661  	s.setStateObject(obj)
   662  	return obj
   663  }
   664  
   665  // CreateAccount explicitly creates a new state object, assuming that the
   666  // account did not previously exist in the state. If the account already
   667  // exists, this function will silently overwrite it which might lead to a
   668  // consensus bug eventually.
   669  func (s *StateDB) CreateAccount(addr common.Address) {
   670  	s.createObject(addr)
   671  }
   672  
   673  // CreateContract is used whenever a contract is created. This may be preceded
   674  // by CreateAccount, but that is not required if it already existed in the
   675  // state due to funds sent beforehand.
   676  // This operation sets the 'newContract'-flag, which is required in order to
   677  // correctly handle EIP-6780 'delete-in-same-transaction' logic.
   678  func (s *StateDB) CreateContract(addr common.Address) {
   679  	obj := s.getStateObject(addr)
   680  	if !obj.newContract {
   681  		obj.newContract = true
   682  		s.journal.append(createContractChange{account: addr})
   683  	}
   684  }
   685  
   686  // Copy creates a deep, independent copy of the state.
   687  // Snapshots of the copied state cannot be applied to the copy.
   688  func (s *StateDB) Copy() *StateDB {
   689  	// Copy all the basic fields, initialize the memory ones
   690  	state := &StateDB{
   691  		db:                   s.db,
   692  		trie:                 s.db.CopyTrie(s.trie),
   693  		hasher:               crypto.NewKeccakState(),
   694  		originalRoot:         s.originalRoot,
   695  		accounts:             copySet(s.accounts),
   696  		storages:             copy2DSet(s.storages),
   697  		accountsOrigin:       copySet(s.accountsOrigin),
   698  		storagesOrigin:       copy2DSet(s.storagesOrigin),
   699  		stateObjects:         make(map[common.Address]*stateObject, len(s.stateObjects)),
   700  		stateObjectsDestruct: maps.Clone(s.stateObjectsDestruct),
   701  		mutations:            make(map[common.Address]*mutation, len(s.mutations)),
   702  		dbErr:                s.dbErr,
   703  		refund:               s.refund,
   704  		thash:                s.thash,
   705  		txIndex:              s.txIndex,
   706  		logs:                 make(map[common.Hash][]*types.Log, len(s.logs)),
   707  		logSize:              s.logSize,
   708  		preimages:            maps.Clone(s.preimages),
   709  		journal:              s.journal.copy(),
   710  		validRevisions:       slices.Clone(s.validRevisions),
   711  		nextRevisionId:       s.nextRevisionId,
   712  
   713  		// In order for the block producer to be able to use and make additions
   714  		// to the snapshot tree, we need to copy that as well. Otherwise, any
   715  		// block mined by ourselves will cause gaps in the tree, and force the
   716  		// miner to operate trie-backed only.
   717  		snaps: s.snaps,
   718  		snap:  s.snap,
   719  	}
   720  	// Deep copy cached state objects.
   721  	for addr, obj := range s.stateObjects {
   722  		state.stateObjects[addr] = obj.deepCopy(state)
   723  	}
   724  	// Deep copy the object state markers.
   725  	for addr, op := range s.mutations {
   726  		state.mutations[addr] = op.copy()
   727  	}
   728  	// Deep copy the logs occurred in the scope of block
   729  	for hash, logs := range s.logs {
   730  		cpy := make([]*types.Log, len(logs))
   731  		for i, l := range logs {
   732  			cpy[i] = new(types.Log)
   733  			*cpy[i] = *l
   734  		}
   735  		state.logs[hash] = cpy
   736  	}
   737  	// Do we need to copy the access list and transient storage?
   738  	// In practice: No. At the start of a transaction, these two lists are empty.
   739  	// In practice, we only ever copy state _between_ transactions/blocks, never
   740  	// in the middle of a transaction. However, it doesn't cost us much to copy
   741  	// empty lists, so we do it anyway to not blow up if we ever decide copy them
   742  	// in the middle of a transaction.
   743  	state.accessList = s.accessList.Copy()
   744  	state.transientStorage = s.transientStorage.Copy()
   745  
   746  	// If there's a prefetcher running, make an inactive copy of it that can
   747  	// only access data but does not actively preload (since the user will not
   748  	// know that they need to explicitly terminate an active copy).
   749  	if s.prefetcher != nil {
   750  		state.prefetcher = s.prefetcher.copy()
   751  	}
   752  	return state
   753  }
   754  
   755  // Snapshot returns an identifier for the current revision of the state.
   756  func (s *StateDB) Snapshot() int {
   757  	id := s.nextRevisionId
   758  	s.nextRevisionId++
   759  	s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()})
   760  	return id
   761  }
   762  
   763  // RevertToSnapshot reverts all state changes made since the given revision.
   764  func (s *StateDB) RevertToSnapshot(revid int) {
   765  	// Find the snapshot in the stack of valid snapshots.
   766  	idx := sort.Search(len(s.validRevisions), func(i int) bool {
   767  		return s.validRevisions[i].id >= revid
   768  	})
   769  	if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid {
   770  		panic(fmt.Errorf("revision id %v cannot be reverted", revid))
   771  	}
   772  	snapshot := s.validRevisions[idx].journalIndex
   773  
   774  	// Replay the journal to undo changes and remove invalidated snapshots
   775  	s.journal.revert(s, snapshot)
   776  	s.validRevisions = s.validRevisions[:idx]
   777  }
   778  
   779  // GetRefund returns the current value of the refund counter.
   780  func (s *StateDB) GetRefund() uint64 {
   781  	return s.refund
   782  }
   783  
   784  // Finalise finalises the state by removing the destructed objects and clears
   785  // the journal as well as the refunds. Finalise, however, will not push any updates
   786  // into the tries just yet. Only IntermediateRoot or Commit will do that.
   787  func (s *StateDB) Finalise(deleteEmptyObjects bool) {
   788  	addressesToPrefetch := make([][]byte, 0, len(s.journal.dirties))
   789  	for addr := range s.journal.dirties {
   790  		obj, exist := s.stateObjects[addr]
   791  		if !exist {
   792  			// ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
   793  			// That tx goes out of gas, and although the notion of 'touched' does not exist there, the
   794  			// touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
   795  			// it will persist in the journal even though the journal is reverted. In this special circumstance,
   796  			// it may exist in `s.journal.dirties` but not in `s.stateObjects`.
   797  			// Thus, we can safely ignore it here
   798  			continue
   799  		}
   800  		if obj.selfDestructed || (deleteEmptyObjects && obj.empty()) {
   801  			delete(s.stateObjects, obj.address)
   802  			s.markDelete(addr)
   803  
   804  			// If ether was sent to account post-selfdestruct it is burnt.
   805  			if bal := obj.Balance(); s.logger != nil && s.logger.OnBalanceChange != nil && obj.selfDestructed && bal.Sign() != 0 {
   806  				s.logger.OnBalanceChange(obj.address, bal.ToBig(), new(big.Int), tracing.BalanceDecreaseSelfdestructBurn)
   807  			}
   808  			// We need to maintain account deletions explicitly (will remain
   809  			// set indefinitely). Note only the first occurred self-destruct
   810  			// event is tracked.
   811  			if _, ok := s.stateObjectsDestruct[obj.address]; !ok {
   812  				s.stateObjectsDestruct[obj.address] = obj.origin
   813  			}
   814  			// Note, we can't do this only at the end of a block because multiple
   815  			// transactions within the same block might self destruct and then
   816  			// resurrect an account; but the snapshotter needs both events.
   817  			delete(s.accounts, obj.addrHash)      // Clear out any previously updated account data (may be recreated via a resurrect)
   818  			delete(s.storages, obj.addrHash)      // Clear out any previously updated storage data (may be recreated via a resurrect)
   819  			delete(s.accountsOrigin, obj.address) // Clear out any previously updated account data (may be recreated via a resurrect)
   820  			delete(s.storagesOrigin, obj.address) // Clear out any previously updated storage data (may be recreated via a resurrect)
   821  		} else {
   822  			obj.finalise(true) // Prefetch slots in the background
   823  			s.markUpdate(addr)
   824  		}
   825  		// At this point, also ship the address off to the precacher. The precacher
   826  		// will start loading tries, and when the change is eventually committed,
   827  		// the commit-phase will be a lot faster
   828  		addressesToPrefetch = append(addressesToPrefetch, common.CopyBytes(addr[:])) // Copy needed for closure
   829  	}
   830  	if s.prefetcher != nil && len(addressesToPrefetch) > 0 {
   831  		s.prefetcher.prefetch(common.Hash{}, s.originalRoot, common.Address{}, addressesToPrefetch)
   832  	}
   833  	// Invalidate journal because reverting across transactions is not allowed.
   834  	s.clearJournalAndRefund()
   835  }
   836  
   837  // IntermediateRoot computes the current root hash of the state trie.
   838  // It is called in between transactions to get the root hash that
   839  // goes into transaction receipts.
   840  func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
   841  	// Finalise all the dirty storage states and write them into the tries
   842  	s.Finalise(deleteEmptyObjects)
   843  
   844  	// If there was a trie prefetcher operating, it gets aborted and irrevocably
   845  	// modified after we start retrieving tries. Remove it from the statedb after
   846  	// this round of use.
   847  	//
   848  	// This is weird pre-byzantium since the first tx runs with a prefetcher and
   849  	// the remainder without, but pre-byzantium even the initial prefetcher is
   850  	// useless, so no sleep lost.
   851  	prefetcher := s.prefetcher
   852  	if s.prefetcher != nil {
   853  		defer func() {
   854  			s.prefetcher.close()
   855  			s.prefetcher = nil
   856  		}()
   857  	}
   858  	// Although naively it makes sense to retrieve the account trie and then do
   859  	// the contract storage and account updates sequentially, that short circuits
   860  	// the account prefetcher. Instead, let's process all the storage updates
   861  	// first, giving the account prefetches just a few more milliseconds of time
   862  	// to pull useful data from disk.
   863  	start := time.Now()
   864  	for addr, op := range s.mutations {
   865  		if op.applied {
   866  			continue
   867  		}
   868  		if op.isDelete() {
   869  			continue
   870  		}
   871  		s.stateObjects[addr].updateRoot()
   872  	}
   873  	s.StorageUpdates += time.Since(start)
   874  
   875  	// Now we're about to start to write changes to the trie. The trie is so far
   876  	// _untouched_. We can check with the prefetcher, if it can give us a trie
   877  	// which has the same root, but also has some content loaded into it.
   878  	if prefetcher != nil {
   879  		if trie := prefetcher.trie(common.Hash{}, s.originalRoot); trie != nil {
   880  			s.trie = trie
   881  		}
   882  	}
   883  	// Perform updates before deletions.  This prevents resolution of unnecessary trie nodes
   884  	// in circumstances similar to the following:
   885  	//
   886  	// Consider nodes `A` and `B` who share the same full node parent `P` and have no other siblings.
   887  	// During the execution of a block:
   888  	// - `A` self-destructs,
   889  	// - `C` is created, and also shares the parent `P`.
   890  	// If the self-destruct is handled first, then `P` would be left with only one child, thus collapsed
   891  	// into a shortnode. This requires `B` to be resolved from disk.
   892  	// Whereas if the created node is handled first, then the collapse is avoided, and `B` is not resolved.
   893  	var (
   894  		usedAddrs    [][]byte
   895  		deletedAddrs []common.Address
   896  	)
   897  	for addr, op := range s.mutations {
   898  		if op.applied {
   899  			continue
   900  		}
   901  		op.applied = true
   902  
   903  		if op.isDelete() {
   904  			deletedAddrs = append(deletedAddrs, addr)
   905  		} else {
   906  			s.updateStateObject(s.stateObjects[addr])
   907  			s.AccountUpdated += 1
   908  		}
   909  		usedAddrs = append(usedAddrs, common.CopyBytes(addr[:])) // Copy needed for closure
   910  	}
   911  	for _, deletedAddr := range deletedAddrs {
   912  		s.deleteStateObject(deletedAddr)
   913  		s.AccountDeleted += 1
   914  	}
   915  	if prefetcher != nil {
   916  		prefetcher.used(common.Hash{}, s.originalRoot, usedAddrs)
   917  	}
   918  	// Track the amount of time wasted on hashing the account trie
   919  	defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now())
   920  
   921  	return s.trie.Hash()
   922  }
   923  
   924  // SetTxContext sets the current transaction hash and index which are
   925  // used when the EVM emits new state logs. It should be invoked before
   926  // transaction execution.
   927  func (s *StateDB) SetTxContext(thash common.Hash, ti int) {
   928  	s.thash = thash
   929  	s.txIndex = ti
   930  }
   931  
   932  func (s *StateDB) clearJournalAndRefund() {
   933  	if len(s.journal.entries) > 0 {
   934  		s.journal = newJournal()
   935  		s.refund = 0
   936  	}
   937  	s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entries
   938  }
   939  
   940  // fastDeleteStorage is the function that efficiently deletes the storage trie
   941  // of a specific account. It leverages the associated state snapshot for fast
   942  // storage iteration and constructs trie node deletion markers by creating
   943  // stack trie with iterated slots.
   944  func (s *StateDB) fastDeleteStorage(addrHash common.Hash, root common.Hash) (common.StorageSize, map[common.Hash][]byte, *trienode.NodeSet, error) {
   945  	iter, err := s.snaps.StorageIterator(s.originalRoot, addrHash, common.Hash{})
   946  	if err != nil {
   947  		return 0, nil, nil, err
   948  	}
   949  	defer iter.Release()
   950  
   951  	var (
   952  		size  common.StorageSize
   953  		nodes = trienode.NewNodeSet(addrHash)
   954  		slots = make(map[common.Hash][]byte)
   955  	)
   956  	stack := trie.NewStackTrie(func(path []byte, hash common.Hash, blob []byte) {
   957  		nodes.AddNode(path, trienode.NewDeleted())
   958  		size += common.StorageSize(len(path))
   959  	})
   960  	for iter.Next() {
   961  		slot := common.CopyBytes(iter.Slot())
   962  		if err := iter.Error(); err != nil { // error might occur after Slot function
   963  			return 0, nil, nil, err
   964  		}
   965  		size += common.StorageSize(common.HashLength + len(slot))
   966  		slots[iter.Hash()] = slot
   967  
   968  		if err := stack.Update(iter.Hash().Bytes(), slot); err != nil {
   969  			return 0, nil, nil, err
   970  		}
   971  	}
   972  	if err := iter.Error(); err != nil { // error might occur during iteration
   973  		return 0, nil, nil, err
   974  	}
   975  	if stack.Hash() != root {
   976  		return 0, nil, nil, fmt.Errorf("snapshot is not matched, exp %x, got %x", root, stack.Hash())
   977  	}
   978  	return size, slots, nodes, nil
   979  }
   980  
   981  // slowDeleteStorage serves as a less-efficient alternative to "fastDeleteStorage,"
   982  // employed when the associated state snapshot is not available. It iterates the
   983  // storage slots along with all internal trie nodes via trie directly.
   984  func (s *StateDB) slowDeleteStorage(addr common.Address, addrHash common.Hash, root common.Hash) (common.StorageSize, map[common.Hash][]byte, *trienode.NodeSet, error) {
   985  	tr, err := s.db.OpenStorageTrie(s.originalRoot, addr, root, s.trie)
   986  	if err != nil {
   987  		return 0, nil, nil, fmt.Errorf("failed to open storage trie, err: %w", err)
   988  	}
   989  	it, err := tr.NodeIterator(nil)
   990  	if err != nil {
   991  		return 0, nil, nil, fmt.Errorf("failed to open storage iterator, err: %w", err)
   992  	}
   993  	var (
   994  		size  common.StorageSize
   995  		nodes = trienode.NewNodeSet(addrHash)
   996  		slots = make(map[common.Hash][]byte)
   997  	)
   998  	for it.Next(true) {
   999  		if it.Leaf() {
  1000  			slots[common.BytesToHash(it.LeafKey())] = common.CopyBytes(it.LeafBlob())
  1001  			size += common.StorageSize(common.HashLength + len(it.LeafBlob()))
  1002  			continue
  1003  		}
  1004  		if it.Hash() == (common.Hash{}) {
  1005  			continue
  1006  		}
  1007  		size += common.StorageSize(len(it.Path()))
  1008  		nodes.AddNode(it.Path(), trienode.NewDeleted())
  1009  	}
  1010  	if err := it.Error(); err != nil {
  1011  		return 0, nil, nil, err
  1012  	}
  1013  	return size, slots, nodes, nil
  1014  }
  1015  
  1016  // deleteStorage is designed to delete the storage trie of a designated account.
  1017  // It could potentially be terminated if the storage size is excessively large,
  1018  // potentially leading to an out-of-memory panic. The function will make an attempt
  1019  // to utilize an efficient strategy if the associated state snapshot is reachable;
  1020  // otherwise, it will resort to a less-efficient approach.
  1021  func (s *StateDB) deleteStorage(addr common.Address, addrHash common.Hash, root common.Hash) (map[common.Hash][]byte, *trienode.NodeSet, error) {
  1022  	var (
  1023  		start = time.Now()
  1024  		err   error
  1025  		size  common.StorageSize
  1026  		slots map[common.Hash][]byte
  1027  		nodes *trienode.NodeSet
  1028  	)
  1029  	// The fast approach can be failed if the snapshot is not fully
  1030  	// generated, or it's internally corrupted. Fallback to the slow
  1031  	// one just in case.
  1032  	if s.snap != nil {
  1033  		size, slots, nodes, err = s.fastDeleteStorage(addrHash, root)
  1034  	}
  1035  	if s.snap == nil || err != nil {
  1036  		size, slots, nodes, err = s.slowDeleteStorage(addr, addrHash, root)
  1037  	}
  1038  	if err != nil {
  1039  		return nil, nil, err
  1040  	}
  1041  	// Report the metrics
  1042  	n := int64(len(slots))
  1043  
  1044  	slotDeletionMaxCount.UpdateIfGt(int64(len(slots)))
  1045  	slotDeletionMaxSize.UpdateIfGt(int64(size))
  1046  
  1047  	slotDeletionTimer.UpdateSince(start)
  1048  	slotDeletionCount.Mark(n)
  1049  	slotDeletionSize.Mark(int64(size))
  1050  
  1051  	return slots, nodes, nil
  1052  }
  1053  
  1054  // handleDestruction processes all destruction markers and deletes the account
  1055  // and associated storage slots if necessary. There are four possible situations
  1056  // here:
  1057  //
  1058  //   - the account was not existent and be marked as destructed
  1059  //
  1060  //   - the account was not existent and be marked as destructed,
  1061  //     however, it's resurrected later in the same block.
  1062  //
  1063  //   - the account was existent and be marked as destructed
  1064  //
  1065  //   - the account was existent and be marked as destructed,
  1066  //     however it's resurrected later in the same block.
  1067  //
  1068  // In case (a), nothing needs be deleted, nil to nil transition can be ignored.
  1069  //
  1070  // In case (b), nothing needs be deleted, nil is used as the original value for
  1071  // newly created account and storages
  1072  //
  1073  // In case (c), **original** account along with its storages should be deleted,
  1074  // with their values be tracked as original value.
  1075  //
  1076  // In case (d), **original** account along with its storages should be deleted,
  1077  // with their values be tracked as original value.
  1078  func (s *StateDB) handleDestruction(nodes *trienode.MergedNodeSet) error {
  1079  	// Short circuit if geth is running with hash mode. This procedure can consume
  1080  	// considerable time and storage deletion isn't supported in hash mode, thus
  1081  	// preemptively avoiding unnecessary expenses.
  1082  	if s.db.TrieDB().Scheme() == rawdb.HashScheme {
  1083  		return nil
  1084  	}
  1085  	for addr, prev := range s.stateObjectsDestruct {
  1086  		// The original account was non-existing, and it's marked as destructed
  1087  		// in the scope of block. It can be case (a) or (b).
  1088  		// - for (a), skip it without doing anything.
  1089  		// - for (b), track account's original value as nil. It may overwrite
  1090  		//   the data cached in s.accountsOrigin set by 'updateStateObject'.
  1091  		addrHash := crypto.Keccak256Hash(addr[:])
  1092  		if prev == nil {
  1093  			if _, ok := s.accounts[addrHash]; ok {
  1094  				s.accountsOrigin[addr] = nil // case (b)
  1095  			}
  1096  			continue
  1097  		}
  1098  		// It can overwrite the data in s.accountsOrigin set by 'updateStateObject'.
  1099  		s.accountsOrigin[addr] = types.SlimAccountRLP(*prev) // case (c) or (d)
  1100  
  1101  		// Short circuit if the storage was empty.
  1102  		if prev.Root == types.EmptyRootHash {
  1103  			continue
  1104  		}
  1105  		// Remove storage slots belong to the account.
  1106  		slots, set, err := s.deleteStorage(addr, addrHash, prev.Root)
  1107  		if err != nil {
  1108  			return fmt.Errorf("failed to delete storage, err: %w", err)
  1109  		}
  1110  		if s.storagesOrigin[addr] == nil {
  1111  			s.storagesOrigin[addr] = slots
  1112  		} else {
  1113  			// It can overwrite the data in s.storagesOrigin[addrHash] set by
  1114  			// 'object.updateTrie'.
  1115  			for key, val := range slots {
  1116  				s.storagesOrigin[addr][key] = val
  1117  			}
  1118  		}
  1119  		if err := nodes.Merge(set); err != nil {
  1120  			return err
  1121  		}
  1122  	}
  1123  	return nil
  1124  }
  1125  
  1126  // GetTrie returns the account trie.
  1127  func (s *StateDB) GetTrie() Trie {
  1128  	return s.trie
  1129  }
  1130  
  1131  // Commit writes the state to the underlying in-memory trie database.
  1132  // Once the state is committed, tries cached in stateDB (including account
  1133  // trie, storage tries) will no longer be functional. A new state instance
  1134  // must be created with new root and updated database for accessing post-
  1135  // commit states.
  1136  //
  1137  // The associated block number of the state transition is also provided
  1138  // for more chain context.
  1139  func (s *StateDB) Commit(block uint64, deleteEmptyObjects bool) (common.Hash, error) {
  1140  	// Short circuit in case any database failure occurred earlier.
  1141  	if s.dbErr != nil {
  1142  		return common.Hash{}, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr)
  1143  	}
  1144  	// Finalize any pending changes and merge everything into the tries
  1145  	s.IntermediateRoot(deleteEmptyObjects)
  1146  
  1147  	// Commit objects to the trie, measuring the elapsed time
  1148  	var (
  1149  		accountTrieNodesUpdated int
  1150  		accountTrieNodesDeleted int
  1151  		storageTrieNodesUpdated int
  1152  		storageTrieNodesDeleted int
  1153  		nodes                   = trienode.NewMergedNodeSet()
  1154  	)
  1155  	// Handle all state deletions first
  1156  	if err := s.handleDestruction(nodes); err != nil {
  1157  		return common.Hash{}, err
  1158  	}
  1159  	// Handle all state updates afterwards, concurrently to one another to shave
  1160  	// off some milliseconds from the commit operation. Also accumulate the code
  1161  	// writes to run in parallel with the computations.
  1162  	start := time.Now()
  1163  	var (
  1164  		code    = s.db.DiskDB().NewBatch()
  1165  		lock    sync.Mutex
  1166  		root    common.Hash
  1167  		workers errgroup.Group
  1168  	)
  1169  	// Schedule the account trie first since that will be the biggest, so give
  1170  	// it the most time to crunch.
  1171  	//
  1172  	// TODO(karalabe): This account trie commit is *very* heavy. 5-6ms at chain
  1173  	// heads, which seems excessive given that it doesn't do hashing, it just
  1174  	// shuffles some data. For comparison, the *hashing* at chain head is 2-3ms.
  1175  	// We need to investigate what's happening as it seems something's wonky.
  1176  	// Obviously it's not an end of the world issue, just something the original
  1177  	// code didn't anticipate for.
  1178  	workers.Go(func() error {
  1179  		// Write the account trie changes, measuring the amount of wasted time
  1180  		newroot, set, err := s.trie.Commit(true)
  1181  		if err != nil {
  1182  			return err
  1183  		}
  1184  		root = newroot
  1185  
  1186  		// Merge the dirty nodes of account trie into global set
  1187  		lock.Lock()
  1188  		defer lock.Unlock()
  1189  
  1190  		if set != nil {
  1191  			if err = nodes.Merge(set); err != nil {
  1192  				return err
  1193  			}
  1194  			accountTrieNodesUpdated, accountTrieNodesDeleted = set.Size()
  1195  		}
  1196  		s.AccountCommits = time.Since(start)
  1197  		return nil
  1198  	})
  1199  	// Schedule each of the storage tries that need to be updated, so they can
  1200  	// run concurrently to one another.
  1201  	//
  1202  	// TODO(karalabe): Experimentally, the account commit takes approximately the
  1203  	// same time as all the storage commits combined, so we could maybe only have
  1204  	// 2 threads in total. But that kind of depends on the account commit being
  1205  	// more expensive than it should be, so let's fix that and revisit this todo.
  1206  	for addr, op := range s.mutations {
  1207  		if op.isDelete() {
  1208  			continue
  1209  		}
  1210  		// Write any contract code associated with the state object
  1211  		obj := s.stateObjects[addr]
  1212  		if obj.code != nil && obj.dirtyCode {
  1213  			rawdb.WriteCode(code, common.BytesToHash(obj.CodeHash()), obj.code)
  1214  			obj.dirtyCode = false
  1215  		}
  1216  		// Run the storage updates concurrently to one another
  1217  		workers.Go(func() error {
  1218  			// Write any storage changes in the state object to its storage trie
  1219  			set, err := obj.commit()
  1220  			if err != nil {
  1221  				return err
  1222  			}
  1223  			// Merge the dirty nodes of storage trie into global set. It is possible
  1224  			// that the account was destructed and then resurrected in the same block.
  1225  			// In this case, the node set is shared by both accounts.
  1226  			lock.Lock()
  1227  			defer lock.Unlock()
  1228  
  1229  			if set != nil {
  1230  				if err = nodes.Merge(set); err != nil {
  1231  					return err
  1232  				}
  1233  				updates, deleted := set.Size()
  1234  				storageTrieNodesUpdated += updates
  1235  				storageTrieNodesDeleted += deleted
  1236  			}
  1237  			s.StorageCommits = time.Since(start) // overwrite with the longest storage commit runtime
  1238  			return nil
  1239  		})
  1240  	}
  1241  	// Schedule the code commits to run concurrently too. This shouldn't really
  1242  	// take much since we don't often commit code, but since it's disk access,
  1243  	// it's always yolo.
  1244  	workers.Go(func() error {
  1245  		if code.ValueSize() > 0 {
  1246  			if err := code.Write(); err != nil {
  1247  				log.Crit("Failed to commit dirty codes", "error", err)
  1248  			}
  1249  		}
  1250  		return nil
  1251  	})
  1252  	// Wait for everything to finish and update the metrics
  1253  	if err := workers.Wait(); err != nil {
  1254  		return common.Hash{}, err
  1255  	}
  1256  	accountUpdatedMeter.Mark(int64(s.AccountUpdated))
  1257  	storageUpdatedMeter.Mark(int64(s.StorageUpdated))
  1258  	accountDeletedMeter.Mark(int64(s.AccountDeleted))
  1259  	storageDeletedMeter.Mark(int64(s.StorageDeleted))
  1260  	accountTrieUpdatedMeter.Mark(int64(accountTrieNodesUpdated))
  1261  	accountTrieDeletedMeter.Mark(int64(accountTrieNodesDeleted))
  1262  	storageTriesUpdatedMeter.Mark(int64(storageTrieNodesUpdated))
  1263  	storageTriesDeletedMeter.Mark(int64(storageTrieNodesDeleted))
  1264  	s.AccountUpdated, s.AccountDeleted = 0, 0
  1265  	s.StorageUpdated, s.StorageDeleted = 0, 0
  1266  
  1267  	// If snapshotting is enabled, update the snapshot tree with this new version
  1268  	if s.snap != nil {
  1269  		start = time.Now()
  1270  		// Only update if there's a state transition (skip empty Clique blocks)
  1271  		if parent := s.snap.Root(); parent != root {
  1272  			if err := s.snaps.Update(root, parent, s.convertAccountSet(s.stateObjectsDestruct), s.accounts, s.storages); err != nil {
  1273  				log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err)
  1274  			}
  1275  			// Keep TriesInMemory diff layers in the memory, persistent layer is 129th.
  1276  			// - head layer is paired with HEAD state
  1277  			// - head-1 layer is paired with HEAD-1 state
  1278  			// - head-127 layer(bottom-most diff layer) is paired with HEAD-127 state
  1279  			if err := s.snaps.Cap(root, TriesInMemory); err != nil {
  1280  				log.Warn("Failed to cap snapshot tree", "root", root, "layers", TriesInMemory, "err", err)
  1281  			}
  1282  		}
  1283  		s.SnapshotCommits += time.Since(start)
  1284  		s.snap = nil
  1285  	}
  1286  	if root == (common.Hash{}) {
  1287  		root = types.EmptyRootHash
  1288  	}
  1289  	origin := s.originalRoot
  1290  	if origin == (common.Hash{}) {
  1291  		origin = types.EmptyRootHash
  1292  	}
  1293  	if root != origin {
  1294  		start = time.Now()
  1295  		set := triestate.New(s.accountsOrigin, s.storagesOrigin)
  1296  		if err := s.db.TrieDB().Update(root, origin, block, nodes, set); err != nil {
  1297  			return common.Hash{}, err
  1298  		}
  1299  		s.originalRoot = root
  1300  		s.TrieDBCommits += time.Since(start)
  1301  
  1302  		if s.onCommit != nil {
  1303  			s.onCommit(set)
  1304  		}
  1305  	}
  1306  	// Clear all internal flags at the end of commit operation.
  1307  	s.accounts = make(map[common.Hash][]byte)
  1308  	s.storages = make(map[common.Hash]map[common.Hash][]byte)
  1309  	s.accountsOrigin = make(map[common.Address][]byte)
  1310  	s.storagesOrigin = make(map[common.Address]map[common.Hash][]byte)
  1311  	s.mutations = make(map[common.Address]*mutation)
  1312  	s.stateObjectsDestruct = make(map[common.Address]*types.StateAccount)
  1313  	return root, nil
  1314  }
  1315  
  1316  // Prepare handles the preparatory steps for executing a state transition with.
  1317  // This method must be invoked before state transition.
  1318  //
  1319  // Berlin fork:
  1320  // - Add sender to access list (2929)
  1321  // - Add destination to access list (2929)
  1322  // - Add precompiles to access list (2929)
  1323  // - Add the contents of the optional tx access list (2930)
  1324  //
  1325  // Potential EIPs:
  1326  // - Reset access list (Berlin)
  1327  // - Add coinbase to access list (EIP-3651)
  1328  // - Reset transient storage (EIP-1153)
  1329  func (s *StateDB) Prepare(rules params.Rules, sender, coinbase common.Address, dst *common.Address, precompiles []common.Address, list types.AccessList) {
  1330  	if rules.IsBerlin {
  1331  		// Clear out any leftover from previous executions
  1332  		al := newAccessList()
  1333  		s.accessList = al
  1334  
  1335  		al.AddAddress(sender)
  1336  		if dst != nil {
  1337  			al.AddAddress(*dst)
  1338  			// If it's a create-tx, the destination will be added inside evm.create
  1339  		}
  1340  		for _, addr := range precompiles {
  1341  			al.AddAddress(addr)
  1342  		}
  1343  		for _, el := range list {
  1344  			al.AddAddress(el.Address)
  1345  			for _, key := range el.StorageKeys {
  1346  				al.AddSlot(el.Address, key)
  1347  			}
  1348  		}
  1349  		if rules.IsShanghai { // EIP-3651: warm coinbase
  1350  			al.AddAddress(coinbase)
  1351  		}
  1352  	}
  1353  	// Reset transient storage at the beginning of transaction execution
  1354  	s.transientStorage = newTransientStorage()
  1355  }
  1356  
  1357  // AddAddressToAccessList adds the given address to the access list
  1358  func (s *StateDB) AddAddressToAccessList(addr common.Address) {
  1359  	if s.accessList.AddAddress(addr) {
  1360  		s.journal.append(accessListAddAccountChange{&addr})
  1361  	}
  1362  }
  1363  
  1364  // AddSlotToAccessList adds the given (address, slot)-tuple to the access list
  1365  func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash) {
  1366  	addrMod, slotMod := s.accessList.AddSlot(addr, slot)
  1367  	if addrMod {
  1368  		// In practice, this should not happen, since there is no way to enter the
  1369  		// scope of 'address' without having the 'address' become already added
  1370  		// to the access list (via call-variant, create, etc).
  1371  		// Better safe than sorry, though
  1372  		s.journal.append(accessListAddAccountChange{&addr})
  1373  	}
  1374  	if slotMod {
  1375  		s.journal.append(accessListAddSlotChange{
  1376  			address: &addr,
  1377  			slot:    &slot,
  1378  		})
  1379  	}
  1380  }
  1381  
  1382  // AddressInAccessList returns true if the given address is in the access list.
  1383  func (s *StateDB) AddressInAccessList(addr common.Address) bool {
  1384  	return s.accessList.ContainsAddress(addr)
  1385  }
  1386  
  1387  // SlotInAccessList returns true if the given (address, slot)-tuple is in the access list.
  1388  func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool) {
  1389  	return s.accessList.Contains(addr, slot)
  1390  }
  1391  
  1392  // convertAccountSet converts a provided account set from address keyed to hash keyed.
  1393  func (s *StateDB) convertAccountSet(set map[common.Address]*types.StateAccount) map[common.Hash]struct{} {
  1394  	ret := make(map[common.Hash]struct{}, len(set))
  1395  	for addr := range set {
  1396  		obj, exist := s.stateObjects[addr]
  1397  		if !exist {
  1398  			ret[crypto.Keccak256Hash(addr[:])] = struct{}{}
  1399  		} else {
  1400  			ret[obj.addrHash] = struct{}{}
  1401  		}
  1402  	}
  1403  	return ret
  1404  }
  1405  
  1406  // copySet returns a deep-copied set.
  1407  func copySet[k comparable](set map[k][]byte) map[k][]byte {
  1408  	copied := make(map[k][]byte, len(set))
  1409  	for key, val := range set {
  1410  		copied[key] = common.CopyBytes(val)
  1411  	}
  1412  	return copied
  1413  }
  1414  
  1415  // copy2DSet returns a two-dimensional deep-copied set.
  1416  func copy2DSet[k comparable](set map[k]map[common.Hash][]byte) map[k]map[common.Hash][]byte {
  1417  	copied := make(map[k]map[common.Hash][]byte, len(set))
  1418  	for addr, subset := range set {
  1419  		copied[addr] = make(map[common.Hash][]byte, len(subset))
  1420  		for key, val := range subset {
  1421  			copied[addr][key] = common.CopyBytes(val)
  1422  		}
  1423  	}
  1424  	return copied
  1425  }
  1426  
  1427  func (s *StateDB) markDelete(addr common.Address) {
  1428  	if _, ok := s.mutations[addr]; !ok {
  1429  		s.mutations[addr] = &mutation{}
  1430  	}
  1431  	s.mutations[addr].applied = false
  1432  	s.mutations[addr].typ = deletion
  1433  }
  1434  
  1435  func (s *StateDB) markUpdate(addr common.Address) {
  1436  	if _, ok := s.mutations[addr]; !ok {
  1437  		s.mutations[addr] = &mutation{}
  1438  	}
  1439  	s.mutations[addr].applied = false
  1440  	s.mutations[addr].typ = update
  1441  }