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