github.com/ethereum-optimism/optimism/l2geth@v0.0.0-20230612200230-50b04ade19e3/core/state/statedb.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package state provides a caching layer atop the Ethereum state trie.
    18  package state
    19  
    20  import (
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"sort"
    25  	"time"
    26  
    27  	"github.com/ethereum-optimism/optimism/l2geth/statedumper"
    28  
    29  	"github.com/ethereum-optimism/optimism/l2geth/common"
    30  	"github.com/ethereum-optimism/optimism/l2geth/core/types"
    31  	"github.com/ethereum-optimism/optimism/l2geth/crypto"
    32  	"github.com/ethereum-optimism/optimism/l2geth/log"
    33  	"github.com/ethereum-optimism/optimism/l2geth/metrics"
    34  	"github.com/ethereum-optimism/optimism/l2geth/rlp"
    35  	"github.com/ethereum-optimism/optimism/l2geth/rollup/dump"
    36  	"github.com/ethereum-optimism/optimism/l2geth/rollup/rcfg"
    37  	"github.com/ethereum-optimism/optimism/l2geth/trie"
    38  	"golang.org/x/crypto/sha3"
    39  )
    40  
    41  type revision struct {
    42  	id           int
    43  	journalIndex int
    44  }
    45  
    46  var (
    47  	// emptyRoot is the known root hash of an empty trie.
    48  	emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
    49  
    50  	// emptyCode is the known hash of the empty EVM bytecode.
    51  	emptyCode = crypto.Keccak256Hash(nil)
    52  )
    53  
    54  type proofList [][]byte
    55  
    56  func (n *proofList) Put(key []byte, value []byte) error {
    57  	*n = append(*n, value)
    58  	return nil
    59  }
    60  
    61  func (n *proofList) Delete(key []byte) error {
    62  	panic("not supported")
    63  }
    64  
    65  func GetOVMBalanceKey(addr common.Address) common.Hash {
    66  	position := common.Big0
    67  	hasher := sha3.NewLegacyKeccak256()
    68  	hasher.Write(common.LeftPadBytes(addr.Bytes(), 32))
    69  	hasher.Write(common.LeftPadBytes(position.Bytes(), 32))
    70  	digest := hasher.Sum(nil)
    71  	return common.BytesToHash(digest)
    72  }
    73  
    74  // StateDBs within the ethereum protocol are used to store anything
    75  // within the merkle trie. StateDBs take care of caching and storing
    76  // nested states. It's the general query interface to retrieve:
    77  // * Contracts
    78  // * Accounts
    79  type StateDB struct {
    80  	db   Database
    81  	trie Trie
    82  
    83  	// This map holds 'live' objects, which will get modified while processing a state transition.
    84  	stateObjects        map[common.Address]*stateObject
    85  	stateObjectsPending map[common.Address]struct{} // State objects finalized but not yet written to the trie
    86  	stateObjectsDirty   map[common.Address]struct{} // State objects modified in the current execution
    87  
    88  	// DB error.
    89  	// State objects are used by the consensus core and VM which are
    90  	// unable to deal with database-level errors. Any error that occurs
    91  	// during a database read is memoized here and will eventually be returned
    92  	// by StateDB.Commit.
    93  	dbErr error
    94  
    95  	// The refund counter, also used by state transitioning.
    96  	refund uint64
    97  
    98  	thash, bhash common.Hash
    99  	txIndex      int
   100  	logs         map[common.Hash][]*types.Log
   101  	logSize      uint
   102  
   103  	preimages map[common.Hash][]byte
   104  
   105  	// Per-transaction access list
   106  	accessList *accessList
   107  
   108  	// Journal of state modifications. This is the backbone of
   109  	// Snapshot and RevertToSnapshot.
   110  	journal        *journal
   111  	validRevisions []revision
   112  	nextRevisionId int
   113  
   114  	// Measurements gathered during execution for debugging purposes
   115  	AccountReads   time.Duration
   116  	AccountHashes  time.Duration
   117  	AccountUpdates time.Duration
   118  	AccountCommits time.Duration
   119  	StorageReads   time.Duration
   120  	StorageHashes  time.Duration
   121  	StorageUpdates time.Duration
   122  	StorageCommits time.Duration
   123  }
   124  
   125  // Create a new state from a given trie.
   126  func New(root common.Hash, db Database) (*StateDB, error) {
   127  	tr, err := db.OpenTrie(root)
   128  	if err != nil {
   129  		return nil, err
   130  	}
   131  	return &StateDB{
   132  		db:                  db,
   133  		trie:                tr,
   134  		stateObjects:        make(map[common.Address]*stateObject),
   135  		stateObjectsPending: make(map[common.Address]struct{}),
   136  		stateObjectsDirty:   make(map[common.Address]struct{}),
   137  		logs:                make(map[common.Hash][]*types.Log),
   138  		preimages:           make(map[common.Hash][]byte),
   139  		journal:             newJournal(),
   140  		accessList:          newAccessList(),
   141  	}, nil
   142  }
   143  
   144  // setError remembers the first non-nil error it is called with.
   145  func (s *StateDB) setError(err error) {
   146  	if s.dbErr == nil {
   147  		s.dbErr = err
   148  	}
   149  }
   150  
   151  func (s *StateDB) Error() error {
   152  	return s.dbErr
   153  }
   154  
   155  // Reset clears out all ephemeral state objects from the state db, but keeps
   156  // the underlying state trie to avoid reloading data for the next operations.
   157  func (s *StateDB) Reset(root common.Hash) error {
   158  	tr, err := s.db.OpenTrie(root)
   159  	if err != nil {
   160  		return err
   161  	}
   162  	s.trie = tr
   163  	s.stateObjects = make(map[common.Address]*stateObject)
   164  	s.stateObjectsPending = make(map[common.Address]struct{})
   165  	s.stateObjectsDirty = make(map[common.Address]struct{})
   166  	s.thash = common.Hash{}
   167  	s.bhash = common.Hash{}
   168  	s.txIndex = 0
   169  	s.logs = make(map[common.Hash][]*types.Log)
   170  	s.logSize = 0
   171  	s.preimages = make(map[common.Hash][]byte)
   172  	s.accessList = newAccessList()
   173  	s.clearJournalAndRefund()
   174  	return nil
   175  }
   176  
   177  func (s *StateDB) AddLog(log *types.Log) {
   178  	s.journal.append(addLogChange{txhash: s.thash})
   179  
   180  	log.TxHash = s.thash
   181  	log.BlockHash = s.bhash
   182  	log.TxIndex = uint(s.txIndex)
   183  	log.Index = s.logSize
   184  	s.logs[s.thash] = append(s.logs[s.thash], log)
   185  	s.logSize++
   186  }
   187  
   188  func (s *StateDB) GetLogs(hash common.Hash) []*types.Log {
   189  	return s.logs[hash]
   190  }
   191  
   192  func (s *StateDB) Logs() []*types.Log {
   193  	var logs []*types.Log
   194  	for _, lgs := range s.logs {
   195  		logs = append(logs, lgs...)
   196  	}
   197  	return logs
   198  }
   199  
   200  // AddPreimage records a SHA3 preimage seen by the VM.
   201  func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
   202  	if _, ok := s.preimages[hash]; !ok {
   203  		s.journal.append(addPreimageChange{hash: hash})
   204  		pi := make([]byte, len(preimage))
   205  		copy(pi, preimage)
   206  		s.preimages[hash] = pi
   207  	}
   208  }
   209  
   210  // Preimages returns a list of SHA3 preimages that have been submitted.
   211  func (s *StateDB) Preimages() map[common.Hash][]byte {
   212  	return s.preimages
   213  }
   214  
   215  // AddRefund adds gas to the refund counter
   216  func (s *StateDB) AddRefund(gas uint64) {
   217  	s.journal.append(refundChange{prev: s.refund})
   218  	s.refund += gas
   219  }
   220  
   221  // SubRefund removes gas from the refund counter.
   222  // This method will panic if the refund counter goes below zero
   223  func (s *StateDB) SubRefund(gas uint64) {
   224  	s.journal.append(refundChange{prev: s.refund})
   225  	if gas > s.refund {
   226  		panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund))
   227  	}
   228  	s.refund -= gas
   229  }
   230  
   231  // Exist reports whether the given account address exists in the state.
   232  // Notably this also returns true for suicided accounts.
   233  func (s *StateDB) Exist(addr common.Address) bool {
   234  	return s.getStateObject(addr) != nil
   235  }
   236  
   237  // Empty returns whether the state object is either non-existent
   238  // or empty according to the EIP161 specification (balance = nonce = code = 0)
   239  func (s *StateDB) Empty(addr common.Address) bool {
   240  	so := s.getStateObject(addr)
   241  	return so == nil || so.empty()
   242  }
   243  
   244  // Retrieve the balance from the given address or 0 if object not found
   245  func (s *StateDB) GetBalance(addr common.Address) *big.Int {
   246  	if rcfg.UsingOVM {
   247  		// Get balance from the OVM_ETH contract.
   248  		// NOTE: We may remove this feature in a future release.
   249  		statedumper.WriteETH(addr)
   250  		key := GetOVMBalanceKey(addr)
   251  		bal := s.GetState(dump.OvmEthAddress, key)
   252  		return bal.Big()
   253  	} else {
   254  		stateObject := s.getStateObject(addr)
   255  		if stateObject != nil {
   256  			return stateObject.Balance()
   257  		}
   258  		return common.Big0
   259  	}
   260  }
   261  
   262  func (s *StateDB) GetNonce(addr common.Address) uint64 {
   263  	stateObject := s.getStateObject(addr)
   264  	if stateObject != nil {
   265  		return stateObject.Nonce()
   266  	}
   267  
   268  	return 0
   269  }
   270  
   271  // TxIndex returns the current transaction index set by Prepare.
   272  func (s *StateDB) TxIndex() int {
   273  	return s.txIndex
   274  }
   275  
   276  // BlockHash returns the current block hash set by Prepare.
   277  func (s *StateDB) BlockHash() common.Hash {
   278  	return s.bhash
   279  }
   280  
   281  func (s *StateDB) GetCode(addr common.Address) []byte {
   282  	stateObject := s.getStateObject(addr)
   283  	if stateObject != nil {
   284  		return stateObject.Code(s.db)
   285  	}
   286  	return nil
   287  }
   288  
   289  func (s *StateDB) GetCodeSize(addr common.Address) int {
   290  	stateObject := s.getStateObject(addr)
   291  	if stateObject == nil {
   292  		return 0
   293  	}
   294  	if stateObject.code != nil {
   295  		return len(stateObject.code)
   296  	}
   297  	size, err := s.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash()))
   298  	if err != nil {
   299  		s.setError(err)
   300  	}
   301  	return size
   302  }
   303  
   304  func (s *StateDB) GetCodeHash(addr common.Address) common.Hash {
   305  	stateObject := s.getStateObject(addr)
   306  	if stateObject == nil {
   307  		return common.Hash{}
   308  	}
   309  	return common.BytesToHash(stateObject.CodeHash())
   310  }
   311  
   312  // GetState retrieves a value from the given account's storage trie.
   313  func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash {
   314  	stateObject := s.getStateObject(addr)
   315  	if stateObject != nil {
   316  		return stateObject.GetState(s.db, hash)
   317  	}
   318  	return common.Hash{}
   319  }
   320  
   321  // GetProof returns the MerkleProof for a given Account
   322  func (s *StateDB) GetProof(a common.Address) ([][]byte, error) {
   323  	var proof proofList
   324  	err := s.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof)
   325  	return [][]byte(proof), err
   326  }
   327  
   328  // GetProof returns the StorageProof for given key
   329  func (s *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
   330  	var proof proofList
   331  	trie := s.StorageTrie(a)
   332  	if trie == nil {
   333  		return proof, errors.New("storage trie for requested address does not exist")
   334  	}
   335  	err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof)
   336  	return [][]byte(proof), err
   337  }
   338  
   339  // GetCommittedState retrieves a value from the given account's committed storage trie.
   340  func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
   341  	stateObject := s.getStateObject(addr)
   342  	if stateObject != nil {
   343  		return stateObject.GetCommittedState(s.db, hash)
   344  	}
   345  	return common.Hash{}
   346  }
   347  
   348  // Database retrieves the low level database supporting the lower level trie ops.
   349  func (s *StateDB) Database() Database {
   350  	return s.db
   351  }
   352  
   353  // StorageTrie returns the storage trie of an account.
   354  // The return value is a copy and is nil for non-existent accounts.
   355  func (s *StateDB) StorageTrie(addr common.Address) Trie {
   356  	stateObject := s.getStateObject(addr)
   357  	if stateObject == nil {
   358  		return nil
   359  	}
   360  	cpy := stateObject.deepCopy(s)
   361  	return cpy.updateTrie(s.db)
   362  }
   363  
   364  func (s *StateDB) HasSuicided(addr common.Address) bool {
   365  	stateObject := s.getStateObject(addr)
   366  	if stateObject != nil {
   367  		return stateObject.suicided
   368  	}
   369  	return false
   370  }
   371  
   372  /*
   373   * SETTERS
   374   */
   375  
   376  // AddBalance adds amount to the account associated with addr.
   377  func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) {
   378  	if rcfg.UsingOVM {
   379  		// Mutate the storage slot inside of OVM_ETH to change balances.
   380  		// Note that we don't need to check for overflows or underflows here because the code that
   381  		// uses this codepath already checks for them. You can follow the original codepath below
   382  		// (stateObject.AddBalance) to confirm that there are no checks being performed here.
   383  		statedumper.WriteETH(addr)
   384  		key := GetOVMBalanceKey(addr)
   385  		value := s.GetState(dump.OvmEthAddress, key)
   386  		bal := value.Big()
   387  		bal = bal.Add(bal, amount)
   388  		s.SetState(dump.OvmEthAddress, key, common.BigToHash(bal))
   389  	} else {
   390  		stateObject := s.GetOrNewStateObject(addr)
   391  		if stateObject != nil {
   392  			stateObject.AddBalance(amount)
   393  		}
   394  	}
   395  }
   396  
   397  // SubBalance subtracts amount from the account associated with addr.
   398  func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) {
   399  	if rcfg.UsingOVM {
   400  		// Mutate the storage slot inside of OVM_ETH to change balances.
   401  		// Note that we don't need to check for overflows or underflows here because the code that
   402  		// uses this codepath already checks for them. You can follow the original codepath below
   403  		// (stateObject.SubBalance) to confirm that there are no checks being performed here.
   404  		statedumper.WriteETH(addr)
   405  		key := GetOVMBalanceKey(addr)
   406  		value := s.GetState(dump.OvmEthAddress, key)
   407  		bal := value.Big()
   408  		bal = bal.Sub(bal, amount)
   409  		s.SetState(dump.OvmEthAddress, key, common.BigToHash(bal))
   410  	} else {
   411  		stateObject := s.GetOrNewStateObject(addr)
   412  		if stateObject != nil {
   413  			stateObject.SubBalance(amount)
   414  		}
   415  	}
   416  }
   417  
   418  func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) {
   419  	if rcfg.UsingOVM {
   420  		// Mutate the storage slot inside of OVM_ETH to change balances.
   421  		statedumper.WriteETH(addr)
   422  		key := GetOVMBalanceKey(addr)
   423  		s.SetState(dump.OvmEthAddress, key, common.BigToHash(amount))
   424  	} else {
   425  		stateObject := s.GetOrNewStateObject(addr)
   426  		if stateObject != nil {
   427  			stateObject.SetBalance(amount)
   428  		}
   429  	}
   430  }
   431  
   432  func (s *StateDB) SetNonce(addr common.Address, nonce uint64) {
   433  	stateObject := s.GetOrNewStateObject(addr)
   434  	if stateObject != nil {
   435  		stateObject.SetNonce(nonce)
   436  	}
   437  }
   438  
   439  func (s *StateDB) SetCode(addr common.Address, code []byte) {
   440  	stateObject := s.GetOrNewStateObject(addr)
   441  	if stateObject != nil {
   442  		stateObject.SetCode(crypto.Keccak256Hash(code), code)
   443  	}
   444  }
   445  
   446  func (s *StateDB) SetState(addr common.Address, key, value common.Hash) {
   447  	stateObject := s.GetOrNewStateObject(addr)
   448  	if stateObject != nil {
   449  		stateObject.SetState(s.db, key, value)
   450  	}
   451  }
   452  
   453  // SetStorage replaces the entire storage for the specified account with given
   454  // storage. This function should only be used for debugging.
   455  func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) {
   456  	stateObject := s.GetOrNewStateObject(addr)
   457  	if stateObject != nil {
   458  		stateObject.SetStorage(storage)
   459  	}
   460  }
   461  
   462  // Suicide marks the given account as suicided.
   463  // This clears the account balance.
   464  //
   465  // The account's state object is still available until the state is committed,
   466  // getStateObject will return a non-nil account after Suicide.
   467  func (s *StateDB) Suicide(addr common.Address) bool {
   468  	stateObject := s.getStateObject(addr)
   469  	if stateObject == nil {
   470  		return false
   471  	}
   472  	s.journal.append(suicideChange{
   473  		account:     &addr,
   474  		prev:        stateObject.suicided,
   475  		prevbalance: new(big.Int).Set(stateObject.Balance()),
   476  	})
   477  	stateObject.markSuicided()
   478  	stateObject.data.Balance = new(big.Int)
   479  
   480  	return true
   481  }
   482  
   483  //
   484  // Setting, updating & deleting state object methods.
   485  //
   486  
   487  // updateStateObject writes the given object to the trie.
   488  func (s *StateDB) updateStateObject(obj *stateObject) {
   489  	// Track the amount of time wasted on updating the account from the trie
   490  	if metrics.EnabledExpensive {
   491  		defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
   492  	}
   493  	// Encode the account and update the account trie
   494  	addr := obj.Address()
   495  
   496  	data, err := rlp.EncodeToBytes(obj)
   497  	if err != nil {
   498  		panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
   499  	}
   500  	s.setError(s.trie.TryUpdate(addr[:], data))
   501  }
   502  
   503  // deleteStateObject removes the given object from the state trie.
   504  func (s *StateDB) deleteStateObject(obj *stateObject) {
   505  	// Track the amount of time wasted on deleting the account from the trie
   506  	if metrics.EnabledExpensive {
   507  		defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
   508  	}
   509  	// Delete the account from the trie
   510  	addr := obj.Address()
   511  	s.setError(s.trie.TryDelete(addr[:]))
   512  }
   513  
   514  // getStateObject retrieves a state object given by the address, returning nil if
   515  // the object is not found or was deleted in this execution context. If you need
   516  // to differentiate between non-existent/just-deleted, use getDeletedStateObject.
   517  func (s *StateDB) getStateObject(addr common.Address) *stateObject {
   518  	if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted {
   519  		return obj
   520  	}
   521  	return nil
   522  }
   523  
   524  // getDeletedStateObject is similar to getStateObject, but instead of returning
   525  // nil for a deleted state object, it returns the actual object with the deleted
   526  // flag set. This is needed by the state journal to revert to the correct s-
   527  // destructed object instead of wiping all knowledge about the state object.
   528  func (s *StateDB) getDeletedStateObject(addr common.Address) *stateObject {
   529  	// Prefer live objects if any is available
   530  	if obj := s.stateObjects[addr]; obj != nil {
   531  		return obj
   532  	}
   533  	// Track the amount of time wasted on loading the object from the database
   534  	if metrics.EnabledExpensive {
   535  		defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now())
   536  	}
   537  	// Load the object from the database
   538  	enc, err := s.trie.TryGet(addr[:])
   539  	if len(enc) == 0 {
   540  		s.setError(err)
   541  		return nil
   542  	}
   543  	var data Account
   544  	if err := rlp.DecodeBytes(enc, &data); err != nil {
   545  		log.Error("Failed to decode state object", "addr", addr, "err", err)
   546  		return nil
   547  	}
   548  	// Insert into the live set
   549  	obj := newObject(s, addr, data)
   550  	s.setStateObject(obj)
   551  	return obj
   552  }
   553  
   554  func (s *StateDB) setStateObject(object *stateObject) {
   555  	s.stateObjects[object.Address()] = object
   556  }
   557  
   558  // Retrieve a state object or create a new state object if nil.
   559  func (s *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
   560  	stateObject := s.getStateObject(addr)
   561  	if stateObject == nil {
   562  		stateObject, _ = s.createObject(addr)
   563  	}
   564  	return stateObject
   565  }
   566  
   567  // createObject creates a new state object. If there is an existing account with
   568  // the given address, it is overwritten and returned as the second return value.
   569  func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
   570  	prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that!
   571  
   572  	newobj = newObject(s, addr, Account{})
   573  	newobj.setNonce(0) // sets the object to dirty
   574  	if prev == nil {
   575  		s.journal.append(createObjectChange{account: &addr})
   576  	} else {
   577  		s.journal.append(resetObjectChange{prev: prev})
   578  	}
   579  	s.setStateObject(newobj)
   580  	return newobj, prev
   581  }
   582  
   583  // CreateAccount explicitly creates a state object. If a state object with the address
   584  // already exists the balance is carried over to the new account.
   585  //
   586  // CreateAccount is called during the EVM CREATE operation. The situation might arise that
   587  // a contract does the following:
   588  //
   589  //  1. sends funds to sha(account ++ (nonce + 1))
   590  //  2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
   591  //
   592  // Carrying over the balance ensures that Ether doesn't disappear.
   593  func (s *StateDB) CreateAccount(addr common.Address) {
   594  	newObj, prev := s.createObject(addr)
   595  	if prev != nil {
   596  		newObj.setBalance(prev.data.Balance)
   597  	}
   598  }
   599  
   600  func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {
   601  	so := db.getStateObject(addr)
   602  	if so == nil {
   603  		return nil
   604  	}
   605  	it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
   606  
   607  	for it.Next() {
   608  		key := common.BytesToHash(db.trie.GetKey(it.Key))
   609  		if value, dirty := so.dirtyStorage[key]; dirty {
   610  			if !cb(key, value) {
   611  				return nil
   612  			}
   613  			continue
   614  		}
   615  
   616  		if len(it.Value) > 0 {
   617  			_, content, _, err := rlp.Split(it.Value)
   618  			if err != nil {
   619  				return err
   620  			}
   621  			if !cb(key, common.BytesToHash(content)) {
   622  				return nil
   623  			}
   624  		}
   625  	}
   626  	return nil
   627  }
   628  
   629  // Copy creates a deep, independent copy of the state.
   630  // Snapshots of the copied state cannot be applied to the copy.
   631  func (s *StateDB) Copy() *StateDB {
   632  	// Copy all the basic fields, initialize the memory ones
   633  	state := &StateDB{
   634  		db:                  s.db,
   635  		trie:                s.db.CopyTrie(s.trie),
   636  		stateObjects:        make(map[common.Address]*stateObject, len(s.journal.dirties)),
   637  		stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)),
   638  		stateObjectsDirty:   make(map[common.Address]struct{}, len(s.journal.dirties)),
   639  		refund:              s.refund,
   640  		logs:                make(map[common.Hash][]*types.Log, len(s.logs)),
   641  		logSize:             s.logSize,
   642  		preimages:           make(map[common.Hash][]byte, len(s.preimages)),
   643  		journal:             newJournal(),
   644  	}
   645  	// Copy the dirty states, logs, and preimages
   646  	for addr := range s.journal.dirties {
   647  		// As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527),
   648  		// and in the Finalise-method, there is a case where an object is in the journal but not
   649  		// in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
   650  		// nil
   651  		if object, exist := s.stateObjects[addr]; exist {
   652  			// Even though the original object is dirty, we are not copying the journal,
   653  			// so we need to make sure that anyside effect the journal would have caused
   654  			// during a commit (or similar op) is already applied to the copy.
   655  			state.stateObjects[addr] = object.deepCopy(state)
   656  
   657  			state.stateObjectsDirty[addr] = struct{}{}   // Mark the copy dirty to force internal (code/state) commits
   658  			state.stateObjectsPending[addr] = struct{}{} // Mark the copy pending to force external (account) commits
   659  		}
   660  	}
   661  	// Above, we don't copy the actual journal. This means that if the copy is copied, the
   662  	// loop above will be a no-op, since the copy's journal is empty.
   663  	// Thus, here we iterate over stateObjects, to enable copies of copies
   664  	for addr := range s.stateObjectsPending {
   665  		if _, exist := state.stateObjects[addr]; !exist {
   666  			state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
   667  		}
   668  		state.stateObjectsPending[addr] = struct{}{}
   669  	}
   670  	for addr := range s.stateObjectsDirty {
   671  		if _, exist := state.stateObjects[addr]; !exist {
   672  			state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
   673  		}
   674  		state.stateObjectsDirty[addr] = struct{}{}
   675  	}
   676  	for hash, logs := range s.logs {
   677  		cpy := make([]*types.Log, len(logs))
   678  		for i, l := range logs {
   679  			cpy[i] = new(types.Log)
   680  			*cpy[i] = *l
   681  		}
   682  		state.logs[hash] = cpy
   683  	}
   684  	for hash, preimage := range s.preimages {
   685  		state.preimages[hash] = preimage
   686  	}
   687  	// Do we need to copy the access list? In practice: No. At the start of a
   688  	// transaction, the access list is empty. In practice, we only ever copy state
   689  	// _between_ transactions/blocks, never in the middle of a transaction.
   690  	// However, it doesn't cost us much to copy an empty list, so we do it anyway
   691  	// to not blow up if we ever decide copy it in the middle of a transaction
   692  	state.accessList = s.accessList.Copy()
   693  
   694  	return state
   695  }
   696  
   697  // Snapshot returns an identifier for the current revision of the state.
   698  func (s *StateDB) Snapshot() int {
   699  	id := s.nextRevisionId
   700  	s.nextRevisionId++
   701  	s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()})
   702  	return id
   703  }
   704  
   705  // RevertToSnapshot reverts all state changes made since the given revision.
   706  func (s *StateDB) RevertToSnapshot(revid int) {
   707  	// Find the snapshot in the stack of valid snapshots.
   708  	idx := sort.Search(len(s.validRevisions), func(i int) bool {
   709  		return s.validRevisions[i].id >= revid
   710  	})
   711  	if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid {
   712  		panic(fmt.Errorf("revision id %v cannot be reverted", revid))
   713  	}
   714  	snapshot := s.validRevisions[idx].journalIndex
   715  
   716  	// Replay the journal to undo changes and remove invalidated snapshots
   717  	s.journal.revert(s, snapshot)
   718  	s.validRevisions = s.validRevisions[:idx]
   719  }
   720  
   721  // GetRefund returns the current value of the refund counter.
   722  func (s *StateDB) GetRefund() uint64 {
   723  	return s.refund
   724  }
   725  
   726  // Finalise finalises the state by removing the s destructed objects and clears
   727  // the journal as well as the refunds. Finalise, however, will not push any updates
   728  // into the tries just yet. Only IntermediateRoot or Commit will do that.
   729  func (s *StateDB) Finalise(deleteEmptyObjects bool) {
   730  	for addr := range s.journal.dirties {
   731  		obj, exist := s.stateObjects[addr]
   732  		if !exist {
   733  			// ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
   734  			// That tx goes out of gas, and although the notion of 'touched' does not exist there, the
   735  			// touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
   736  			// it will persist in the journal even though the journal is reverted. In this special circumstance,
   737  			// it may exist in `s.journal.dirties` but not in `s.stateObjects`.
   738  			// Thus, we can safely ignore it here
   739  			continue
   740  		}
   741  		if obj.suicided || (deleteEmptyObjects && obj.empty()) {
   742  			obj.deleted = true
   743  		} else {
   744  			obj.finalise()
   745  		}
   746  		s.stateObjectsPending[addr] = struct{}{}
   747  		s.stateObjectsDirty[addr] = struct{}{}
   748  	}
   749  	// Invalidate journal because reverting across transactions is not allowed.
   750  	s.clearJournalAndRefund()
   751  }
   752  
   753  // IntermediateRoot computes the current root hash of the state trie.
   754  // It is called in between transactions to get the root hash that
   755  // goes into transaction receipts.
   756  func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
   757  	// Finalise all the dirty storage states and write them into the tries
   758  	s.Finalise(deleteEmptyObjects)
   759  
   760  	for addr := range s.stateObjectsPending {
   761  		obj := s.stateObjects[addr]
   762  		if obj.deleted {
   763  			s.deleteStateObject(obj)
   764  		} else {
   765  			obj.updateRoot(s.db)
   766  			s.updateStateObject(obj)
   767  		}
   768  	}
   769  	if len(s.stateObjectsPending) > 0 {
   770  		s.stateObjectsPending = make(map[common.Address]struct{})
   771  	}
   772  	// Track the amount of time wasted on hashing the account trie
   773  	if metrics.EnabledExpensive {
   774  		defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now())
   775  	}
   776  	return s.trie.Hash()
   777  }
   778  
   779  // Prepare sets the current transaction hash and index and block hash which is
   780  // used when the EVM emits new state logs.
   781  func (s *StateDB) Prepare(thash, bhash common.Hash, ti int) {
   782  	s.thash = thash
   783  	s.bhash = bhash
   784  	s.txIndex = ti
   785  	s.accessList = newAccessList()
   786  }
   787  
   788  func (s *StateDB) clearJournalAndRefund() {
   789  	if len(s.journal.entries) > 0 {
   790  		s.journal = newJournal()
   791  		s.refund = 0
   792  	}
   793  	s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entires
   794  }
   795  
   796  // Commit writes the state to the underlying in-memory trie database.
   797  func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) {
   798  	// Finalize any pending changes and merge everything into the tries
   799  	s.IntermediateRoot(deleteEmptyObjects)
   800  
   801  	// Commit objects to the trie, measuring the elapsed time
   802  	for addr := range s.stateObjectsDirty {
   803  		if obj := s.stateObjects[addr]; !obj.deleted {
   804  			// Write any contract code associated with the state object
   805  			if obj.code != nil && obj.dirtyCode {
   806  				s.db.TrieDB().InsertBlob(common.BytesToHash(obj.CodeHash()), obj.code)
   807  				obj.dirtyCode = false
   808  			}
   809  			// Write any storage changes in the state object to its storage trie
   810  			if err := obj.CommitTrie(s.db); err != nil {
   811  				return common.Hash{}, err
   812  			}
   813  		}
   814  	}
   815  	if len(s.stateObjectsDirty) > 0 {
   816  		s.stateObjectsDirty = make(map[common.Address]struct{})
   817  	}
   818  	// Write the account trie changes, measuing the amount of wasted time
   819  	if metrics.EnabledExpensive {
   820  		defer func(start time.Time) { s.AccountCommits += time.Since(start) }(time.Now())
   821  	}
   822  	return s.trie.Commit(func(leaf []byte, parent common.Hash) error {
   823  		var account Account
   824  		if err := rlp.DecodeBytes(leaf, &account); err != nil {
   825  			return nil
   826  		}
   827  		if account.Root != emptyRoot {
   828  			s.db.TrieDB().Reference(account.Root, parent)
   829  		}
   830  		code := common.BytesToHash(account.CodeHash)
   831  		if code != emptyCode {
   832  			s.db.TrieDB().Reference(code, parent)
   833  		}
   834  		return nil
   835  	})
   836  }
   837  
   838  // PrepareAccessList handles the preparatory steps for executing a state transition with
   839  // regards to both EIP-2929 and EIP-2930:
   840  //
   841  // - Add sender to access list (2929)
   842  // - Add destination to access list (2929)
   843  // - Add precompiles to access list (2929)
   844  // - Add the contents of the optional tx access list (2930)
   845  //
   846  // This method should only be called if Berlin/2929+2930 is applicable at the current number.
   847  func (s *StateDB) PrepareAccessList(sender common.Address, dst *common.Address, precompiles []common.Address, list types.AccessList) {
   848  	s.AddAddressToAccessList(sender)
   849  	if dst != nil {
   850  		s.AddAddressToAccessList(*dst)
   851  	}
   852  	for _, addr := range precompiles {
   853  		s.AddAddressToAccessList(addr)
   854  	}
   855  	for _, el := range list {
   856  		s.AddAddressToAccessList(el.Address)
   857  		for _, key := range el.StorageKeys {
   858  			s.AddSlotToAccessList(el.Address, key)
   859  		}
   860  	}
   861  }
   862  
   863  // AddAddressToAccessList adds the given address to the access list
   864  func (s *StateDB) AddAddressToAccessList(addr common.Address) {
   865  	if s.accessList.AddAddress(addr) {
   866  		s.journal.append(accessListAddAccountChange{&addr})
   867  	}
   868  }
   869  
   870  // AddSlotToAccessList adds the given (address, slot)-tuple to the access list
   871  func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash) {
   872  	addrMod, slotMod := s.accessList.AddSlot(addr, slot)
   873  	if addrMod {
   874  		// In practice, this should not happen, since there is no way to enter the
   875  		// scope of 'address' without having the 'address' become already added
   876  		// to the access list (via call-variant, create, etc).
   877  		// Better safe than sorry, though
   878  		s.journal.append(accessListAddAccountChange{&addr})
   879  	}
   880  	if slotMod {
   881  		s.journal.append(accessListAddSlotChange{
   882  			address: &addr,
   883  			slot:    &slot,
   884  		})
   885  	}
   886  }
   887  
   888  // AddressInAccessList returns true if the given address is in the access list.
   889  func (s *StateDB) AddressInAccessList(addr common.Address) bool {
   890  	return s.accessList.ContainsAddress(addr)
   891  }
   892  
   893  // SlotInAccessList returns true if the given (address, slot)-tuple is in the access list.
   894  func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool) {
   895  	return s.accessList.Contains(addr, slot)
   896  }