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