github.com/chainopen/ethchaincode@v0.0.0-20190924072703-d975acdaa1c6/core/state/statedb.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package state provides a caching layer atop the Ethereum state trie.
    18  package state
    19  
    20  import (
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"sort"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/core/types"
    29  	"github.com/ethereum/go-ethereum/crypto"
    30  	"github.com/ethereum/go-ethereum/log"
    31  	"github.com/ethereum/go-ethereum/metrics"
    32  	"github.com/ethereum/go-ethereum/rlp"
    33  	"github.com/ethereum/go-ethereum/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 (self *StateDB) setError(err error) {
   128  	if self.dbErr == nil {
   129  		self.dbErr = err
   130  	}
   131  }
   132  
   133  func (self *StateDB) Error() error {
   134  	return self.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 (self *StateDB) Reset(root common.Hash) error {
   140  	tr, err := self.db.OpenTrie(root)
   141  	if err != nil {
   142  		return err
   143  	}
   144  	self.trie = tr
   145  	self.stateObjects = make(map[common.Address]*stateObject)
   146  	self.stateObjectsPending = make(map[common.Address]struct{})
   147  	self.stateObjectsDirty = make(map[common.Address]struct{})
   148  	self.thash = common.Hash{}
   149  	self.bhash = common.Hash{}
   150  	self.txIndex = 0
   151  	self.logs = make(map[common.Hash][]*types.Log)
   152  	self.logSize = 0
   153  	self.preimages = make(map[common.Hash][]byte)
   154  	self.clearJournalAndRefund()
   155  	return nil
   156  }
   157  
   158  func (self *StateDB) AddLog(log *types.Log) {
   159  	self.journal.append(addLogChange{txhash: self.thash})
   160  
   161  	log.TxHash = self.thash
   162  	log.BlockHash = self.bhash
   163  	log.TxIndex = uint(self.txIndex)
   164  	log.Index = self.logSize
   165  	self.logs[self.thash] = append(self.logs[self.thash], log)
   166  	self.logSize++
   167  }
   168  
   169  func (self *StateDB) GetLogs(hash common.Hash) []*types.Log {
   170  	return self.logs[hash]
   171  }
   172  
   173  func (self *StateDB) Logs() []*types.Log {
   174  	var logs []*types.Log
   175  	for _, lgs := range self.logs {
   176  		logs = append(logs, lgs...)
   177  	}
   178  	return logs
   179  }
   180  
   181  // AddPreimage records a SHA3 preimage seen by the VM.
   182  func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
   183  	if _, ok := self.preimages[hash]; !ok {
   184  		self.journal.append(addPreimageChange{hash: hash})
   185  		pi := make([]byte, len(preimage))
   186  		copy(pi, preimage)
   187  		self.preimages[hash] = pi
   188  	}
   189  }
   190  
   191  // Preimages returns a list of SHA3 preimages that have been submitted.
   192  func (self *StateDB) Preimages() map[common.Hash][]byte {
   193  	return self.preimages
   194  }
   195  
   196  // AddRefund adds gas to the refund counter
   197  func (self *StateDB) AddRefund(gas uint64) {
   198  	self.journal.append(refundChange{prev: self.refund})
   199  	self.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 (self *StateDB) SubRefund(gas uint64) {
   205  	self.journal.append(refundChange{prev: self.refund})
   206  	if gas > self.refund {
   207  		panic("Refund counter below zero")
   208  	}
   209  	self.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 (self *StateDB) Exist(addr common.Address) bool {
   215  	return self.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 (self *StateDB) Empty(addr common.Address) bool {
   221  	so := self.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 (self *StateDB) GetBalance(addr common.Address) *big.Int {
   227  	stateObject := self.getStateObject(addr)
   228  	if stateObject != nil {
   229  		return stateObject.Balance()
   230  	}
   231  	return common.Big0
   232  }
   233  
   234  func (self *StateDB) GetNonce(addr common.Address) uint64 {
   235  	stateObject := self.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 (self *StateDB) TxIndex() int {
   245  	return self.txIndex
   246  }
   247  
   248  // BlockHash returns the current block hash set by Prepare.
   249  func (self *StateDB) BlockHash() common.Hash {
   250  	return self.bhash
   251  }
   252  
   253  func (self *StateDB) GetCode(addr common.Address) []byte {
   254  	stateObject := self.getStateObject(addr)
   255  	if stateObject != nil {
   256  		return stateObject.Code(self.db)
   257  	}
   258  	return nil
   259  }
   260  
   261  func (self *StateDB) GetCodeSize(addr common.Address) int {
   262  	stateObject := self.getStateObject(addr)
   263  	if stateObject == nil {
   264  		return 0
   265  	}
   266  	if stateObject.code != nil {
   267  		return len(stateObject.code)
   268  	}
   269  	size, err := self.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash()))
   270  	if err != nil {
   271  		self.setError(err)
   272  	}
   273  	return size
   274  }
   275  
   276  func (self *StateDB) GetCodeHash(addr common.Address) common.Hash {
   277  	stateObject := self.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 (self *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash {
   286  	stateObject := self.getStateObject(addr)
   287  	if stateObject != nil {
   288  		return stateObject.GetState(self.db, hash)
   289  	}
   290  	return common.Hash{}
   291  }
   292  
   293  // GetProof returns the MerkleProof for a given Account
   294  func (self *StateDB) GetProof(a common.Address) ([][]byte, error) {
   295  	var proof proofList
   296  	err := self.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 (self *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
   302  	var proof proofList
   303  	trie := self.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 (self *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
   313  	stateObject := self.getStateObject(addr)
   314  	if stateObject != nil {
   315  		return stateObject.GetCommittedState(self.db, hash)
   316  	}
   317  	return common.Hash{}
   318  }
   319  
   320  // Database retrieves the low level database supporting the lower level trie ops.
   321  func (self *StateDB) Database() Database {
   322  	return self.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 (self *StateDB) StorageTrie(addr common.Address) Trie {
   328  	stateObject := self.getStateObject(addr)
   329  	if stateObject == nil {
   330  		return nil
   331  	}
   332  	cpy := stateObject.deepCopy(self)
   333  	return cpy.updateTrie(self.db)
   334  }
   335  
   336  func (self *StateDB) HasSuicided(addr common.Address) bool {
   337  	stateObject := self.getStateObject(addr)
   338  	if stateObject != nil {
   339  		return stateObject.suicided
   340  	}
   341  	return false
   342  }
   343  
   344  /*
   345   * SETTERS
   346   */
   347  
   348  // AddBalance adds amount to the account associated with addr.
   349  func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) {
   350  	stateObject := self.GetOrNewStateObject(addr)
   351  	if stateObject != nil {
   352  		stateObject.AddBalance(amount)
   353  	}
   354  }
   355  
   356  // SubBalance subtracts amount from the account associated with addr.
   357  func (self *StateDB) SubBalance(addr common.Address, amount *big.Int) {
   358  	stateObject := self.GetOrNewStateObject(addr)
   359  	if stateObject != nil {
   360  		stateObject.SubBalance(amount)
   361  	}
   362  }
   363  
   364  func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) {
   365  	stateObject := self.GetOrNewStateObject(addr)
   366  	if stateObject != nil {
   367  		stateObject.SetBalance(amount)
   368  	}
   369  }
   370  
   371  func (self *StateDB) SetNonce(addr common.Address, nonce uint64) {
   372  	stateObject := self.GetOrNewStateObject(addr)
   373  	if stateObject != nil {
   374  		stateObject.SetNonce(nonce)
   375  	}
   376  }
   377  
   378  func (self *StateDB) SetCode(addr common.Address, code []byte) {
   379  	stateObject := self.GetOrNewStateObject(addr)
   380  	if stateObject != nil {
   381  		stateObject.SetCode(crypto.Keccak256Hash(code), code)
   382  	}
   383  }
   384  
   385  func (self *StateDB) SetState(addr common.Address, key, value common.Hash) {
   386  	stateObject := self.GetOrNewStateObject(addr)
   387  	if stateObject != nil {
   388  		stateObject.SetState(self.db, key, value)
   389  	}
   390  }
   391  
   392  // SetStorage replaces the entire storage for the specified account with given
   393  // storage. This function should only be used for debugging.
   394  func (self *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) {
   395  	stateObject := self.GetOrNewStateObject(addr)
   396  	if stateObject != nil {
   397  		stateObject.SetStorage(storage)
   398  	}
   399  }
   400  
   401  // Suicide marks the given account as suicided.
   402  // This clears the account balance.
   403  //
   404  // The account's state object is still available until the state is committed,
   405  // getStateObject will return a non-nil account after Suicide.
   406  func (self *StateDB) Suicide(addr common.Address) bool {
   407  	stateObject := self.getStateObject(addr)
   408  	if stateObject == nil {
   409  		return false
   410  	}
   411  	self.journal.append(suicideChange{
   412  		account:     &addr,
   413  		prev:        stateObject.suicided,
   414  		prevbalance: new(big.Int).Set(stateObject.Balance()),
   415  	})
   416  	stateObject.markSuicided()
   417  	stateObject.data.Balance = new(big.Int)
   418  
   419  	return true
   420  }
   421  
   422  //
   423  // Setting, updating & deleting state object methods.
   424  //
   425  
   426  // updateStateObject writes the given object to the trie.
   427  func (s *StateDB) updateStateObject(obj *stateObject) {
   428  	// Track the amount of time wasted on updating the account from the trie
   429  	if metrics.EnabledExpensive {
   430  		defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
   431  	}
   432  	// Encode the account and update the account trie
   433  	addr := obj.Address()
   434  
   435  	data, err := rlp.EncodeToBytes(obj)
   436  	if err != nil {
   437  		panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
   438  	}
   439  	s.setError(s.trie.TryUpdate(addr[:], data))
   440  }
   441  
   442  // deleteStateObject removes the given object from the state trie.
   443  func (s *StateDB) deleteStateObject(obj *stateObject) {
   444  	// Track the amount of time wasted on deleting the account from the trie
   445  	if metrics.EnabledExpensive {
   446  		defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
   447  	}
   448  	// Delete the account from the trie
   449  	addr := obj.Address()
   450  	s.setError(s.trie.TryDelete(addr[:]))
   451  }
   452  
   453  // getStateObject retrieves a state object given by the address, returning nil if
   454  // the object is not found or was deleted in this execution context. If you need
   455  // to differentiate between non-existent/just-deleted, use getDeletedStateObject.
   456  func (s *StateDB) getStateObject(addr common.Address) *stateObject {
   457  	if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted {
   458  		return obj
   459  	}
   460  	return nil
   461  }
   462  
   463  // getDeletedStateObject is similar to getStateObject, but instead of returning
   464  // nil for a deleted state object, it returns the actual object with the deleted
   465  // flag set. This is needed by the state journal to revert to the correct self-
   466  // destructed object instead of wiping all knowledge about the state object.
   467  func (s *StateDB) getDeletedStateObject(addr common.Address) *stateObject {
   468  	// Prefer live objects if any is available
   469  	if obj := s.stateObjects[addr]; obj != nil {
   470  		return obj
   471  	}
   472  	// Track the amount of time wasted on loading the object from the database
   473  	if metrics.EnabledExpensive {
   474  		defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now())
   475  	}
   476  	// Load the object from the database
   477  	enc, err := s.trie.TryGet(addr[:])
   478  	if len(enc) == 0 {
   479  		s.setError(err)
   480  		return nil
   481  	}
   482  	var data Account
   483  	if err := rlp.DecodeBytes(enc, &data); err != nil {
   484  		log.Error("Failed to decode state object", "addr", addr, "err", err)
   485  		return nil
   486  	}
   487  	// Insert into the live set
   488  	obj := newObject(s, addr, data)
   489  	s.setStateObject(obj)
   490  	return obj
   491  }
   492  
   493  func (self *StateDB) setStateObject(object *stateObject) {
   494  	self.stateObjects[object.Address()] = object
   495  }
   496  
   497  // Retrieve a state object or create a new state object if nil.
   498  func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
   499  	stateObject := self.getStateObject(addr)
   500  	if stateObject == nil {
   501  		stateObject, _ = self.createObject(addr)
   502  	}
   503  	return stateObject
   504  }
   505  
   506  // createObject creates a new state object. If there is an existing account with
   507  // the given address, it is overwritten and returned as the second return value.
   508  func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
   509  	prev = self.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that!
   510  
   511  	newobj = newObject(self, addr, Account{})
   512  	newobj.setNonce(0) // sets the object to dirty
   513  	if prev == nil {
   514  		self.journal.append(createObjectChange{account: &addr})
   515  	} else {
   516  		self.journal.append(resetObjectChange{prev: prev})
   517  	}
   518  	self.setStateObject(newobj)
   519  	return newobj, prev
   520  }
   521  
   522  // CreateAccount explicitly creates a state object. If a state object with the address
   523  // already exists the balance is carried over to the new account.
   524  //
   525  // CreateAccount is called during the EVM CREATE operation. The situation might arise that
   526  // a contract does the following:
   527  //
   528  //   1. sends funds to sha(account ++ (nonce + 1))
   529  //   2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
   530  //
   531  // Carrying over the balance ensures that Ether doesn't disappear.
   532  func (self *StateDB) CreateAccount(addr common.Address) {
   533  	newObj, prev := self.createObject(addr)
   534  	if prev != nil {
   535  		newObj.setBalance(prev.data.Balance)
   536  	}
   537  }
   538  
   539  func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {
   540  	so := db.getStateObject(addr)
   541  	if so == nil {
   542  		return nil
   543  	}
   544  	it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
   545  
   546  	for it.Next() {
   547  		key := common.BytesToHash(db.trie.GetKey(it.Key))
   548  		if value, dirty := so.dirtyStorage[key]; dirty {
   549  			if !cb(key, value) {
   550  				return nil
   551  			}
   552  			continue
   553  		}
   554  
   555  		if len(it.Value) > 0 {
   556  			_, content, _, err := rlp.Split(it.Value)
   557  			if err != nil {
   558  				return err
   559  			}
   560  			if !cb(key, common.BytesToHash(content)) {
   561  				return nil
   562  			}
   563  		}
   564  	}
   565  	return nil
   566  }
   567  
   568  // Copy creates a deep, independent copy of the state.
   569  // Snapshots of the copied state cannot be applied to the copy.
   570  func (self *StateDB) Copy() *StateDB {
   571  	// Copy all the basic fields, initialize the memory ones
   572  	state := &StateDB{
   573  		db:                  self.db,
   574  		trie:                self.db.CopyTrie(self.trie),
   575  		stateObjects:        make(map[common.Address]*stateObject, len(self.journal.dirties)),
   576  		stateObjectsPending: make(map[common.Address]struct{}, len(self.stateObjectsPending)),
   577  		stateObjectsDirty:   make(map[common.Address]struct{}, len(self.journal.dirties)),
   578  		refund:              self.refund,
   579  		logs:                make(map[common.Hash][]*types.Log, len(self.logs)),
   580  		logSize:             self.logSize,
   581  		preimages:           make(map[common.Hash][]byte, len(self.preimages)),
   582  		journal:             newJournal(),
   583  	}
   584  	// Copy the dirty states, logs, and preimages
   585  	for addr := range self.journal.dirties {
   586  		// As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527),
   587  		// and in the Finalise-method, there is a case where an object is in the journal but not
   588  		// in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
   589  		// nil
   590  		if object, exist := self.stateObjects[addr]; exist {
   591  			state.stateObjects[addr] = object.deepCopy(state)
   592  			state.stateObjectsDirty[addr] = struct{}{}
   593  		}
   594  	}
   595  	// Above, we don't copy the actual journal. This means that if the copy is copied, the
   596  	// loop above will be a no-op, since the copy's journal is empty.
   597  	// Thus, here we iterate over stateObjects, to enable copies of copies
   598  	for addr := range self.stateObjectsPending {
   599  		if _, exist := state.stateObjects[addr]; !exist {
   600  			state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state)
   601  		}
   602  		state.stateObjectsPending[addr] = struct{}{}
   603  	}
   604  	for addr := range self.stateObjectsDirty {
   605  		if _, exist := state.stateObjects[addr]; !exist {
   606  			state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state)
   607  		}
   608  		state.stateObjectsDirty[addr] = struct{}{}
   609  	}
   610  	for hash, logs := range self.logs {
   611  		cpy := make([]*types.Log, len(logs))
   612  		for i, l := range logs {
   613  			cpy[i] = new(types.Log)
   614  			*cpy[i] = *l
   615  		}
   616  		state.logs[hash] = cpy
   617  	}
   618  	for hash, preimage := range self.preimages {
   619  		state.preimages[hash] = preimage
   620  	}
   621  	return state
   622  }
   623  
   624  // Snapshot returns an identifier for the current revision of the state.
   625  func (self *StateDB) Snapshot() int {
   626  	id := self.nextRevisionId
   627  	self.nextRevisionId++
   628  	self.validRevisions = append(self.validRevisions, revision{id, self.journal.length()})
   629  	return id
   630  }
   631  
   632  // RevertToSnapshot reverts all state changes made since the given revision.
   633  func (self *StateDB) RevertToSnapshot(revid int) {
   634  	// Find the snapshot in the stack of valid snapshots.
   635  	idx := sort.Search(len(self.validRevisions), func(i int) bool {
   636  		return self.validRevisions[i].id >= revid
   637  	})
   638  	if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid {
   639  		panic(fmt.Errorf("revision id %v cannot be reverted", revid))
   640  	}
   641  	snapshot := self.validRevisions[idx].journalIndex
   642  
   643  	// Replay the journal to undo changes and remove invalidated snapshots
   644  	self.journal.revert(self, snapshot)
   645  	self.validRevisions = self.validRevisions[:idx]
   646  }
   647  
   648  // GetRefund returns the current value of the refund counter.
   649  func (self *StateDB) GetRefund() uint64 {
   650  	return self.refund
   651  }
   652  
   653  // Finalise finalises the state by removing the self destructed objects and clears
   654  // the journal as well as the refunds. Finalise, however, will not push any updates
   655  // into the tries just yet. Only IntermediateRoot or Commit will do that.
   656  func (s *StateDB) Finalise(deleteEmptyObjects bool) {
   657  	for addr := range s.journal.dirties {
   658  		obj, exist := s.stateObjects[addr]
   659  		if !exist {
   660  			// ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
   661  			// That tx goes out of gas, and although the notion of 'touched' does not exist there, the
   662  			// touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
   663  			// it will persist in the journal even though the journal is reverted. In this special circumstance,
   664  			// it may exist in `s.journal.dirties` but not in `s.stateObjects`.
   665  			// Thus, we can safely ignore it here
   666  			continue
   667  		}
   668  		if obj.suicided || (deleteEmptyObjects && obj.empty()) {
   669  			obj.deleted = true
   670  		} else {
   671  			obj.finalise()
   672  		}
   673  		s.stateObjectsPending[addr] = struct{}{}
   674  		s.stateObjectsDirty[addr] = struct{}{}
   675  	}
   676  	// Invalidate journal because reverting across transactions is not allowed.
   677  	s.clearJournalAndRefund()
   678  }
   679  
   680  // IntermediateRoot computes the current root hash of the state trie.
   681  // It is called in between transactions to get the root hash that
   682  // goes into transaction receipts.
   683  func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
   684  	// Finalise all the dirty storage states and write them into the tries
   685  	s.Finalise(deleteEmptyObjects)
   686  
   687  	for addr := range s.stateObjectsPending {
   688  		obj := s.stateObjects[addr]
   689  		if obj.deleted {
   690  			s.deleteStateObject(obj)
   691  		} else {
   692  			obj.updateRoot(s.db)
   693  			s.updateStateObject(obj)
   694  		}
   695  	}
   696  	if len(s.stateObjectsPending) > 0 {
   697  		s.stateObjectsPending = make(map[common.Address]struct{})
   698  	}
   699  	// Track the amount of time wasted on hashing the account trie
   700  	if metrics.EnabledExpensive {
   701  		defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now())
   702  	}
   703  	return s.trie.Hash()
   704  }
   705  
   706  // Prepare sets the current transaction hash and index and block hash which is
   707  // used when the EVM emits new state logs.
   708  func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) {
   709  	self.thash = thash
   710  	self.bhash = bhash
   711  	self.txIndex = ti
   712  }
   713  
   714  func (s *StateDB) clearJournalAndRefund() {
   715  	if len(s.journal.entries) > 0 {
   716  		s.journal = newJournal()
   717  		s.refund = 0
   718  	}
   719  	s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entires
   720  }
   721  
   722  // Commit writes the state to the underlying in-memory trie database.
   723  func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) {
   724  	// Finalize any pending changes and merge everything into the tries
   725  	s.IntermediateRoot(deleteEmptyObjects)
   726  
   727  	// Commit objects to the trie, measuring the elapsed time
   728  	for addr := range s.stateObjectsDirty {
   729  		if obj := s.stateObjects[addr]; !obj.deleted {
   730  			// Write any contract code associated with the state object
   731  			if obj.code != nil && obj.dirtyCode {
   732  				s.db.TrieDB().InsertBlob(common.BytesToHash(obj.CodeHash()), obj.code)
   733  				obj.dirtyCode = false
   734  			}
   735  			// Write any storage changes in the state object to its storage trie
   736  			if err := obj.CommitTrie(s.db); err != nil {
   737  				return common.Hash{}, err
   738  			}
   739  		}
   740  	}
   741  	if len(s.stateObjectsDirty) > 0 {
   742  		s.stateObjectsDirty = make(map[common.Address]struct{})
   743  	}
   744  	// Write the account trie changes, measuing the amount of wasted time
   745  	if metrics.EnabledExpensive {
   746  		defer func(start time.Time) { s.AccountCommits += time.Since(start) }(time.Now())
   747  	}
   748  	return s.trie.Commit(func(leaf []byte, parent common.Hash) error {
   749  		var account Account
   750  		if err := rlp.DecodeBytes(leaf, &account); err != nil {
   751  			return nil
   752  		}
   753  		if account.Root != emptyRoot {
   754  			s.db.TrieDB().Reference(account.Root, parent)
   755  		}
   756  		code := common.BytesToHash(account.CodeHash)
   757  		if code != emptyCode {
   758  			s.db.TrieDB().Reference(code, parent)
   759  		}
   760  		return nil
   761  	})
   762  }