github.com/neatio-net/neatio@v1.7.3-0.20231114194659-f4d7a2226baa/chain/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 Neatio Blockchain state trie.
    18  package state
    19  
    20  import (
    21  	"fmt"
    22  	"math/big"
    23  	"sort"
    24  
    25  	"github.com/neatio-net/neatio/chain/core/types"
    26  	"github.com/neatio-net/neatio/chain/log"
    27  	"github.com/neatio-net/neatio/chain/trie"
    28  	"github.com/neatio-net/neatio/utilities/common"
    29  	"github.com/neatio-net/neatio/utilities/crypto"
    30  	"github.com/neatio-net/neatio/utilities/rlp"
    31  )
    32  
    33  type revision struct {
    34  	id           int
    35  	journalIndex int
    36  }
    37  
    38  var (
    39  	// emptyRoot is the known root hash of an empty trie.
    40  	emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
    41  
    42  	// emptyCode is the known hash of the empty EVM bytecode.
    43  	emptyCode = crypto.Keccak256Hash(nil)
    44  )
    45  
    46  // StateDBs within the ethereum protocol are used to store anything
    47  // within the merkle trie. StateDBs take care of caching and storing
    48  // nested states. It's the general query interface to retrieve:
    49  // * Contracts
    50  // * Accounts
    51  type StateDB struct {
    52  	db   Database
    53  	trie Trie
    54  
    55  	// This map holds 'live' objects, which will get modified while processing a state transition.
    56  	stateObjects      map[common.Address]*stateObject
    57  	stateObjectsDirty map[common.Address]struct{}
    58  
    59  	// Cache of Delegate Refund Set
    60  	delegateRefundSet      DelegateRefundSet
    61  	delegateRefundSetDirty bool
    62  
    63  	// Cache of Reward Set
    64  	rewardSet      RewardSet
    65  	rewardSetDirty bool
    66  
    67  	// candidate set
    68  	candidateSet      CandidateSet
    69  	candidateSetDirty bool
    70  
    71  	// banned set
    72  	bannedSet      BannedSet
    73  	bannedSetDirty bool
    74  
    75  	// Cache of Side Chain Reward Per Block
    76  	sideChainRewardPerBlock      *big.Int
    77  	sideChainRewardPerBlockDirty bool
    78  
    79  	// DB error.
    80  	// State objects are used by the consensus core and VM which are
    81  	// unable to deal with database-level errors. Any error that occurs
    82  	// during a database read is memoized here and will eventually be returned
    83  	// by StateDB.Commit.
    84  	dbErr error
    85  
    86  	// The refund counter, also used by state transitioning.
    87  	refund uint64
    88  
    89  	thash, bhash common.Hash
    90  	txIndex      int
    91  	logs         map[common.Hash][]*types.Log
    92  	logSize      uint
    93  
    94  	preimages map[common.Hash][]byte
    95  
    96  	// Journal of state modifications. This is the backbone of
    97  	// Snapshot and RevertToSnapshot.
    98  	journal        journal
    99  	validRevisions []revision
   100  	nextRevisionId int
   101  }
   102  
   103  // Create a new state from a given trie
   104  func New(root common.Hash, db Database) (*StateDB, error) {
   105  	tr, err := db.OpenTrie(root)
   106  	if err != nil {
   107  		return nil, err
   108  	}
   109  
   110  	return &StateDB{
   111  		db:                           db,
   112  		trie:                         tr,
   113  		stateObjects:                 make(map[common.Address]*stateObject),
   114  		stateObjectsDirty:            make(map[common.Address]struct{}),
   115  		delegateRefundSet:            make(DelegateRefundSet),
   116  		delegateRefundSetDirty:       false,
   117  		rewardSet:                    make(RewardSet),
   118  		rewardSetDirty:               false,
   119  		candidateSet:                 make(CandidateSet),
   120  		candidateSetDirty:            false,
   121  		bannedSet:                    make(BannedSet),
   122  		bannedSetDirty:               false,
   123  		sideChainRewardPerBlock:      nil,
   124  		sideChainRewardPerBlockDirty: false,
   125  		logs:                         make(map[common.Hash][]*types.Log),
   126  		preimages:                    make(map[common.Hash][]byte),
   127  	}, nil
   128  }
   129  
   130  // setError remembers the first non-nil error it is called with.
   131  func (self *StateDB) setError(err error) {
   132  	if self.dbErr == nil {
   133  		self.dbErr = err
   134  	}
   135  }
   136  
   137  func (self *StateDB) Error() error {
   138  	return self.dbErr
   139  }
   140  
   141  // Reset clears out all emphemeral state objects from the state db, but keeps
   142  // the underlying state trie to avoid reloading data for the next operations.
   143  func (self *StateDB) Reset(root common.Hash) error {
   144  	tr, err := self.db.OpenTrie(root)
   145  	if err != nil {
   146  		return err
   147  	}
   148  	self.trie = tr
   149  	self.stateObjects = make(map[common.Address]*stateObject)
   150  	self.stateObjectsDirty = make(map[common.Address]struct{})
   151  	self.delegateRefundSet = make(DelegateRefundSet)
   152  	self.rewardSet = make(RewardSet)
   153  	self.candidateSet = make(CandidateSet)
   154  	self.bannedSet = make(BannedSet)
   155  	self.sideChainRewardPerBlock = nil
   156  	self.thash = common.Hash{}
   157  	self.bhash = common.Hash{}
   158  	self.txIndex = 0
   159  	self.logs = make(map[common.Hash][]*types.Log)
   160  	self.logSize = 0
   161  	self.preimages = make(map[common.Hash][]byte)
   162  	self.clearJournalAndRefund()
   163  	return nil
   164  }
   165  
   166  func (self *StateDB) AddLog(log *types.Log) {
   167  	self.journal = append(self.journal, addLogChange{txhash: self.thash})
   168  
   169  	log.TxHash = self.thash
   170  	log.BlockHash = self.bhash
   171  	log.TxIndex = uint(self.txIndex)
   172  	log.Index = self.logSize
   173  	self.logs[self.thash] = append(self.logs[self.thash], log)
   174  	self.logSize++
   175  }
   176  
   177  func (self *StateDB) GetLogs(hash common.Hash) []*types.Log {
   178  	return self.logs[hash]
   179  }
   180  
   181  func (self *StateDB) Logs() []*types.Log {
   182  	var logs []*types.Log
   183  	for _, lgs := range self.logs {
   184  		logs = append(logs, lgs...)
   185  	}
   186  	return logs
   187  }
   188  
   189  // AddPreimage records a SHA3 preimage seen by the VM.
   190  func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
   191  	if _, ok := self.preimages[hash]; !ok {
   192  		self.journal = append(self.journal, addPreimageChange{hash: hash})
   193  		pi := make([]byte, len(preimage))
   194  		copy(pi, preimage)
   195  		self.preimages[hash] = pi
   196  	}
   197  }
   198  
   199  // Preimages returns a list of SHA3 preimages that have been submitted.
   200  func (self *StateDB) Preimages() map[common.Hash][]byte {
   201  	return self.preimages
   202  }
   203  
   204  func (self *StateDB) AddRefund(gas uint64) {
   205  	self.journal = append(self.journal, refundChange{prev: self.refund})
   206  	self.refund += gas
   207  }
   208  
   209  // SubRefund removes gas from the refund counter.
   210  // This method will panic if the refund counter goes below zero
   211  func (self *StateDB) SubRefund(gas uint64) {
   212  	self.journal = append(self.journal, refundChange{prev: self.refund})
   213  	if gas > self.refund {
   214  		panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, self.refund))
   215  	}
   216  	self.refund -= gas
   217  }
   218  
   219  // Exist reports whether the given account address exists in the state.
   220  // Notably this also returns true for suicided accounts.
   221  func (self *StateDB) Exist(addr common.Address) bool {
   222  	return self.getStateObject(addr) != nil
   223  }
   224  
   225  // Empty returns whether the state object is either non-existent
   226  // or empty according to the EIP161 specification (balance = nonce = code = 0)
   227  func (self *StateDB) Empty(addr common.Address) bool {
   228  	so := self.getStateObject(addr)
   229  	return so == nil || so.empty()
   230  }
   231  
   232  // Retrieve the balance from the given address or 0 if object not found
   233  func (self *StateDB) GetBalance(addr common.Address) *big.Int {
   234  	stateObject := self.getStateObject(addr)
   235  	if stateObject != nil {
   236  		return stateObject.Balance()
   237  	}
   238  	return common.Big0
   239  }
   240  
   241  func (self *StateDB) GetNonce(addr common.Address) uint64 {
   242  	stateObject := self.getStateObject(addr)
   243  	if stateObject != nil {
   244  		return stateObject.Nonce()
   245  	}
   246  
   247  	return 0
   248  }
   249  
   250  // TxIndex returns the current transaction index set by Prepare.
   251  func (self *StateDB) TxIndex() int {
   252  	return self.txIndex
   253  }
   254  
   255  // BlockHash returns the current block hash set by Prepare.
   256  func (self *StateDB) BlockHash() common.Hash {
   257  	return self.bhash
   258  }
   259  
   260  func (self *StateDB) GetCode(addr common.Address) []byte {
   261  	stateObject := self.getStateObject(addr)
   262  	if stateObject != nil {
   263  		return stateObject.Code(self.db)
   264  	}
   265  	return nil
   266  }
   267  
   268  func (self *StateDB) GetCodeSize(addr common.Address) int {
   269  	stateObject := self.getStateObject(addr)
   270  	if stateObject == nil {
   271  		return 0
   272  	}
   273  	if stateObject.code != nil {
   274  		return len(stateObject.code)
   275  	}
   276  	size, err := self.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash()))
   277  	if err != nil {
   278  		self.setError(err)
   279  	}
   280  	return size
   281  }
   282  
   283  func (self *StateDB) GetCodeHash(addr common.Address) common.Hash {
   284  	stateObject := self.getStateObject(addr)
   285  	if stateObject == nil {
   286  		return common.Hash{}
   287  	}
   288  	return common.BytesToHash(stateObject.CodeHash())
   289  }
   290  
   291  func (self *StateDB) GetState(a common.Address, b common.Hash) common.Hash {
   292  	stateObject := self.getStateObject(a)
   293  	if stateObject != nil {
   294  		return stateObject.GetState(self.db, b)
   295  	}
   296  	return common.Hash{}
   297  }
   298  
   299  // GetCommittedState retrieves a value from the given account's committed storage trie.
   300  func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
   301  	stateObject := s.getStateObject(addr)
   302  	if stateObject != nil {
   303  		return stateObject.GetCommittedState(s.db, hash)
   304  	}
   305  	return common.Hash{}
   306  }
   307  
   308  func (self *StateDB) HasTX1(a common.Address, txHash common.Hash) bool {
   309  	stateObject := self.getStateObject(a)
   310  	if stateObject != nil {
   311  		return stateObject.HasTX1(self.db, txHash)
   312  	}
   313  	return false
   314  }
   315  
   316  func (self *StateDB) HasTX3(a common.Address, txHash common.Hash) bool {
   317  	stateObject := self.getStateObject(a)
   318  	if stateObject != nil {
   319  		return stateObject.HasTX3(self.db, txHash)
   320  	}
   321  	return false
   322  }
   323  
   324  // Database retrieves the low level database supporting the lower level trie ops.
   325  func (self *StateDB) Database() Database {
   326  	return self.db
   327  }
   328  
   329  // StorageTrie returns the storage trie of an account.
   330  // The return value is a copy and is nil for non-existent accounts.
   331  func (self *StateDB) StorageTrie(a common.Address) Trie {
   332  	stateObject := self.getStateObject(a)
   333  	if stateObject == nil {
   334  		return nil
   335  	}
   336  	cpy := stateObject.deepCopy(self, nil)
   337  	return cpy.updateTrie(self.db)
   338  }
   339  
   340  // TX1Trie returns the TX1 trie of an account.
   341  // The return value is a copy and is nil for non-existent accounts.
   342  func (self *StateDB) TX1Trie(a common.Address) Trie {
   343  	stateObject := self.getStateObject(a)
   344  	if stateObject == nil {
   345  		return nil
   346  	}
   347  	cpy := stateObject.deepCopy(self, nil)
   348  	return cpy.updateTX1Trie(self.db)
   349  }
   350  
   351  // TX3Trie returns the TX3 trie of an account.
   352  // The return value is a copy and is nil for non-existent accounts.
   353  func (self *StateDB) TX3Trie(a common.Address) Trie {
   354  	stateObject := self.getStateObject(a)
   355  	if stateObject == nil {
   356  		return nil
   357  	}
   358  	cpy := stateObject.deepCopy(self, nil)
   359  	return cpy.updateTX3Trie(self.db)
   360  }
   361  
   362  func (self *StateDB) HasSuicided(addr common.Address) bool {
   363  	stateObject := self.getStateObject(addr)
   364  	if stateObject != nil {
   365  		return stateObject.suicided
   366  	}
   367  	return false
   368  }
   369  
   370  /*
   371   * SETTERS
   372   */
   373  
   374  // AddBalance adds amount to the account associated with addr
   375  func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) {
   376  	stateObject := self.GetOrNewStateObject(addr)
   377  	if stateObject != nil {
   378  		stateObject.AddBalance(amount)
   379  	}
   380  }
   381  
   382  // SubBalance subtracts amount from the account associated with addr
   383  func (self *StateDB) SubBalance(addr common.Address, amount *big.Int) {
   384  	stateObject := self.GetOrNewStateObject(addr)
   385  	if stateObject != nil {
   386  		stateObject.SubBalance(amount)
   387  	}
   388  }
   389  
   390  func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) {
   391  	stateObject := self.GetOrNewStateObject(addr)
   392  	if stateObject != nil {
   393  		stateObject.SetBalance(amount)
   394  	}
   395  }
   396  
   397  func (self *StateDB) SetNonce(addr common.Address, nonce uint64) {
   398  	stateObject := self.GetOrNewStateObject(addr)
   399  	if stateObject != nil {
   400  		stateObject.SetNonce(nonce)
   401  	}
   402  }
   403  
   404  func (self *StateDB) SetCode(addr common.Address, code []byte) {
   405  	stateObject := self.GetOrNewStateObject(addr)
   406  	if stateObject != nil {
   407  		stateObject.SetCode(crypto.Keccak256Hash(code), code)
   408  	}
   409  }
   410  
   411  func (self *StateDB) SetState(addr common.Address, key common.Hash, value common.Hash) {
   412  	stateObject := self.GetOrNewStateObject(addr)
   413  	if stateObject != nil {
   414  		stateObject.SetState(self.db, key, value)
   415  	}
   416  }
   417  
   418  func (self *StateDB) AddTX1(addr common.Address, txHash common.Hash) {
   419  	stateObject := self.GetOrNewStateObject(addr)
   420  	if stateObject != nil {
   421  		stateObject.AddTX1(self.db, txHash)
   422  	}
   423  }
   424  
   425  func (self *StateDB) AddTX3(addr common.Address, txHash common.Hash) {
   426  	stateObject := self.GetOrNewStateObject(addr)
   427  	if stateObject != nil {
   428  		stateObject.AddTX3(self.db, txHash)
   429  	}
   430  }
   431  
   432  // Suicide marks the given account as suicided.
   433  // This clears the account balance.
   434  //
   435  // The account's state object is still available until the state is committed,
   436  // getStateObject will return a non-nil account after Suicide.
   437  func (self *StateDB) Suicide(addr common.Address) bool {
   438  	stateObject := self.getStateObject(addr)
   439  	if stateObject == nil {
   440  		return false
   441  	}
   442  	self.journal = append(self.journal, suicideChange{
   443  		account:     &addr,
   444  		prev:        stateObject.suicided,
   445  		prevbalance: new(big.Int).Set(stateObject.Balance()),
   446  	})
   447  	stateObject.markSuicided()
   448  	stateObject.data.Balance = new(big.Int)
   449  
   450  	return true
   451  }
   452  
   453  //
   454  // Setting, updating & deleting state object methods
   455  //
   456  
   457  // updateStateObject writes the given object to the trie.
   458  func (self *StateDB) updateStateObject(stateObject *stateObject) {
   459  	addr := stateObject.Address()
   460  	data, err := rlp.EncodeToBytes(stateObject)
   461  	if err != nil {
   462  		panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
   463  	}
   464  	self.setError(self.trie.TryUpdate(addr[:], data))
   465  }
   466  
   467  // deleteStateObject removes the given object from the state trie.
   468  func (self *StateDB) deleteStateObject(stateObject *stateObject) {
   469  	stateObject.deleted = true
   470  	addr := stateObject.Address()
   471  	self.setError(self.trie.TryDelete(addr[:]))
   472  }
   473  
   474  // Retrieve a state object given my the address. Returns nil if not found.
   475  func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) {
   476  	// Prefer 'live' objects.
   477  	if obj := self.stateObjects[addr]; obj != nil {
   478  		if obj.deleted {
   479  			return nil
   480  		}
   481  		return obj
   482  	}
   483  
   484  	// Load the object from the database.
   485  	enc, err := self.trie.TryGet(addr[:])
   486  	if len(enc) == 0 {
   487  		self.setError(err)
   488  		return nil
   489  	}
   490  	var data Account
   491  	if err := rlp.DecodeBytes(enc, &data); err != nil {
   492  		log.Error("Failed to decode state object", "addr", addr, "err", err)
   493  		return nil
   494  	}
   495  	// Insert into the live set.
   496  	obj := newObject(self, addr, data, self.MarkStateObjectDirty)
   497  	self.setStateObject(obj)
   498  	return obj
   499  }
   500  
   501  func (self *StateDB) setStateObject(object *stateObject) {
   502  	self.stateObjects[object.Address()] = object
   503  }
   504  
   505  // Retrieve a state object or create a new state object if nil
   506  func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
   507  	stateObject := self.getStateObject(addr)
   508  	if stateObject == nil || stateObject.deleted {
   509  		stateObject, _ = self.createObject(addr)
   510  	}
   511  	return stateObject
   512  }
   513  
   514  // MarkStateObjectDirty adds the specified object to the dirty map to avoid costly
   515  // state object cache iteration to find a handful of modified ones.
   516  func (self *StateDB) MarkStateObjectDirty(addr common.Address) {
   517  	self.stateObjectsDirty[addr] = struct{}{}
   518  	//fmt.Printf("core state append journal=%v, address=%v, hexaddress\n", self.journal, addr, addr.String())
   519  }
   520  
   521  // createObject creates a new state object. If there is an existing account with
   522  // the given address, it is overwritten and returned as the second return value.
   523  func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
   524  	prev = self.getStateObject(addr)
   525  	newobj = newObject(self, addr, Account{}, self.MarkStateObjectDirty)
   526  	newobj.setNonce(0) // sets the object to dirty
   527  	if prev == nil {
   528  		self.journal = append(self.journal, createObjectChange{account: &addr})
   529  	} else {
   530  		self.journal = append(self.journal, resetObjectChange{prev: prev})
   531  	}
   532  	self.setStateObject(newobj)
   533  	return newobj, prev
   534  }
   535  
   536  // CreateAccount explicitly creates a state object. If a state object with the address
   537  // already exists the balance is carried over to the new account.
   538  //
   539  // CreateAccount is called during the EVM CREATE operation. The situation might arise that
   540  // a contract does the following:
   541  //
   542  //  1. sends funds to sha(account ++ (nonce + 1))
   543  //  2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
   544  //
   545  // Carrying over the balance ensures that Ether doesn't disappear.
   546  func (self *StateDB) CreateAccount(addr common.Address) {
   547  	new, prev := self.createObject(addr)
   548  	if prev != nil {
   549  		new.setBalance(prev.data.Balance)
   550  	}
   551  }
   552  
   553  func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {
   554  	so := db.getStateObject(addr)
   555  	if so == nil {
   556  		return nil
   557  	}
   558  	it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
   559  
   560  	for it.Next() {
   561  		key := common.BytesToHash(db.trie.GetKey(it.Key))
   562  		if value, dirty := so.dirtyStorage[key]; dirty {
   563  			if !cb(key, value) {
   564  				return nil
   565  			}
   566  			continue
   567  		}
   568  
   569  		if len(it.Value) > 0 {
   570  			_, content, _, err := rlp.Split(it.Value)
   571  			if err != nil {
   572  				return err
   573  			}
   574  			if !cb(key, common.BytesToHash(content)) {
   575  				return nil
   576  			}
   577  		}
   578  	}
   579  	return nil
   580  }
   581  
   582  func (db *StateDB) ForEachTX1(addr common.Address, cb func(tx1 common.Hash) bool) {
   583  	so := db.getStateObject(addr)
   584  	if so == nil {
   585  		return
   586  	}
   587  
   588  	it := trie.NewIterator(so.getTX1Trie(db.db).NodeIterator(nil))
   589  	for it.Next() {
   590  		key := common.BytesToHash(db.trie.GetKey(it.Key)) // key is the tx1 hash
   591  		if ret := cb(key); !ret {
   592  			break
   593  		}
   594  	}
   595  }
   596  
   597  func (db *StateDB) ForEachTX3(addr common.Address, cb func(tx3 common.Hash) bool) {
   598  	so := db.getStateObject(addr)
   599  	if so == nil {
   600  		return
   601  	}
   602  
   603  	it := trie.NewIterator(so.getTX3Trie(db.db).NodeIterator(nil))
   604  	for it.Next() {
   605  		key := common.BytesToHash(db.trie.GetKey(it.Key)) // key is the tx3 hash
   606  		if ret := cb(key); !ret {
   607  			break
   608  		}
   609  	}
   610  }
   611  
   612  func (db *StateDB) ForEachProxied(addr common.Address, cb func(key common.Address, proxiedBalance, depositProxiedBalance, pendingRefundBalance *big.Int) bool) {
   613  	so := db.getStateObject(addr)
   614  	if so == nil {
   615  		return
   616  	}
   617  	it := trie.NewIterator(so.getProxiedTrie(db.db).NodeIterator(nil))
   618  	for it.Next() {
   619  		key := common.BytesToAddress(db.trie.GetKey(it.Key))
   620  		if value, dirty := so.dirtyProxied[key]; dirty {
   621  			cb(key, value.ProxiedBalance, value.DepositProxiedBalance, value.PendingRefundBalance)
   622  			continue
   623  		}
   624  		var apb accountProxiedBalance
   625  		rlp.DecodeBytes(it.Value, &apb)
   626  		cb(key, apb.ProxiedBalance, apb.DepositProxiedBalance, apb.PendingRefundBalance)
   627  	}
   628  }
   629  
   630  // Copy creates a deep, independent copy of the state.
   631  // Snapshots of the copied state cannot be applied to the copy.
   632  func (self *StateDB) Copy() *StateDB {
   633  	// Copy all the basic fields, initialize the memory ones
   634  	state := &StateDB{
   635  		db:                           self.db,
   636  		trie:                         self.db.CopyTrie(self.trie),
   637  		stateObjects:                 make(map[common.Address]*stateObject, len(self.stateObjectsDirty)),
   638  		stateObjectsDirty:            make(map[common.Address]struct{}, len(self.stateObjectsDirty)),
   639  		delegateRefundSet:            make(DelegateRefundSet, len(self.delegateRefundSet)),
   640  		delegateRefundSetDirty:       self.delegateRefundSetDirty,
   641  		rewardSet:                    make(RewardSet, len(self.rewardSet)),
   642  		rewardSetDirty:               self.rewardSetDirty,
   643  		candidateSet:                 make(CandidateSet, len(self.candidateSet)),
   644  		candidateSetDirty:            self.candidateSetDirty,
   645  		bannedSet:                    make(BannedSet, len(self.bannedSet)),
   646  		bannedSetDirty:               self.bannedSetDirty,
   647  		sideChainRewardPerBlockDirty: self.sideChainRewardPerBlockDirty,
   648  		refund:                       self.refund,
   649  		logs:                         make(map[common.Hash][]*types.Log, len(self.logs)),
   650  		logSize:                      self.logSize,
   651  		preimages:                    make(map[common.Hash][]byte, len(self.preimages)),
   652  	}
   653  	// Copy the dirty states, logs, and preimages
   654  	for addr := range self.stateObjectsDirty {
   655  		state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state, state.MarkStateObjectDirty)
   656  		state.stateObjectsDirty[addr] = struct{}{}
   657  	}
   658  	for addr := range self.delegateRefundSet {
   659  		state.delegateRefundSet[addr] = struct{}{}
   660  	}
   661  	for addr := range self.rewardSet {
   662  		state.rewardSet[addr] = struct{}{}
   663  	}
   664  
   665  	for addr := range self.candidateSet {
   666  		state.candidateSet[addr] = struct{}{}
   667  	}
   668  
   669  	for addr := range self.bannedSet {
   670  		state.bannedSet[addr] = struct{}{}
   671  	}
   672  
   673  	if self.sideChainRewardPerBlock != nil {
   674  		state.sideChainRewardPerBlock = new(big.Int).Set(self.sideChainRewardPerBlock)
   675  	}
   676  	for hash, logs := range self.logs {
   677  		state.logs[hash] = make([]*types.Log, len(logs))
   678  		copy(state.logs[hash], logs)
   679  	}
   680  	for hash, preimage := range self.preimages {
   681  		state.preimages[hash] = preimage
   682  	}
   683  	return state
   684  }
   685  
   686  // Snapshot returns an identifier for the current revision of the state.
   687  func (self *StateDB) Snapshot() int {
   688  	id := self.nextRevisionId
   689  	self.nextRevisionId++
   690  	self.validRevisions = append(self.validRevisions, revision{id, len(self.journal)})
   691  	return id
   692  }
   693  
   694  // RevertToSnapshot reverts all state changes made since the given revision.
   695  func (self *StateDB) RevertToSnapshot(revid int) {
   696  	// Find the snapshot in the stack of valid snapshots.
   697  	idx := sort.Search(len(self.validRevisions), func(i int) bool {
   698  		return self.validRevisions[i].id >= revid
   699  	})
   700  	if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid {
   701  		panic(fmt.Errorf("revision id %v cannot be reverted", revid))
   702  	}
   703  	snapshot := self.validRevisions[idx].journalIndex
   704  
   705  	// Replay the journal to undo changes.
   706  	for i := len(self.journal) - 1; i >= snapshot; i-- {
   707  		self.journal[i].undo(self)
   708  	}
   709  	self.journal = self.journal[:snapshot]
   710  
   711  	// Remove invalidated snapshots from the stack.
   712  	self.validRevisions = self.validRevisions[:idx]
   713  }
   714  
   715  // GetRefund returns the current value of the refund counter.
   716  func (self *StateDB) GetRefund() uint64 {
   717  	return self.refund
   718  }
   719  
   720  // Finalise finalises the state by removing the self destructed objects
   721  // and clears the journal as well as the refunds.
   722  func (s *StateDB) Finalise(deleteEmptyObjects bool) {
   723  	//fmt.Printf("core state statedb.go Finalise s.journal.dirtied=%v\n", s.stateObjectsDirty)
   724  	for addr := range s.stateObjectsDirty {
   725  		stateObject := s.stateObjects[addr]
   726  		if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) {
   727  			s.deleteStateObject(stateObject)
   728  		} else {
   729  			stateObject.updateRoot(s.db)
   730  			stateObject.updateTX1Root(s.db)
   731  			stateObject.updateTX3Root(s.db)
   732  			stateObject.updateProxiedRoot(s.db)
   733  			stateObject.updateRewardRoot(s.db)
   734  			s.updateStateObject(stateObject)
   735  		}
   736  	}
   737  
   738  	// Update Delegate Refund Set if something changed
   739  	if s.delegateRefundSetDirty {
   740  		s.commitDelegateRefundSet()
   741  	}
   742  
   743  	// Update Reward Set if something changed
   744  	if s.rewardSetDirty {
   745  		s.commitRewardSet()
   746  	}
   747  
   748  	if s.candidateSetDirty {
   749  		fmt.Printf("candidate set bug, candidate set dirty commit candidate set")
   750  		s.commitCandidateSet()
   751  	}
   752  
   753  	if s.bannedSetDirty {
   754  		s.commitBannedSet()
   755  	}
   756  
   757  	// Update Side Chain Reward per Block if something changed
   758  	if s.sideChainRewardPerBlockDirty {
   759  		s.commitSideChainRewardPerBlock()
   760  	}
   761  
   762  	// Invalidate journal because reverting across transactions is not allowed.
   763  	s.clearJournalAndRefund()
   764  }
   765  
   766  // IntermediateRoot computes the current root hash of the state trie.
   767  // It is called in between transactions to get the root hash that
   768  // goes into transaction receipts.
   769  func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
   770  	s.Finalise(deleteEmptyObjects)
   771  	//fmt.Printf("core state statedb.go IntermediateRoot hash=%v\n", s.trie.Hash().String())
   772  	return s.trie.Hash()
   773  }
   774  
   775  // Prepare sets the current transaction hash and index and block hash which is
   776  // used when the EVM emits new state logs.
   777  func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) {
   778  	self.thash = thash
   779  	self.bhash = bhash
   780  	self.txIndex = ti
   781  }
   782  
   783  // DeleteSuicides flags the suicided objects for deletion so that it
   784  // won't be referenced again when called / queried up on.
   785  //
   786  // DeleteSuicides should not be used for consensus related updates
   787  // under any circumstances.
   788  func (s *StateDB) DeleteSuicides() {
   789  	// Reset refund so that any used-gas calculations can use this method.
   790  	s.clearJournalAndRefund()
   791  
   792  	for addr := range s.stateObjectsDirty {
   793  		stateObject := s.stateObjects[addr]
   794  
   795  		// If the object has been removed by a suicide
   796  		// flag the object as deleted.
   797  		if stateObject.suicided {
   798  			stateObject.deleted = true
   799  		}
   800  		delete(s.stateObjectsDirty, addr)
   801  	}
   802  }
   803  
   804  func (s *StateDB) clearJournalAndRefund() {
   805  	s.journal = nil
   806  	s.validRevisions = s.validRevisions[:0]
   807  	s.refund = 0
   808  }
   809  
   810  // Commit writes the state to the underlying in-memory trie database.
   811  func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) {
   812  	defer s.clearJournalAndRefund()
   813  
   814  	// Commit objects to the trie.
   815  	for addr, stateObject := range s.stateObjects {
   816  		_, isDirty := s.stateObjectsDirty[addr]
   817  		switch {
   818  		case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()):
   819  			// If the object has been removed, don't bother syncing it
   820  			// and just mark it for deletion in the trie.
   821  			s.deleteStateObject(stateObject)
   822  		case isDirty:
   823  			// Write any contract code associated with the state object
   824  			if stateObject.code != nil && stateObject.dirtyCode {
   825  				s.db.TrieDB().InsertBlob(common.BytesToHash(stateObject.CodeHash()), stateObject.code)
   826  				stateObject.dirtyCode = false
   827  			}
   828  			// Write any storage changes in the state object to its storage trie.
   829  			if err := stateObject.CommitTrie(s.db); err != nil {
   830  				return common.Hash{}, err
   831  			}
   832  			// Write any TX1 changes in the state object to its TX1 trie.
   833  			if err := stateObject.CommitTX1Trie(s.db); err != nil {
   834  				return common.Hash{}, err
   835  			}
   836  			// Write any TX3 changes in the state object to its TX3 trie.
   837  			if err := stateObject.CommitTX3Trie(s.db); err != nil {
   838  				return common.Hash{}, err
   839  			}
   840  			// Write any Proxied Delegate Balance changes in the state object to its proxied trie.
   841  			if err := stateObject.CommitProxiedTrie(s.db); err != nil {
   842  				return common.Hash{}, err
   843  			}
   844  			// Write any Reward Balance changes in the state object to its reward trie.
   845  			if err := stateObject.CommitRewardTrie(s.db); err != nil {
   846  				return common.Hash{}, err
   847  			}
   848  			// Update the object in the main account trie.
   849  			s.updateStateObject(stateObject)
   850  		}
   851  		delete(s.stateObjectsDirty, addr)
   852  	}
   853  
   854  	// Commit Delegate Refund Set to the trie
   855  	if s.delegateRefundSetDirty {
   856  		s.commitDelegateRefundSet()
   857  		s.delegateRefundSetDirty = false
   858  	}
   859  
   860  	// Commit Reward Set to the trie
   861  	if s.rewardSetDirty {
   862  		s.commitRewardSet()
   863  		s.rewardSetDirty = false
   864  	}
   865  
   866  	if s.candidateSetDirty {
   867  		s.commitCandidateSet()
   868  		s.candidateSetDirty = false
   869  	}
   870  
   871  	if s.bannedSetDirty {
   872  		s.commitBannedSet()
   873  		s.bannedSetDirty = false
   874  	}
   875  
   876  	// Commit Reward Per Block to the trie
   877  	if s.sideChainRewardPerBlockDirty {
   878  		s.commitSideChainRewardPerBlock()
   879  		s.sideChainRewardPerBlockDirty = false
   880  	}
   881  
   882  	// Write trie changes.
   883  	root, err = s.trie.Commit(func(leaf []byte, parent common.Hash) error {
   884  		var account Account
   885  		if err := rlp.DecodeBytes(leaf, &account); err != nil {
   886  			return nil
   887  		}
   888  		if account.Root != emptyRoot {
   889  			s.db.TrieDB().Reference(account.Root, parent)
   890  		}
   891  		if account.TX1Root != emptyRoot {
   892  			s.db.TrieDB().Reference(account.TX1Root, parent)
   893  		}
   894  		if account.TX3Root != emptyRoot {
   895  			s.db.TrieDB().Reference(account.TX3Root, parent)
   896  		}
   897  		if account.ProxiedRoot != emptyRoot {
   898  			s.db.TrieDB().Reference(account.ProxiedRoot, parent)
   899  		}
   900  		if account.RewardRoot != emptyRoot {
   901  			s.db.TrieDB().Reference(account.RewardRoot, parent)
   902  		}
   903  		code := common.BytesToHash(account.CodeHash)
   904  		if code != emptyCode {
   905  			s.db.TrieDB().Reference(code, parent)
   906  		}
   907  		return nil
   908  	})
   909  	return root, err
   910  }