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