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