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