github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/core/state/statedb.go (about)

     1  //  Copyright 2018 The go-ethereum Authors
     2  //  Copyright 2019 The go-aigar Authors
     3  //  This file is part of the go-aigar library.
     4  //
     5  //  The go-aigar library is free software: you can redistribute it and/or modify
     6  //  it under the terms of the GNU Lesser General Public License as published by
     7  //  the Free Software Foundation, either version 3 of the License, or
     8  //  (at your option) any later version.
     9  //
    10  //  The go-aigar library is distributed in the hope that it will be useful,
    11  //  but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  //  GNU Lesser General Public License for more details.
    14  //
    15  //  You should have received a copy of the GNU Lesser General Public License
    16  //  along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  // Package state provides a caching layer atop the Ethereum state trie.
    19  package state
    20  
    21  import (
    22  	"errors"
    23  	"fmt"
    24  	"math/big"
    25  	"sort"
    26  	"time"
    27  
    28  	"github.com/AigarNetwork/aigar/common"
    29  	"github.com/AigarNetwork/aigar/core/types"
    30  	"github.com/AigarNetwork/aigar/crypto"
    31  	"github.com/AigarNetwork/aigar/log"
    32  	"github.com/AigarNetwork/aigar/metrics"
    33  	"github.com/AigarNetwork/aigar/rlp"
    34  	"github.com/AigarNetwork/aigar/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  func (self *StateDB) GetNonce(addr common.Address) uint64 {
   236  	stateObject := self.getStateObject(addr)
   237  	if stateObject != nil {
   238  		return stateObject.Nonce()
   239  	}
   240  
   241  	return 0
   242  }
   243  
   244  // TxIndex returns the current transaction index set by Prepare.
   245  func (self *StateDB) TxIndex() int {
   246  	return self.txIndex
   247  }
   248  
   249  // BlockHash returns the current block hash set by Prepare.
   250  func (self *StateDB) BlockHash() common.Hash {
   251  	return self.bhash
   252  }
   253  
   254  func (self *StateDB) GetCode(addr common.Address) []byte {
   255  	stateObject := self.getStateObject(addr)
   256  	if stateObject != nil {
   257  		return stateObject.Code(self.db)
   258  	}
   259  	return nil
   260  }
   261  
   262  func (self *StateDB) GetCodeSize(addr common.Address) int {
   263  	stateObject := self.getStateObject(addr)
   264  	if stateObject == nil {
   265  		return 0
   266  	}
   267  	if stateObject.code != nil {
   268  		return len(stateObject.code)
   269  	}
   270  	size, err := self.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash()))
   271  	if err != nil {
   272  		self.setError(err)
   273  	}
   274  	return size
   275  }
   276  
   277  func (self *StateDB) GetCodeHash(addr common.Address) common.Hash {
   278  	stateObject := self.getStateObject(addr)
   279  	if stateObject == nil {
   280  		return common.Hash{}
   281  	}
   282  	return common.BytesToHash(stateObject.CodeHash())
   283  }
   284  
   285  // GetState retrieves a value from the given account's storage trie.
   286  func (self *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash {
   287  	stateObject := self.getStateObject(addr)
   288  	if stateObject != nil {
   289  		return stateObject.GetState(self.db, hash)
   290  	}
   291  	return common.Hash{}
   292  }
   293  
   294  // GetProof returns the MerkleProof for a given Account
   295  func (self *StateDB) GetProof(a common.Address) ([][]byte, error) {
   296  	var proof proofList
   297  	err := self.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof)
   298  	return [][]byte(proof), err
   299  }
   300  
   301  // GetProof returns the StorageProof for given key
   302  func (self *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
   303  	var proof proofList
   304  	trie := self.StorageTrie(a)
   305  	if trie == nil {
   306  		return proof, errors.New("storage trie for requested address does not exist")
   307  	}
   308  	err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof)
   309  	return [][]byte(proof), err
   310  }
   311  
   312  // GetCommittedState retrieves a value from the given account's committed storage trie.
   313  func (self *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
   314  	stateObject := self.getStateObject(addr)
   315  	if stateObject != nil {
   316  		return stateObject.GetCommittedState(self.db, hash)
   317  	}
   318  	return common.Hash{}
   319  }
   320  
   321  // Database retrieves the low level database supporting the lower level trie ops.
   322  func (self *StateDB) Database() Database {
   323  	return self.db
   324  }
   325  
   326  // StorageTrie returns the storage trie of an account.
   327  // The return value is a copy and is nil for non-existent accounts.
   328  func (self *StateDB) StorageTrie(addr common.Address) Trie {
   329  	stateObject := self.getStateObject(addr)
   330  	if stateObject == nil {
   331  		return nil
   332  	}
   333  	cpy := stateObject.deepCopy(self)
   334  	return cpy.updateTrie(self.db)
   335  }
   336  
   337  func (self *StateDB) HasSuicided(addr common.Address) bool {
   338  	stateObject := self.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 (self *StateDB) AddBalance(addr common.Address, amount *big.Int) {
   351  	stateObject := self.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 (self *StateDB) SubBalance(addr common.Address, amount *big.Int) {
   359  	stateObject := self.GetOrNewStateObject(addr)
   360  	if stateObject != nil {
   361  		stateObject.SubBalance(amount)
   362  	}
   363  }
   364  
   365  func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) {
   366  	stateObject := self.GetOrNewStateObject(addr)
   367  	if stateObject != nil {
   368  		stateObject.SetBalance(amount)
   369  	}
   370  }
   371  
   372  func (self *StateDB) SetNonce(addr common.Address, nonce uint64) {
   373  	stateObject := self.GetOrNewStateObject(addr)
   374  	if stateObject != nil {
   375  		stateObject.SetNonce(nonce)
   376  	}
   377  }
   378  
   379  func (self *StateDB) SetCode(addr common.Address, code []byte) {
   380  	stateObject := self.GetOrNewStateObject(addr)
   381  	if stateObject != nil {
   382  		stateObject.SetCode(crypto.Keccak256Hash(code), code)
   383  	}
   384  }
   385  
   386  func (self *StateDB) SetState(addr common.Address, key, value common.Hash) {
   387  	stateObject := self.GetOrNewStateObject(addr)
   388  	if stateObject != nil {
   389  		stateObject.SetState(self.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 (self *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) {
   396  	stateObject := self.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 (self *StateDB) Suicide(addr common.Address) bool {
   408  	stateObject := self.getStateObject(addr)
   409  	if stateObject == nil {
   410  		return false
   411  	}
   412  	self.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 self-
   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 (self *StateDB) setStateObject(object *stateObject) {
   495  	self.stateObjects[object.Address()] = object
   496  }
   497  
   498  // Retrieve a state object or create a new state object if nil.
   499  func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
   500  	stateObject := self.getStateObject(addr)
   501  	if stateObject == nil {
   502  		stateObject, _ = self.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 (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
   510  	prev = self.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that!
   511  
   512  	newobj = newObject(self, addr, Account{})
   513  	newobj.setNonce(0) // sets the object to dirty
   514  	if prev == nil {
   515  		self.journal.append(createObjectChange{account: &addr})
   516  	} else {
   517  		self.journal.append(resetObjectChange{prev: prev})
   518  	}
   519  	self.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 (self *StateDB) CreateAccount(addr common.Address) {
   534  	newObj, prev := self.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 (self *StateDB) Copy() *StateDB {
   572  	// Copy all the basic fields, initialize the memory ones
   573  	state := &StateDB{
   574  		db:                  self.db,
   575  		trie:                self.db.CopyTrie(self.trie),
   576  		stateObjects:        make(map[common.Address]*stateObject, len(self.journal.dirties)),
   577  		stateObjectsPending: make(map[common.Address]struct{}, len(self.stateObjectsPending)),
   578  		stateObjectsDirty:   make(map[common.Address]struct{}, len(self.journal.dirties)),
   579  		refund:              self.refund,
   580  		logs:                make(map[common.Hash][]*types.Log, len(self.logs)),
   581  		logSize:             self.logSize,
   582  		preimages:           make(map[common.Hash][]byte, len(self.preimages)),
   583  		journal:             newJournal(),
   584  	}
   585  	// Copy the dirty states, logs, and preimages
   586  	for addr := range self.journal.dirties {
   587  		// As documented [here](https://github.com/AigarNetwork/aigar/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 := self.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 self.stateObjectsPending {
   605  		if _, exist := state.stateObjects[addr]; !exist {
   606  			state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state)
   607  		}
   608  		state.stateObjectsPending[addr] = struct{}{}
   609  	}
   610  	for addr := range self.stateObjectsDirty {
   611  		if _, exist := state.stateObjects[addr]; !exist {
   612  			state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state)
   613  		}
   614  		state.stateObjectsDirty[addr] = struct{}{}
   615  	}
   616  	for hash, logs := range self.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 self.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 (self *StateDB) Snapshot() int {
   632  	id := self.nextRevisionId
   633  	self.nextRevisionId++
   634  	self.validRevisions = append(self.validRevisions, revision{id, self.journal.length()})
   635  	return id
   636  }
   637  
   638  // RevertToSnapshot reverts all state changes made since the given revision.
   639  func (self *StateDB) RevertToSnapshot(revid int) {
   640  	// Find the snapshot in the stack of valid snapshots.
   641  	idx := sort.Search(len(self.validRevisions), func(i int) bool {
   642  		return self.validRevisions[i].id >= revid
   643  	})
   644  	if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid {
   645  		panic(fmt.Errorf("revision id %v cannot be reverted", revid))
   646  	}
   647  	snapshot := self.validRevisions[idx].journalIndex
   648  
   649  	// Replay the journal to undo changes and remove invalidated snapshots
   650  	self.journal.revert(self, snapshot)
   651  	self.validRevisions = self.validRevisions[:idx]
   652  }
   653  
   654  // GetRefund returns the current value of the refund counter.
   655  func (self *StateDB) GetRefund() uint64 {
   656  	return self.refund
   657  }
   658  
   659  // Finalise finalises the state by removing the self 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 (self *StateDB) Prepare(thash, bhash common.Hash, ti int) {
   715  	self.thash = thash
   716  	self.bhash = bhash
   717  	self.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  	return s.trie.Commit(func(leaf []byte, parent common.Hash) error {
   755  		var account Account
   756  		if err := rlp.DecodeBytes(leaf, &account); err != nil {
   757  			return nil
   758  		}
   759  		if account.Root != emptyRoot {
   760  			s.db.TrieDB().Reference(account.Root, parent)
   761  		}
   762  		code := common.BytesToHash(account.CodeHash)
   763  		if code != emptyCode {
   764  			s.db.TrieDB().Reference(code, parent)
   765  		}
   766  		return nil
   767  	})
   768  }