git.pirl.io/community/pirl@v0.0.0-20201111064343-9d3d31ff74be/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  	"git.pirl.io/community/pirl/common"
    28  	"git.pirl.io/community/pirl/core/types"
    29  	"git.pirl.io/community/pirl/crypto"
    30  	"git.pirl.io/community/pirl/log"
    31  	"git.pirl.io/community/pirl/metrics"
    32  	"git.pirl.io/community/pirl/rlp"
    33  	"git.pirl.io/community/pirl/trie"
    34  )
    35  
    36  type revision struct {
    37  	id           int
    38  	journalIndex int
    39  }
    40  
    41  var (
    42  	// emptyRoot is the known root hash of an empty trie.
    43  	emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
    44  
    45  	// emptyCode is the known hash of the empty EVM bytecode.
    46  	emptyCode = crypto.Keccak256Hash(nil)
    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  // StateDBs 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  	// This map holds 'live' objects, which will get modified while processing a state transition.
    70  	stateObjects        map[common.Address]*stateObject
    71  	stateObjectsPending map[common.Address]struct{} // State objects finalized but not yet written to the trie
    72  	stateObjectsDirty   map[common.Address]struct{} // State objects modified in the current execution
    73  
    74  	// DB error.
    75  	// State objects are used by the consensus core and VM which are
    76  	// unable to deal with database-level errors. Any error that occurs
    77  	// during a database read is memoized here and will eventually be returned
    78  	// by StateDB.Commit.
    79  	dbErr error
    80  
    81  	// The refund counter, also used by state transitioning.
    82  	refund uint64
    83  
    84  	thash, bhash common.Hash
    85  	txIndex      int
    86  	logs         map[common.Hash][]*types.Log
    87  	logSize      uint
    88  
    89  	preimages map[common.Hash][]byte
    90  
    91  	// Journal of state modifications. This is the backbone of
    92  	// Snapshot and RevertToSnapshot.
    93  	journal        *journal
    94  	validRevisions []revision
    95  	nextRevisionId int
    96  
    97  	// Measurements gathered during execution for debugging purposes
    98  	AccountReads   time.Duration
    99  	AccountHashes  time.Duration
   100  	AccountUpdates time.Duration
   101  	AccountCommits time.Duration
   102  	StorageReads   time.Duration
   103  	StorageHashes  time.Duration
   104  	StorageUpdates time.Duration
   105  	StorageCommits time.Duration
   106  }
   107  
   108  // Create a new state from a given trie.
   109  func New(root common.Hash, db Database) (*StateDB, error) {
   110  	tr, err := db.OpenTrie(root)
   111  	if err != nil {
   112  		return nil, err
   113  	}
   114  	return &StateDB{
   115  		db:                  db,
   116  		trie:                tr,
   117  		stateObjects:        make(map[common.Address]*stateObject),
   118  		stateObjectsPending: make(map[common.Address]struct{}),
   119  		stateObjectsDirty:   make(map[common.Address]struct{}),
   120  		logs:                make(map[common.Hash][]*types.Log),
   121  		preimages:           make(map[common.Hash][]byte),
   122  		journal:             newJournal(),
   123  	}, nil
   124  }
   125  
   126  // setError remembers the first non-nil error it is called with.
   127  func (s *StateDB) setError(err error) {
   128  	if s.dbErr == nil {
   129  		s.dbErr = err
   130  	}
   131  }
   132  
   133  func (s *StateDB) Error() error {
   134  	return s.dbErr
   135  }
   136  
   137  // Reset clears out all ephemeral state objects from the state db, but keeps
   138  // the underlying state trie to avoid reloading data for the next operations.
   139  func (s *StateDB) Reset(root common.Hash) error {
   140  	tr, err := s.db.OpenTrie(root)
   141  	if err != nil {
   142  		return err
   143  	}
   144  	s.trie = tr
   145  	s.stateObjects = make(map[common.Address]*stateObject)
   146  	s.stateObjectsPending = make(map[common.Address]struct{})
   147  	s.stateObjectsDirty = make(map[common.Address]struct{})
   148  	s.thash = common.Hash{}
   149  	s.bhash = common.Hash{}
   150  	s.txIndex = 0
   151  	s.logs = make(map[common.Hash][]*types.Log)
   152  	s.logSize = 0
   153  	s.preimages = make(map[common.Hash][]byte)
   154  	s.clearJournalAndRefund()
   155  	return nil
   156  }
   157  
   158  func (s *StateDB) AddLog(log *types.Log) {
   159  	s.journal.append(addLogChange{txhash: s.thash})
   160  
   161  	log.TxHash = s.thash
   162  	log.BlockHash = s.bhash
   163  	log.TxIndex = uint(s.txIndex)
   164  	log.Index = s.logSize
   165  	s.logs[s.thash] = append(s.logs[s.thash], log)
   166  	s.logSize++
   167  }
   168  
   169  func (s *StateDB) GetLogs(hash common.Hash) []*types.Log {
   170  	return s.logs[hash]
   171  }
   172  
   173  func (s *StateDB) Logs() []*types.Log {
   174  	var logs []*types.Log
   175  	for _, lgs := range s.logs {
   176  		logs = append(logs, lgs...)
   177  	}
   178  	return logs
   179  }
   180  
   181  // AddPreimage records a SHA3 preimage seen by the VM.
   182  func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
   183  	if _, ok := s.preimages[hash]; !ok {
   184  		s.journal.append(addPreimageChange{hash: hash})
   185  		pi := make([]byte, len(preimage))
   186  		copy(pi, preimage)
   187  		s.preimages[hash] = pi
   188  	}
   189  }
   190  
   191  // Preimages returns a list of SHA3 preimages that have been submitted.
   192  func (s *StateDB) Preimages() map[common.Hash][]byte {
   193  	return s.preimages
   194  }
   195  
   196  // AddRefund adds gas to the refund counter
   197  func (s *StateDB) AddRefund(gas uint64) {
   198  	s.journal.append(refundChange{prev: s.refund})
   199  	s.refund += gas
   200  }
   201  
   202  // SubRefund removes gas from the refund counter.
   203  // This method will panic if the refund counter goes below zero
   204  func (s *StateDB) SubRefund(gas uint64) {
   205  	s.journal.append(refundChange{prev: s.refund})
   206  	if gas > s.refund {
   207  		panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund))
   208  	}
   209  	s.refund -= gas
   210  }
   211  
   212  // Exist reports whether the given account address exists in the state.
   213  // Notably this also returns true for suicided accounts.
   214  func (s *StateDB) Exist(addr common.Address) bool {
   215  	return s.getStateObject(addr) != nil
   216  }
   217  
   218  // Empty returns whether the state object is either non-existent
   219  // or empty according to the EIP161 specification (balance = nonce = code = 0)
   220  func (s *StateDB) Empty(addr common.Address) bool {
   221  	so := s.getStateObject(addr)
   222  	return so == nil || so.empty()
   223  }
   224  
   225  // Retrieve the balance from the given address or 0 if object not found
   226  func (s *StateDB) GetBalance(addr common.Address) *big.Int {
   227  	stateObject := s.getStateObject(addr)
   228  	if stateObject != nil {
   229  		return stateObject.Balance()
   230  	}
   231  	return common.Big0
   232  }
   233  
   234  func (s *StateDB) GetNonce(addr common.Address) uint64 {
   235  	stateObject := s.getStateObject(addr)
   236  	if stateObject != nil {
   237  		return stateObject.Nonce()
   238  	}
   239  
   240  	return 0
   241  }
   242  
   243  // TxIndex returns the current transaction index set by Prepare.
   244  func (s *StateDB) TxIndex() int {
   245  	return s.txIndex
   246  }
   247  
   248  // BlockHash returns the current block hash set by Prepare.
   249  func (s *StateDB) BlockHash() common.Hash {
   250  	return s.bhash
   251  }
   252  
   253  func (s *StateDB) GetCode(addr common.Address) []byte {
   254  	stateObject := s.getStateObject(addr)
   255  	if stateObject != nil {
   256  		return stateObject.Code(s.db)
   257  	}
   258  	return nil
   259  }
   260  
   261  func (s *StateDB) GetCodeSize(addr common.Address) int {
   262  	stateObject := s.getStateObject(addr)
   263  	if stateObject == nil {
   264  		return 0
   265  	}
   266  	if stateObject.code != nil {
   267  		return len(stateObject.code)
   268  	}
   269  	size, err := s.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash()))
   270  	if err != nil {
   271  		s.setError(err)
   272  	}
   273  	return size
   274  }
   275  
   276  func (s *StateDB) GetCodeHash(addr common.Address) common.Hash {
   277  	stateObject := s.getStateObject(addr)
   278  	if stateObject == nil {
   279  		return common.Hash{}
   280  	}
   281  	return common.BytesToHash(stateObject.CodeHash())
   282  }
   283  
   284  // GetState retrieves a value from the given account's storage trie.
   285  func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash {
   286  	stateObject := s.getStateObject(addr)
   287  	if stateObject != nil {
   288  		return stateObject.GetState(s.db, hash)
   289  	}
   290  	return common.Hash{}
   291  }
   292  
   293  // GetProof returns the MerkleProof for a given Account
   294  func (s *StateDB) GetProof(a common.Address) ([][]byte, error) {
   295  	var proof proofList
   296  	err := s.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof)
   297  	return [][]byte(proof), err
   298  }
   299  
   300  // GetProof returns the StorageProof for given key
   301  func (s *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
   302  	var proof proofList
   303  	trie := s.StorageTrie(a)
   304  	if trie == nil {
   305  		return proof, errors.New("storage trie for requested address does not exist")
   306  	}
   307  	err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof)
   308  	return [][]byte(proof), err
   309  }
   310  
   311  // GetCommittedState retrieves a value from the given account's committed storage trie.
   312  func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
   313  	stateObject := s.getStateObject(addr)
   314  	if stateObject != nil {
   315  		return stateObject.GetCommittedState(s.db, hash)
   316  	}
   317  	return common.Hash{}
   318  }
   319  
   320  // Database retrieves the low level database supporting the lower level trie ops.
   321  func (s *StateDB) Database() Database {
   322  	return s.db
   323  }
   324  
   325  // StorageTrie returns the storage trie of an account.
   326  // The return value is a copy and is nil for non-existent accounts.
   327  func (s *StateDB) StorageTrie(addr common.Address) Trie {
   328  	stateObject := s.getStateObject(addr)
   329  	if stateObject == nil {
   330  		return nil
   331  	}
   332  	cpy := stateObject.deepCopy(s)
   333  	cpy.updateTrie(s.db)
   334  	return cpy.getTrie(s.db)
   335  }
   336  
   337  func (s *StateDB) HasSuicided(addr common.Address) bool {
   338  	stateObject := s.getStateObject(addr)
   339  	if stateObject != nil {
   340  		return stateObject.suicided
   341  	}
   342  	return false
   343  }
   344  
   345  /*
   346   * SETTERS
   347   */
   348  
   349  // AddBalance adds amount to the account associated with addr.
   350  func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) {
   351  	stateObject := s.GetOrNewStateObject(addr)
   352  	if stateObject != nil {
   353  		stateObject.AddBalance(amount)
   354  	}
   355  }
   356  
   357  // SubBalance subtracts amount from the account associated with addr.
   358  func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) {
   359  	stateObject := s.GetOrNewStateObject(addr)
   360  	if stateObject != nil {
   361  		stateObject.SubBalance(amount)
   362  	}
   363  }
   364  
   365  func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) {
   366  	stateObject := s.GetOrNewStateObject(addr)
   367  	if stateObject != nil {
   368  		stateObject.SetBalance(amount)
   369  	}
   370  }
   371  
   372  func (s *StateDB) SetNonce(addr common.Address, nonce uint64) {
   373  	stateObject := s.GetOrNewStateObject(addr)
   374  	if stateObject != nil {
   375  		stateObject.SetNonce(nonce)
   376  	}
   377  }
   378  
   379  func (s *StateDB) SetCode(addr common.Address, code []byte) {
   380  	stateObject := s.GetOrNewStateObject(addr)
   381  	if stateObject != nil {
   382  		stateObject.SetCode(crypto.Keccak256Hash(code), code)
   383  	}
   384  }
   385  
   386  func (s *StateDB) SetState(addr common.Address, key, value common.Hash) {
   387  	stateObject := s.GetOrNewStateObject(addr)
   388  	if stateObject != nil {
   389  		stateObject.SetState(s.db, key, value)
   390  	}
   391  }
   392  
   393  // SetStorage replaces the entire storage for the specified account with given
   394  // storage. This function should only be used for debugging.
   395  func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) {
   396  	stateObject := s.GetOrNewStateObject(addr)
   397  	if stateObject != nil {
   398  		stateObject.SetStorage(storage)
   399  	}
   400  }
   401  
   402  // Suicide marks the given account as suicided.
   403  // This clears the account balance.
   404  //
   405  // The account's state object is still available until the state is committed,
   406  // getStateObject will return a non-nil account after Suicide.
   407  func (s *StateDB) Suicide(addr common.Address) bool {
   408  	stateObject := s.getStateObject(addr)
   409  	if stateObject == nil {
   410  		return false
   411  	}
   412  	s.journal.append(suicideChange{
   413  		account:     &addr,
   414  		prev:        stateObject.suicided,
   415  		prevbalance: new(big.Int).Set(stateObject.Balance()),
   416  	})
   417  	stateObject.markSuicided()
   418  	stateObject.data.Balance = new(big.Int)
   419  
   420  	return true
   421  }
   422  
   423  //
   424  // Setting, updating & deleting state object methods.
   425  //
   426  
   427  // updateStateObject writes the given object to the trie.
   428  func (s *StateDB) updateStateObject(obj *stateObject) {
   429  	// Track the amount of time wasted on updating the account from the trie
   430  	if metrics.EnabledExpensive {
   431  		defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
   432  	}
   433  	// Encode the account and update the account trie
   434  	addr := obj.Address()
   435  
   436  	data, err := rlp.EncodeToBytes(obj)
   437  	if err != nil {
   438  		panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
   439  	}
   440  	s.setError(s.trie.TryUpdate(addr[:], data))
   441  }
   442  
   443  // deleteStateObject removes the given object from the state trie.
   444  func (s *StateDB) deleteStateObject(obj *stateObject) {
   445  	// Track the amount of time wasted on deleting the account from the trie
   446  	if metrics.EnabledExpensive {
   447  		defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
   448  	}
   449  	// Delete the account from the trie
   450  	addr := obj.Address()
   451  	s.setError(s.trie.TryDelete(addr[:]))
   452  }
   453  
   454  // getStateObject retrieves a state object given by the address, returning nil if
   455  // the object is not found or was deleted in this execution context. If you need
   456  // to differentiate between non-existent/just-deleted, use getDeletedStateObject.
   457  func (s *StateDB) getStateObject(addr common.Address) *stateObject {
   458  	if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted {
   459  		return obj
   460  	}
   461  	return nil
   462  }
   463  
   464  // getDeletedStateObject is similar to getStateObject, but instead of returning
   465  // nil for a deleted state object, it returns the actual object with the deleted
   466  // flag set. This is needed by the state journal to revert to the correct s-
   467  // destructed object instead of wiping all knowledge about the state object.
   468  func (s *StateDB) getDeletedStateObject(addr common.Address) *stateObject {
   469  	// Prefer live objects if any is available
   470  	if obj := s.stateObjects[addr]; obj != nil {
   471  		return obj
   472  	}
   473  	// Track the amount of time wasted on loading the object from the database
   474  	if metrics.EnabledExpensive {
   475  		defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now())
   476  	}
   477  	// Load the object from the database
   478  	enc, err := s.trie.TryGet(addr[:])
   479  	if len(enc) == 0 {
   480  		s.setError(err)
   481  		return nil
   482  	}
   483  	var data Account
   484  	if err := rlp.DecodeBytes(enc, &data); err != nil {
   485  		log.Error("Failed to decode state object", "addr", addr, "err", err)
   486  		return nil
   487  	}
   488  	// Insert into the live set
   489  	obj := newObject(s, addr, data)
   490  	s.setStateObject(obj)
   491  	return obj
   492  }
   493  
   494  func (s *StateDB) setStateObject(object *stateObject) {
   495  	s.stateObjects[object.Address()] = object
   496  }
   497  
   498  // Retrieve a state object or create a new state object if nil.
   499  func (s *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
   500  	stateObject := s.getStateObject(addr)
   501  	if stateObject == nil {
   502  		stateObject, _ = s.createObject(addr)
   503  	}
   504  	return stateObject
   505  }
   506  
   507  // createObject creates a new state object. If there is an existing account with
   508  // the given address, it is overwritten and returned as the second return value.
   509  func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
   510  	prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that!
   511  
   512  	newobj = newObject(s, addr, Account{})
   513  	newobj.setNonce(0) // sets the object to dirty
   514  	if prev == nil {
   515  		s.journal.append(createObjectChange{account: &addr})
   516  	} else {
   517  		s.journal.append(resetObjectChange{prev: prev})
   518  	}
   519  	s.setStateObject(newobj)
   520  	return newobj, prev
   521  }
   522  
   523  // CreateAccount explicitly creates a state object. If a state object with the address
   524  // already exists the balance is carried over to the new account.
   525  //
   526  // CreateAccount is called during the EVM CREATE operation. The situation might arise that
   527  // a contract does the following:
   528  //
   529  //   1. sends funds to sha(account ++ (nonce + 1))
   530  //   2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
   531  //
   532  // Carrying over the balance ensures that Ether doesn't disappear.
   533  func (s *StateDB) CreateAccount(addr common.Address) {
   534  	newObj, prev := s.createObject(addr)
   535  	if prev != nil {
   536  		newObj.setBalance(prev.data.Balance)
   537  	}
   538  }
   539  
   540  func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {
   541  	so := db.getStateObject(addr)
   542  	if so == nil {
   543  		return nil
   544  	}
   545  	it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
   546  
   547  	for it.Next() {
   548  		key := common.BytesToHash(db.trie.GetKey(it.Key))
   549  		if value, dirty := so.dirtyStorage[key]; dirty {
   550  			if !cb(key, value) {
   551  				return nil
   552  			}
   553  			continue
   554  		}
   555  
   556  		if len(it.Value) > 0 {
   557  			_, content, _, err := rlp.Split(it.Value)
   558  			if err != nil {
   559  				return err
   560  			}
   561  			if !cb(key, common.BytesToHash(content)) {
   562  				return nil
   563  			}
   564  		}
   565  	}
   566  	return nil
   567  }
   568  
   569  // Copy creates a deep, independent copy of the state.
   570  // Snapshots of the copied state cannot be applied to the copy.
   571  func (s *StateDB) Copy() *StateDB {
   572  	// Copy all the basic fields, initialize the memory ones
   573  	state := &StateDB{
   574  		db:                  s.db,
   575  		trie:                s.db.CopyTrie(s.trie),
   576  		stateObjects:        make(map[common.Address]*stateObject, len(s.journal.dirties)),
   577  		stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)),
   578  		stateObjectsDirty:   make(map[common.Address]struct{}, len(s.journal.dirties)),
   579  		refund:              s.refund,
   580  		logs:                make(map[common.Hash][]*types.Log, len(s.logs)),
   581  		logSize:             s.logSize,
   582  		preimages:           make(map[common.Hash][]byte, len(s.preimages)),
   583  		journal:             newJournal(),
   584  	}
   585  	// Copy the dirty states, logs, and preimages
   586  	for addr := range s.journal.dirties {
   587  		// As documented [here](https://git.pirl.io/community/pirl/pull/16485#issuecomment-380438527),
   588  		// and in the Finalise-method, there is a case where an object is in the journal but not
   589  		// in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
   590  		// nil
   591  		if object, exist := s.stateObjects[addr]; exist {
   592  			// Even though the original object is dirty, we are not copying the journal,
   593  			// so we need to make sure that anyside effect the journal would have caused
   594  			// during a commit (or similar op) is already applied to the copy.
   595  			state.stateObjects[addr] = object.deepCopy(state)
   596  
   597  			state.stateObjectsDirty[addr] = struct{}{}   // Mark the copy dirty to force internal (code/state) commits
   598  			state.stateObjectsPending[addr] = struct{}{} // Mark the copy pending to force external (account) commits
   599  		}
   600  	}
   601  	// Above, we don't copy the actual journal. This means that if the copy is copied, the
   602  	// loop above will be a no-op, since the copy's journal is empty.
   603  	// Thus, here we iterate over stateObjects, to enable copies of copies
   604  	for addr := range s.stateObjectsPending {
   605  		if _, exist := state.stateObjects[addr]; !exist {
   606  			state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
   607  		}
   608  		state.stateObjectsPending[addr] = struct{}{}
   609  	}
   610  	for addr := range s.stateObjectsDirty {
   611  		if _, exist := state.stateObjects[addr]; !exist {
   612  			state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
   613  		}
   614  		state.stateObjectsDirty[addr] = struct{}{}
   615  	}
   616  	for hash, logs := range s.logs {
   617  		cpy := make([]*types.Log, len(logs))
   618  		for i, l := range logs {
   619  			cpy[i] = new(types.Log)
   620  			*cpy[i] = *l
   621  		}
   622  		state.logs[hash] = cpy
   623  	}
   624  	for hash, preimage := range s.preimages {
   625  		state.preimages[hash] = preimage
   626  	}
   627  	return state
   628  }
   629  
   630  // Snapshot returns an identifier for the current revision of the state.
   631  func (s *StateDB) Snapshot() int {
   632  	id := s.nextRevisionId
   633  	s.nextRevisionId++
   634  	s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()})
   635  	return id
   636  }
   637  
   638  // RevertToSnapshot reverts all state changes made since the given revision.
   639  func (s *StateDB) RevertToSnapshot(revid int) {
   640  	// Find the snapshot in the stack of valid snapshots.
   641  	idx := sort.Search(len(s.validRevisions), func(i int) bool {
   642  		return s.validRevisions[i].id >= revid
   643  	})
   644  	if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid {
   645  		panic(fmt.Errorf("revision id %v cannot be reverted", revid))
   646  	}
   647  	snapshot := s.validRevisions[idx].journalIndex
   648  
   649  	// Replay the journal to undo changes and remove invalidated snapshots
   650  	s.journal.revert(s, snapshot)
   651  	s.validRevisions = s.validRevisions[:idx]
   652  }
   653  
   654  // GetRefund returns the current value of the refund counter.
   655  func (s *StateDB) GetRefund() uint64 {
   656  	return s.refund
   657  }
   658  
   659  // Finalise finalises the state by removing the s destructed objects and clears
   660  // the journal as well as the refunds. Finalise, however, will not push any updates
   661  // into the tries just yet. Only IntermediateRoot or Commit will do that.
   662  func (s *StateDB) Finalise(deleteEmptyObjects bool) {
   663  	for addr := range s.journal.dirties {
   664  		obj, exist := s.stateObjects[addr]
   665  		if !exist {
   666  			// ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
   667  			// That tx goes out of gas, and although the notion of 'touched' does not exist there, the
   668  			// touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
   669  			// it will persist in the journal even though the journal is reverted. In this special circumstance,
   670  			// it may exist in `s.journal.dirties` but not in `s.stateObjects`.
   671  			// Thus, we can safely ignore it here
   672  			continue
   673  		}
   674  		if obj.suicided || (deleteEmptyObjects && obj.empty()) {
   675  			obj.deleted = true
   676  		} else {
   677  			obj.finalise()
   678  		}
   679  		s.stateObjectsPending[addr] = struct{}{}
   680  		s.stateObjectsDirty[addr] = struct{}{}
   681  	}
   682  	// Invalidate journal because reverting across transactions is not allowed.
   683  	s.clearJournalAndRefund()
   684  }
   685  
   686  // IntermediateRoot computes the current root hash of the state trie.
   687  // It is called in between transactions to get the root hash that
   688  // goes into transaction receipts.
   689  func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
   690  	// Finalise all the dirty storage states and write them into the tries
   691  	s.Finalise(deleteEmptyObjects)
   692  
   693  	for addr := range s.stateObjectsPending {
   694  		obj := s.stateObjects[addr]
   695  		if obj.deleted {
   696  			s.deleteStateObject(obj)
   697  		} else {
   698  			obj.updateRoot(s.db)
   699  			s.updateStateObject(obj)
   700  		}
   701  	}
   702  	if len(s.stateObjectsPending) > 0 {
   703  		s.stateObjectsPending = make(map[common.Address]struct{})
   704  	}
   705  	// Track the amount of time wasted on hashing the account trie
   706  	if metrics.EnabledExpensive {
   707  		defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now())
   708  	}
   709  	return s.trie.Hash()
   710  }
   711  
   712  // Prepare sets the current transaction hash and index and block hash which is
   713  // used when the EVM emits new state logs.
   714  func (s *StateDB) Prepare(thash, bhash common.Hash, ti int) {
   715  	s.thash = thash
   716  	s.bhash = bhash
   717  	s.txIndex = ti
   718  }
   719  
   720  func (s *StateDB) clearJournalAndRefund() {
   721  	if len(s.journal.entries) > 0 {
   722  		s.journal = newJournal()
   723  		s.refund = 0
   724  	}
   725  	s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entires
   726  }
   727  
   728  // Commit writes the state to the underlying in-memory trie database.
   729  func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) {
   730  	// Finalize any pending changes and merge everything into the tries
   731  	s.IntermediateRoot(deleteEmptyObjects)
   732  
   733  	// Commit objects to the trie, measuring the elapsed time
   734  	for addr := range s.stateObjectsDirty {
   735  		if obj := s.stateObjects[addr]; !obj.deleted {
   736  			// Write any contract code associated with the state object
   737  			if obj.code != nil && obj.dirtyCode {
   738  				s.db.TrieDB().InsertBlob(common.BytesToHash(obj.CodeHash()), obj.code)
   739  				obj.dirtyCode = false
   740  			}
   741  			// Write any storage changes in the state object to its storage trie
   742  			if err := obj.CommitTrie(s.db); err != nil {
   743  				return common.Hash{}, err
   744  			}
   745  		}
   746  	}
   747  	if len(s.stateObjectsDirty) > 0 {
   748  		s.stateObjectsDirty = make(map[common.Address]struct{})
   749  	}
   750  	// Write the account trie changes, measuing the amount of wasted time
   751  	if metrics.EnabledExpensive {
   752  		defer func(start time.Time) { s.AccountCommits += time.Since(start) }(time.Now())
   753  	}
   754  	// The onleaf func is called _serially_, so we can reuse the same account
   755  	// for unmarshalling every time.
   756  	var account Account
   757  	return s.trie.Commit(func(leaf []byte, parent common.Hash) error {
   758  		if err := rlp.DecodeBytes(leaf, &account); err != nil {
   759  			return nil
   760  		}
   761  		if account.Root != emptyRoot {
   762  			s.db.TrieDB().Reference(account.Root, parent)
   763  		}
   764  		code := common.BytesToHash(account.CodeHash)
   765  		if code != emptyCode {
   766  			s.db.TrieDB().Reference(code, parent)
   767  		}
   768  		return nil
   769  	})
   770  }