github.com/MetalBlockchain/subnet-evm@v0.4.9/core/state/statedb.go (about)

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