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