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